Carry source identity through builds and delivery

This commit is contained in:
2026-12-05 21:22:38 +00:00
parent 3b925231d5
commit bbee996f84
20 changed files with 423 additions and 95 deletions

View File

@@ -2,6 +2,7 @@ package releasekit
import (
"context"
"errors"
"fmt"
"io"
@@ -34,7 +35,7 @@ type BuildRequest struct {
// Source selects explicit source and publication capabilities. Nil retains
// the ModuleDir Go-module shorthand.
Source *SourceSpec
Version string // stable vMAJOR.MINOR.PATCH value injected at link time.
Version string // selected production identifier injected at link time.
Spec BuildSpec // application package, artifact name, and targets.
OutputDir string // output location; relative paths use ModuleDir and empty selects <module>/dist.
Output io.Writer // optional build progress destination.
@@ -50,11 +51,18 @@ type BuildArtifact struct {
// BuildResult describes the source and artifacts reached by Build.
type BuildResult struct {
RepositoryDir string // absolute source repository path.
ModuleDir string // absolute selected module directory.
ModulePath string // selected module's declared Go path.
Tag string // complete tag derived for this version.
CandidateCommit string // Git HEAD observed when the build started.
RepositoryDir string // absolute source repository path.
SourceDir string // absolute selected source directory.
SourceSubdir string // repository-relative selected source directory.
GoEnabled bool // whether Go capability was selected.
Publication PublicationMode // selected publication mode.
VersionFormat VersionFormat // selected production identifier format.
VersionPrefix string // selected production identifier prefix.
IdentityKind string // production or diagnostic identity kind.
ModuleDir string // absolute selected module directory.
ModulePath string // selected module's declared Go path.
Tag string // complete tag derived for this version.
CandidateCommit string // Git HEAD observed when the build started.
// SourceVerified reports clean source and the same HEAD observed before and
// after a completed build. It is required for binary delivery, not an attestation.
SourceVerified bool
@@ -82,7 +90,7 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
result.Settings = artifact.NormalizeSettings(spec.MainPackage, spec.BinaryName, spec.Targets)
return publicBuildResult(result), err
}
if !versioncontract.ValidStableVersion(request.Version) {
if request.Source == nil && !versioncontract.ValidStableVersion(request.Version) {
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
}
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
@@ -91,13 +99,14 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
}
result.RepositoryDir = repositoryDir
identity, err := releaseidentity.FromWorkingSource(ctx, repositoryDir, request.ModuleDir, request.Version, internalSourceSpec(request.Source))
result.Identity = identity
result.ModuleDir, result.ModulePath, result.Tag = identity.ModuleDir, identity.ModulePath, identity.Tag
if err != nil {
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
}
return failure(err)
}
if identity.Publication == "source" {
return failure(fmt.Errorf("general source builds are not yet supported"))
}
result, err = internalbuild.BuildResolved(ctx, internalbuild.Request{
Identity: identity,
Spec: spec,
@@ -110,6 +119,13 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
func publicBuildResult(result internalbuild.Result) BuildResult {
public := BuildResult{
RepositoryDir: result.RepositoryDir,
SourceDir: result.Identity.SourceDir,
SourceSubdir: result.Identity.SourceSubdir,
GoEnabled: result.Identity.GoEnabled,
Publication: PublicationMode(result.Identity.Publication),
VersionFormat: VersionFormat(result.Identity.VersionFormat),
VersionPrefix: result.Identity.VersionPrefix,
IdentityKind: result.Identity.Kind,
ModuleDir: result.ModuleDir,
ModulePath: result.ModulePath,
Tag: result.Tag,
@@ -152,6 +168,7 @@ func internalBuildResult(result BuildResult) *internalbuild.Result {
input := internalBuildSpec(&BuildSpec{MainPackage: result.MainPackage, BinaryName: result.BinaryName, Targets: result.Targets})
settings := artifact.NormalizeSettings(input.MainPackage, input.BinaryName, input.Targets)
converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, ModuleDir: result.ModuleDir, ModulePath: result.ModulePath, Tag: result.Tag, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Settings: settings, Version: result.Version, OutputDir: result.OutputDir, Compiler: result.Compiler}
converted.Identity = releaseidentity.Identity{Kind: result.IdentityKind, SourceDir: result.SourceDir, SourceSubdir: result.SourceSubdir, GoEnabled: result.GoEnabled, Publication: string(result.Publication), VersionFormat: string(result.VersionFormat), VersionPrefix: result.VersionPrefix}
for _, artifact := range result.Artifacts {
converted.Artifacts = append(converted.Artifacts, internalbuild.Artifact{Path: artifact.Path, Filename: artifact.Filename, Target: internalbuild.Target{OS: artifact.Target.OS, Arch: artifact.Target.Arch}, SHA256: artifact.SHA256})
}

View File

@@ -49,7 +49,7 @@ func TestCIDeliveryRejectsModuleTagMismatchBeforePreparation(t *testing.T) {
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"ci-deliver", "--repo", repository, "--prepared", "--commit", commit, "--expected-module", "child", "v1.2.3"}, &stdout, &stderr)
if status != 1 || !strings.Contains(stderr.String(), `expected delivery tag "v1.2.3"`) || !strings.Contains(stderr.String(), `selected module tag "child/v1.2.3"`) {
if status != 1 || !strings.Contains(stderr.String(), `expected delivery tag "v1.2.3"`) || !strings.Contains(stderr.String(), `selected source tag "child/v1.2.3"`) {
t.Fatalf("status=%d stderr=%q, want module tag mismatch", status, stderr.String())
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {

View File

@@ -15,10 +15,9 @@ import (
"go.maximumdirect.net/releasekit/internal/process"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/versioncontract"
)
const Usage = "usage: releasekit version\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] [--record-dir DIR] [--expected-module DIR] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG\n releasekit reconcile --record FILE [--json]\n releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]"
const Usage = "usage: releasekit version\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] [--record-dir DIR] [--expected-module DIR] [--expected-source DIR] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG\n releasekit reconcile --record FILE [--json]\n releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]"
type Command string
@@ -44,6 +43,7 @@ type Invocation struct {
Commit string
Version string
ExpectedModule string
ExpectedSource string
ExpectedTag string
Prepared bool
RecordPath string
@@ -102,8 +102,10 @@ func Parse(args []string) (Invocation, error) {
}
var remote *string
expectedModule := ""
expectedSource := ""
if action == PublishAction || action == CIDeliveryAction {
flags.StringVar(&expectedModule, "expected-module", "", "expected module directory from a launcher mapping")
flags.StringVar(&expectedSource, "expected-source", "", "expected source directory from a launcher mapping")
}
recordDir := ""
if action == PublishAction {
@@ -135,18 +137,12 @@ func Parse(args []string) (Invocation, error) {
if slash := strings.LastIndex(version, "/"); slash >= 0 {
version = version[slash+1:]
}
if !versioncontract.ValidStableVersion(version) {
return Invocation{}, errors.New("ci-deliver TAG must end in a stable vMAJOR.MINOR.PATCH version")
}
}
if !versioncontract.ValidStableVersion(version) {
return Invocation{}, errors.New("VERSION must be a stable vMAJOR.MINOR.PATCH version")
}
parsedRemote := ""
if remote != nil {
parsedRemote = *remote
}
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedTag: expectedTag, Prepared: prepared, RecordDir: recordDir}, nil
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedSource: expectedSource, ExpectedTag: expectedTag, Prepared: prepared, RecordDir: recordDir}, nil
default:
return Invocation{}, fmt.Errorf("unknown command %q", args[0])
}

View File

@@ -67,6 +67,10 @@ func TestParse(t *testing.T) {
if err != nil || publishMapped.ExpectedModule != "integrations/ckconfig" {
t.Fatalf("Parse(publish --expected-module) = %#v, error = %v", publishMapped, err)
}
publishSource, err := Parse([]string{"publish", "--expected-source", "config", "2026-12-01"})
if err != nil || publishSource.ExpectedSource != "config" || publishSource.Version != "2026-12-01" {
t.Fatalf("Parse(publish --expected-source) = %#v, error = %v", publishSource, err)
}
build, err := Parse([]string{"build", "--repo", "candidate", "--config", "releasekit.json", "--output", "output with spaces", "v1.2.5"})
if err != nil {
t.Fatal(err)
@@ -98,8 +102,9 @@ func TestParse(t *testing.T) {
if _, err := Parse([]string{"ci-deliver", "--commit", "abc123", "v1.2.3"}); err == nil || !strings.Contains(err.Error(), "full Git object ID") {
t.Fatalf("Parse(ci-deliver with abbreviated commit) error = %v, want full object ID error", err)
}
if _, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "integrations/ckconfig/latest"}); err == nil || !strings.Contains(err.Error(), "stable vMAJOR.MINOR.PATCH") {
t.Fatalf("Parse(ci-deliver unstable terminal tag) error = %v", err)
calendar, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "config/2026-12-01"})
if err != nil || calendar.Version != "2026-12-01" || calendar.ExpectedTag != "config/2026-12-01" {
t.Fatalf("Parse(ci-deliver calendar tag) = %#v, error = %v", calendar, err)
}
if _, err := Parse([]string{"check", "v1.2.3", "--repo", "repository"}); err == nil {
t.Fatal("Parse accepted a flag after the version")

View File

@@ -19,6 +19,7 @@ import (
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/versioncontract"
)
func main() {
@@ -69,8 +70,8 @@ func runCheckOrPublish(ctx context.Context, invocation cli.Invocation, stdout, s
}
request := candidateRequest(invocation, settings, stderr)
if invocation.Command == cli.PublishAction {
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err)
if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
fmt.Fprintf(stderr, "%s: %v\n", selectionErrorLabel(invocation.ExpectedSource), err)
return 2
}
request.ExpectedPushURL = settings.ExpectedPushURL
@@ -338,28 +339,40 @@ func candidateFailureText(err error) string {
return err.Error()
}
func checkExpectedModule(ctx context.Context, repositoryDir, expectedModule, profileModule string) error {
if expectedModule == "" {
func checkExpectedSelection(ctx context.Context, repositoryDir, expectedModule, expectedSource string, settings cli.Settings) error {
if expectedModule == "" && expectedSource == "" {
return nil
}
commit, err := git.CaptureHead(ctx, repositoryDir)
if err != nil {
return err
}
expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectedModule, commit)
selected, err := releaseidentity.ResolveCommittedSource(ctx, repositoryDir, settings.ModuleDir, commit, settings.SourceSpec())
if err != nil {
return fmt.Errorf("normalize expected module %q: %w", expectedModule, err)
return fmt.Errorf("normalize profile source: %w", err)
}
selected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, profileModule, commit)
if err != nil {
return fmt.Errorf("normalize profile module %q: %w", profileModule, err)
}
if expected.ModuleSubdir != selected.ModuleSubdir {
return fmt.Errorf("expected module %q resolves to %q, but the profile selects %q", expectedModule, expected.ModuleSubdir, selected.ModuleSubdir)
for _, expectation := range []struct{ kind, dir string }{{"module", expectedModule}, {"source", expectedSource}} {
if expectation.dir == "" {
continue
}
expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectation.dir, commit)
if err != nil {
return fmt.Errorf("normalize expected %s %q: %w", expectation.kind, expectation.dir, err)
}
if expected.ModuleSubdir != selected.ModuleSubdir {
return fmt.Errorf("expected %s %q resolves to %q, but the profile selects %q", expectation.kind, expectation.dir, expected.ModuleSubdir, selected.ModuleSubdir)
}
}
return nil
}
func selectionErrorLabel(expectedSource string) string {
if expectedSource != "" {
return "profile source selection"
}
return "profile module selection"
}
func selectedModuleLabel(moduleDir string) string {
if moduleDir == "" {
return "."
@@ -404,19 +417,26 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
fmt.Fprintf(stderr, "load profile: %v\n", err)
return 2
}
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err)
if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
fmt.Fprintf(stderr, "%s: %v\n", selectionErrorLabel(invocation.ExpectedSource), err)
return 2
}
identity, err := releaseidentity.FromCommitted(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit)
identity, err := releaseidentity.FromCommittedSource(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit, settings.SourceSpec())
if err != nil {
fmt.Fprintf(stderr, "resolve CI release identity: %v\n", err)
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
return 2
}
return 1
}
if invocation.ExpectedTag != identity.Tag {
fmt.Fprintf(stderr, "expected delivery tag %q does not match selected module tag %q\n", invocation.ExpectedTag, identity.Tag)
fmt.Fprintf(stderr, "expected delivery tag %q does not match selected source tag %q\n", invocation.ExpectedTag, identity.Tag)
return 1
}
if !identity.GoEnabled && settings.Build != nil && len(settings.Build.Targets) != 0 {
fmt.Fprintln(stderr, "build targets require Go capability")
return 2
}
destination, status := deliveryDestination(invocation.Repository, settings, stderr)
if status != 0 {
return status
@@ -428,7 +448,7 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
}
if err := releasekit.PrepareBuildDependencies(ctx, releasekit.DependencyPreparationRequest{
RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir,
ModuleDir: identity.ModuleSubdir,
}); err != nil {
fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err)
return 1
@@ -512,7 +532,7 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
fmt.Fprintf(stderr, "capture asset source commit: %v\n", err)
return 1
}
selection, err := releaseidentity.ResolveCommittedSelection(ctx, invocation.Repository, settings.ModuleDir, commit)
selection, err := releaseidentity.ResolveCommittedSource(ctx, invocation.Repository, settings.ModuleDir, commit, settings.SourceSpec())
if err != nil {
fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err)
return 1

View File

@@ -24,11 +24,13 @@ func TestNativeCheckFromChildUsesRootProfileAndSuite(t *testing.T) {
}
}
func TestNativeBuildClassifiesInvalidVersionBeforeSourceAccess(t *testing.T) {
func TestNativeBuildClassifiesInvalidVersionAfterProfileSelection(t *testing.T) {
binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
command := exec.Command(binary, "build", "--repo", filepath.Join(t.TempDir(), "absent"), "bad-version")
repository := newCLIRepository(t)
writeRepositoryFile(t, repository, "releasekit.json", `{"product":"Example Product","build":{}}`)
command := exec.Command(binary, "build", "--repo", repository, "bad-version")
output, err := command.CombinedOutput()
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 2 || !strings.Contains(string(output), "stable vMAJOR.MINOR.PATCH") {
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 2 || !strings.Contains(string(output), "invalid stable version") {
t.Fatalf("invalid build error = %v, output = %s", err, output)
}
}

View File

@@ -1,6 +1,7 @@
package main
import (
"bytes"
"context"
"os"
"path/filepath"
@@ -29,6 +30,32 @@ func TestSourceSelectionMapsToRequest(t *testing.T) {
}
}
func TestCIDeliveryChecksFullCalendarTagAgainstProfile(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "config/docs/releases/2026-12-01.md", "# Config 2026-12-01\n")
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{"dir":"config"},"version":{"format":"date"}}`)
cliGitRun(t, repo, "add", "config", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "configure source release")
commit := cliGitOutput(t, repo, "rev-parse", "HEAD")
cliGitRun(t, repo, "tag", "config/2026-12-01")
cliGitRun(t, repo, "tag", "other/2026-12-01")
for _, tt := range []struct {
tag, message string
status int
}{
{tag: "other/2026-12-01", status: 1, message: "does not match"},
{tag: "config/2026-12-01", status: 2, message: "delivery.forge"},
} {
t.Run(tt.tag, func(t *testing.T) {
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"ci-deliver", "--repo", repo, "--prepared", "--expected-source", "config", "--commit", commit, tt.tag}, &stdout, &stderr)
if status != tt.status || !strings.Contains(stderr.String(), tt.message) {
t.Fatalf("status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
})
}
}
func TestSourceCheckCommandUsesSelectedDirectoryAndEnvironment(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX shell check")
@@ -56,3 +83,18 @@ func TestSourceCheckCommandUsesSelectedDirectoryAndEnvironment(t *testing.T) {
t.Fatalf("check context = %q, want %q", data, want)
}
}
func TestExpectedSourceChecksTheProfileSelection(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "config/data.json", "{}")
writeRepositoryFile(t, repo, "other/data.json", "{}")
cliGitRun(t, repo, "add", "config", "other")
cliGitRun(t, repo, "commit", "-m", "add source directories")
settings := cli.Settings{Source: &cli.SourceSettings{Dir: "config"}}
if err := checkExpectedSelection(context.Background(), repo, "config", "config", settings); err != nil {
t.Fatalf("matching expected source: %v", err)
}
if err := checkExpectedSelection(context.Background(), repo, "other", "config", settings); err == nil {
t.Fatal("accepted conflicting expected directories")
}
}

View File

@@ -125,10 +125,16 @@ type DeliveryRequest struct {
// failures may leave some declared assets unreported.
type DeliveryResult struct {
RepositoryDir string
SourceDir string
SourceSubdir string
GoEnabled bool
Publication PublicationMode
VersionFormat VersionFormat
VersionPrefix string
ModuleDir string
ModulePath string
Tag string // complete derived Git tag.
Version string // selected stable semantic version.
Version string // selected production identifier.
CandidateCommit string
ReleaseURL string
State DeliveryState
@@ -178,6 +184,12 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
Output: request.Output,
})
result.RepositoryDir = internalResult.RepositoryDir
result.SourceDir = internalResult.Identity.SourceDir
result.SourceSubdir = internalResult.Identity.SourceSubdir
result.GoEnabled = internalResult.Identity.GoEnabled
result.Publication = PublicationMode(internalResult.Identity.Publication)
result.VersionFormat = VersionFormat(internalResult.Identity.VersionFormat)
result.VersionPrefix = internalResult.Identity.VersionPrefix
result.ModuleDir = internalResult.ModuleDir
result.ModulePath = internalResult.ModulePath
result.Tag = internalResult.Tag

View File

@@ -22,7 +22,7 @@ Check a local candidate:
go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION
```
`VERSION` must use stable `vMAJOR.MINOR.PATCH` syntax. Options must precede the
`VERSION` must match the profile's selected identifier format. Options must precede the
version. The repository argument defaults to the current directory. ReleaseKit
resolves its containing Git checkout root before selecting the module or profile;
the profile defaults to `<repository-root>/releasekit.json`. A successful command prints the
@@ -34,9 +34,10 @@ selected package compilation and committed Go formatting, followed by
configured additional checks in profile order. It does not inspect remote
availability or publish a tag.
The profile's optional `module_dir` selects a repository-relative physical
module directory; omission selects the root module. Validation and configured
product checks use that module selection. Additional check commands run with
For legacy profiles, `module_dir` selects a repository-relative physical
module directory; omission selects the root module. Explicit profiles select
source and Go capabilities as described in the [configuration reference](config.md).
Additional check commands run with
the selected source as their working directory and receive
`RELEASEKIT_VERSION`, `RELEASEKIT_CANDIDATE`, `RELEASEKIT_REPOSITORY_DIR`,
`RELEASEKIT_SOURCE_DIR`, `RELEASEKIT_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their
@@ -78,7 +79,7 @@ Unsupported argument sequences print usage to standard error.
Publish a source tag:
```sh
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] [--record-dir DIR] VERSION
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] [--expected-source DIR] [--record-dir DIR] VERSION
```
`publish` reads the same product, remote, validation, and additional-check
@@ -90,8 +91,8 @@ tests. Selected package compilation and committed Go formatting follow. The
selected file checks then run in order: workspace files, local replacements,
file size, and Markdown. Configured checks run afterward in profile order. It
then creates an annotated local tag
and pushes only its exact full tag object. It prints the confirmed semantic
version, full tag, candidate commit, and tag object
and pushes only its exact full tag object. It prints the confirmed identifier,
full tag, candidate commit, and tag object
on success. Validation
progress and failed publication state, including the captured publication
endpoint for recovery, are written to standard error. HTTP(S) endpoint
@@ -130,10 +131,11 @@ It reports outside-checkout links to standard error unless boundary enforcement
is selected; submodule contents remain out of scope. Markdown failures stop
publication before product checks or tag creation.
`--expected-module DIR` optionally checks a launcher's selected physical module
against the profile's `module_dir` before candidate work. Both paths are
normalized relative to the repository; the profile remains the source of module
selection. The root selection is `.`.
`--expected-module DIR` and `--expected-source DIR` optionally check a
launcher's selected physical directory against the profile's source selection
before candidate work. Paths are normalized relative to the repository; the
profile remains the source of selection. If both flags are supplied, both must
match. The root selection is `.`.
The optional profile field `expected_push_url` applies only to `publish`. A
nonempty value must exactly match the effective push URL resolved by Git;
@@ -231,6 +233,10 @@ output directory are invalidated; no new receipt is written. An
empty target list returns the source commit without building or writing a
receipt.
The current receipt format supports the legacy prefixed SemVer module identity.
For other source identities, use the Go `Build` API until receipt support is
updated.
The command returns status 0 on completion, 1 for build or output failure, and
2 for usage, profile, or invalid-version errors. It builds the current source
tree and does not perform candidate validation or remote publication. `check`
@@ -302,21 +308,21 @@ known missing assets are added. See the
Prepare a tagged CI checkout and deliver it:
```sh
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG
```
`TAG` is the complete Git tag name, including any module path prefix. Its last
path component must be a stable semantic version; other commands continue to
take a semantic `VERSION`. By default, `ci-deliver` fetches the exact `TAG` from
`TAG` is the complete Git tag name, including any source path prefix. Its last
component is validated against the profile's selected version format after
checkout. By default, `ci-deliver` fetches the exact `TAG` from
the selected Git remote (default `origin`), requires its peeled commit to match
the required full `--commit` object ID, checks out that commit detached, then
verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those
checks read-only against the existing checkout and does not fetch or check out.
Preparation diagnostics mask userinfo in HTTP(S) remote URLs.
In either mode, it loads the profile from the verified source. `--expected-module`
optionally checks that the profile selects the module chosen by a launcher;
module selection itself remains profile-owned. The command compares the selected
module's derived release tag with the full event tag before forge access or
In either mode, it loads the profile from the verified source. The optional
`--expected-module` and `--expected-source` checks verify the launcher's
selected directory against the profile. The command compares the selected
source's derived release tag with the full event tag before forge access or
dependency preparation, then validates explicit forge selection and resolves
the configured token. For binary profiles, it performs a read-only repository
preflight before downloading application

View File

@@ -41,9 +41,9 @@ and empty for calendar formats. `source.tag_prefix` overrides the physical
source directory used as the source-tag prefix; an explicit empty string
selects an unprefixed tag. Go module publication requires prefixed SemVer and
rejects tag-prefix overrides that conflict with Go's module tag rules. The Go
facade's `Check` and `Publish` support these
selections; the current CLI version argument is restricted as described in the
[command reference](cli.md).
facade's `Check`, `Publish`, `Build`, and `Deliver` and the CLI candidate and
delivery commands use the selected format. See the [command reference](cli.md)
for invocation details.
Each check requires a nonempty `args` array whose first element names the
executable. Arguments are passed directly to the child process; ReleaseKit does

View File

@@ -36,9 +36,9 @@ func build(ctx context.Context) error {
}
```
`Build` resolves `ModuleDir` and the selected module's working-tree declaration
once, records the repository's current `HEAD`, injects the selected stable
version into `buildinfo.Version`, and returns repository/module identity, the
`Build` resolves the selected source and module's working-tree declaration
once, records the repository's current `HEAD`, injects the selected identifier
into `buildinfo.Version`, and returns repository/source and module identity, the
derived tag, compiler identity, normalized targets, artifact paths, filenames,
and SHA-256 digests. It does not require a release note, unused tag, clean
`main`, or publication. Names follow
@@ -47,6 +47,8 @@ target pair is built once, at its first position. Local builds may use modified
source. `SourceVerified` is true only after a complete build observes clean
source and the same HEAD before and after compilation; binary delivery requires
that fact. This observation is not a source snapshot or attestation guarantee.
An explicit `Source` with `GoEnabled` can select general source publication and
a calendar format or a product major independent of the module import path.
Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that
module. The default output directory is `<module>/dist`; a relative `OutputDir`

View File

@@ -9,12 +9,13 @@ The operation accepts historical lightweight and annotated tags, including a
detached checkout, when the checked-out `HEAD` identifies the selected tag
commit. It does not require the old remote `main` to match.
Delivery resolves the selected module's declaration and release note from the
captured commit. `Version` remains the semantic version; the full tag includes
the selected module's repository-relative physical path when it is nested. The
profile or API request selects the physical module directory. The optional API
Delivery resolves the selected source and release note from the captured commit;
it reads a module declaration only when Go is enabled. `Version` follows the
selected identifier format, and the full tag follows the selected publication
mode. The profile or API request selects the physical source directory. The optional API
`ExpectedTag` checks that a CI event's literal tag agrees with the derived tag
before any build or hosted request.
before any build or hosted request. Page-only source delivery does not require a
Go module or compiler.
## CI preparation

View File

@@ -40,6 +40,10 @@ declared module stored at `integrations/core` derives the same tag. ReleaseKit
removes a final physical `/v2` directory from the tag prefix only when the
module declaration has that `/v2` suffix. A module-local note stays at
`<module>/docs/releases/<version>.md`, including a physical `/v2` directory.
General source releases instead derive the tag from their selected source
directory or explicit product prefix and the selected identifier; the source
note remains under `<source>/docs/releases/`. See the
[configuration reference](../config.md) for selection and version formats.
The default shared validation convention uses repository-root `COPYRIGHT`,
`LICENSE`, and `docs/oss/attribution.md` when present. Consumers own their license
layout and release-note links. Use the complete derived tag as the immutable

View File

@@ -192,6 +192,13 @@ behavior. Reuse existing publication failure fixtures.
## Stage 4: Carry general identity through builds and hosted delivery
**Completed:** Builds and delivery use the selected production identity,
including source-only pages, calendar identifiers, and prebuilt selection
binding. Tagged preparation accepts complete valid tags, and CLI launcher
expectations compare the selected source directory. Focused build, delivery,
tag-preparation, and CI mapping tests pass, as do `go test ./...` and
`go run ./internal/apicheck`. Receipt format migration follows in Stage 5.
**Work:** adapt `internal/build`, `internal/artifact`, `internal/delivery`,
`internal/preparation`, and facade conversions.

View File

@@ -42,6 +42,7 @@ type Artifact struct {
}
type Result struct {
Identity releaseidentity.Identity
RepositoryDir string
ModuleDir string
ModulePath string
@@ -63,6 +64,7 @@ func buildResolved(ctx context.Context, request Request, remove func(string) err
identity := request.Identity
settings := artifact.NormalizeSettings(request.Spec.MainPackage, request.Spec.BinaryName, request.Spec.Targets)
result = Result{
Identity: identity,
RepositoryDir: identity.RepositoryDir,
ModuleDir: identity.ModuleDir,
ModulePath: identity.ModulePath,
@@ -70,10 +72,33 @@ func buildResolved(ctx context.Context, request Request, remove func(string) err
Settings: settings,
Version: identity.Version,
}
if !versioncontract.ValidStableVersion(identity.Version) {
format, prefix := identity.VersionFormat, identity.VersionPrefix
if format == "" {
format, prefix = "semver", "v"
}
if !versioncontract.ValidIdentifier(identity.Version, format, prefix) {
return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, identity.Version)
}
if identity.RepositoryDir == "" || identity.ModuleDir == "" || identity.ModulePath == "" {
if identity.RepositoryDir == "" {
return result, errors.New("build requires a resolved source identity")
}
if identity.Kind == "production" && !identity.GoEnabled {
if len(settings.Targets) != 0 {
return result, errors.New("build targets require Go capability")
}
commit, err := git.CaptureHead(ctx, identity.RepositoryDir)
if err != nil {
return result, fmt.Errorf("read source commit: %w", err)
}
if identity.Commit != "" && identity.Commit != commit {
return result, errors.New("source commit changed before build")
}
result.Identity.Commit = commit
result.CandidateCommit = commit
result.OutputDir = artifact.OutputDirectory(identity.SourceDir, request.OutputDir)
return result, nil
}
if identity.ModuleDir == "" || identity.ModulePath == "" {
return result, errors.New("build requires a resolved module identity")
}
if len(settings.Targets) != 0 {
@@ -106,6 +131,10 @@ func buildResolved(ctx context.Context, request Request, remove func(string) err
if err != nil {
return result, fmt.Errorf("read source commit: %w", err)
}
if identity.Commit != "" && identity.Commit != commit {
return result, errors.New("source commit changed before build")
}
result.Identity.Commit = commit
result.CandidateCommit = commit
statusBefore, err := git.WorktreeStatus(ctx, repositoryDir)
if err != nil {

View File

@@ -44,6 +44,7 @@ type Request struct {
}
type Result struct {
Identity releaseidentity.Identity
RepositoryDir string
ModuleDir string
ModulePath string
@@ -64,7 +65,7 @@ func Deliver(ctx context.Context, request Request) (Result, error) {
func deliver(ctx context.Context, request Request, remove func(string) error) (result Result, resultErr error) {
result = Result{State: NotAttempted}
if !versioncontract.ValidStableVersion(request.Version) {
if request.Source == nil && !versioncontract.ValidStableVersion(request.Version) {
return result, candidate.ErrInvalidVersion
}
if strings.TrimSpace(request.Product) == "" {
@@ -87,21 +88,25 @@ func deliver(ctx context.Context, request Request, remove func(string) error) (r
}
result.CandidateCommit = commit
identity, err := releaseidentity.FromCommittedSource(ctx, repositoryDir, request.ModuleDir, request.Version, commit, request.Source)
result.Identity = identity
result.ModuleDir = identity.ModuleDir
result.ModulePath = identity.ModulePath
result.Tag = identity.Tag
if err != nil {
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
return result, candidate.ErrInvalidVersion
}
return result, fmt.Errorf("resolve committed delivery identity: %w", err)
}
if identity.Publication == "source" {
return result, errors.New("general source delivery is not yet supported")
if !identity.GoEnabled && request.Build != nil && len(request.Build.Targets) != 0 {
return result, errors.New("build targets require Go capability")
}
result.RepositoryDir = identity.RepositoryDir
result.ModuleDir = identity.ModuleDir
result.ModulePath = identity.ModulePath
result.Tag = identity.Tag
if request.ExpectedTag != "" && request.ExpectedTag != identity.Tag {
return result, fmt.Errorf("expected delivery tag %q does not match selected module tag %q", request.ExpectedTag, identity.Tag)
return result, fmt.Errorf("expected delivery tag %q does not match selected source tag %q", request.ExpectedTag, identity.Tag)
}
source, err := git.InspectTaggedSource(ctx, repositoryDir, identity.Tag)
if err != nil {
@@ -246,13 +251,21 @@ func validateBuildIdentity(identity releaseidentity.Identity, commit string, bui
if err != nil {
return fmt.Errorf("resolve build repository: %w", err)
}
buildModule, err := filepath.Abs(build.ModuleDir)
if err != nil {
return fmt.Errorf("resolve build module: %w", err)
buildModule := ""
if build.ModuleDir != "" {
buildModule, err = filepath.Abs(build.ModuleDir)
if err != nil {
return fmt.Errorf("resolve build module: %w", err)
}
}
if buildRepository != identity.RepositoryDir || buildModule != identity.ModuleDir || build.ModulePath != identity.ModulePath || build.Tag != identity.Tag || build.CandidateCommit != commit || build.Version != identity.Version {
return errors.New("build result does not identify the selected tagged module")
}
if identity.Publication == "source" || build.Identity.Kind != "" {
if build.Identity.Kind != identity.Kind || build.Identity.SourceDir != identity.SourceDir || build.Identity.SourceSubdir != identity.SourceSubdir || build.Identity.GoEnabled != identity.GoEnabled || build.Identity.Publication != identity.Publication || build.Identity.VersionFormat != identity.VersionFormat || build.Identity.VersionPrefix != identity.VersionPrefix {
return errors.New("build result does not match the selected source identity")
}
}
if len(build.Settings.Targets) == 0 {
return nil
}

View File

@@ -8,10 +8,8 @@ import (
"fmt"
"strings"
"go.maximumdirect.net/releasekit/internal/candidate"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/versioncontract"
)
type TaggedCheckoutRequest struct {
@@ -23,10 +21,8 @@ type TaggedCheckoutRequest struct {
}
func PrepareTaggedCheckout(ctx context.Context, request TaggedCheckoutRequest) error {
lastSlash := strings.LastIndex(request.Tag, "/")
version := request.Tag[lastSlash+1:]
if !versioncontract.ValidStableVersion(version) {
return fmt.Errorf("%w: tag %q must end in a stable semantic version", candidate.ErrInvalidVersion, request.Tag)
if err := git.CheckTagRef(ctx, request.RepositoryDir, request.Tag); err != nil {
return fmt.Errorf("invalid tagged checkout ref: %w", err)
}
if strings.TrimSpace(request.ExpectedCommit) == "" {
return errors.New("expected commit is required")

View File

@@ -209,7 +209,7 @@ func TestPrepareTaggedCheckoutValidatesInputsBeforeFetching(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
publishPreparationTag(t, repository)
for _, request := range []releasekit.TaggedCheckoutRequest{
{RepositoryDir: repository, Tag: "not-a-version", ExpectedCommit: buildGit(t, repository, "rev-parse", "HEAD")},
{RepositoryDir: repository, Tag: "invalid..tag", ExpectedCommit: buildGit(t, repository, "rev-parse", "HEAD")},
{RepositoryDir: repository, Tag: "v1.2.3"},
{RepositoryDir: repository, Tag: "v1.2.3", ExpectedCommit: "not-an-object-id"},
} {
@@ -221,11 +221,6 @@ func TestPrepareTaggedCheckoutValidatesInputsBeforeFetching(t *testing.T) {
t.Fatal("input validation fetched the tag before rejecting the request")
}
}
if err := releasekit.PrepareTaggedCheckout(context.Background(), releasekit.TaggedCheckoutRequest{
RepositoryDir: repository, Tag: "invalid", ExpectedCommit: "bad",
}); !errors.Is(err, releasekit.ErrInvalidVersion) {
t.Fatalf("invalid-version error = %v, want ErrInvalidVersion", err)
}
}
func TestPrepareTaggedCheckoutVerifyOnlyIsReadOnly(t *testing.T) {

73
source_build_test.go Normal file
View File

@@ -0,0 +1,73 @@
package releasekit_test
import (
"os/exec"
"path/filepath"
"runtime"
"testing"
releasekit "go.maximumdirect.net/releasekit"
)
func TestBuildSourceVersions(t *testing.T) {
repo := newBuildConsumer(t, `package main
import (
"fmt"
"os"
"go.maximumdirect.net/releasekit/buildinfo"
)
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
`)
for _, test := range []struct {
version string
format releasekit.VersionFormat
}{{"2026-12-01.1", releasekit.VersionDate}, {"v2.0.0", releasekit.VersionSemver}} {
t.Run(test.version, func(t *testing.T) {
result, err := releasekit.Build(t.Context(), releasekit.BuildRequest{
RepositoryDir: repo, Version: test.version,
Source: &releasekit.SourceSpec{GoEnabled: true, VersionFormat: test.format},
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
OutputDir: t.TempDir(),
})
if err != nil {
t.Fatalf("source build = %+v, error = %v", result, err)
}
wantName := "fixture-" + test.version + "-" + runtime.GOOS + "-" + runtime.GOARCH
if runtime.GOOS == "windows" {
wantName += ".exe"
}
if len(result.Artifacts) != 1 || result.Artifacts[0].Filename != wantName {
t.Fatalf("source build artifacts = %+v", result.Artifacts)
}
output, err := exec.Command(filepath.Join(result.OutputDir, wantName), "version").CombinedOutput()
if err != nil || string(output) != "fixture "+test.version+"\n" {
t.Fatalf("version output = %q, error = %v", output, err)
}
})
}
}
func TestBuildSourceOnlyWithoutTargets(t *testing.T) {
base := t.TempDir()
repo := filepath.Join(base, "repo")
gitRun(t, base, "init", "-b", "main", repo)
gitRun(t, repo, "config", "user.name", "ReleaseKit Test")
gitRun(t, repo, "config", "user.email", "releasekit@example.invalid")
writeFile(t, repo, "settings.json", "{}")
gitRun(t, repo, "add", ".")
gitRun(t, repo, "commit", "-m", "source candidate")
result, err := releasekit.Build(t.Context(), releasekit.BuildRequest{
RepositoryDir: repo, Version: "2026.12.0",
Source: &releasekit.SourceSpec{VersionFormat: releasekit.VersionYearMonth},
})
if err != nil || result.SourceDir != repo || result.ModuleDir != "" || result.GoEnabled || result.CandidateCommit == "" || len(result.Artifacts) != 0 {
t.Fatalf("source-only build = %+v, error = %v", result, err)
}
_, err = releasekit.Build(t.Context(), releasekit.BuildRequest{
RepositoryDir: repo, Version: "2026.12.0", Source: &releasekit.SourceSpec{VersionFormat: releasekit.VersionYearMonth},
Spec: releasekit.BuildSpec{Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
})
if err == nil {
t.Fatal("source-only build accepted binary targets")
}
}

108
source_delivery_test.go Normal file
View File

@@ -0,0 +1,108 @@
package releasekit_test
import (
"os"
"path/filepath"
"runtime"
"testing"
releasekit "go.maximumdirect.net/releasekit"
)
func TestDeliverSourceOnlyCalendarPage(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX Go shim")
}
base := t.TempDir()
repo := filepath.Join(base, "repo")
gitRun(t, base, "init", "-b", "main", repo)
gitRun(t, repo, "config", "user.name", "ReleaseKit Test")
gitRun(t, repo, "config", "user.email", "releasekit@example.invalid")
note := "# Fixture 2026-12-01\n\nConfiguration release.\n"
writeFile(t, repo, "config/docs/releases/2026-12-01.md", note)
gitRun(t, repo, "add", ".")
gitRun(t, repo, "commit", "-m", "configuration release")
gitRun(t, repo, "tag", "config/2026-12-01")
commit := gitText(t, repo, "rev-parse", "HEAD")
if err := releasekit.PrepareTaggedCheckout(t.Context(), releasekit.TaggedCheckoutRequest{
RepositoryDir: repo, Tag: "config/2026-12-01", ExpectedCommit: commit, VerifyOnly: true,
}); err != nil {
t.Fatalf("verify calendar tag: %v", err)
}
server, remote := newFacadeDeliveryServer(t, repo)
defer server.Close()
remote.update(func(data *facadeDeliveryData) {
data.tag, data.version, data.noteBody = "config/2026-12-01", "2026-12-01", note
})
shim := t.TempDir()
if err := os.WriteFile(filepath.Join(shim, "go"), []byte("#!/bin/sh\nexit 99\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", shim+string(os.PathListSeparator)+os.Getenv("PATH"))
result, err := releasekit.Deliver(t.Context(), releasekit.DeliveryRequest{
RepositoryDir: repo, Product: "Fixture", Version: "2026-12-01",
Source: &releasekit.SourceSpec{Dir: "config", VersionFormat: releasekit.VersionDate},
ExpectedTag: "config/2026-12-01", Destination: facadeDeliveryDestination(server.URL),
Build: &releasekit.BuildSpec{},
})
if err != nil || result.State != releasekit.DeliveryComplete || result.Tag != "config/2026-12-01" || result.SourceDir != filepath.Join(repo, "config") || result.SourceSubdir != "config" || result.ModulePath != "" || result.GoEnabled || result.Publication != releasekit.PublicationSource {
t.Fatalf("delivery = %+v, error = %v", result, err)
}
if got := remote.snapshot(); got.createdBody != note || len(got.assets) != 0 {
t.Fatalf("hosted page = %+v", got)
}
}
func TestDeliverRejectsPrebuiltForDifferentPublicationSelection(t *testing.T) {
repo := newTaggedDeliveryConsumer(t)
built, err := releasekit.Build(t.Context(), releasekit.BuildRequest{
RepositoryDir: repo, Version: "v1.2.3", Source: &releasekit.SourceSpec{GoEnabled: true},
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
OutputDir: t.TempDir(),
})
if err != nil {
t.Fatal(err)
}
server, remote := newFacadeDeliveryServer(t, repo)
defer server.Close()
_, err = releasekit.Deliver(t.Context(), releasekit.DeliveryRequest{
RepositoryDir: repo, Product: "Fixture", Version: "v1.2.3",
Prebuilt: &built, Destination: facadeDeliveryDestination(server.URL),
})
if err == nil || remote.snapshot().requests != 0 {
t.Fatalf("delivery error = %v, hosted requests = %d", err, remote.snapshot().requests)
}
}
func TestDeliverCalendarPrebuiltAssets(t *testing.T) {
repo := newTaggedDeliveryConsumer(t)
version := "2026-12-01.1"
note := "# Fixture " + version + "\n\nCalendar release.\n"
writeFile(t, repo, "docs/releases/"+version+".md", note)
gitRun(t, repo, "add", "docs/releases/"+version+".md")
gitRun(t, repo, "commit", "-m", "add calendar release note")
gitRun(t, repo, "tag", version)
source := &releasekit.SourceSpec{GoEnabled: true, VersionFormat: releasekit.VersionDate}
built, err := releasekit.Build(t.Context(), releasekit.BuildRequest{
RepositoryDir: repo, Version: version, Source: source,
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
OutputDir: t.TempDir(),
})
if err != nil {
t.Fatal(err)
}
server, remote := newFacadeDeliveryServer(t, repo)
defer server.Close()
remote.update(func(data *facadeDeliveryData) { data.tag, data.version, data.noteBody = version, version, note })
result, err := releasekit.Deliver(t.Context(), releasekit.DeliveryRequest{
RepositoryDir: repo, Product: "Fixture", Version: version, Source: source,
Prebuilt: &built, Destination: facadeDeliveryDestination(server.URL),
})
if err != nil || result.State != releasekit.DeliveryComplete {
t.Fatalf("calendar delivery = %+v, error = %v", result, err)
}
assets := remote.snapshot().assets
if len(assets) != 2 || len(assets[built.Artifacts[0].Filename]) == 0 || len(assets["SHA256SUMS"]) == 0 {
t.Fatalf("uploaded calendar assets = %v", mapKeys(assets))
}
}