diff --git a/docs/integrations/rehearsal-records.md b/docs/integrations/rehearsal-records.md index 2ed0442..f94f3e4 100644 --- a/docs/integrations/rehearsal-records.md +++ b/docs/integrations/rehearsal-records.md @@ -66,7 +66,10 @@ the independent CI job or establish that cleanup is safe. ## Cleanup and recovery Recovery selects one explicit record and uses its captured destinations with -current explicitly supplied credentials. A started or uncertain dispatch is +current explicitly supplied credentials. A recorded `push: "not_dispatched"` +means Git supplied definite rejection or failure-before-dispatch evidence; +cleanup removes the owned local tag without requiring CI completion. A started +or uncertain dispatch is eligible for cleanup only after every matching observed pipeline and relevant job is terminal and the CI search is checked again. Missing, active, or unavailable CI evidence leaves cleanup pending. Cleanup verifies the recorded diff --git a/docs/roadmap/remediation.md b/docs/roadmap/remediation.md index ba8f1f0..bfd6149 100644 --- a/docs/roadmap/remediation.md +++ b/docs/roadmap/remediation.md @@ -192,6 +192,12 @@ selected release version and preserve currently supported Go module paths. ## 4. A definitively rejected push strands cleanup waiting for nonexistent CI +**Completed:** Git push errors retain definite non-dispatch/rejection evidence; +the coordinator records `not_dispatched` and cleanup removes owned local +resources without CI. Ambiguous writes retain observation-based recovery. +Native rejecting-hook, pre-dispatch, lost-acknowledgment, unavailable-observation, +Git/rehearsal, and source-publication regression checks pass. + **Priority:** P2. **Stages:** 9, 10, 12, 13. **Relevant code:** [`Start`](../../internal/rehearsal/coordinator.go), lines diff --git a/internal/git/diagnostic.go b/internal/git/diagnostic.go index 0e1f27d..a04d295 100644 --- a/internal/git/diagnostic.go +++ b/internal/git/diagnostic.go @@ -41,7 +41,13 @@ func checkDiagnosticTag(ctx context.Context, repo, tag, object, commit string) e // PushDiagnosticTag publishes a verified local diagnostic object without // moving a conflicting remote ref. Callers reconcile an error by observation. -func (endpoint Endpoint) PushDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error { +func (endpoint Endpoint) PushDiagnosticTag(ctx context.Context, repo, tag, object, commit string) (resultErr error) { + delegated := false + defer func() { + if resultErr != nil && !delegated { + resultErr = &PushError{PushNotAttempted, resultErr} + } + }() if err := checkDiagnosticTag(ctx, repo, tag, object, commit); err != nil { return err } @@ -62,6 +68,7 @@ func (endpoint Endpoint) PushDiagnosticTag(ctx context.Context, repo, tag, objec if remote.State != RefAbsent { return fmt.Errorf("diagnostic tag already exists with different evidence: %w", ErrRemoteTagConflict) } + delegated = true return endpoint.PushTag(ctx, repo, tag, object) } diff --git a/internal/git/diagnostic_test.go b/internal/git/diagnostic_test.go index 1a66291..c213219 100644 --- a/internal/git/diagnostic_test.go +++ b/internal/git/diagnostic_test.go @@ -2,10 +2,58 @@ package git import ( "errors" + "os" + "path/filepath" "strings" "testing" ) +func TestDiagnosticPushRetainsNonDispatchEvidence(t *testing.T) { + fixture := newRemoteFixture(t) + endpoint, err := Resolve(t.Context(), fixture.work, "origin") + if err != nil { + t.Fatal(err) + } + tag := "releasekit-test/root/" + strings.Repeat("b", 32) + object, err := CreateAnnotatedTag(t.Context(), fixture.work, tag, fixture.commit, []byte("diagnostic\n")) + if err != nil { + t.Fatal(err) + } + var failure *PushError + err = endpoint.PushDiagnosticTag(t.Context(), fixture.work, tag, strings.Repeat("c", len(object)), fixture.commit) + if !errors.As(err, &failure) || failure.Disposition != PushNotAttempted { + t.Fatalf("pre-dispatch error=%v evidence=%+v", err, failure) + } + if err := os.WriteFile(filepath.Join(fixture.bare, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil { + t.Fatal(err) + } + err = endpoint.PushDiagnosticTag(t.Context(), fixture.work, tag, object, fixture.commit) + if !errors.As(err, &failure) || failure.Disposition != PushRejected { + t.Fatalf("rejected error=%v evidence=%+v", err, failure) + } + observed, err := endpoint.QueryTag(t.Context(), fixture.work, tag) + if err != nil || observed.State != RefAbsent { + t.Fatalf("rejected ref=%+v error=%v", observed, err) + } +} + +func TestPushRejectionRequiresDefinitiveExactRefStatus(t *testing.T) { + ref := "refs/tags/releasekit-test/root/" + strings.Repeat("a", 32) + for _, test := range []struct { + summary, destination string + want bool + }{ + {"[remote rejected] (pre-receive hook declined)", ref, true}, + {"[rejected] (already exists)", ref, true}, + {"[remote failure] (remote failed to report status)", ref, false}, + {"[remote rejected] (pre-receive hook declined)", "refs/tags/foreign", false}, + } { + if got := rejectedPush("!\tobject:"+test.destination+"\t"+test.summary+"\n", ref); got != test.want { + t.Fatalf("summary=%q destination=%q result=%t", test.summary, test.destination, got) + } + } +} + func TestDiagnosticTagDeletionRequiresRecordedObjectAndCommit(t *testing.T) { fixture := newRemoteFixture(t) ctx := t.Context() diff --git a/internal/git/remote.go b/internal/git/remote.go index 639326b..2e5ed84 100644 --- a/internal/git/remote.go +++ b/internal/git/remote.go @@ -291,6 +291,14 @@ func pushURLs(ctx context.Context, repositoryDir, remoteName string) ([]string, } func run(ctx context.Context, dir string, config []string, args ...string) (string, error) { + return runWithEnvironment(ctx, dir, config, nil, args...) +} + +func runWithEnvironment(ctx context.Context, dir string, config []string, environment map[string]string, args ...string) (string, error) { + if environment == nil { + environment = make(map[string]string) + } + environment["GIT_NO_REPLACE_OBJECTS"] = "1" commandArgs := make([]string, 0, len(config)*2+len(args)) for _, value := range config { commandArgs = append(commandArgs, "-c", value) @@ -300,7 +308,7 @@ func run(ctx context.Context, dir string, config []string, args ...string) (stri err := process.Run(ctx, process.Invocation{ Args: append([]string{"git"}, commandArgs...), Dir: dir, - Env: map[string]string{"GIT_NO_REPLACE_OBJECTS": "1"}, + Env: environment, Stdout: &stdout, Stderr: &stderr, }) diff --git a/internal/git/tag.go b/internal/git/tag.go index a39b62e..f005bd8 100644 --- a/internal/git/tag.go +++ b/internal/git/tag.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "os" + "os/exec" "strings" ) @@ -203,17 +204,64 @@ func (endpoint Endpoint) QueryTag(ctx context.Context, repositoryDir, tag string return finalizeRef(remoteTag), nil } +// PushDisposition describes evidence from one exact tag push. +type PushDisposition string + +const ( + PushNotAttempted PushDisposition = "not_attempted" + PushRejected PushDisposition = "rejected" + PushUnknown PushDisposition = "unknown" +) + +// PushError preserves the cause and evidence about whether dispatch occurred. +type PushError struct { + Disposition PushDisposition + Err error +} + +func (err *PushError) Error() string { return err.Err.Error() } +func (err *PushError) Unwrap() error { return err.Err } + // PushTag publishes only the captured tag object to its exact tag ref. func (endpoint Endpoint) PushTag(ctx context.Context, repositoryDir, tag, tagObject string) error { if err := CheckTagRef(ctx, repositoryDir, tag); err != nil { - return err + return &PushError{PushNotAttempted, err} } if !validObjectID(tagObject) { - return fmt.Errorf("invalid tag publication object %q at %q", tagObject, tag) + return &PushError{PushNotAttempted, fmt.Errorf("invalid tag publication object %q at %q", tagObject, tag)} } - refspec := tagObject + ":refs/tags/" + tag - if _, err := run(ctx, repositoryDir, endpoint.scopedConfig(), "push", "--no-follow-tags", "--recurse-submodules=no", "--porcelain", endpoint.ScopedName, refspec); err != nil { - return fmt.Errorf("push annotated tag %s to %s: %w", tag, DisplayURL(endpoint.PushURL), err) + if err := ctx.Err(); err != nil { + return &PushError{PushNotAttempted, err} } - return nil + ref := "refs/tags/" + tag + output, err := runWithEnvironment(ctx, repositoryDir, endpoint.scopedConfig(), map[string]string{"LC_ALL": "C"}, "push", "--no-follow-tags", "--recurse-submodules=no", "--porcelain", endpoint.ScopedName, tagObject+":"+ref) + if err == nil { + return nil + } + disposition := PushUnknown + var start *exec.Error + var pathError *os.PathError + if errors.As(err, &start) || errors.As(err, &pathError) { + disposition = PushNotAttempted + } else if rejectedPush(output, ref) { + disposition = PushRejected + } + return &PushError{disposition, fmt.Errorf("push annotated tag %s to %s: %w", tag, DisplayURL(endpoint.PushURL), err)} +} + +func rejectedPush(output, ref string) bool { + count, rejected := 0, false + for _, line := range strings.Split(output, "\n") { + fields := strings.SplitN(line, "\t", 3) + if len(fields) != 3 { + continue + } + _, destination, ok := strings.Cut(fields[1], ":") + if !ok || destination != ref { + continue + } + count++ + rejected = fields[0] == "!" && (strings.HasPrefix(fields[2], "[rejected]") || strings.HasPrefix(fields[2], "[remote rejected]")) + } + return count == 1 && rejected } diff --git a/internal/rehearsal/cleanup.go b/internal/rehearsal/cleanup.go index f0c7744..2d40bae 100644 --- a/internal/rehearsal/cleanup.go +++ b/internal/rehearsal/cleanup.go @@ -69,11 +69,11 @@ func cleanup(ctx context.Context, request RecoveryRequest, store *Store, attempt defer cancel() result.Cleanup = "pending" push := attempt.Outcomes["push"] - if push != "not_attempted" && push != "dispatched" && push != "unknown" && push != "attempting" { + if push != "not_attempted" && push != "not_dispatched" && push != "dispatched" && push != "unknown" && push != "attempting" { return result, errors.New("record does not establish diagnostic dispatch state") } remoteComplete := attempt.Outcomes["cleanup-page"] == "complete" && attempt.Outcomes["cleanup-remote-tag"] == "complete" - if push != "not_attempted" && !remoteComplete { + if push != "not_attempted" && push != "not_dispatched" && !remoteComplete { if request.Backend == nil { return result, errors.New("diagnostic forge access is required") } @@ -410,12 +410,12 @@ func Resume(ctx context.Context, request RecoveryRequest) (Outcome, error) { return result, nil } push := attempt.Outcomes["push"] - if push != "not_attempted" && push != "dispatched" && push != "unknown" && push != "attempting" { + if push != "not_attempted" && push != "not_dispatched" && push != "dispatched" && push != "unknown" && push != "attempting" { return result, errors.New("record does not establish diagnostic dispatch state") } var observationErr error remoteComplete := attempt.Outcomes["cleanup-page"] == "complete" && attempt.Outcomes["cleanup-remote-tag"] == "complete" - if push != "not_attempted" && !remoteComplete && !hasVerifiedEvidence(attempt) { + if push != "not_attempted" && push != "not_dispatched" && !remoteComplete && !hasVerifiedEvidence(attempt) { observationCtx := ctx cancel := func() {} if request.ObservationTimeout > 0 { diff --git a/internal/rehearsal/coordinator.go b/internal/rehearsal/coordinator.go index 5d3c02a..6c1ef38 100644 --- a/internal/rehearsal/coordinator.go +++ b/internal/rehearsal/coordinator.go @@ -206,6 +206,11 @@ func Start(ctx context.Context, request StartRequest) (Outcome, error) { } pushErr := endpoint.PushDiagnosticTag(ctx, repo, identity.Tag, object, commit) if pushErr != nil { + var failure *git.PushError + if errors.As(pushErr, &failure) && (failure.Disposition == git.PushNotAttempted || failure.Disposition == git.PushRejected) { + attempt.Outcomes["push"] = "not_dispatched" + return result, errors.Join(pushErr, save()) + } 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) { diff --git a/internal/rehearsal/coordinator_test.go b/internal/rehearsal/coordinator_test.go index 94105d6..0312aed 100644 --- a/internal/rehearsal/coordinator_test.go +++ b/internal/rehearsal/coordinator_test.go @@ -11,12 +11,14 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "sync/atomic" "testing" "time" "go.maximumdirect.net/releasekit/internal/forge" + "go.maximumdirect.net/releasekit/internal/git" "go.maximumdirect.net/releasekit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/woodpecker" ) @@ -69,66 +71,73 @@ func recordManifest(t *testing.T, repo string) Manifest { 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 + for _, lost := range []bool{false, true} { + t.Run(fmt.Sprintf("lost-ack=%t", lost), func(t *testing.T) { + repo, bare, commit := coordinatorFixture(t) + if lost { + installLostPushAcknowledgment(t, false) } - if lists.Add(1) == 1 { - fmt.Fprint(w, `[]`) - return + if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte("dirty profile"), 0600); err != nil { + t.Fatal(err) } - 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{}}) + 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.Error(err) + t.Fatal(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) + 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) { @@ -235,3 +244,92 @@ func TestStartRequiresCIDeclarationInCapturedProfile(t *testing.T) { t.Fatalf("remote tags=%q error=%v", out, err) } } + +func installLostPushAcknowledgment(t *testing.T, unavailable bool) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("POSIX Git wrapper fixture") + } + realGit, err := exec.LookPath("git") + if err != nil { + t.Fatal(err) + } + directory := t.TempDir() + wrapper := `#!/bin/sh +case " $* " in + *" push "*) + "$REAL_GIT" "$@" > /dev/null + result=$? + if [ "$result" -ne 0 ]; then exit "$result"; fi + : > "$PUSH_MARKER" + exit 1 ;; + *" ls-remote "*) + if [ "$UNAVAILABLE_OBSERVATION" = yes ] && [ -f "$PUSH_MARKER" ]; then exit 1; fi ;; +esac +exec "$REAL_GIT" "$@" +` + if err := os.WriteFile(filepath.Join(directory, "git"), []byte(wrapper), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("REAL_GIT", realGit) + t.Setenv("PUSH_MARKER", filepath.Join(directory, "pushed")) + mode := "no" + if unavailable { + mode = "yes" + } + t.Setenv("UNAVAILABLE_OBSERVATION", mode) + t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +func TestStartRejectedPushCleansLocalResourcesWithoutCI(t *testing.T) { + repo, bare, _ := coordinatorFixture(t) + if err := os.WriteFile(filepath.Join(bare, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil { + t.Fatal(err) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/repos/42" { + t.Errorf("unexpected CI observation %s", r.URL.Path) + } + fmt.Fprint(w, `{"id":42}`) + })) + defer server.Close() + result, err := Start(t.Context(), StartRequest{RepositoryDir: repo, Product: "Example", Source: &releaseidentity.SourceSpec{}, Backend: readyBackend{}, Woodpecker: woodpecker.Client{BaseURL: server.URL, RepositoryID: 42, Token: "token"}, Workflow: "release", Step: "deliver", CIConfigured: true}) + var push *git.PushError + if !errors.As(err, &push) || push.Disposition != git.PushRejected || result.Attempt.Outcomes["push"] != "not_dispatched" { + t.Fatalf("result=%+v error=%v", result, err) + } + cleaned, cleanupErr := Cleanup(t.Context(), RecoveryRequest{RecordPath: result.RecordPath}) + if cleanupErr != nil || cleaned.Cleanup != "complete" { + t.Fatalf("cleanup=%+v error=%v", cleaned, cleanupErr) + } + local, _, localErr := git.QueryLocalDiagnosticTag(t.Context(), repo, result.Attempt.Manifest.Tag) + if localErr != nil || local != git.RefAbsent { + t.Fatalf("local=%v error=%v", local, localErr) + } +} + +func TestStartAmbiguousPushWithUnavailableObservationRetainsEvidence(t *testing.T) { + repo, _, _ := coordinatorFixture(t) + installLostPushAcknowledgment(t, true) + 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() + client := woodpecker.Client{BaseURL: server.URL, RepositoryID: 42, Token: "token"} + result, err := Start(t.Context(), StartRequest{RepositoryDir: repo, Product: "Example", Source: &releaseidentity.SourceSpec{}, Backend: readyBackend{}, Woodpecker: client, Workflow: "release", Step: "deliver", CIConfigured: true}) + if err == nil || result.Attempt.Outcomes["push"] != "unknown" { + t.Fatalf("result=%+v error=%v", result, err) + } + cleaned, cleanupErr := Cleanup(t.Context(), RecoveryRequest{RecordPath: result.RecordPath, Backend: &diagnosticForge{}, Woodpecker: client}) + if cleanupErr == nil || cleaned.Cleanup != "pending" { + t.Fatalf("cleanup=%+v error=%v", cleaned, cleanupErr) + } + local, _, localErr := git.QueryLocalDiagnosticTag(t.Context(), repo, result.Attempt.Manifest.Tag) + if localErr != nil || local != git.RefPresent { + t.Fatalf("local=%v error=%v", local, localErr) + } +}