From a348da32dad7f278c00f8709f90e1e21ebaf0d6e Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Sat, 5 Dec 2026 23:14:15 +0000 Subject: [PATCH] Coordinate diagnostic attempts and CI observation --- .../releasekit_delivery_workflow_test.go | 2 +- docs/integrations/rehearsal-records.md | 9 +- docs/internal/overview.md | 2 +- docs/roadmap/implementation.md | 10 + internal/readiness/committed.go | 68 +++ internal/readiness/committed_test.go | 62 +++ internal/readiness/readiness.go | 68 ++- internal/rehearsal/coordinator.go | 424 ++++++++++++++++++ internal/rehearsal/coordinator_test.go | 237 ++++++++++ internal/rehearsal/manifest_test.go | 2 +- internal/rehearsal/record.go | 71 +-- internal/rehearsal/record_test.go | 7 +- internal/rehearsal/result.go | 5 +- rehearsal.go | 128 ++++++ rehearsal_test.go | 19 + 15 files changed, 1068 insertions(+), 46 deletions(-) create mode 100644 internal/readiness/committed.go create mode 100644 internal/readiness/committed_test.go create mode 100644 internal/rehearsal/coordinator.go create mode 100644 internal/rehearsal/coordinator_test.go create mode 100644 rehearsal.go create mode 100644 rehearsal_test.go diff --git a/cmd/releasekit/releasekit_delivery_workflow_test.go b/cmd/releasekit/releasekit_delivery_workflow_test.go index 1da898d..72a2135 100644 --- a/cmd/releasekit/releasekit_delivery_workflow_test.go +++ b/cmd/releasekit/releasekit_delivery_workflow_test.go @@ -36,7 +36,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) { cliGitRun(t, repository, "config", "user.email", "releasekit@example.test") // The workflow builds the tagged CLI, including changes under test that may // not yet be committed in the repository from which this fixture was cloned. - files := []string{"cmd/releasekit/main.go", "cmd/releasekit/readiness.go", "cmd/releasekit/diagnostic.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go", "readiness.go", "internal/readiness/readiness.go", "internal/woodpecker/client.go", "internal/git/remote.go", "internal/git/source.go", "internal/gitea/backend.go", "internal/gotool/gotool.go", "internal/build/build.go", "internal/delivery/delivery.go", "internal/delivery/diagnostic.go", "internal/rehearsal/manifest.go", "internal/rehearsal/result.go", "internal/releaseidentity/diagnostic.go"} + files := []string{"cmd/releasekit/main.go", "cmd/releasekit/readiness.go", "cmd/releasekit/diagnostic.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go", "readiness.go", "internal/readiness/readiness.go", "internal/readiness/committed.go", "internal/woodpecker/client.go", "internal/git/remote.go", "internal/git/source.go", "internal/gitea/backend.go", "internal/gotool/gotool.go", "internal/build/build.go", "internal/delivery/delivery.go", "internal/delivery/diagnostic.go", "internal/rehearsal/manifest.go", "internal/rehearsal/result.go", "internal/releaseidentity/diagnostic.go"} for _, name := range files { contents, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(name))) if err != nil { diff --git a/docs/integrations/rehearsal-records.md b/docs/integrations/rehearsal-records.md index c78c08d..bb3d20e 100644 --- a/docs/integrations/rehearsal-records.md +++ b/docs/integrations/rehearsal-records.md @@ -16,7 +16,8 @@ proof of ownership or permission to delete anything. A profile is read from the captured commit rather than the current working tree. Private attempt records use `format_version: 1` and retain the manifest, Git -endpoint and remote, forge and Woodpecker destinations, planned page evidence, +endpoint and remote, forge and Woodpecker destinations, planned page and asset +identities, tag object, observed resource IDs, timestamps, and outcomes. They do not store resolved forge or Woodpecker tokens. Endpoints and paths may themselves contain sensitive information, so treat records as private. By default they are stored @@ -42,3 +43,9 @@ result. The observer reads complete log lines, accepts identical retransmissions and rejects malformed, conflicting, or mismatched evidence without echoing the raw log. The page and declared assets are read back before managed build output is removed. + +The start coordinator records tag creation and push intent before dispatch. It +keeps matching pipeline numbers, workflow and step observations, the job result, +and partial outcomes in the selected attempt record. A timeout or cancellation +leaves those observations available for explicit recovery; it does not cancel +the independent CI job or establish that cleanup is safe. diff --git a/docs/internal/overview.md b/docs/internal/overview.md index 4ae0f6c..bd72ec0 100644 --- a/docs/internal/overview.md +++ b/docs/internal/overview.md @@ -53,7 +53,7 @@ reports these implemented packages: | `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. | | `internal/readiness` | Working-input inspection and read-only setup observations for explicitly selected capabilities. | | `internal/recordstore` | Shared private-record location and worktree safety checks. | -| `internal/rehearsal` | Diagnostic tag manifests and private attempt evidence for rehearsal recovery. | +| `internal/rehearsal` | Diagnostic tag manifests, private attempt evidence, dispatch, and exact CI job observation for rehearsal recovery. | | `internal/releaseidentity` | Committed-object and working-tree module selection, declaration reading, and semantic-version-to-tag derivation. | | `internal/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. | | `internal/publish` | Publication guards, one validation run, annotated tag creation, push, pre-push evidence recording, saved-attempt discovery, later observation, and recovery state. | diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index aa3f1ac..9fa647f 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -602,6 +602,16 @@ chunked logs, absent/foreign/conflicting results; and temporary output lifetime. ## Stage 12: Coordinate rehearsal start and CI observation +**Completed:** The root facade starts recorded diagnostic attempts with +explicit credentials, checks readiness against the captured commit, and pushes +only the recorded tag after saving planned resources and intent. Observation +tracks exact matching pipelines, workflows, steps, reruns, and framed evidence; +timeouts and cancellation retain partial records for recovery. Local Git and +HTTP fixtures cover delayed dispatch, missing evidence, failed jobs, active +reruns, unsafe record locations, and dirty working inputs. The offline +`go test ./...` suite, focused race tests, and API/dependency checks pass. +Cleanup and recovery are completed by the following stage. + **Work:** implement `internal/rehearsal` coordination and the root facade. 1. Expose `Rehearse(ctx, RehearsalRequest) (RehearsalResult, error)`. The request diff --git a/internal/readiness/committed.go b/internal/readiness/committed.go new file mode 100644 index 0000000..499c646 --- /dev/null +++ b/internal/readiness/committed.go @@ -0,0 +1,68 @@ +package readiness + +import ( + "context" + "errors" + "fmt" + "path" + "strings" + + "go.maximumdirect.net/releasekit/internal/artifact" + "go.maximumdirect.net/releasekit/internal/git" + "go.maximumdirect.net/releasekit/internal/releaseidentity" +) + +func committedFile(ctx context.Context, repo, commit, name string) ([]byte, error) { + resolver := git.CommittedPaths(repo, commit) + destination, err := resolver.ResolveDestination(ctx, "root", name) + if err != nil { + return nil, err + } + if destination.Kind != git.DestinationEntry { + return nil, fmt.Errorf("committed input %q is %s", git.DisplayDiagnostic(name), destination.Kind) + } + entry, found, err := resolver.Lookup(ctx, destination.Path) + if err != nil { + return nil, err + } + if !found || (entry.Mode != "100644" && entry.Mode != "100755") { + return nil, errors.New("committed input is not a regular file") + } + return git.ReadBlob(ctx, repo, entry.ObjectID) +} + +func inspectCommittedBuild(ctx context.Context, source releaseidentity.ResolvedSource, commit string, build artifact.Settings) error { + if err := validateBuildSettings(build); err != nil { + return err + } + name := build.MainPackage + if name == source.ModulePath { + name = "." + } else if strings.HasPrefix(name, source.ModulePath+"/") { + name = "./" + strings.TrimPrefix(name, source.ModulePath+"/") + } + if name != "." && !strings.HasPrefix(name, "./") { + return nil + } + resolver := git.CommittedPaths(source.RepositoryDir, commit) + destination, err := resolver.ResolveDestination(ctx, path.Join(source.ModuleSubdir, "placeholder"), name) + if err != nil { + return err + } + if destination.Kind != git.DestinationDirectory { + return fmt.Errorf("committed main package is %s", destination.Kind) + } + entries, err := git.ReadTree(ctx, source.RepositoryDir, commit) + if err != nil { + return err + } + for _, entry := range entries { + if path.Dir(entry.Path) != destination.Path || !strings.HasSuffix(entry.Path, ".go") || strings.HasSuffix(entry.Path, "_test.go") { + continue + } + if _, err := committedFile(ctx, source.RepositoryDir, commit, entry.Path); err == nil { + return nil + } + } + return errors.New("committed main package contains no non-test Go source") +} diff --git a/internal/readiness/committed_test.go b/internal/readiness/committed_test.go new file mode 100644 index 0000000..bd8433e --- /dev/null +++ b/internal/readiness/committed_test.go @@ -0,0 +1,62 @@ +package readiness + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "go.maximumdirect.net/releasekit/internal/artifact" + "go.maximumdirect.net/releasekit/internal/releaseidentity" +) + +func TestCommittedReadinessUsesCapturedModuleAndMainPackage(t *testing.T) { + repo := t.TempDir() + run := func(args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = repo + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v: %s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + run("init", "--initial-branch=main") + run("config", "user.name", "ReleaseKit Test") + run("config", "user.email", "releasekit@example.test") + if err := os.WriteFile(filepath.Join(repo, "go.mod"), []byte("module example.com/fixture\n\ngo 1.25.0\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(repo, "main.go"), []byte("package main\nfunc main() {}\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(repo, "required.txt"), []byte("captured"), 0600); err != nil { + t.Fatal(err) + } + run("add", "--all") + run("commit", "-m", "capture inputs") + commit := run("rev-parse", "HEAD") + os.Remove(filepath.Join(repo, "main.go")) + os.Remove(filepath.Join(repo, "required.txt")) + os.WriteFile(filepath.Join(repo, "go.mod"), []byte("invalid working module"), 0600) + request := Request{RepositoryDir: repo, Commit: commit, Product: "Example", Context: "local", Source: &releaseidentity.SourceSpec{GoEnabled: true}, Operations: []string{"build"}, Build: &artifact.Settings{MainPackage: ".", BinaryName: "fixture", Targets: []artifact.Target{{OS: "linux", Arch: "amd64"}}}, RequiredFiles: []string{"required.txt", filepath.Join(repo, "required.txt")}} + report := Run(t.Context(), request) + for _, check := range report.Checks { + if check.Status == "failed" { + t.Fatalf("captured readiness failed: %+v", check) + } + } + request.Commit = "" + report = Run(t.Context(), request) + failed := false + for _, check := range report.Checks { + if check.Status == "failed" { + failed = true + } + } + if !failed { + t.Fatal("working readiness unexpectedly accepted missing and invalid inputs") + } +} diff --git a/internal/readiness/readiness.go b/internal/readiness/readiness.go index 36fd865..afe66b8 100644 --- a/internal/readiness/readiness.go +++ b/internal/readiness/readiness.go @@ -20,6 +20,7 @@ import ( type Request struct { RepositoryDir, ModuleDir, Product, Remote, ExpectedPushURL, Context string + Commit string Source *releaseidentity.SourceSpec Operations []string Offline bool @@ -89,7 +90,11 @@ func Run(ctx context.Context, request Request) Report { var source releaseidentity.ResolvedSource var sourceErr error if repoErr == nil { - source, sourceErr = releaseidentity.LoadWorkingSource(ctx, repository, request.ModuleDir, request.Source) + if request.Commit == "" { + source, sourceErr = releaseidentity.LoadWorkingSource(ctx, repository, request.ModuleDir, request.Source) + } else { + source, sourceErr = releaseidentity.LoadCommittedSource(ctx, repository, request.ModuleDir, request.Commit, request.Source) + } if sourceErr == nil { sourceErr = inspectSourceConfiguration(ctx, request, source) } @@ -114,6 +119,13 @@ func Run(ctx context.Context, request Request) Report { } for _, name := range request.RequiredFiles { path := name + committedName := name + committedInput := request.Commit != "" && !filepath.IsAbs(name) + if request.Commit != "" && filepath.IsAbs(name) && repoErr == nil { + if relative, relErr := filepath.Rel(repository, filepath.Clean(name)); relErr == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) { + committedName, committedInput = relative, true + } + } if !filepath.IsAbs(path) { path = filepath.Join(repository, path) } @@ -124,6 +136,8 @@ func Run(ctx context.Context, request Request) Report { err = errors.New("relative required file path escapes the repository") } else if repoErr != nil && !filepath.IsAbs(name) { err = errors.New("repository unavailable for relative required file") + } else if committedInput { + _, err = committedFile(ctx, repository, request.Commit, filepath.ToSlash(committedName)) } else { var info os.FileInfo info, err = os.Stat(path) @@ -180,7 +194,17 @@ func Run(ctx context.Context, request Request) Report { buildNeeded := selected["build"] || selected["rehearsal"] && request.Build != nil && len(request.Build.Targets) > 0 goNeeded := selected["go"] || buildNeeded || selected["rehearsal"] && source.GoEnabled if goNeeded && repoErr == nil && sourceErr == nil && source.GoEnabled { - report.record("go-toolchain", "go", "required_input", inspectGo(ctx, source.ModuleDir)) + var goErr error + if request.Commit == "" { + goErr = inspectGo(ctx, source.ModuleDir) + } else { + var declaration []byte + declaration, goErr = committedFile(ctx, repository, request.Commit, filepath.ToSlash(filepath.Join(source.ModuleSubdir, "go.mod"))) + if goErr == nil { + goErr = inspectGoDeclaration(ctx, repository, declaration) + } + } + report.record("go-toolchain", "go", "required_input", goErr) report.note("go-dependencies", "go", "unchecked", "not_executed", "dependency cache and build execution were not checked") } else if goNeeded { report.note("go-toolchain", "go", "skipped", "dependency", "selected Go source unavailable") @@ -189,7 +213,13 @@ func Run(ctx context.Context, request Request) Report { if repoErr != nil || sourceErr != nil || !source.GoEnabled { report.note("build-inputs", "build", "skipped", "dependency", "selected Go source unavailable") } else { - if report.record("build-inputs", "build", "configuration", inspectBuild(source, *request.Build)) && !localMainPackage(source, request.Build.MainPackage) { + var buildErr error + if request.Commit == "" { + buildErr = inspectBuild(source, *request.Build) + } else { + buildErr = inspectCommittedBuild(ctx, source, request.Commit, *request.Build) + } + if report.record("build-inputs", "build", "configuration", buildErr) && !localMainPackage(source, request.Build.MainPackage) { report.note("main-package", "build", "unchecked", "not_executed", "external package inputs require build execution") } } @@ -269,7 +299,12 @@ func inspectSourceConfiguration(ctx context.Context, request Request, source rel version = source.VersionPrefix + "2000.01.0" } } - _, err := releaseidentity.FromWorkingSource(ctx, source.RepositoryDir, request.ModuleDir, version, request.Source) + var err error + if request.Commit == "" { + _, err = releaseidentity.FromWorkingSource(ctx, source.RepositoryDir, request.ModuleDir, version, request.Source) + } else { + _, err = releaseidentity.FromCommittedSource(ctx, source.RepositoryDir, request.ModuleDir, version, request.Commit, request.Source) + } return err } @@ -278,6 +313,10 @@ func inspectGo(ctx context.Context, dir string) error { if err != nil { return err } + return inspectGoDeclaration(ctx, dir, data) +} + +func inspectGoDeclaration(ctx context.Context, dir string, data []byte) error { declaration, err := modfile.Parse("go.mod", data, nil) if err != nil { return err @@ -297,13 +336,8 @@ func inspectGo(ctx context.Context, dir string) error { } func inspectBuild(source releaseidentity.ResolvedSource, build artifact.Settings) error { - if strings.TrimSpace(build.MainPackage) == "" || !artifact.ValidComponent(build.BinaryName) { - return errors.New("build requires a main package and valid binary name") - } - for _, target := range build.Targets { - if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) { - return fmt.Errorf("invalid build target %q/%q", target.OS, target.Arch) - } + if err := validateBuildSettings(build); err != nil { + return err } name := build.MainPackage if name == source.ModulePath { @@ -357,6 +391,18 @@ func inspectBuild(source releaseidentity.ResolvedSource, build artifact.Settings return nil } +func validateBuildSettings(build artifact.Settings) error { + if strings.TrimSpace(build.MainPackage) == "" || !artifact.ValidComponent(build.BinaryName) { + return errors.New("build requires a main package and valid binary name") + } + for _, target := range build.Targets { + if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) { + return fmt.Errorf("invalid build target %q/%q", target.OS, target.Arch) + } + } + return nil +} + func localMainPackage(source releaseidentity.ResolvedSource, name string) bool { return name == "." || strings.HasPrefix(name, "./") || name == source.ModulePath || strings.HasPrefix(name, source.ModulePath+"/") } diff --git a/internal/rehearsal/coordinator.go b/internal/rehearsal/coordinator.go new file mode 100644 index 0000000..65ba397 --- /dev/null +++ b/internal/rehearsal/coordinator.go @@ -0,0 +1,424 @@ +package rehearsal + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "path/filepath" + "strings" + "time" + + "go.maximumdirect.net/releasekit/internal/artifact" + "go.maximumdirect.net/releasekit/internal/forge" + "go.maximumdirect.net/releasekit/internal/git" + "go.maximumdirect.net/releasekit/internal/readiness" + "go.maximumdirect.net/releasekit/internal/releaseidentity" + "go.maximumdirect.net/releasekit/internal/woodpecker" +) + +type JobObservation struct { + PipelineID int64 `json:"pipeline_id"` + PipelineNumber int64 `json:"pipeline_number"` + WorkflowID int64 `json:"workflow_id"` + StepID int64 `json:"step_id"` + PipelineStatus string `json:"pipeline_status"` + WorkflowState string `json:"workflow_state"` + StepState string `json:"step_state"` +} + +type WorkflowObservation struct { + PipelineID int64 `json:"pipeline_id"` + PipelineNumber int64 `json:"pipeline_number"` + ID int64 `json:"id"` + Name string `json:"name"` + State string `json:"state"` +} + +type StartRequest struct { + RepositoryDir, Ref, ProfilePath, ModuleDir, Product, Selector string + Source *releaseidentity.SourceSpec + Remote, ExpectedPushURL, RecordDir string + Build *artifact.Settings + RequiredFiles []string + ForgeBaseURL, ForgeOwner, ForgeRepository string + Backend forge.Backend + Woodpecker woodpecker.Client + Workflow, Step string + CIConfigured bool + ObservationTimeout time.Duration + Output io.Writer +} +type Outcome struct { + Attempt Attempt + RecordPath string + Workflow, Build, Verification, Cleanup string + Diagnostics []string +} + +// Start captures and records an attempt before pushing its diagnostic tag. +func Start(ctx context.Context, request StartRequest) (Outcome, error) { + result := Outcome{Workflow: "not_started", Build: "not_started", Verification: "not_started", Cleanup: "pending"} + if request.ObservationTimeout < 0 { + return result, errors.New("observation timeout cannot be negative") + } + if !request.CIConfigured { + return result, errors.New("committed profile must declare CI delivery credentials") + } + if request.Backend == nil { + return result, errors.New("delivery backend is required") + } + if request.Workflow == "" || request.Step == "" { + return result, errors.New("Woodpecker workflow and step are required") + } + repo, err := git.RepositoryRoot(ctx, request.RepositoryDir) + if err != nil { + return result, err + } + commit, err := git.ResolveCommit(ctx, repo, request.Ref) + if err != nil { + return result, err + } + profilePath := request.ProfilePath + if profilePath == "" { + profilePath = "releasekit.json" + } + if filepath.IsAbs(profilePath) { + profilePath, err = filepath.Rel(repo, filepath.Clean(profilePath)) + if err != nil { + return result, err + } + } + profilePath = filepath.ToSlash(filepath.Clean(profilePath)) + profile, err := git.ReadCommitFile(ctx, repo, commit, profilePath) + if err != nil { + return result, fmt.Errorf("rehearsal profile must be committed within the checkout: %w", err) + } + var declarations struct { + Delivery *struct { + Credentials *struct { + CI *struct{} `json:"ci"` + } `json:"credentials"` + } `json:"delivery"` + } + if err := json.Unmarshal(profile, &declarations); err != nil || declarations.Delivery == nil || declarations.Delivery.Credentials == nil || declarations.Delivery.Credentials.CI == nil { + return result, errors.New("committed profile must declare CI delivery credentials") + } + source, err := releaseidentity.LoadCommittedSource(ctx, repo, request.ModuleDir, commit, request.Source) + if err != nil { + return result, err + } + selector := request.Selector + if selector == "" { + selector = "root" + } + identity, attemptID, err := releaseidentity.NewDiagnostic(ctx, source, selector, commit) + if err != nil { + return result, err + } + manifest := NewManifest(identity, attemptID, selector, profilePath, profile) + remote := request.Remote + if remote == "" { + remote = "origin" + } + wood := request.Woodpecker + input := readiness.Request{RepositoryDir: repo, ModuleDir: request.ModuleDir, Product: request.Product, Remote: remote, ExpectedPushURL: request.ExpectedPushURL, Context: "local", Commit: commit, Source: request.Source, Operations: []string{"rehearsal"}, Build: request.Build, HasDelivery: true, HasRehearsal: true, RequiredFiles: request.RequiredFiles, + DeliveryConfig: func() error { + if v, ok := request.Backend.(interface{ ValidateConfiguration() error }); ok { + return v.ValidateConfiguration() + } + return errors.New("delivery settings cannot be validated") + }, + Credential: func() error { return nil }, Delivery: request.Backend.Preflight, RehearsalConfig: wood.ValidateConfiguration, Rehearsal: wood.CheckRepository} + checked := readiness.Run(ctx, input) + var failures []error + for _, check := range checked.Checks { + if check.Status == "failed" { + if check.Cause != nil { + failures = append(failures, fmt.Errorf("%s: %w", check.ID, check.Cause)) + } else { + failures = append(failures, errors.New(check.Message)) + } + } + if check.Status == "unchecked" && check.Reason == "unavailable" { + failures = append(failures, errors.New(check.Message)) + } + } + if len(failures) > 0 { + return result, fmt.Errorf("rehearsal readiness: %w", errors.Join(failures...)) + } + endpoint, err := git.Resolve(ctx, repo, remote) + if err != nil { + return result, err + } + if request.ExpectedPushURL != "" && endpoint.PushURL != request.ExpectedPushURL { + return result, errors.New("publication endpoint does not match expected endpoint") + } + remoteTag, err := endpoint.QueryTag(ctx, repo, identity.Tag) + if err != nil { + return result, err + } + if remoteTag.State != git.RefAbsent { + return result, fmt.Errorf("diagnostic tag already exists: %w", git.ErrRemoteTagConflict) + } + note := DiagnosticNote(request.Product, manifest) + digest := sha256.Sum256([]byte(note)) + attempt := Attempt{Manifest: manifest, RepositoryDir: repo, Endpoint: endpoint.PushURL, Remote: remote, ForgeBaseURL: request.ForgeBaseURL, ForgeOwner: request.ForgeOwner, ForgeRepository: request.ForgeRepository, WoodpeckerBaseURL: wood.BaseURL, WoodpeckerRepositoryID: wood.RepositoryID, Workflow: request.Workflow, Step: request.Step, ExpectedPageTitle: strings.TrimPrefix(strings.SplitN(note, "\n", 2)[0], "# "), ExpectedBodySHA256: hex.EncodeToString(digest[:]), Outcomes: map[string]string{"tag": "planned", "push": "not_attempted", "workflow": "not_started", "verification": "not_started", "cleanup": "pending"}} + if request.Build != nil && len(request.Build.Targets) > 0 { + settings := artifact.NormalizeSettings(request.Build.MainPackage, request.Build.BinaryName, request.Build.Targets) + for _, item := range artifact.ExpectedBuild(settings.BinaryName, identity.Version, settings.Targets) { + attempt.PlannedAssets = append(attempt.PlannedAssets, item.Filename) + } + attempt.PlannedAssets = append(attempt.PlannedAssets, artifact.ManifestFilename) + } + store, err := CreateAttempt(ctx, repo, request.RecordDir, attempt) + if err != nil { + return result, err + } + result.RecordPath = store.Path + result.Attempt = attempt + save := func() error { result.Attempt = attempt; return store.Save(attempt) } + attempt.Outcomes["tag"] = "creating" + if err := save(); err != nil { + return result, fmt.Errorf("record tag intent: %w", err) + } + object, tagErr := CreateDiagnosticTag(ctx, repo, manifest) + if object != "" { + attempt.TagObject = object + } + if tagErr != nil { + attempt.Outcomes["tag"] = "unknown" + saveErr := save() + return result, errors.Join(tagErr, saveErr) + } + attempt.Outcomes["tag"] = "created" + if err := save(); err != nil { + return result, fmt.Errorf("record diagnostic tag: %w", err) + } + attempt.Outcomes["push"] = "attempting" + if err := save(); err != nil { + return result, fmt.Errorf("record push intent: %w", err) + } + pushErr := endpoint.PushDiagnosticTag(ctx, repo, identity.Tag, object, commit) + if pushErr != nil { + attempt.Outcomes["push"] = "unknown" + observed, observeErr := endpoint.QueryTag(ctx, repo, identity.Tag) + if observeErr == nil && observed.State == git.RefPresent && git.EqualObjectID(observed.Object, object) && git.EqualObjectID(observed.Peeled, commit) { + attempt.Outcomes["push"] = "dispatched" + } else { + saveErr := save() + return result, errors.Join(pushErr, observeErr, saveErr) + } + } else { + attempt.Outcomes["push"] = "dispatched" + } + if err := save(); err != nil { + return result, fmt.Errorf("record diagnostic push: %w", err) + } + if request.Output != nil { + if _, err := fmt.Fprintf(request.Output, "diagnostic attempt %s recorded at %s\n", attemptID, git.DisplayDiagnostic(store.Path)); err != nil { + return result, fmt.Errorf("write rehearsal progress: %w", err) + } + } + observationCtx := ctx + cancel := func() {} + if request.ObservationTimeout > 0 { + observationCtx, cancel = context.WithTimeout(ctx, request.ObservationTimeout) + } + defer cancel() + result, err = observe(observationCtx, wood, request.Workflow, request.Step, store, attempt, result) + return result, err +} + +func observe(ctx context.Context, client woodpecker.Client, workflow, step string, store *Store, attempt Attempt, result Outcome) (outcome Outcome, resultErr error) { + defer func() { outcome.Attempt = attempt }() + save := func() error { result.Attempt = attempt; return store.Save(attempt) } + for { + if err := ctx.Err(); err != nil { + attempt.Outcomes["workflow"] = "unknown" + result.Workflow = "unknown" + return result, errors.Join(err, save()) + } + pipelines, err := client.MatchingPipelines(ctx, attempt.Manifest.Tag, attempt.Manifest.Commit) + if err != nil { + attempt.Outcomes["workflow"] = "unknown" + result.Workflow = "unknown" + return result, errors.Join(err, save()) + } + terminalOnly := len(pipelines) > 0 + var success *JobResult + var failed bool + var workflowComplete bool + jobs := make([]JobObservation, 0) + workflows := make([]WorkflowObservation, 0) + for _, listed := range pipelines { + if !containsID(attempt.PipelineIDs, listed.ID) { + attempt.PipelineIDs = append(attempt.PipelineIDs, listed.ID) + attempt.PipelineNumbers = append(attempt.PipelineNumbers, listed.Number) + } + detail, err := client.DiagnosticPipeline(ctx, listed.Number, attempt.Manifest.Tag, attempt.Manifest.Commit) + if err != nil { + attempt.Outcomes["workflow"] = "unknown" + result.Workflow = "unknown" + return result, errors.Join(err, save()) + } + if detail.ID != listed.ID { + return result, errors.Join(errors.New("pipeline identity changed during observation"), save()) + } + for _, observed := range detail.Workflows { + workflows = append(workflows, WorkflowObservation{PipelineID: detail.ID, PipelineNumber: detail.Number, ID: observed.ID, Name: observed.Name, State: observed.State}) + } + if woodpecker.StateClass(detail.Status) != "terminal" { + terminalOnly = false + } + selected, selectionErr := detail.Jobs(workflow, step) + if selectionErr != nil { + if woodpecker.StateClass(detail.Status) == "terminal" { + failed = true + } + continue + } + for _, job := range selected { + jobs = append(jobs, JobObservation{PipelineID: job.PipelineID, PipelineNumber: job.PipelineNumber, WorkflowID: job.WorkflowID, StepID: job.StepID, PipelineStatus: job.PipelineStatus, WorkflowState: job.WorkflowState, StepState: job.StepState}) + if job.WorkflowState != "success" || job.StepState != "success" { + if woodpecker.StateClass(job.WorkflowState) == "terminal" || woodpecker.StateClass(job.StepState) == "terminal" && job.StepState != "success" { + failed = true + if woodpecker.StateClass(job.StepState) == "terminal" { + if stream, err := client.OpenLog(ctx, job.PipelineNumber, job.StepID); err == nil { + evidence, readErr := ReadResult(stream, attempt.Manifest) + closeErr := stream.Close() + if readErr != nil && !errors.Is(readErr, ErrResultAbsent) || closeErr != nil { + attempt.Jobs, attempt.Workflows = jobs, workflows + attempt.Outcomes["workflow"], attempt.Outcomes["verification"] = "failed", "incomplete" + result.Workflow, result.Verification = "failed", "incomplete" + return result, errors.Join(readErr, closeErr, save()) + } + if readErr == nil && closeErr == nil { + attempt.JobEvidence = &evidence + attempt.PageID = evidence.PageID + } + } + } + } else { + terminalOnly = false + } + continue + } + workflowComplete = true + stream, err := client.OpenLog(ctx, job.PipelineNumber, job.StepID) + if err != nil { + attempt.Jobs = jobs + attempt.Workflows = workflows + attempt.Outcomes["workflow"] = "complete" + attempt.Outcomes["verification"] = "incomplete" + result.Workflow, result.Verification = "complete", "incomplete" + return result, errors.Join(err, save()) + } + evidence, readErr := ReadResult(stream, attempt.Manifest) + closeErr := stream.Close() + if err := errors.Join(readErr, closeErr); err != nil { + attempt.Jobs = jobs + attempt.Workflows = workflows + attempt.Outcomes["workflow"] = "complete" + attempt.Outcomes["verification"] = "incomplete" + result.Workflow, result.Verification = "complete", "incomplete" + return result, errors.Join(err, save()) + } + if evidence.Verification != "complete" || evidence.Delivery != "complete" { + failed = true + attempt.JobEvidence = &evidence + attempt.PageID = evidence.PageID + continue + } + if !matchesPlannedAssets(attempt.PlannedAssets, evidence.Artifacts) { + attempt.Jobs, attempt.Workflows = jobs, workflows + attempt.Outcomes["workflow"], attempt.Outcomes["verification"] = "complete", "incomplete" + result.Workflow, result.Verification = "complete", "incomplete" + return result, errors.Join(errors.New("verified assets do not match the recorded plan"), save()) + } + if success != nil { + left, _ := EncodeResult(*success) + right, _ := EncodeResult(evidence) + if !bytes.Equal(left, right) { + return result, errors.Join(errors.New("matching jobs returned conflicting evidence"), save()) + } + } + copy := evidence + success = © + } + } + attempt.Jobs = jobs + attempt.Workflows = workflows + if success != nil { + attempt.JobEvidence = success + attempt.PageID = success.PageID + attempt.Outcomes["workflow"] = "complete" + attempt.Outcomes["build"] = success.Build + attempt.Outcomes["verification"] = "complete" + result.Workflow = "complete" + result.Build = success.Build + result.Verification = "complete" + return result, save() + } + if terminalOnly && failed { + attempt.Outcomes["workflow"] = "failed" + attempt.Outcomes["verification"] = "incomplete" + result.Workflow = "failed" + result.Verification = "incomplete" + if workflowComplete { + attempt.Outcomes["workflow"] = "complete" + result.Workflow = "complete" + } + if attempt.JobEvidence != nil { + result.Build = attempt.JobEvidence.Build + attempt.Outcomes["build"] = result.Build + } + return result, errors.Join(errors.New("matching CI delivery did not complete successfully"), save()) + } + attempt.Outcomes["workflow"] = "waiting" + result.Workflow = "waiting" + if err := save(); err != nil { + return result, err + } + timer := time.NewTimer(time.Second) + select { + case <-ctx.Done(): + if !timer.Stop() { + <-timer.C + } + attempt.Outcomes["workflow"] = "unknown" + result.Workflow = "unknown" + return result, errors.Join(ctx.Err(), save()) + case <-timer.C: + } + } +} +func containsID(values []int64, value int64) bool { + for _, item := range values { + if item == value { + return true + } + } + return false +} + +func matchesPlannedAssets(planned []string, observed []ArtifactEvidence) bool { + if len(planned) != len(observed) { + return false + } + want := make(map[string]bool, len(planned)) + for _, name := range planned { + want[name] = true + } + for _, item := range observed { + if !want[item.Name] { + return false + } + delete(want, item.Name) + } + return len(want) == 0 +} diff --git a/internal/rehearsal/coordinator_test.go b/internal/rehearsal/coordinator_test.go new file mode 100644 index 0000000..94105d6 --- /dev/null +++ b/internal/rehearsal/coordinator_test.go @@ -0,0 +1,237 @@ +package rehearsal + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "go.maximumdirect.net/releasekit/internal/forge" + "go.maximumdirect.net/releasekit/internal/releaseidentity" + "go.maximumdirect.net/releasekit/internal/woodpecker" +) + +type readyBackend struct{} + +func (readyBackend) ValidateConfiguration() error { return nil } +func (readyBackend) Preflight(context.Context) error { return nil } +func (readyBackend) TagCommit(context.Context, string) (string, error) { return "", nil } +func (readyBackend) FindRelease(context.Context, string) (forge.Release, error) { + return forge.Release{}, nil +} +func (readyBackend) CreateRelease(context.Context, forge.CreateReleaseRequest) (forge.Release, forge.WriteEvidence, error) { + return forge.Release{}, forge.WriteEvidence{}, nil +} +func (readyBackend) ListAssets(context.Context, any) ([]forge.Asset, error) { return nil, nil } +func (readyBackend) OpenAsset(context.Context, any) (io.ReadCloser, error) { return nil, nil } +func (readyBackend) UploadAsset(context.Context, any, string, io.Reader) (forge.WriteEvidence, error) { + return forge.WriteEvidence{}, nil +} + +func coordinatorFixture(t *testing.T) (string, string, string) { + t.Helper() + repo, _, _, identity, _ := rehearsalFixture(t) + bare := filepath.Join(t.TempDir(), "remote.git") + run := func(dir string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v: %s", args, err, output) + } + } + run(repo, "init", "--bare", bare) + run(repo, "remote", "add", "origin", bare) + run(repo, "push", "origin", "HEAD:refs/heads/main") + return repo, bare, identity.Commit +} +func recordManifest(t *testing.T, repo string) Manifest { + t.Helper() + names, err := os.ReadDir(filepath.Join(repo, ".git", "releasekit", "rehearsals")) + if err != nil || len(names) != 1 { + t.Errorf("record files=%v error=%v", names, err) + return Manifest{} + } + attempt, err := LoadAttempt(filepath.Join(repo, ".git", "releasekit", "rehearsals", names[0].Name())) + if err != nil { + t.Error(err) + } + return attempt.Manifest +} +func TestStartRecordsBeforeDispatchAndObservesExactJob(t *testing.T) { + repo, bare, commit := coordinatorFixture(t) + if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte("dirty profile"), 0600); err != nil { + t.Fatal(err) + } + var lists atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer wood-token" { + t.Error("unexpected Woodpecker credential") + } + switch r.URL.Path { + case "/api/repos/42": + fmt.Fprint(w, `{"id":42}`) + case "/api/repos/42/pipelines": + if r.URL.Query().Get("page") != "1" { + fmt.Fprint(w, `[]`) + return + } + if lists.Add(1) == 1 { + fmt.Fprint(w, `[]`) + return + } + m := recordManifest(t, repo) + json.NewEncoder(w).Encode([]woodpecker.Pipeline{{ID: 2, Number: 7, Event: "tag", Ref: "refs/tags/" + m.Tag, Commit: m.Commit, Status: "success"}, {ID: 3, Number: 8, Event: "tag", Ref: "refs/tags/unrelated", Commit: m.Commit, Status: "success"}, {ID: 4, Number: 9, Event: "tag", Ref: "refs/tags/" + m.Tag, Commit: m.Commit, Status: "running"}}) + case "/api/repos/42/pipelines/7": + m := recordManifest(t, repo) + json.NewEncoder(w).Encode(woodpecker.Pipeline{ID: 2, Number: 7, Event: "tag", Ref: "refs/tags/" + m.Tag, Commit: m.Commit, Status: "success", Workflows: []woodpecker.Workflow{{ID: 11, Name: "release", State: "success", Steps: []woodpecker.Step{{ID: 19, Name: "deliver", State: "success"}}}}}) + case "/api/repos/42/pipelines/9": + m := recordManifest(t, repo) + json.NewEncoder(w).Encode(woodpecker.Pipeline{ID: 4, Number: 9, Event: "tag", Ref: "refs/tags/" + m.Tag, Commit: m.Commit, Status: "running", Workflows: []woodpecker.Workflow{{ID: 12, Name: "release", State: "running", Steps: []woodpecker.Step{{ID: 20, Name: "deliver", State: "running"}}}}}) + case "/api/repos/42/logs/7/19/download": + m := recordManifest(t, repo) + frame, err := EncodeResult(JobResult{Manifest: m, Scope: "page", Build: "not_requested", Delivery: "complete", Verification: "complete", PageID: 13, Artifacts: []ArtifactEvidence{}}) + if err != nil { + t.Error(err) + } + w.Write(frame) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + req := StartRequest{RepositoryDir: repo, Ref: commit, Product: "Example", Source: &releaseidentity.SourceSpec{}, Backend: readyBackend{}, Woodpecker: woodpecker.Client{BaseURL: server.URL, RepositoryID: 42, Token: "wood-token"}, Workflow: "release", Step: "deliver", CIConfigured: true, ObservationTimeout: 5 * time.Second} + result, err := Start(t.Context(), req) + if err != nil { + t.Fatal(err) + } + if result.Workflow != "complete" || result.Verification != "complete" || result.Attempt.PageID != 13 || len(result.Attempt.PipelineIDs) != 2 || result.Attempt.PipelineNumbers[0] != 7 || result.Attempt.PipelineNumbers[1] != 9 || len(result.Attempt.Jobs) != 2 || result.RecordPath == "" || lists.Load() < 2 { + t.Fatalf("result=%+v", result) + } + saved, err := LoadAttempt(result.RecordPath) + if err != nil || saved.JobEvidence == nil || saved.JobEvidence.Verification != "complete" || saved.Manifest.Commit != commit { + t.Fatalf("saved=%+v err=%v", saved, err) + } + content, err := os.ReadFile(result.RecordPath) + if err != nil || strings.Contains(string(content), "wood-token") { + t.Fatalf("record leaked credential or could not be read: %v", err) + } + cmd := exec.Command("git", "--git-dir", bare, "rev-parse", "refs/tags/"+result.Attempt.Manifest.Tag) + if output, err := cmd.CombinedOutput(); err != nil || strings.TrimSpace(string(output)) != result.Attempt.TagObject { + t.Fatalf("remote tag=%s err=%v", output, err) + } +} +func TestStartPreservesRecordOnTimeoutAndRejectsUnsafeStoreBeforePush(t *testing.T) { + repo, bare, commit := coordinatorFixture(t) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/repos/42" { + fmt.Fprint(w, `{"id":42}`) + } else { + fmt.Fprint(w, `[]`) + } + })) + defer server.Close() + req := StartRequest{RepositoryDir: repo, Ref: commit, Product: "Example", Source: &releaseidentity.SourceSpec{}, Backend: readyBackend{}, Woodpecker: woodpecker.Client{BaseURL: server.URL, RepositoryID: 42, Token: "token"}, Workflow: "release", Step: "deliver", CIConfigured: true, RecordDir: "records", ObservationTimeout: 50 * time.Millisecond} + if _, err := Start(t.Context(), req); err == nil || !strings.Contains(err.Error(), "not ignored") { + t.Fatalf("unsafe store error=%v", err) + } + cmd := exec.Command("git", "--git-dir", bare, "tag", "--list", "releasekit-test/*") + output, err := cmd.CombinedOutput() + if err != nil || len(output) != 0 { + t.Fatalf("remote mutated: %s %v", output, err) + } + req.RecordDir = "" + result, err := Start(t.Context(), req) + if !errors.Is(err, context.DeadlineExceeded) || result.RecordPath == "" || result.Workflow != "unknown" { + t.Fatalf("result=%+v error=%v", result, err) + } + saved, err := LoadAttempt(result.RecordPath) + if err != nil || saved.Outcomes["push"] != "dispatched" || saved.Outcomes["workflow"] != "unknown" { + t.Fatalf("saved=%+v err=%v", saved, err) + } +} + +func TestObservationDistinguishesJobFailureFromMissingEvidence(t *testing.T) { + repo, profile, _, identity, attemptID := rehearsalFixture(t) + manifest := NewManifest(identity, attemptID, "root", "releasekit.json", profile) + for _, test := range []struct { + name, workflowState, stepState, log string + wantWorkflow, wantBuild, wantVerification string + }{ + {name: "missing result", workflowState: "success", stepState: "success", log: "ordinary output\n", wantWorkflow: "complete", wantBuild: "not_started", wantVerification: "incomplete"}, + {name: "failed build", workflowState: "failure", stepState: "failure", log: "failed-build", wantWorkflow: "failed", wantBuild: "failed", wantVerification: "incomplete"}, + } { + t.Run(test.name, func(t *testing.T) { + record := Attempt{Manifest: manifest, Outcomes: map[string]string{"workflow": "waiting"}} + store, err := CreateAttempt(t.Context(), repo, t.TempDir(), record) + if err != nil { + t.Fatal(err) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/repos/42/pipelines": + if r.URL.Query().Get("page") != "1" { + fmt.Fprint(w, `[]`) + return + } + json.NewEncoder(w).Encode([]woodpecker.Pipeline{{ID: 1, Number: 2, Event: "tag", Ref: "refs/tags/" + manifest.Tag, Commit: manifest.Commit, Status: "failure"}}) + case "/api/repos/42/pipelines/2": + json.NewEncoder(w).Encode(woodpecker.Pipeline{ID: 1, Number: 2, Event: "tag", Ref: "refs/tags/" + manifest.Tag, Commit: manifest.Commit, Status: "failure", Workflows: []woodpecker.Workflow{{ID: 3, Name: "release", State: test.workflowState, Steps: []woodpecker.Step{{ID: 4, Name: "deliver", State: test.stepState}}}}}) + case "/api/repos/42/logs/2/4/download": + if test.log == "failed-build" { + frame, _ := EncodeResult(JobResult{Manifest: manifest, Scope: "page-and-assets", Build: "failed", Delivery: "not_attempted", Verification: "not_attempted", Artifacts: []ArtifactEvidence{}}) + w.Write(frame) + } else { + fmt.Fprint(w, test.log) + } + default: + http.NotFound(w, r) + } + })) + defer server.Close() + result, err := observe(t.Context(), woodpecker.Client{BaseURL: server.URL, RepositoryID: 42, Token: "token"}, "release", "deliver", store, record, Outcome{Workflow: "not_started", Build: "not_started", Verification: "not_started", RecordPath: store.Path}) + if err == nil || result.Workflow != test.wantWorkflow || result.Build != test.wantBuild || result.Verification != test.wantVerification { + t.Fatalf("result=%+v error=%v", result, err) + } + saved, err := LoadAttempt(store.Path) + if err != nil || saved.Outcomes["verification"] != "incomplete" { + t.Fatalf("saved=%+v error=%v", saved, err) + } + }) + } +} + +func TestStartRequiresCIDeclarationInCapturedProfile(t *testing.T) { + repo, bare, _ := coordinatorFixture(t) + if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte(`{"product":"Example","source":{}}`), 0600); err != nil { + t.Fatal(err) + } + run := func(args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = repo + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v: %s", args, err, out) + } + } + run("add", "releasekit.json") + run("commit", "-m", "remove CI declaration") + request := StartRequest{RepositoryDir: repo, Product: "Example", Source: &releaseidentity.SourceSpec{}, Backend: readyBackend{}, Woodpecker: woodpecker.Client{BaseURL: "https://ci.example", RepositoryID: 1, Token: "token"}, Workflow: "release", Step: "deliver", CIConfigured: true} + if _, err := Start(t.Context(), request); err == nil || !strings.Contains(err.Error(), "committed profile must declare") { + t.Fatalf("error=%v", err) + } + cmd := exec.Command("git", "--git-dir", bare, "tag", "--list", "releasekit-test/*") + if out, err := cmd.CombinedOutput(); err != nil || len(out) != 0 { + t.Fatalf("remote tags=%q error=%v", out, err) + } +} diff --git a/internal/rehearsal/manifest_test.go b/internal/rehearsal/manifest_test.go index 69b0d57..d7bac75 100644 --- a/internal/rehearsal/manifest_test.go +++ b/internal/rehearsal/manifest_test.go @@ -30,7 +30,7 @@ func rehearsalFixture(t *testing.T) (string, []byte, releaseidentity.ResolvedSou run("config", "user.name", "ReleaseKit Test") run("config", "user.email", "releasekit@example.test") run("config", "tag.gpgsign", "false") - profile := []byte("{\"product\":\"Example\",\"source\":{}}\n") + profile := []byte("{\"product\":\"Example\",\"source\":{},\"delivery\":{\"credentials\":{\"ci\":{}}}}\n") if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), profile, 0600); err != nil { t.Fatal(err) } diff --git a/internal/rehearsal/record.go b/internal/rehearsal/record.go index c86dede..1edd55b 100644 --- a/internal/rehearsal/record.go +++ b/internal/rehearsal/record.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "reflect" + "slices" "sync" "time" "unicode/utf8" @@ -19,27 +20,32 @@ import ( // Attempt retains the immutable identity and observations needed for recovery. // It deliberately contains no resolved forge or Woodpecker token. type Attempt struct { - FormatVersion int `json:"format_version"` - Manifest Manifest `json:"manifest"` - RepositoryDir string `json:"repository_dir,omitempty"` - Endpoint string `json:"endpoint,omitempty"` - Remote string `json:"remote,omitempty"` - ForgeBaseURL string `json:"forge_base_url,omitempty"` - ForgeOwner string `json:"forge_owner,omitempty"` - ForgeRepository string `json:"forge_repository,omitempty"` - WoodpeckerBaseURL string `json:"woodpecker_base_url,omitempty"` - WoodpeckerRepositoryID int64 `json:"woodpecker_repository_id,omitempty"` - Workflow string `json:"workflow,omitempty"` - Step string `json:"step,omitempty"` - ExpectedPageTitle string `json:"expected_page_title,omitempty"` - ExpectedBodySHA256 string `json:"expected_body_sha256,omitempty"` - TagObject string `json:"tag_object,omitempty"` - PageID int64 `json:"page_id,omitempty"` - PipelineIDs []int64 `json:"pipeline_ids,omitempty"` - Outcomes map[string]string `json:"outcomes,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - IdentityBytes map[string][]byte `json:"identity_bytes,omitempty"` + FormatVersion int `json:"format_version"` + Manifest Manifest `json:"manifest"` + RepositoryDir string `json:"repository_dir,omitempty"` + Endpoint string `json:"endpoint,omitempty"` + Remote string `json:"remote,omitempty"` + ForgeBaseURL string `json:"forge_base_url,omitempty"` + ForgeOwner string `json:"forge_owner,omitempty"` + ForgeRepository string `json:"forge_repository,omitempty"` + WoodpeckerBaseURL string `json:"woodpecker_base_url,omitempty"` + WoodpeckerRepositoryID int64 `json:"woodpecker_repository_id,omitempty"` + Workflow string `json:"workflow,omitempty"` + Step string `json:"step,omitempty"` + ExpectedPageTitle string `json:"expected_page_title,omitempty"` + ExpectedBodySHA256 string `json:"expected_body_sha256,omitempty"` + PlannedAssets []string `json:"planned_assets,omitempty"` + TagObject string `json:"tag_object,omitempty"` + PageID int64 `json:"page_id,omitempty"` + PipelineIDs []int64 `json:"pipeline_ids,omitempty"` + PipelineNumbers []int64 `json:"pipeline_numbers,omitempty"` + Jobs []JobObservation `json:"jobs,omitempty"` + Workflows []WorkflowObservation `json:"workflows,omitempty"` + JobEvidence *JobResult `json:"job_evidence,omitempty"` + Outcomes map[string]string `json:"outcomes,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` + IdentityBytes map[string][]byte `json:"identity_bytes,omitempty"` } func attemptFields(a *Attempt) []stringField { @@ -112,6 +118,9 @@ func LoadAttempt(path string) (Attempt, error) { if err := validateManifestStructure(attempt.Manifest); err != nil { return Attempt{}, fmt.Errorf("invalid rehearsal identity: %w", err) } + if attempt.JobEvidence != nil { + attempt.JobEvidence.Manifest = attempt.Manifest + } if err := decodeStringOverrides(overrides, attemptFields(&attempt)); err != nil { return Attempt{}, fmt.Errorf("decode rehearsal identity bytes: %w", err) } @@ -120,12 +129,13 @@ func LoadAttempt(path string) (Attempt, error) { // Store serializes updates made through one handle for one attempt. type Store struct { - Path string - mu sync.Mutex - manifest Manifest - createdAt string - identity attemptIdentity - tagObject string + Path string + mu sync.Mutex + manifest Manifest + createdAt string + identity attemptIdentity + tagObject string + plannedAssets []string } type attemptIdentity struct { @@ -186,7 +196,7 @@ func CreateAttempt(ctx context.Context, repositoryDir, override string, attempt _ = os.Remove(filename) return nil, fmt.Errorf("close rehearsal record: %w", err) } - return &Store{Path: filename, manifest: attempt.Manifest, createdAt: attempt.CreatedAt, identity: identityOf(attempt), tagObject: attempt.TagObject}, nil + return &Store{Path: filename, manifest: attempt.Manifest, createdAt: attempt.CreatedAt, identity: identityOf(attempt), tagObject: attempt.TagObject, plannedAssets: slices.Clone(attempt.PlannedAssets)}, nil } // OpenStore selects a previously recorded attempt explicitly. @@ -199,7 +209,7 @@ func OpenStore(path string) (*Store, Attempt, error) { if err != nil { return nil, Attempt{}, err } - return &Store{Path: absolute, manifest: attempt.Manifest, createdAt: attempt.CreatedAt, identity: identityOf(attempt), tagObject: attempt.TagObject}, attempt, nil + return &Store{Path: absolute, manifest: attempt.Manifest, createdAt: attempt.CreatedAt, identity: identityOf(attempt), tagObject: attempt.TagObject, plannedAssets: slices.Clone(attempt.PlannedAssets)}, attempt, nil } // Save atomically replaces one attempt record after an observation or intent. @@ -212,6 +222,9 @@ func (store *Store) Save(attempt Attempt) (resultErr error) { if identityOf(attempt) != store.identity { return errors.New("rehearsal destinations cannot change") } + if !slices.Equal(attempt.PlannedAssets, store.plannedAssets) { + return errors.New("planned rehearsal assets cannot change") + } if store.tagObject != "" && attempt.TagObject != store.tagObject { return errors.New("rehearsal tag object cannot change") } diff --git a/internal/rehearsal/record_test.go b/internal/rehearsal/record_test.go index 326c7b2..140a0a6 100644 --- a/internal/rehearsal/record_test.go +++ b/internal/rehearsal/record_test.go @@ -66,7 +66,7 @@ func TestIndependentAttemptsUseSeparateRecords(t *testing.T) { func TestAttemptRecordPreservesIdentityAndUpdates(t *testing.T) { repo, profile, _, identity, attemptID := rehearsalFixture(t) raw := string([]byte{'x', 0xff, 'y'}) - attempt := Attempt{Manifest: NewManifest(identity, attemptID, "root", "releasekit.json", profile), RepositoryDir: repo, Endpoint: raw, Remote: "origin", ExpectedPageTitle: "diagnostic", Outcomes: map[string]string{"tag": "planned"}} + attempt := Attempt{Manifest: NewManifest(identity, attemptID, "root", "releasekit.json", profile), RepositoryDir: repo, Endpoint: raw, Remote: "origin", ExpectedPageTitle: "diagnostic", PlannedAssets: []string{"fixture", "SHA256SUMS"}, Outcomes: map[string]string{"tag": "planned"}} store, err := CreateAttempt(t.Context(), repo, "", attempt) if err != nil { t.Fatal(err) @@ -96,6 +96,11 @@ func TestAttemptRecordPreservesIdentityAndUpdates(t *testing.T) { t.Fatal("accepted changed destination") } changed = loaded + changed.PlannedAssets = []string{"other"} + if err := store.Save(changed); err == nil { + t.Fatal("accepted changed planned assets") + } + changed = loaded changed.Manifest.Tag = "other" if err := store.Save(changed); err == nil { t.Fatal("accepted changed manifest") diff --git a/internal/rehearsal/result.go b/internal/rehearsal/result.go index d524725..5f351f4 100644 --- a/internal/rehearsal/result.go +++ b/internal/rehearsal/result.go @@ -15,6 +15,9 @@ import ( const ResultPrefix = "RELEASEKIT_REHEARSAL_RESULT_V1 " +// ErrResultAbsent means no framed result was found in a job log. +var ErrResultAbsent = errors.New("rehearsal result is absent") + type ArtifactEvidence struct { Name string `json:"name"` Size int64 `json:"size"` @@ -139,7 +142,7 @@ func ReadResult(reader io.Reader, expected Manifest) (JobResult, error) { } } if canonical == nil { - return JobResult{}, errors.New("rehearsal result is absent") + return JobResult{}, ErrResultAbsent } return found, nil } diff --git a/rehearsal.go b/rehearsal.go new file mode 100644 index 0000000..b80de9e --- /dev/null +++ b/rehearsal.go @@ -0,0 +1,128 @@ +package releasekit + +import ( + "context" + "fmt" + "io" + "strings" + "time" + + "go.maximumdirect.net/releasekit/internal/rehearsal" + "go.maximumdirect.net/releasekit/internal/woodpecker" +) + +// RehearsalTimeout is a duration expressed in nanoseconds, like time.Duration. +type RehearsalTimeout time.Duration + +// RehearsalRequest supplies captured-source selection and explicit credentials. +// ProfilePath names a file in Ref, or in HEAD when Ref is empty. Product, +// Source, Build, and the CI credential declaration must correspond to that +// profile; the CLI verifies this binding before calling the facade. +type RehearsalRequest struct { + RepositoryDir string + Ref string + ProfilePath string + ModuleDir string + Source *SourceSpec + Product string + Selector string + Remote string + ExpectedPushURL string + Build *BuildSpec + RequiredFiles []string + Destination DeliveryDestination + Woodpecker WoodpeckerObservation + CIConfigured bool + RecordDir string + // ObservationTimeout zero observes until the context is canceled. + ObservationTimeout RehearsalTimeout + // CleanupTimeout is reserved for the independent cleanup operation; zero uses its default. + CleanupTimeout RehearsalTimeout + Output io.Writer +} + +// RehearsalJob identifies an observed CI workflow and delivery step. +type RehearsalJob struct { + PipelineID, PipelineNumber, WorkflowID, StepID int64 + PipelineStatus, WorkflowState, StepState string +} + +// RehearsalWorkflow reports a workflow observed in a matching pipeline. +type RehearsalWorkflow struct { + PipelineID, PipelineNumber, ID int64 + Name, State string +} + +// RehearsalArtifact describes content verified by the delivery job. +type RehearsalArtifact struct { + Name string + Size int64 + SHA256 string +} + +// RehearsalResult retains partial outcomes and the explicit recovery record. +type RehearsalResult struct { + AttemptID, Tag, Commit, ProfilePath, ProfileSHA256 string + RecordPath, TagObject string + Workflow, Build, Verification, Cleanup string + PageID int64 + PipelineIDs, PipelineNumbers []int64 + PipelineURLs []string + Jobs []RehearsalJob + Workflows []RehearsalWorkflow + Artifacts []RehearsalArtifact + Remaining []string + Diagnostics []string +} + +// RehearsalError preserves the underlying failure or cancellation. +type RehearsalError struct{ Err error } + +func (err *RehearsalError) Error() string { return "rehearsal: " + err.Err.Error() } +func (err *RehearsalError) Unwrap() error { return err.Err } + +// Rehearse validates captured inputs, records and pushes a temporary diagnostic +// tag, and observes the selected CI job. It never loads ambient credentials. +func Rehearse(ctx context.Context, request RehearsalRequest) (RehearsalResult, error) { + backend, err := deliveryBackend(request.Destination) + if err != nil { + return RehearsalResult{}, &RehearsalError{Err: err} + } + var build = internalBuildSpec(request.Build) + if request.Woodpecker.CredentialError != nil { + return RehearsalResult{}, &RehearsalError{Err: request.Woodpecker.CredentialError} + } + outcome, err := rehearsal.Start(ctx, rehearsal.StartRequest{RepositoryDir: request.RepositoryDir, Ref: request.Ref, ProfilePath: request.ProfilePath, ModuleDir: request.ModuleDir, Source: internalSourceSpec(request.Source), Product: request.Product, Selector: request.Selector, Remote: request.Remote, ExpectedPushURL: request.ExpectedPushURL, Build: build, RequiredFiles: request.RequiredFiles, ForgeBaseURL: request.Destination.BaseURL, ForgeOwner: request.Destination.Owner, ForgeRepository: request.Destination.Repository, Backend: backend, Woodpecker: woodpecker.Client{BaseURL: request.Woodpecker.BaseURL, RepositoryID: request.Woodpecker.RepositoryID, Token: request.Woodpecker.Token}, Workflow: request.Woodpecker.Workflow, Step: request.Woodpecker.Step, CIConfigured: request.CIConfigured, RecordDir: request.RecordDir, ObservationTimeout: time.Duration(request.ObservationTimeout), Output: request.Output}) + result := publicRehearsalOutcome(outcome) + if err != nil { + return result, &RehearsalError{Err: err} + } + return result, nil +} + +func publicRehearsalOutcome(outcome rehearsal.Outcome) RehearsalResult { + attempt := outcome.Attempt + manifest := attempt.Manifest + result := RehearsalResult{AttemptID: manifest.AttemptID, Tag: manifest.Tag, Commit: manifest.Commit, ProfilePath: manifest.ProfilePath, ProfileSHA256: manifest.ProfileSHA256, RecordPath: outcome.RecordPath, TagObject: attempt.TagObject, Workflow: outcome.Workflow, Build: outcome.Build, Verification: outcome.Verification, Cleanup: outcome.Cleanup, PageID: attempt.PageID, PipelineIDs: append([]int64(nil), attempt.PipelineIDs...), PipelineNumbers: append([]int64(nil), attempt.PipelineNumbers...), Diagnostics: append([]string(nil), outcome.Diagnostics...)} + for _, job := range attempt.Jobs { + result.Jobs = append(result.Jobs, RehearsalJob{PipelineID: job.PipelineID, PipelineNumber: job.PipelineNumber, WorkflowID: job.WorkflowID, StepID: job.StepID, PipelineStatus: job.PipelineStatus, WorkflowState: job.WorkflowState, StepState: job.StepState}) + } + for _, workflow := range attempt.Workflows { + result.Workflows = append(result.Workflows, RehearsalWorkflow{PipelineID: workflow.PipelineID, PipelineNumber: workflow.PipelineNumber, ID: workflow.ID, Name: workflow.Name, State: workflow.State}) + } + for _, number := range attempt.PipelineNumbers { + result.PipelineURLs = append(result.PipelineURLs, fmt.Sprintf("%s/repos/%d/pipeline/%d", strings.TrimRight(attempt.WoodpeckerBaseURL, "/"), attempt.WoodpeckerRepositoryID, number)) + } + if attempt.Outcomes["tag"] == "created" || attempt.Outcomes["tag"] == "unknown" { + result.Remaining = append(result.Remaining, "local diagnostic tag") + } + if attempt.Outcomes["push"] == "dispatched" || attempt.Outcomes["push"] == "unknown" || attempt.Outcomes["push"] == "attempting" { + result.Remaining = append(result.Remaining, "remote diagnostic tag and possible hosted release") + } + if attempt.JobEvidence != nil { + for _, a := range attempt.JobEvidence.Artifacts { + result.Artifacts = append(result.Artifacts, RehearsalArtifact{Name: a.Name, Size: a.Size, SHA256: a.SHA256}) + } + } + return result +} diff --git a/rehearsal_test.go b/rehearsal_test.go new file mode 100644 index 0000000..6347cfd --- /dev/null +++ b/rehearsal_test.go @@ -0,0 +1,19 @@ +package releasekit_test + +import ( + "context" + "errors" + "testing" + + releasekit "go.maximumdirect.net/releasekit" +) + +func TestRehearsePreservesCancellationCause(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + result, err := releasekit.Rehearse(ctx, releasekit.RehearsalRequest{RepositoryDir: t.TempDir(), CIConfigured: true, Destination: releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea}, Woodpecker: releasekit.WoodpeckerObservation{Workflow: "release", Step: "deliver"}}) + var failure *releasekit.RehearsalError + if !errors.As(err, &failure) || !errors.Is(err, context.Canceled) || result.Workflow != "not_started" { + t.Fatalf("result=%+v error=%v", result, err) + } +}