From 323ca345373f6d7f4a3b8f41c2abc91e5bafbf1e Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 18 Sep 2026 11:06:34 -0400 Subject: [PATCH 1/2] feat(cli): receipt the absorbed update under the job token A run in flight absorbs an update and the run queued behind it does the work again, so steering costs more than preserving alone: two reviews of one head where preserving alone produces one. After a successful run that absorbed at least one steer, the runner posts a receipt naming the follow-up runs it consumed. A queued run reads the latest receipt in its pre-flight, before the start comment and before the pre-script, and exits 0 without starting the agent when it finds its own run id. The receipt's author is the whole of the authentication, and it is the GitHub Actions job token's. Two conditions are enforced rather than assumed: minting must actually have swapped the credential, since otherwise it stays in the environment a post-script inherits; and the receipt login must differ from the role's, since the action's github_token is a caller-supplied input that can resolve to the identity the agent posts under. No receipt is honoured while any provider definition in .fullsend/providers/ expands GH_WORKFLOW_TOKEN, whichever harness uses it: that hands the job token to a sandbox, where the agent can recover it and forge one (ADR 0114). A queued review also skips when the review App already reviewed the pull request's current head after the queued run was created. Two events on one head route two reviews, and the run in flight writes no receipt for a run it rejects as not fresh. A human /fs-review, a manual re-run, an unreadable event and every error run the review, steering or not. Only an outright success writes a receipt, once per run, naming what the iteration whose output shipped absorbed. Everything fails open: a false "already handled" drops work, a false "not handled" costs one run. The terminal status comment keeps an informational copy of the marker that the skip check does not honour, and agent-authored text is neutralized before it reaches that comment. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/cli/issues.go | 12 +- internal/cli/issues_test.go | 24 + internal/cli/review_skip.go | 269 +++++ internal/cli/review_skip_test.go | 469 +++++++++ internal/cli/run.go | 137 ++- internal/cli/steer.go | 407 +++++++- internal/cli/steer_test.go | 977 +++++++++++++++++++ internal/forge/forge.go | 3 + internal/forge/github/github.go | 2 + internal/forge/github/github_comment_test.go | 2 + internal/sandbox/sandbox.go | 16 +- internal/sandbox/sandbox_test.go | 62 ++ internal/statuscomment/statuscomment.go | 44 +- internal/statuscomment/steermarker.go | 195 ++++ internal/statuscomment/steermarker_test.go | 358 +++++++ internal/sticky/sticky.go | 47 +- internal/sticky/sticky_test.go | 62 ++ 17 files changed, 3062 insertions(+), 24 deletions(-) create mode 100644 internal/cli/review_skip.go create mode 100644 internal/cli/review_skip_test.go create mode 100644 internal/statuscomment/steermarker.go create mode 100644 internal/statuscomment/steermarker_test.go diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 928c1e8e27..0f836c9169 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -13,6 +13,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/statuscomment" "github.com/fullsend-ai/fullsend/internal/sticky" "github.com/fullsend-ai/fullsend/internal/tracker" "github.com/fullsend-ai/fullsend/internal/ui" @@ -414,12 +415,19 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st } existing := findMarkedTrackerComment(comments, cfg.Marker) - markedBody := cfg.Marker + "\n" + body + // Same reason as sticky.Post: the body is agent output, and an agent + // can be induced to write fullsend marker syntax into it. Defanged + // before this comment's own marker is prepended. + markedBody := cfg.Marker + "\n" + statuscomment.NeutralizeMarkers(body) if existing != nil { printer.StepStart("Found existing comment, updating in-place") - newBody := sticky.BuildUpdatedBody(string(existing.Body), markedBody, cfg) + // Same as sticky.Post: the old body is re-posted as history, so a + // marker smuggled into it earlier must not survive the edit — and + // the runner's own marker is left intact so BuildUpdatedBody can + // still strip it by exact prefix. + newBody := sticky.BuildUpdatedBody(sticky.NeutralizeHistory(string(existing.Body), cfg), markedBody, cfg) if cfg.DryRun { printer.StepInfo("Dry run — would update comment " + existing.ID) diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 066448f51d..bac5189272 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -17,6 +17,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/statuscomment" "github.com/fullsend-ai/fullsend/internal/sticky" "github.com/fullsend-ai/fullsend/internal/tracker" "github.com/fullsend-ai/fullsend/internal/ui" @@ -1005,3 +1006,26 @@ func TestIssuesPostCommentCmd_TrackerNotRequired(t *testing.T) { assert.NotContains(t, err.Error(), `required flag(s) "tracker"`) assert.Contains(t, err.Error(), "--tracker is required") } + +// Both agent-output posting paths must defang marker syntax, or the one +// that does not becomes the way to plant a forged steer receipt. +func TestPostTrackerStickyComment_NeutralizesMarkers(t *testing.T) { + tc := tracker.NewForgeClient(forge.NewFakeClient()) + printer := ui.New(io.Discard) + + body := "## Review\n\nLGTM.\n" + _, err := postTrackerStickyComment(context.Background(), tc, "org/repo", 7, body, + sticky.Config{Marker: ""}, printer) + require.NoError(t, err) + + comments, err := tc.ListComments(context.Background(), "org/repo", 7) + require.NoError(t, err) + require.Len(t, comments, 1) + + posted := string(comments[0].Body) + assert.Contains(t, posted, "<!-- fullsend:steer", "the planted receipt must be defanged") + assert.Contains(t, posted, "", "the comment's own marker is untouched") + + _, ok := statuscomment.ParseSteerMarker(posted) + assert.False(t, ok, "no parseable receipt may reach the timeline") +} diff --git a/internal/cli/review_skip.go b/internal/cli/review_skip.go new file mode 100644 index 0000000000..e0b997d283 --- /dev/null +++ b/internal/cli/review_skip.go @@ -0,0 +1,269 @@ +package cli + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/repos" + "github.com/fullsend-ai/fullsend/internal/steerwatch" +) + +// headReviewedRunReader reads the run that dispatched this job, from the +// repository the workflow runs in. +type headReviewedRunReader interface { + GetWorkflowRun(ctx context.Context, owner, repo string, runID int) (*forge.WorkflowRun, error) +} + +// headReviewedPRReader reads the pull request under review. +type headReviewedPRReader interface { + GetPullRequestHeadSHA(ctx context.Context, owner, repo string, number int) (string, error) + ListPullRequestReviews(ctx context.Context, owner, repo string, number int) ([]forge.PullRequestReview, error) +} + +// Overridable in tests. +var ( + headReviewedRunClientFn = func(token string) headReviewedRunReader { return newGitHubLiveClient(token, "") } + headReviewedPRClientFn = func(token string) headReviewedPRReader { return newGitHubLiveClient(token, "") } +) + +// headReviewedTransitions are the events that may be a duplicate of a review +// that already ran. A comment is never among them: a human /fs-review runs, +// bare or with text. Anything else, including an event the runner could not +// read, runs too. +var headReviewedTransitions = map[normevent.TransitionKind]bool{ + normevent.TransitionOpened: true, + normevent.TransitionReopened: true, + normevent.TransitionSynchronized: true, + normevent.TransitionMarkedReady: true, + normevent.TransitionLabelChanged: true, +} + +// headReviewedInput is what the head-reviewed check decides on. +type headReviewedInput struct { + role string + transition normevent.TransitionKind + runAttempt string + runRepo string // owner/repo the workflow runs in + runID int64 + prRepo string // owner/repo of the pull request + prNumber int +} + +// headAlreadyReviewed reports whether the review App already reviewed the +// pull request's current head after this run was created, so this run would +// review the same head again. +// +// Two events on one head, such as a PR opened and labelled a second apart, +// both route to review. With runs queued rather than cancelled (ADR 0106), +// both would run a full review. The steer receipt does not cover this: the +// run in flight rejects the other as not fresh, absorbs nothing, and so +// writes no receipt. +// +// The evidence is the review App's own review, not a receipt. It skips only +// when every condition holds; any error or missing field runs the review, +// because a false skip loses a review and a false run costs one. +func headAlreadyReviewed(ctx context.Context, in headReviewedInput, runs headReviewedRunReader, prs headReviewedPRReader) (bool, string, error) { + if resolveRole(in.role) != "review" { + return false, fmt.Sprintf("stage %q is not review", in.role), nil + } + if !headReviewedTransitions[in.transition] { + return false, fmt.Sprintf("event %q is not one a duplicate review comes from", in.transition), nil + } + if in.runAttempt != "" && in.runAttempt != "1" { + return false, fmt.Sprintf("run attempt %s is a manual re-run", in.runAttempt), nil + } + if runs == nil || prs == nil { + return false, "no forge client", nil + } + if in.runID <= 0 { + return false, "no run id", nil + } + if in.prNumber <= 0 { + return false, "no pull request number", nil + } + runOwner, runName, ok := strings.Cut(in.runRepo, "/") + if !ok || runOwner == "" || runName == "" { + return false, fmt.Sprintf("run repository %q is not owner/repo", in.runRepo), nil + } + prOwner, prName, ok := strings.Cut(in.prRepo, "/") + if !ok || prOwner == "" || prName == "" { + return false, fmt.Sprintf("pull request repository %q is not owner/repo", in.prRepo), nil + } + + run, err := runs.GetWorkflowRun(ctx, runOwner, runName, int(in.runID)) + if err != nil { + return false, "", fmt.Errorf("reading this run: %w", err) + } + if run == nil { + return false, "this run was not found", nil + } + created, err := time.Parse(time.RFC3339Nano, run.CreatedAt) + if err != nil { + return false, fmt.Sprintf("this run's created_at %q is unreadable", run.CreatedAt), nil + } + + head, err := prs.GetPullRequestHeadSHA(ctx, prOwner, prName, in.prNumber) + if err != nil { + return false, "", fmt.Errorf("reading the pull request head: %w", err) + } + reviews, err := prs.ListPullRequestReviews(ctx, prOwner, prName, in.prNumber) + if err != nil { + return false, "", fmt.Errorf("listing reviews: %w", err) + } + + if head == "" { + return false, "the pull request head is unknown", nil + } + if !appReviewedHeadSince(reviews, head, prOwner, created) { + return false, fmt.Sprintf("no review App review of %s after %s", shortHead(head), run.CreatedAt), nil + } + return true, fmt.Sprintf("the review App reviewed %s after %s", shortHead(head), run.CreatedAt), nil +} + +// shortHead abbreviates a commit for a log line. +func shortHead(sha string) string { + if len(sha) > 12 { + return sha[:12] + } + return sha +} + +// appReviewedHeadSince reports whether the review App reviewed head after +// since. Only the App's reviews count: a later human review fires its own +// review_submitted run, which is not a skippable event, so ignoring it drops +// nothing. A pending or dismissed review, or one without a readable time, is +// not evidence. +func appReviewedHeadSince(reviews []forge.PullRequestReview, head, owner string, since time.Time) bool { + for _, r := range reviews { + if r.State == "PENDING" || r.State == "DISMISSED" { + continue + } + if !r.AuthorIsApp || !isReviewAppLogin(r.User, owner) || !strings.EqualFold(r.CommitID, head) { + continue + } + t, err := time.Parse(time.RFC3339Nano, r.SubmittedAt) + if err == nil && t.After(since) { + return true + } + } + return false +} + +// isReviewAppLogin reports whether login is exactly one of the review App's +// logins. Never a login's shape: a user account can look like a bot. +func isReviewAppLogin(login, owner string) bool { + for _, l := range steerwatch.ReviewBotLogins(owner) { + if strings.EqualFold(login, l) { + return true + } + } + return false +} + +// checkHeadAlreadyReviewed runs the head-reviewed skip for this run. It runs +// whether or not steering is enabled, because the duplicate comes from runs +// being queued rather than cancelled, not from steering. +func checkHeadAlreadyReviewed(ctx context.Context, o steerOpts, eventMap map[string]any) bool { + if os.Getenv("GITHUB_ACTIONS") != "true" || o.forgePlatform == repos.ForgeGitLab || o.jobToken == "" || o.roleToken == "" { + o.printer.StepInfo("Head-reviewed skip not checked: needs GitHub Actions with a job token and a role token") + return false + } + in := headReviewedInput{ + role: o.harness.Role, + transition: headReviewedTransition(eventMap, os.Getenv("GITHUB_EVENT_NAME"), os.Getenv("GITHUB_EVENT_PATH"), o.statusNum), + runAttempt: os.Getenv("GITHUB_RUN_ATTEMPT"), + runRepo: os.Getenv("GITHUB_REPOSITORY"), + runID: steerRunID(), + prRepo: o.statusRepo, + prNumber: o.statusNum, + } + skip, why, err := headAlreadyReviewed(ctx, in, headReviewedRunClientFn(o.jobToken), headReviewedPRClientFn(o.roleToken)) + if err != nil { + o.printer.StepWarn("Could not check whether this head was already reviewed: " + err.Error()) + return false + } + if !skip { + o.printer.StepInfo("Head-reviewed skip not applied: " + why) + } + return skip +} + +// headReviewedTransition names the event that dispatched this run. The +// normalized event wins when the run was given one. The built-in stages are +// not: their route passes a reduced payload, so the kind is read from the +// event GitHub delivered to the job instead. A reusable workflow sees its +// caller's event. An event with no pull request action, such as a +// workflow_dispatch, names no kind, so it runs. The delivered event must +// name the pull request this run reports on, so a mismatched payload can +// never drive a skip. +func headReviewedTransition(eventMap map[string]any, eventName, eventPath string, prNumber int) normevent.TransitionKind { + if k := extractMapString(eventMap, "transition", "kind"); k != "" { + return normevent.TransitionKind(k) + } + if eventPath == "" { + return "" + } + data, err := os.ReadFile(eventPath) + if err != nil { + return "" + } + var raw struct { + Action string `json:"action"` + PullRequest struct { + Number int `json:"number"` + } `json:"pull_request"` + } + if json.Unmarshal(data, &raw) != nil { + return "" + } + switch eventName { + case "pull_request", "pull_request_target": + if prNumber <= 0 || raw.PullRequest.Number != prNumber { + return "" + } + switch raw.Action { + case "opened": + return normevent.TransitionOpened + case "reopened": + return normevent.TransitionReopened + case "synchronize": + return normevent.TransitionSynchronized + case "ready_for_review": + return normevent.TransitionMarkedReady + case "labeled", "unlabeled": + return normevent.TransitionLabelChanged + } + case "issue_comment": + return normevent.TransitionCommentAdded + } + return "" +} + +// runPreflightSkips reports whether this run has nothing to do, and says why. +// Both skips live here so run has a single call site to keep. +// +// - The steer receipt: the run in flight ahead of this one already +// absorbed the event that dispatched it (ADR 0120). +// - The head-reviewed skip: a second event on a head the review App +// already reviewed, which no receipt covers. +func runPreflightSkips(ctx context.Context, o steerOpts, eventMap map[string]any) bool { + if checkSteerAlreadyHandled(ctx, o) { + o.printer.StepDone(fmt.Sprintf( + "Update already absorbed by the run in flight (follow-up run %s); nothing to do", + os.Getenv("GITHUB_RUN_ID"))) + return true + } + if checkHeadAlreadyReviewed(ctx, o, eventMap) { + o.printer.StepDone(fmt.Sprintf( + "This head was already reviewed after run %s was created; nothing to do", + os.Getenv("GITHUB_RUN_ID"))) + return true + } + return false +} diff --git a/internal/cli/review_skip_test.go b/internal/cli/review_skip_test.go new file mode 100644 index 0000000000..03c8de676d --- /dev/null +++ b/internal/cli/review_skip_test.go @@ -0,0 +1,469 @@ +package cli + +import ( + "context" + "errors" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/repos" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +const ( + reviewedHead = "f3af8c5aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + runCreated = "2026-09-23T16:14:04Z" + afterRunStart = "2026-09-23T16:30:00Z" + beforeRunStart = "2026-09-23T16:10:00Z" +) + +type fakeRunReader struct { + run *forge.WorkflowRun + err error +} + +func (f fakeRunReader) GetWorkflowRun(context.Context, string, string, int) (*forge.WorkflowRun, error) { + return f.run, f.err +} + +type fakePRReader struct { + head string + headErr error + reviews []forge.PullRequestReview + reviewsErr error +} + +func (f fakePRReader) GetPullRequestHeadSHA(context.Context, string, string, int) (string, error) { + return f.head, f.headErr +} + +func (f fakePRReader) ListPullRequestReviews(context.Context, string, string, int) ([]forge.PullRequestReview, error) { + return f.reviews, f.reviewsErr +} + +func appReview(login, commit, submitted string) forge.PullRequestReview { + return forge.PullRequestReview{User: login, State: "APPROVED", CommitID: commit, SubmittedAt: submitted, AuthorIsApp: true} +} + +func headReviewedBase() (headReviewedInput, fakeRunReader, fakePRReader) { + in := headReviewedInput{ + role: "review", + transition: normevent.TransitionLabelChanged, + runAttempt: "1", + runRepo: "org/repo", + runID: 35752742886, + prRepo: "org/repo", + prNumber: 1480, + } + runs := fakeRunReader{run: &forge.WorkflowRun{ID: 35752742886, CreatedAt: runCreated}} + prs := fakePRReader{head: reviewedHead, reviews: []forge.PullRequestReview{ + appReview("org-review[bot]", reviewedHead, afterRunStart), + }} + return in, runs, prs +} + +// TestHeadAlreadyReviewed pins when a queued review skips: only when the +// review App reviewed the current head after this run was created, for an +// event that is not a human command, on the first attempt. +func TestHeadAlreadyReviewed(t *testing.T) { + tests := []struct { + name string + mutate func(*headReviewedInput, *fakeRunReader, *fakePRReader) + skip bool + wantErr bool + }{ + {name: "labelled after the head was reviewed skips", mutate: func(*headReviewedInput, *fakeRunReader, *fakePRReader) {}, skip: true}, + {name: "opened skips", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.transition = normevent.TransitionOpened + }, skip: true}, + {name: "synchronize skips", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.transition = normevent.TransitionSynchronized + }, skip: true}, + {name: "attempt unset counts as the first", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.runAttempt = "" + }, skip: true}, + {name: "shared review App login", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = []forge.PullRequestReview{appReview("fullsend-ai-review[bot]", reviewedHead, afterRunStart)} + }, skip: true}, + {name: "login matched without regard to case", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = []forge.PullRequestReview{appReview("Org-Review[bot]", reviewedHead, afterRunStart)} + }, skip: true}, + + {name: "a human /fs-review comment runs", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.transition = normevent.TransitionCommentAdded + }}, + {name: "an unreadable event runs", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.transition = "" + }}, + {name: "a manual re-run runs", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.runAttempt = "2" + }}, + {name: "another stage runs", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.role = "triage" + }}, + {name: "a review of an older head runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.head = "b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0" + }}, + {name: "a review older than this run runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = []forge.PullRequestReview{appReview("org-review[bot]", reviewedHead, beforeRunStart)} + }}, + {name: "a review at the run's own second runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = []forge.PullRequestReview{appReview("org-review[bot]", reviewedHead, runCreated)} + }}, + {name: "a human reviewer runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + r := appReview("maintainer", reviewedHead, afterRunStart) + r.AuthorIsApp = false + p.reviews = []forge.PullRequestReview{r} + }}, + {name: "a look-alike login runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = []forge.PullRequestReview{appReview("org-review-bot", reviewedHead, afterRunStart)} + }}, + {name: "another App's review runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = []forge.PullRequestReview{appReview("org-coder[bot]", reviewedHead, afterRunStart)} + }}, + {name: "the review App's login without the forge's App verdict runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + r := appReview("org-review[bot]", reviewedHead, afterRunStart) + r.AuthorIsApp = false + p.reviews = []forge.PullRequestReview{r} + }}, + {name: "a later human review does not count, and skips", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + human := appReview("maintainer", reviewedHead, "2026-09-23T16:40:00Z") + human.AuthorIsApp = false + p.reviews = append(p.reviews, human) + }, skip: true}, + {name: "a later App review of an old head does not hide the right one", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = append(p.reviews, appReview("org-review[bot]", "0101010101010101010101010101010101010101", "2026-09-23T16:40:00Z")) + }, skip: true}, + {name: "a newer App review of an old head does not stand in for the current head", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = []forge.PullRequestReview{ + appReview("org-review[bot]", reviewedHead, beforeRunStart), + appReview("org-review[bot]", "0101010101010101010101010101010101010101", afterRunStart), + } + }}, + {name: "a dismissed App review runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews[0].State = "DISMISSED" + }}, + {name: "no reviews runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews = nil + }}, + {name: "a review without a commit runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviews[0].CommitID = "" + }}, + {name: "an empty head against a review without a commit runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.head = "" + p.reviews[0].CommitID = "" + }}, + {name: "an unparseable run time runs", mutate: func(_ *headReviewedInput, r *fakeRunReader, _ *fakePRReader) { + r.run = &forge.WorkflowRun{CreatedAt: "yesterday"} + }}, + {name: "a missing run runs", mutate: func(_ *headReviewedInput, r *fakeRunReader, _ *fakePRReader) { + r.run = nil + }}, + {name: "a malformed run repo runs", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.runRepo = "repo" + }}, + {name: "no run id runs", mutate: func(in *headReviewedInput, _ *fakeRunReader, _ *fakePRReader) { + in.runID = 0 + }}, + + {name: "a run lookup error runs", mutate: func(_ *headReviewedInput, r *fakeRunReader, _ *fakePRReader) { + r.err = errors.New("403") + }, wantErr: true}, + {name: "a head lookup error runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.headErr = errors.New("404") + }, wantErr: true}, + {name: "a review listing error runs", mutate: func(_ *headReviewedInput, _ *fakeRunReader, p *fakePRReader) { + p.reviewsErr = errors.New("502") + }, wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + in, runs, prs := headReviewedBase() + tt.mutate(&in, &runs, &prs) + got, why, err := headAlreadyReviewed(context.Background(), in, runs, prs) + if tt.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err) + assert.NotEmpty(t, why, "every outcome names its reason, so a live run is diagnosable") + } + assert.Equal(t, tt.skip, got) + }) + } +} + +// headReviewedOpts sets up checkHeadAlreadyReviewed with fakes that would +// skip, so each test can take away one input. +func headReviewedOpts(t *testing.T) (steerOpts, map[string]any, *strings.Builder) { + t.Helper() + t.Setenv("GITHUB_ACTIONS", "true") + t.Setenv("GITHUB_RUN_ID", "35752742886") + t.Setenv("GITHUB_RUN_ATTEMPT", "1") + t.Setenv("GITHUB_REPOSITORY", "org/repo") + // The CI job running these tests has its own event; never read it. + t.Setenv("GITHUB_EVENT_NAME", "") + t.Setenv("GITHUB_EVENT_PATH", "") + + _, runs, prs := headReviewedBase() + prevRun, prevPR := headReviewedRunClientFn, headReviewedPRClientFn + t.Cleanup(func() { headReviewedRunClientFn, headReviewedPRClientFn = prevRun, prevPR }) + headReviewedRunClientFn = func(string) headReviewedRunReader { return runs } + headReviewedPRClientFn = func(string) headReviewedPRReader { return prs } + + var out strings.Builder + o := steerOpts{ + harness: steerHarness(false), + statusRepo: "org/repo", + statusNum: 1480, + jobToken: "job-token", + roleToken: "role-token", + printer: ui.New(&out), + } + o.harness.Role = "review" + event := map[string]any{"transition": map[string]any{"kind": "label_changed"}} + return o, event, &out +} + +// TestCheckHeadAlreadyReviewed_Wiring pins how the runner feeds the check: +// the event's transition, the run attempt and the run's repository all come +// from the environment the job runs in, and steering being off does not stop +// it. +func TestCheckHeadAlreadyReviewed_Wiring(t *testing.T) { + o, event, _ := headReviewedOpts(t) + assert.True(t, checkHeadAlreadyReviewed(context.Background(), o, event), + "skips with steering explicitly off: the duplicate is not steering's") + + t.Run("comment event runs", func(t *testing.T) { + o, _, _ := headReviewedOpts(t) + comment := map[string]any{"transition": map[string]any{"kind": "comment_added"}} + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, comment)) + }) + t.Run("no event runs", func(t *testing.T) { + o, _, _ := headReviewedOpts(t) + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, nil)) + }) + t.Run("re-run runs", func(t *testing.T) { + o, event, _ := headReviewedOpts(t) + t.Setenv("GITHUB_RUN_ATTEMPT", "2") + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, event)) + }) + t.Run("outside Actions runs", func(t *testing.T) { + o, event, _ := headReviewedOpts(t) + t.Setenv("GITHUB_ACTIONS", "") + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, event)) + }) + t.Run("GitLab runs", func(t *testing.T) { + o, event, _ := headReviewedOpts(t) + o.forgePlatform = repos.ForgeGitLab + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, event)) + }) + t.Run("no role token runs", func(t *testing.T) { + o, event, _ := headReviewedOpts(t) + o.roleToken = "" + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, event)) + }) + t.Run("an API error runs and says why", func(t *testing.T) { + o, event, out := headReviewedOpts(t) + headReviewedPRClientFn = func(string) headReviewedPRReader { return fakePRReader{headErr: errors.New("boom")} } + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, event)) + assert.Contains(t, out.String(), "Could not check whether this head was already reviewed") + }) +} + +// writeRawEvent writes the event GitHub delivers to a job and points the +// runner at it. +func writeRawEvent(t *testing.T, name, action string) { + t.Helper() + path := filepath.Join(t.TempDir(), "event.json") + require.NoError(t, os.WriteFile(path, []byte(`{"action":"`+action+`","pull_request":{"number":1480}}`), 0o600)) + t.Setenv("GITHUB_EVENT_NAME", name) + t.Setenv("GITHUB_EVENT_PATH", path) +} + +// TestCheckHeadAlreadyReviewed_BuiltInReviewStage is the production shape the +// skip first missed: the built-in review stage gets no normalized event, so +// the kind has to come from the event GitHub delivered to the job. +func TestCheckHeadAlreadyReviewed_BuiltInReviewStage(t *testing.T) { + for _, action := range []string{"opened", "labeled"} { + t.Run(action+" skips", func(t *testing.T) { + o, _, out := headReviewedOpts(t) + writeRawEvent(t, "pull_request_target", action) + assert.True(t, checkHeadAlreadyReviewed(context.Background(), o, nil), + "a PR whose head the App already reviewed skips with no normalized event") + assert.NotContains(t, out.String(), "not applied") + }) + } + t.Run("a payload for another pull request runs", func(t *testing.T) { + o, _, out := headReviewedOpts(t) + writeRawEvent(t, "pull_request_target", "opened") + o.statusNum = 1481 + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, nil)) + assert.Contains(t, out.String(), "Head-reviewed skip not applied") + }) + t.Run("a comment runs", func(t *testing.T) { + o, _, out := headReviewedOpts(t) + writeRawEvent(t, "issue_comment", "created") + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, nil)) + assert.Contains(t, out.String(), `event "comment_added"`) + }) +} + +func TestHeadReviewedTransition(t *testing.T) { + dir := t.TempDir() + raw := func(action string) string { + p := filepath.Join(dir, action+".json") + require.NoError(t, os.WriteFile(p, []byte(`{"action":"`+action+`","pull_request":{"number":7}}`), 0o600)) + return p + } + normalized := map[string]any{"transition": map[string]any{"kind": "synchronized"}} + tests := []struct { + name string + eventMap map[string]any + eventName string + path string + want normevent.TransitionKind + }{ + {"the normalized event wins", normalized, "issue_comment", raw("created"), normevent.TransitionSynchronized}, + {"labeled", nil, "pull_request_target", raw("labeled"), normevent.TransitionLabelChanged}, + {"unlabeled", nil, "pull_request_target", raw("unlabeled"), normevent.TransitionLabelChanged}, + {"opened", nil, "pull_request_target", raw("opened"), normevent.TransitionOpened}, + {"reopened", nil, "pull_request", raw("reopened"), normevent.TransitionReopened}, + {"synchronize", nil, "pull_request_target", raw("synchronize"), normevent.TransitionSynchronized}, + {"ready for review", nil, "pull_request_target", raw("ready_for_review"), normevent.TransitionMarkedReady}, + {"a comment", nil, "issue_comment", raw("created"), normevent.TransitionCommentAdded}, + {"an edited PR", nil, "pull_request_target", raw("edited"), ""}, + {"a workflow_dispatch event", nil, "workflow_dispatch", raw("dispatch"), ""}, + {"no event file", nil, "pull_request_target", "", ""}, + {"another pull request's payload", nil, "pull_request_target", raw("labeled"), ""}, + {"a missing event file", nil, "pull_request_target", filepath.Join(dir, "absent.json"), ""}, + } + t.Run("no pull request number on either side", func(t *testing.T) { + p := filepath.Join(dir, "bare.json") + require.NoError(t, os.WriteFile(p, []byte(`{"action":"labeled"}`), 0o600)) + assert.Equal(t, normevent.TransitionKind(""), headReviewedTransition(nil, "pull_request_target", p, 0)) + }) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + number := 7 + if tt.name == "another pull request's payload" { + number = 8 + } + assert.Equal(t, tt.want, headReviewedTransition(tt.eventMap, tt.eventName, tt.path, number)) + }) + } +} + +// TestCheckHeadAlreadyReviewed_LogsWhyNot pins the one line a run that does +// not skip prints, naming the guard. +func TestCheckHeadAlreadyReviewed_LogsWhyNot(t *testing.T) { + o, _, out := headReviewedOpts(t) + t.Setenv("GITHUB_EVENT_NAME", "workflow_dispatch") + t.Setenv("GITHUB_EVENT_PATH", "") + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, nil)) + assert.Contains(t, out.String(), `Head-reviewed skip not applied: event "" is not one a duplicate review comes from`) + + o, event, out := headReviewedOpts(t) + o.jobToken = "" + assert.False(t, checkHeadAlreadyReviewed(context.Background(), o, event)) + assert.Contains(t, out.String(), "Head-reviewed skip not checked") +} + +// TestCheckHeadAlreadyReviewed_ReadsWithTheRightTokens pins the credentials: +// the run is read with the job token from the repository the workflow runs +// in, and the pull request with the role token. +func TestCheckHeadAlreadyReviewed_ReadsWithTheRightTokens(t *testing.T) { + o, event, _ := headReviewedOpts(t) + var runTok, prTok string + inner := headReviewedRunClientFn + innerPR := headReviewedPRClientFn + headReviewedRunClientFn = func(tok string) headReviewedRunReader { runTok = tok; return inner(tok) } + headReviewedPRClientFn = func(tok string) headReviewedPRReader { prTok = tok; return innerPR(tok) } + checkHeadAlreadyReviewed(context.Background(), o, event) + assert.Equal(t, "job-token", runTok) + assert.Equal(t, "role-token", prTok) +} + +// TestRunPreflightSkips pins both skips behind the one call run makes, and +// the line each prints. +func TestRunPreflightSkips(t *testing.T) { + t.Run("the receipt skips", func(t *testing.T) { + var out strings.Builder + o := baseOpts(t) + o.printer = ui.New(&out) + prev := steerMarkerClientFn + t.Cleanup(func() { steerMarkerClientFn = prev }) + steerMarkerClientFn = func(token string) steerMarkerReader { + if token == o.roleToken { + return fakeMarkerReader{login: "fullsend[bot]"} + } + return fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{ + {Author: "github-actions[bot]", Body: ""}, + }} + } + assert.True(t, runPreflightSkips(context.Background(), o, nil)) + assert.Contains(t, out.String(), "Update already absorbed by the run in flight") + }) + t.Run("a reviewed head skips", func(t *testing.T) { + o, event, out := headReviewedOpts(t) + assert.True(t, runPreflightSkips(context.Background(), o, event)) + assert.Contains(t, out.String(), "This head was already reviewed") + }) + t.Run("neither runs", func(t *testing.T) { + o, _, out := headReviewedOpts(t) + assert.False(t, runPreflightSkips(context.Background(), o, nil)) + assert.NotContains(t, out.String(), "nothing to do") + }) +} + +// TestRunAgentCallsPreflightSkipsFirst pins the call site no unit test can +// reach: runAgent calls runPreflightSkips exactly once, before it posts the +// start comment and before it runs the pre-script. +func TestRunAgentCallsPreflightSkipsFirst(t *testing.T) { + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "run.go", nil, 0) + require.NoError(t, err) + + var body *ast.BlockStmt + for _, d := range file.Decls { + if fn, ok := d.(*ast.FuncDecl); ok && fn.Name.Name == "runAgent" { + body = fn.Body + } + } + require.NotNil(t, body, "runAgent not found in run.go") + + first := map[string]token.Pos{} + count := 0 + ast.Inspect(body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + id, ok := call.Fun.(*ast.Ident) + if !ok { + return true + } + if id.Name == "runPreflightSkips" { + count++ + } + if _, seen := first[id.Name]; !seen { + first[id.Name] = call.Pos() + } + return true + }) + require.Equal(t, 1, count, "runAgent must call runPreflightSkips exactly once") + for _, later := range []string{"setupStatusNotifier", "runPreScript"} { + require.Contains(t, first, later) + assert.Less(t, first["runPreflightSkips"], first[later], + "the pre-flight skips must run before %s", later) + } +} diff --git a/internal/cli/run.go b/internal/cli/run.go index 95f2e9eed5..e0488f1a13 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -1254,6 +1254,13 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // seeded from the harness timeout once it is known, so a run that never // reaches the loop cannot read as timed out on a zero budget. var terminalElapsed, terminalBudget time.Duration + // steerMarker records what this run absorbed; the status-notification + // defer writes it onto the terminal comment so a reader can see what the + // run took in, and the receipt below claims it. It is chosen after the + // iteration loop from iterSteerMarkers, which holds each iteration's own. + var steerMarker statuscomment.SteerMarker + iterSteerMarkers := map[int]statuscomment.SteerMarker{} + // steerSeen and steerBaseline carry the judged follow-up run ids and the // delta window across validation loop iterations, so a retry neither // re-examines them nor re-sends content already delivered. @@ -1278,7 +1285,9 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep statusRepo: sOpts.statusRepo, statusNum: sOpts.statusNum, jobToken: steerJobToken, + receiptToken: steerReceiptToken(steerJobToken, envGHToken(), minted), roleToken: envGHToken(), + providersDir: providerDefsDir(absFullsendDir), runStart: runStartedAt, headSHA: runStartHeadSHA, printer: printer, @@ -1298,6 +1307,36 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep baseSteerOpts.selfLogins = logins } + // Pre-flight skips, before the start comment and before the pre-script, + // whose side effects (label changes, prior-review lookups) are not free. + if runPreflightSkips(ctx, baseSteerOpts, eventMap) { + return nil + } + + // Declared up here rather than beside lastExitCode because the receipt + // defer below closes over it: an agent that exits 0 with an error in its + // transcript has its post-script withheld, and the receipt must not + // claim work the post-script never published. + var transcriptErrorOverride bool + // Closed over by the receipt defer for the same reason: when the last + // iteration to reach extraction could not read its output back from the + // sandbox, the post-script had nothing of the agent's to publish. + var outputExtractFailed bool + + // The receipt for whatever this run absorbs. Registered here, before the + // status notifier and long before the post-script, so it runs LAST: both + // of those are defers too, and the post-script can still turn a + // successful run into a failed one. A receipt claims the work is done, + // so it must see the same final state the status comment reports, not an + // earlier guess at it. + defer func() { + if !shouldPostSteerReceipt(runErr, ctx.Err(), runSkipped, transcriptErrorOverride, + h.PostScript != "" && noPostScript, outputExtractFailed) { + return + } + postSteerReceipt(ctx, baseSteerOpts, steerMarker) + }() + // 1c. Set up status notifications (comments on the issue/PR). // Lives in the CLI layer (not harness or post-script) so it wraps the // entire run lifecycle including sandbox setup, validation loop, and @@ -1329,6 +1368,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // Set RunInfo for the completion footer. aggMetrics // is fully populated by now (after all iterations). notifier.SetRunInfo(runInfoFor(aggMetrics, h.Effort)) + notifier.SetSteerMarker(steerMarkerForStatus(status, steerMarker)) dCtx, dCancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) defer dCancel() if err := notifier.PostCompletionWithDetail(dCtx, description, status, detail); err != nil { @@ -1468,7 +1508,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // (openshell.profiles entries only). Unlisted files under // profiles/ are skipped to prevent stale overrides (#7095). - providersDir := filepath.Join(absFullsendDir, "providers") + providersDir := providerDefsDir(absFullsendDir) declared := make(map[string]struct{}, len(h.Providers)) for _, p := range h.Providers { declared[p] = struct{}{} @@ -1626,7 +1666,6 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // An inbound TRACEPARENT is adopted via the W3C propagator so the root // span continues the parent trace. var lastExitCode int - var transcriptErrorOverride bool var runCount int tracer, tracingCleanup := telemetry.Setup(runDir, Version()) tid := resolveTraceIdentity(ctx, tracer, os.Getenv("TRACEPARENT"), os.Getenv("TRACESTATE"), []attribute.KeyValue{ @@ -2330,6 +2369,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep for iteration := 1; iteration <= maxIterations; iteration++ { runCount = iteration transcriptErrorOverride = false + outputExtractFailed = false // Each iteration gets its own subdirectory for output and transcripts. iterDir := filepath.Join(runDir, fmt.Sprintf("iteration-%d", iteration)) @@ -2493,6 +2533,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // a single writer: the marker records only what the runtime // acknowledged the agent received. steerSess.stop() + iterSteerMarkers[iteration] = steerSess.marker(metrics.Steers) steerSeen = steerSess.seenRunIDs() steerObserved = steerSess.observedRuns() steerBaseline = steerSess.baseline() @@ -2619,6 +2660,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep printer.StepStart("Extracting output files") remoteSrc := fmt.Sprintf("%s/output", sandbox.SandboxWorkspace) extracted, extractErr := sandbox.ExtractOutputFiles(sandboxName, remoteSrc, iterOutputDir) + outputExtractFailed = extractErr != nil if extractErr != nil { printer.StepWarn("Failed to extract output files: " + extractErr.Error()) } else if len(extracted) == 0 { @@ -2770,6 +2812,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep repoExtractedOK = sweep.repoExtractedOK validatedIterNum = sweep.validatedIter } + steerMarker = shippedSteerMarker(iterSteerMarkers, h.ValidationLoop != nil, validatedIterNum, runCount) // Write aggregated behavioral metrics. if err := writeMetricsJSON(runDir, aggMetrics); err != nil { @@ -3013,6 +3056,50 @@ func setupFetchService(ctx context.Context, treeFetcher gitfetch.TreeFetchFunc, // Keys that don't match are skipped to prevent shell injection. var validEnvKeyRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) +// swappedAwayTokens holds the credentials minting replaced, so childScriptEnv +// can strip them wherever they appear. Written by mintAgentTokenAtLevel before +// any goroutine that reads the environment starts — the same ordering +// os.Setenv already requires there. +// +// Mints nest: a stage whose privilege level differs remints and restores +// around its script (ADR 0073), so each cleanup removes only what its own mint +// added. Clearing the whole list would drop the ORIGINAL job token while it is +// still swapped away, and a post-script inheriting a third-name copy of it +// could then sign a receipt. +var swappedAwayTokens []string + +// forgetSwappedAwayToken removes one recorded credential, restoring the list to +// what it held before the matching mint. Removes a single occurrence, so a +// remint that swapped the same value twice stays balanced. +func forgetSwappedAwayToken(v string) { + for i, t := range swappedAwayTokens { + if t == v { + swappedAwayTokens = append(swappedAwayTokens[:i], swappedAwayTokens[i+1:]...) + return + } + } +} + +// strippedByValue reports whether a value carries a credential minting swapped +// out. +// +// Containment rather than equality: a caller is as free to wrap the token in a +// header or a URL — `AUTHORIZATION=Bearer ` — as to export it bare, and +// a post-script that inherits the wrapper holds the credential just as surely. +// The recorded values are forge tokens, so a substring match costs no realistic +// false positive. +func strippedByValue(v string) bool { + if v == "" { + return false + } + for _, t := range swappedAwayTokens { + if t != "" && strings.Contains(v, t) { + return true + } + } + return false +} + // oidcDenyKeys lists OIDC credential env vars that must not leak into // user-controlled or sandbox-visible contexts. The parent harness process // retains these for mintAgentToken and OIDC token refresh; stripping them @@ -3840,13 +3927,14 @@ func postLoopValidationSweep(h *harness.Harness, runDir string, runCount int, cu } // stripOIDCEnv returns a copy of env with OIDC credential entries and -// provider-only keys removed. Use this to filter os.Environ() slices in -// contexts where childScriptEnv is not applicable (e.g., validation scripts -// that compose their env differently). See #5832, #6649. +// provider-only keys removed, and any entry holding a credential minting +// swapped out, as childScriptEnv does. Use this to filter os.Environ() slices +// in contexts where childScriptEnv is not applicable (e.g., validation +// scripts that compose their env differently). See #5832, #6649. func stripOIDCEnv(env []string) []string { result := make([]string, 0, len(env)) for _, e := range env { - if i := strings.IndexByte(e, '='); i > 0 && harnessExpansionDenied(e[:i]) { + if i := strings.IndexByte(e, '='); i > 0 && (harnessExpansionDenied(e[:i]) || strippedByValue(e[i+1:])) { continue } result = append(result, e) @@ -4514,6 +4602,12 @@ func childScriptEnv(runnerEnv map[string]string, traceparent string) []string { if i := strings.IndexByte(e, '='); i > 0 && harnessExpansionDenied(e[:i]) { continue } + // By value, not by name: minting replaces GH_TOKEN and GITHUB_TOKEN, + // but a caller is free to export the same job token under a third + // name, and a post-script holding it can sign a steer receipt. + if i := strings.IndexByte(e, '='); i > 0 && strippedByValue(e[i+1:]) { + continue + } env = append(env, e) } if traceparent != "" { @@ -6003,11 +6097,23 @@ func mintAgentTokenAtLevel(ctx context.Context, role, mintURL, forgePlatform, le // before any goroutines that read env vars (sandbox streaming, // post-script execution) are launched. originals := make(map[string]string) - envVars := []string{"GH_TOKEN"} - if v, ok := os.LookupEnv("GH_TOKEN"); ok { - originals["GH_TOKEN"] = v + // Both spellings, because the swap is what keeps the job token out of + // the sandbox and out of childScriptEnv. Replacing only GH_TOKEN leaves + // a caller-exported GITHUB_TOKEN holding the job token, which a + // post-script inherits and can sign a steer receipt with (ADR 0120). + envVars := []string{"GH_TOKEN", "GITHUB_TOKEN"} + var swappedHere []string + for _, name := range envVars { + if v, ok := os.LookupEnv(name); ok { + originals[name] = v + if v != result.Token { + swappedAwayTokens = append(swappedAwayTokens, v) + swappedHere = append(swappedHere, v) + } + } + os.Setenv(name, result.Token) } - // Preserve the Actions workflow token before GH_TOKEN is replaced so + // Preserve the Actions workflow token GH_TOKEN held before the swap so // provider credentials can authenticate to GitHub Packages. Outside // Actions leave a caller-set value alone and never derive one from a // local PAT (#6649). @@ -6048,7 +6154,6 @@ func mintAgentTokenAtLevel(ctx context.Context, role, mintURL, forgePlatform, le } } } - os.Setenv("GH_TOKEN", result.Token) for _, tv := range roleTokenVars[role] { if v, ok := os.LookupEnv(tv.Name); ok { @@ -6076,6 +6181,9 @@ func mintAgentTokenAtLevel(ctx context.Context, role, mintURL, forgePlatform, le os.Unsetenv(v) } } + for _, v := range swappedHere { + forgetSwappedAwayToken(v) + } } expiresAt := strings.Map(func(r rune) rune { @@ -6475,6 +6583,13 @@ func dedupResolvedProfiles(profiles []resolve.ResolvedProfile) []resolve.Resolve return deduped } +// providerDefsDir is where a run reads its provider definitions. The steer +// skip check scans the same directory the run provisions credentials from, +// so the two cannot drift apart. +func providerDefsDir(fullsendDir string) string { + return filepath.Join(fullsendDir, "providers") +} + // mergeProviderDefs merges local and URL-resolved provider definitions. // Local defs have highest precedence; among URL-resolved defs, last // occurrence wins (child over base). The returned slice is deterministically diff --git a/internal/cli/steer.go b/internal/cli/steer.go index 1f8472f7c8..97d42c5e83 100644 --- a/internal/cli/steer.go +++ b/internal/cli/steer.go @@ -13,7 +13,9 @@ import ( "github.com/fullsend-ai/fullsend/internal/harness" "github.com/fullsend-ai/fullsend/internal/repos" agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/fullsend-ai/fullsend/internal/statuscomment" "github.com/fullsend-ai/fullsend/internal/steerwatch" + "github.com/fullsend-ai/fullsend/internal/tracker" "github.com/fullsend-ai/fullsend/internal/ui" ) @@ -34,10 +36,15 @@ const steerTokenLife = time.Hour // blocks on the watcher. const steerTurnEndBuffer = 1 +// steerReceiptTimeout bounds the receipt post. It runs after the agent is +// done, on a context detached from the run's, so it needs its own bound. +const steerReceiptTimeout = 15 * time.Second + // steerActionsReaderFn builds the forge client the watcher lists follow-up -// runs with, and steerItemReaderFn the one it reads the work item with. -// Production gives the first the job token and the second the minted role -// token. Override in tests to return a stub instead of a live client. +// runs with, steerItemReaderFn the one it reads the work item with, and +// steerMarkerClientFn and steerReceiptClientFn the ones the skip check and +// the receipt writer use. Production gives each the token its call site is +// entitled to. Override in tests to return a stub instead of a live client. var ( // steerActionsReaderFn reads the execution platform's run records with the // JOB token — the GH_TOKEN the action passed in, which is the token @@ -49,6 +56,12 @@ var ( // needs this run's own logins to tell its own output from an update. // Override in tests to answer without a forge. steerSelfLoginFn = func(token string) steerSelfLoginReader { return newGitHubLiveClient(token, "") } + // steerMarkerClientFn reads the timeline for the skip check, and + // steerReceiptClientFn writes the receipt. Both take the JOB token: the + // receipt is authenticated by its author, and the job token's identity + // is the one nothing inside the sandbox can post as. + steerMarkerClientFn = func(token string) steerMarkerReader { return newGitHubLiveClient(token, "") } + steerReceiptClientFn = func(token string) steerReceiptWriter { return newGitHubLiveClient(token, "") } ) // steerSelfLoginReader resolves the login a credential posts under. Narrow @@ -108,13 +121,25 @@ type steerOpts struct { // jobToken is the GH_TOKEN the action passed in, captured before the // runner swapped in the minted role token. It reads the Actions API. jobToken string + // receiptToken is the credential the receipt is written and read under: + // jobToken, but only when minting swapped GH_TOKEN for a role token, and + // empty otherwise (steerReceiptToken). + // + // Separate from jobToken because reading the Actions API with a + // credential the post-script also holds costs nothing — those reads + // prove no authorship. Only the receipt's identity has to be unreachable. + receiptToken string // selfLogins are the logins this run's own output is posted under, // resolved before bootstrap by resolveSteerSelfLogins. Empty means the // run could not name its own output, which is an eligibility defect. selfLogins []string // roleToken is the minted role token; it reads the work item. roleToken string - runStart time.Time + // providersDir is the .fullsend providers/ directory this run provisions + // provider credentials from. The skip check scans every definition in it + // (steerReceiptsHonoured). + providersDir string + runStart time.Time // headSHA is the work item's head at run start when the environment // knows it. The watcher resolves it from the forge when it is empty, // along with whether the item is a pull request at all. @@ -619,3 +644,377 @@ func steerTurnEndHandler(inner func(agentruntime.AgentEvent), sess *steerSession } } } + +// steerReceiptWriter posts the receipt comment. It is the narrow surface of +// the forge client the writer needs, so a test can capture what was posted +// and under which token. +type steerReceiptWriter interface { + CreateIssueComment(ctx context.Context, owner, repo string, number int, body string) (*forge.IssueComment, error) +} + +// steerMarkerReader is the forge read surface the skip check needs: the +// login a credential posts under, and the work item's timeline to look for a +// receipt in. github.LiveClient satisfies it. +type steerMarkerReader interface { + steerSelfLoginReader + ListIssueComments(ctx context.Context, owner, repo string, number int) ([]forge.IssueComment, error) +} + +// marker returns what the run absorbed, for the terminal status comment. +// +// Only steers the runtime acknowledged count. Steer returning means the +// message was handed over, not that the agent received it: the live runtimes +// ack afterwards (Claude's replay echo, pi's response) and Codex when the +// resumed process starts, and the runtime records each ack in +// RunMetrics.Steers. If the runtime dies between the hand-off and the ack, a +// marker built from attempts would tell the queued run its work was already +// done and the update would be lost outright — so an unacknowledged delivery +// is left out and the queued run does the work. +func (s *steerSession) marker(acked []agentruntime.SteerResult) statuscomment.SteerMarker { + if s == nil { + return statuscomment.SteerMarker{} + } + return steerMarkerFrom(s.watcher.Delivered(), s.watcher.Head(), acked) +} + +// steerMarkerFrom intersects what the watcher handed to the runtime with what +// the runtime acknowledged. One message can carry several follow-up runs, +// since a poll folds simultaneous candidates together, so the ack for a +// message id vouches for its whole batch. +// +// The watcher is loss-free only because of this intersection: a Steer that +// returns nil is accepted, not delivered, so treating the watcher's handed-off +// set as consumed would receipt an update the agent never saw and the queued +// run would skip it. TestSteerMarkerFrom_OnlyAcknowledgedDeliveriesCount and +// TestSteerMarkerFrom_NoAcksMeansNoMarkerEntries pin that coupling. +func steerMarkerFrom(delivered []steerwatch.DeliveredSteer, head string, acked []agentruntime.SteerResult) statuscomment.SteerMarker { + ackedIDs := make(map[int64]bool, len(acked)) + for _, r := range acked { + ackedIDs[r.FollowUpRunID] = true + } + + var consumed []int64 + for _, batch := range delivered { + if !ackedIDs[batch.MessageID] { + continue + } + consumed = append(consumed, batch.RunIDs...) + } + return statuscomment.SteerMarker{ConsumedRunIDs: consumed, HeadSHA: head} +} + +// steerAlreadyHandled reports whether an earlier run already absorbed the +// follow-up run that dispatched me (ADR 0113). +// +// Dispatch is never suppressed while a run is in flight: a route arm that +// skipped whenever something was running would lose a steer that lands after +// the in-flight run's last check. Instead the in-flight run posts a receipt +// comment under the job token, and this check reads that. A missed receipt +// costs one redundant run, and for review that is a full review of the same +// head. +// +// The receipt is a SEPARATE comment, and the copy of the marker on the +// terminal status comment is informational only: that comment is App-authored, +// the identity the agent's own output goes out under, so honouring it would +// let an injection compose its own receipt (ADR 0120). +// +// It fails open in every direction — no receipt, an unreadable timeline, an +// unresolvable login — because a false "already handled" silently drops the +// work, while a false "not handled" costs one run. +func steerAlreadyHandled(ctx context.Context, receiptReader, roleReader steerMarkerReader, repo string, number int, myRunID int64) (bool, error) { + if receiptReader == nil || roleReader == nil || myRunID == 0 || number <= 0 { + return false, nil + } + owner, name, ok := strings.Cut(repo, "/") + if !ok || owner == "" || name == "" { + return false, fmt.Errorf("status repo %q is not in owner/repo form", repo) + } + + // The marker means nothing unless the runner's own receipt credential + // wrote it. Any user can paste the HTML into a comment of their own, and + // so can an agent — whose output posts under the role token's identity. + // Both logins are resolved from their tokens rather than hardcoded: they + // differ between github.com and GHES. + receiptLogin, err := receiptReader.GetAuthenticatedUser(ctx) + if err != nil { + return false, fmt.Errorf("resolving the receipt login: %w", err) + } + roleLogin, err := roleReader.GetAuthenticatedUser(ctx) + if err != nil { + return false, fmt.Errorf("resolving the role login: %w", err) + } + // The whole control is that the agent cannot post as the receipt author. + // If the two credentials resolve to the SAME login that is simply untrue + // — the agent's own comments would pass — and no amount of checking the + // author can tell them apart. It is not hypothetical: the action's + // github_token input is a caller-supplied default, so a consumer can + // hand the runner the same App installation token the role resolves to. + // Refuse to skip, which costs one redundant run; honouring it would drop + // the update instead. + if strings.EqualFold(receiptLogin, roleLogin) { + return false, fmt.Errorf( + "the receipt credential and the agent's own credential are the same identity (%s), "+ + "so a receipt proves nothing about who wrote it", receiptLogin) + } + + comments, err := receiptReader.ListIssueComments(ctx, owner, name, number) + if err != nil { + return false, fmt.Errorf("listing comments on %s#%d: %w", repo, number, err) + } + + tcomments := make([]tracker.Comment, 0, len(comments)) + for _, cm := range comments { + // An edited comment is not a receipt. Editing keeps the author, and + // any identity with write access can edit another's comment, so the + // body now on it is not the one the job token wrote. The runner + // never edits a receipt. Dropping it can only make the queued run + // do the work (ADR 0120). + if cm.UpdatedAt != cm.CreatedAt { + continue + } + tcomments = append(tcomments, tracker.Comment{ + ID: strconv.Itoa(cm.ID), + Body: tracker.Body(cm.Body), + Author: cm.Author, + CreatedAt: cm.CreatedAt, + }) + } + + marker, found := statuscomment.LatestSteerMarker(tcomments, receiptLogin) + if !found { + return false, nil + } + return marker.Consumed(myRunID), nil +} + +// checkSteerAlreadyHandled runs the skip check and reports whether this run +// should exit without starting the agent. A failure is warned about and +// treated as "not handled". +func checkSteerAlreadyHandled(ctx context.Context, o steerOpts) bool { + if !o.harness.SteerEnabled() || os.Getenv("GITHUB_ACTIONS") != "true" { + return false + } + // GitLab has no equivalent: its job token cannot post or read notes, so + // there is no receipt to authenticate and the check stays fail-open — + // the queued pipeline does the work, exactly as it does today. + if o.forgePlatform == repos.ForgeGitLab || o.statusRepo == "" || o.statusNum <= 0 || o.receiptToken == "" || o.roleToken == "" { + return false + } + // A manual re-run keeps its run id, so a receipt that consumed the first + // attempt would skip it again. A person asked for the work; it runs. + if a := os.Getenv("GITHUB_RUN_ATTEMPT"); a != "" && a != "1" { + o.printer.StepInfo("Not skipping on a steer receipt: run attempt " + a + " is a manual re-run") + return false + } + if ok, reason := steerReceiptsHonoured(o.providersDir); !ok { + o.printer.StepInfo("Not skipping on a steer receipt: " + reason) + return false + } + handled, err := steerAlreadyHandled(ctx, steerMarkerClientFn(o.receiptToken), steerMarkerClientFn(o.roleToken), + o.statusRepo, o.statusNum, steerRunID()) + if err != nil { + o.printer.StepWarn("Could not check whether this update was already handled: " + err.Error()) + return false + } + return handled +} + +// steerReceiptsHonoured reports whether a receipt can be trusted in this +// repository, and why not when it cannot. +// +// A receipt is authenticated only by its author being the job token's login. +// A provider credential that expands GH_WORKFLOW_TOKEN hands that token to a +// sandbox, where the agent can recover it (ADR 0114) and post a receipt of +// its own. Every job in the repository posts as the same login, so a +// definition any harness uses is enough, not only this run's: the scan covers +// every file in providersDir, not the ones this harness declares. +// +// A missing directory holds no definitions. Anything unreadable refuses, +// because a false skip drops work and a false run costs one run. +func steerReceiptsHonoured(providersDir string) (bool, string) { + if providersDir == "" { + return false, "provider definitions location unknown" + } + defs, err := harness.LoadProviderDefs(providersDir) + if err != nil { + return false, "provider definitions unreadable: " + err.Error() + } + for _, def := range defs { + for _, v := range def.Credentials { + if expandsWorkflowToken(v) { + return false, fmt.Sprintf("provider %q delivers %s to a sandbox (ADR 0114)", def.Name, workflowTokenEnv) + } + } + } + return true, "" +} + +// expandsWorkflowToken reports whether a provider credential value reads the +// workflow token under either ${VAR} or $VAR form, the way expansion does. +func expandsWorkflowToken(v string) bool { + found := false + os.Expand(v, func(k string) string { + if k == workflowTokenEnv { + found = true + } + return "" + }) + return found +} + +// steerMarkerForStatus returns the marker to write on the terminal status +// comment for a run that ended with the given status. +// +// This marker is informational — the skip check reads the job-token receipt, +// never an App-authored status comment (ADR 0120). It still rides only on a +// successful run, because it reports what the run's published output covered: +// a run that absorbed an update and then failed, timed out, was cancelled or +// was skipped produced no such output, and saying otherwise would misinform +// the person reading the comment. Validation failure arrives here as a +// "failure" status, because an unvalidated run returns an error, so it is +// covered by the same rule. +func steerMarkerForStatus(status string, m statuscomment.SteerMarker) statuscomment.SteerMarker { + if status != "success" { + return statuscomment.SteerMarker{} + } + return m +} + +// steerReceiptToken returns the credential the receipt may be written and +// read under: the job token, but only when minting actually swapped it out. +// +// The swap is what puts the credential beyond the sandbox: minting replaces +// GH_TOKEN with the role token before the sandbox exists. With no mint URL +// or no role there is no swap, the same token stays in os.Environ() for +// childScriptEnv to hand the post-script, and a post-script shelling out to +// `gh` could sign a receipt. +// +// roleToken is read from GH_TOKEN after minting, so comparing the two +// catches an absent swap directly rather than trusting `minted`. +// +// Empty otherwise, which turns the writer and the skip check off and leaves +// the queued run to do the work. +func steerReceiptToken(jobToken, roleToken string, minted bool) string { + if !minted || jobToken == "" || jobToken == roleToken { + return "" + } + return jobToken +} + +// shouldPostSteerReceipt reports whether a finished run may claim a receipt. +// +// Only an outright success may. A receipt tells the run queued behind this +// one that the work is done, so claiming it for a run that failed, was +// cancelled, or was skipped would silently drop the update rather than +// merely waste it — the one direction the skip check must never fail in. +// +// A receipt has to mean the output was published, so the remaining +// arguments are ways a successful run can publish nothing. +// agentReportedError is where this is stricter than the terminal status +// comment: a run whose agent exited 0 with an error in its transcript has its +// post-script skipped, and without a validation loop nothing turns that into +// a non-nil runErr, so the status comment reports success. +// postScriptWithheld is `--no-post-script` on a harness that configures one. +// The flag is deliberately not a workflow input, so this cannot happen on a +// run that mints — but the receipt's correctness must not rest on that +// staying true. +// outputExtractFailed is the last extracted iteration's output not being +// read back from the sandbox. A post-script that tolerates missing output then exits 0 +// having published nothing of the agent's. An output directory that was read +// and found empty is not this case. +func shouldPostSteerReceipt(runErr, ctxErr error, runSkipped, agentReportedError, postScriptWithheld, outputExtractFailed bool) bool { + return runErr == nil && ctxErr == nil && !runSkipped && !agentReportedError && !postScriptWithheld && + !outputExtractFailed +} + +// postSteerReceipt writes the run's receipt as its own comment on the work +// item, under the receipt credential. +// +// It is a separate comment rather than the status comment's marker because +// the status comment is posted by the App, the identity the agent's own +// output goes out under, so a marker there authenticates two public strings +// rather than the code path that wrote them. +// +// Best-effort by design: a failure here costs one queued run that redoes +// work already done, where failing the run would throw away work that +// succeeded. +// +// Called only for a successful run, and once per run rather than once per +// steer — the marker is the shipped iteration's (see shippedSteerMarker). +func postSteerReceipt(ctx context.Context, o steerOpts, m statuscomment.SteerMarker) { + if o.forgePlatform == repos.ForgeGitLab || o.statusRepo == "" || o.statusNum <= 0 || o.receiptToken == "" { + return + } + // At least one absorbed run, not merely a renderable marker. The marker + // is non-empty for a head-only run too — the head is worth recording on + // the status comment — but a receipt asserts that a queued run's work is + // already done, and a run that absorbed nothing has nothing to assert. + // Without this every successful run on a steering-enabled repository + // posts a comment saying so. + ids := m.ConsumedRuns() + if len(ids) == 0 { + return + } + marker := statuscomment.BuildSteerMarker(m) + if marker == "" { + return + } + owner, name, ok := strings.Cut(o.statusRepo, "/") + if !ok || owner == "" || name == "" { + o.printer.StepWarn(fmt.Sprintf("Not posting the steer receipt: status repo %q is not in owner/repo form", o.statusRepo)) + return + } + + postCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), steerReceiptTimeout) + defer cancel() + created, err := steerReceiptClientFn(o.receiptToken).CreateIssueComment( + postCtx, owner, name, o.statusNum, marker+"\n"+steerReceiptLine(ids)) + if err != nil { + o.printer.StepWarn("Failed to post the steer receipt; the queued run will redo this work: " + err.Error()) + return + } + // The author is logged because it is the string the next run's skip + // check has to match: that check resolves the same token's login through + // the API, and if the two ever disagree every receipt is silently + // ignored — safe, but useless, and invisible without this line. + // created is non-nil from the live client whenever err is nil, but the + // interface does not promise it and this path is documented + // best-effort: a nil dereference here would panic out of a defer and + // take down a run that had already succeeded. + if created == nil { + o.printer.StepDone("Posted the steer receipt") + return + } + o.printer.StepDone(fmt.Sprintf("Posted the steer receipt as %s", created.Author)) +} + +// steerReceiptLine is the human half of the receipt. The marker above it is +// what the queued run reads; this is what a person scrolling the item sees. +// Never called with an empty list: a run that absorbed nothing posts no +// receipt at all. +func steerReceiptLine(consumed []int64) string { + ids := make([]string, 0, len(consumed)) + for _, id := range consumed { + ids = append(ids, strconv.FormatInt(id, 10)) + } + return fmt.Sprintf( + "_The run already working on this item absorbed follow-up run(s) %s, so a run queued for those events exits without repeating the work._", + strings.Join(ids, ", ")) +} + +// shippedSteerMarker returns the receipts of the iteration whose output the +// run ships: the validated iteration when there is a validation loop, the +// last one otherwise — the same choice postScriptRepoEnv makes. +// +// Receipts are not unioned across iterations. A retry starts from a fresh +// prompt and transcript, and the watcher does not re-deliver runs an earlier +// iteration judged, so an update absorbed by an iteration that failed +// validation never reaches the output that ships. Its receipt would tell the +// run queued behind this one to skip that update. Without it, the queued run +// does the work again, which costs a run but loses nothing. +func shippedSteerMarker(byIteration map[int]statuscomment.SteerMarker, validationLoop bool, validatedIter, lastIter int) statuscomment.SteerMarker { + if validationLoop { + return byIteration[validatedIter] + } + return byIteration[lastIter] +} diff --git a/internal/cli/steer_test.go b/internal/cli/steer_test.go index cbb5ba65d5..3e1e047548 100644 --- a/internal/cli/steer_test.go +++ b/internal/cli/steer_test.go @@ -12,6 +12,7 @@ import ( "net/http/httptest" "os" "os/exec" + "path/filepath" "strings" "testing" "time" @@ -21,9 +22,11 @@ import ( "github.com/fullsend-ai/fullsend/internal/forge" "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/fullsend-ai/fullsend/internal/mintclient" "github.com/fullsend-ai/fullsend/internal/repos" agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" "github.com/fullsend-ai/fullsend/internal/sandbox" + "github.com/fullsend-ai/fullsend/internal/statuscomment" "github.com/fullsend-ai/fullsend/internal/steerwatch" "github.com/fullsend-ai/fullsend/internal/ui" ) @@ -61,6 +64,8 @@ func baseOpts(t *testing.T) steerOpts { t.Helper() t.Setenv("GITHUB_ACTIONS", "true") t.Setenv("GITHUB_RUN_ID", "33740015232") + // A re-run CI job sets its own attempt; these fixtures are a first run. + t.Setenv("GITHUB_RUN_ATTEMPT", "1") // A CI runner sets its own GITHUB_JOB; tests that need one set it. t.Setenv("GITHUB_JOB", "") return steerOpts{ @@ -70,7 +75,10 @@ func baseOpts(t *testing.T) steerOpts { statusRepo: "org/repo", statusNum: 7, jobToken: "job-token", + receiptToken: "job-token", roleToken: "role-token", + // Missing, so it holds no provider definitions and receipts count. + providersDir: filepath.Join(t.TempDir(), "providers"), // Resolved before bootstrap on a real run; the watcher refuses to // start without them, so an eligible fixture carries them. selfLogins: []string{"fullsend-ai-coder[bot]", "org-review[bot]"}, @@ -1228,3 +1236,972 @@ func TestSteerDeclineAnnounced(t *testing.T) { assert.True(t, steerDecline{reason: "pi falls back", announce: true}.announced(implicit)) assert.True(t, steerDecline{reason: "not in GitHub Actions"}.announced(steerHarness(true))) } + +// roleReader is the client the skip check resolves the AGENT's identity +// with. It is a different login from the receipt author in every test that +// expects a skip, because that difference is the entire control. +func roleReader() steerMarkerReader { return fakeMarkerReader{login: "fullsend[bot]"} } + +// withFakeReceiptWriter swaps the receipt client for one that records the +// token it was handed, and restores the original afterwards. +func withFakeReceiptWriter(t *testing.T) *fakeReceiptWriter { + t.Helper() + f := &fakeReceiptWriter{} + prev := steerReceiptClientFn + steerReceiptClientFn = func(token string) steerReceiptWriter { + f.token = token + return f + } + t.Cleanup(func() { steerReceiptClientFn = prev }) + return f +} + +func receiptOpts() steerOpts { + return steerOpts{ + forgePlatform: "github", + statusRepo: "org/repo", + statusNum: 7, + jobToken: "job-token", + receiptToken: "job-token", + roleToken: "role-token", + printer: ui.New(io.Discard), + } +} + +type nilReturningWriter struct{} + +func (nilReturningWriter) CreateIssueComment(context.Context, string, string, int, string) (*forge.IssueComment, error) { + return nil, nil +} + +// terminalStatusBody wraps a marker in a terminal status comment — the +// App-authored shape the skip check must NOT honour, which is what the +// cases using it assert. +func terminalStatusBody(marker string) string { + return "\n\n" + + marker + "\n🤖 Finished Review" +} + +// fakeMarkerReader serves the skip check's two reads. +type fakeMarkerReader struct { + login string + loginErr error + comments []forge.IssueComment + listErr error +} + +func (f fakeMarkerReader) GetAuthenticatedUser(context.Context) (string, error) { + return f.login, f.loginErr +} + +func (f fakeMarkerReader) ListIssueComments(context.Context, string, string, int) ([]forge.IssueComment, error) { + return f.comments, f.listErr +} + +// fakeReceiptWriter captures what the receipt writer posted, and the token +// the client was built with. +type fakeReceiptWriter struct { + token string + owner string + repo string + number int + bodies []string + err error +} + +func (f *fakeReceiptWriter) CreateIssueComment(_ context.Context, owner, repo string, number int, body string) (*forge.IssueComment, error) { + if f.err != nil { + return nil, f.err + } + f.owner, f.repo, f.number = owner, repo, number + f.bodies = append(f.bodies, body) + return &forge.IssueComment{ID: 1, Author: "github-actions[bot]", Body: body}, nil +} + +func TestSteerAlreadyHandled(t *testing.T) { + const myRun = int64(999) + + tests := []struct { + name string + c steerMarkerReader + want bool + }{ + { + name: "my run is listed in a receipt the job token posted", + c: fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{ + {Author: "github-actions[bot]", Body: ""}, + }}, + want: true, + }, + { + name: "a receipt that does not list my run", + c: fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{ + {Author: "github-actions[bot]", Body: ""}, + }}, + want: false, + }, + { + name: "a marker forged by a user is ignored", + c: fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{ + {Author: "attacker", Body: terminalStatusBody("")}, + }}, + want: false, + }, + { + name: "no marker at all", + c: fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{{Author: "github-actions[bot]", Body: "hello"}}}, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := steerAlreadyHandled(context.Background(), tt.c, roleReader(), "org/repo", 7, myRun) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +// TestSteerAlreadyHandled_SameIdentityNeverSkips covers the case where the +// receipt credential and the agent's own credential resolve to one login. +// The action's github_token input is a caller-supplied default, so a +// consumer can hand the runner the same App token the role resolves to — +// and then the agent's own comments carry the trusted author. The receipt +// below is otherwise perfect. +func TestSteerAlreadyHandled_SameIdentityNeverSkips(t *testing.T) { + const myRun = int64(999) + same := fakeMarkerReader{ + login: "fullsend[bot]", + comments: []forge.IssueComment{ + {Author: "fullsend[bot]", Body: ""}, + }, + } + + got, err := steerAlreadyHandled(context.Background(), same, fakeMarkerReader{login: "fullsend[bot]"}, + "org/repo", 7, myRun) + + require.Error(t, err, "the collision must be reported, not passed over in silence") + assert.Contains(t, err.Error(), "same identity") + assert.False(t, got, "a receipt the agent could have written must never suppress a queued run") +} + +// TestSteerAlreadyHandled_SameIdentityIsCaseInsensitive: forge logins are +// case-insensitive, so a comparison that is not would be trivially evaded. +func TestSteerAlreadyHandled_SameIdentityIsCaseInsensitive(t *testing.T) { + same := fakeMarkerReader{ + login: "FullSend[Bot]", + comments: []forge.IssueComment{ + {Author: "FullSend[Bot]", Body: ""}, + }, + } + got, err := steerAlreadyHandled(context.Background(), same, fakeMarkerReader{login: "fullsend[bot]"}, + "org/repo", 7, 999) + require.Error(t, err) + assert.False(t, got) +} + +// TestSteerReceiptToken: the receipt's claim is that the sandbox could not +// have written it, and only the minting swap makes that true. Without it the +// captured credential is still in the environment the post-script inherits. +func TestSteerReceiptToken(t *testing.T) { + assert.Equal(t, "job-token", steerReceiptToken("job-token", "role-token", true)) + assert.Empty(t, steerReceiptToken("job-token", "role-token", false), + "an unswapped job token is reachable from the post-script") + // roleToken is read from GH_TOKEN after minting, so equality proves no + // swap happened whatever `minted` claims. + assert.Empty(t, steerReceiptToken("same", "same", true), + "a job token identical to the role token was never swapped out") + assert.Empty(t, steerReceiptToken("", "role-token", true)) +} + +// TestPostSteerReceipt_NotWhenTheCredentialIsSharedWithTheAgent is the +// writer half of the review's Medium: with minting skipped, roleToken is +// read from the same GH_TOKEN the job token was captured from, so the two +// are equal byte for byte and the agent's own environment holds the +// receipt credential. +func TestPostSteerReceipt_NotWhenTheCredentialIsSharedWithTheAgent(t *testing.T) { + f := withFakeReceiptWriter(t) + o := receiptOpts() + o.jobToken = "shared" + o.roleToken = "shared" + o.receiptToken = steerReceiptToken(o.jobToken, o.roleToken, true) + + postSteerReceipt(context.Background(), o, statuscomment.SteerMarker{ConsumedRunIDs: []int64{101}}) + + assert.Empty(t, f.bodies, "a credential the agent also holds must not sign a receipt") +} + +// TestSteerAlreadyHandled_AppAuthoredReceiptDoesNotSkip is fullsend#7006's +// validation criterion, stated as it is in the issue: a syntactically +// perfect receipt posted through the App by any path available inside the +// sandbox must not cause a queued run to skip. +// +// Every string here is right — the status tags, the terminal tag, the marker, +// the run id. Only the author differs, and that is now the whole of the +// check: the App is the identity the agent's own output is posted under, via +// a post-script shelling out to `gh` or any other path that reaches the role +// token. Nothing in the sandbox holds the job token. +func TestSteerAlreadyHandled_AppAuthoredReceiptDoesNotSkip(t *testing.T) { + const myRun = int64(999) + c := fakeMarkerReader{ + login: "github-actions[bot]", + comments: []forge.IssueComment{ + {Author: "fullsend[bot]", Body: terminalStatusBody("")}, + }, + } + + got, err := steerAlreadyHandled(context.Background(), c, roleReader(), "org/repo", 7, myRun) + require.NoError(t, err) + assert.False(t, got, "a receipt the sandbox could have produced must never suppress a queued run") +} + +// TestSteerAlreadyHandled_JobTokenReceiptSkips is the other half of the same +// criterion: the genuine article still works. +func TestSteerAlreadyHandled_JobTokenReceiptSkips(t *testing.T) { + const myRun = int64(999) + c := fakeMarkerReader{ + login: "github-actions[bot]", + comments: []forge.IssueComment{ + {Author: "github-actions[bot]", Body: "\n_absorbed_"}, + }, + } + + got, err := steerAlreadyHandled(context.Background(), c, roleReader(), "org/repo", 7, myRun) + require.NoError(t, err) + assert.True(t, got) +} + +// TestPostSteerReceipt_UsesTheJobToken pins the credential. The role token is +// the one the sandbox holds, so a receipt posted with it would be forgeable +// by the agent it is meant to be protected from. +func TestPostSteerReceipt_UsesTheJobToken(t *testing.T) { + f := withFakeReceiptWriter(t) + + postSteerReceipt(context.Background(), receiptOpts(), + statuscomment.SteerMarker{ConsumedRunIDs: []int64{101, 102}, HeadSHA: "abc"}) + + assert.Equal(t, "job-token", f.token) + assert.NotEqual(t, "role-token", f.token) + assert.Equal(t, "org", f.owner) + assert.Equal(t, "repo", f.repo) + assert.Equal(t, 7, f.number) + require.Len(t, f.bodies, 1, "one receipt per run, not one per steer") + assert.Contains(t, f.bodies[0], "") + assert.Contains(t, f.bodies[0], "101, 102", "the human line names the runs") +} + +// TestPostSteerReceipt_OnePerRun: one receipt per run, not one per steer, +// and it carries the marker of the iteration whose output actually shipped. +// +// Receipts are deliberately not unioned across iterations. An update +// absorbed by an iteration that then failed validation never reached the +// output that ships, so receipting it would tell the queued run to skip work +// nobody published — see shippedSteerMarker. Here iteration 1 absorbed 101 +// and lost validation; only iteration 2's run is receipted. +func TestPostSteerReceipt_OnePerRun(t *testing.T) { + f := withFakeReceiptWriter(t) + + byIteration := map[int]statuscomment.SteerMarker{ + 1: {ConsumedRunIDs: []int64{101}, HeadSHA: "aaa"}, + 2: {ConsumedRunIDs: []int64{102}, HeadSHA: "bbb"}, + } + postSteerReceipt(context.Background(), receiptOpts(), + shippedSteerMarker(byIteration, true, 2, 2)) + + require.Len(t, f.bodies, 1) + assert.Contains(t, f.bodies[0], "consumed=102 head=bbb") + assert.NotContains(t, f.bodies[0], "101", + "an iteration that lost validation shipped nothing, so its runs are not receipted") +} + +// TestPostSteerReceipt_NotForAHeadOnlyMarker is the regression for the +// review finding: steerMarkerFrom always sets HeadSHA, and BuildSteerMarker +// renders a head-only marker, so gating the post on "the marker string is +// non-empty" posted a receipt after EVERY successful run — one comment per +// run on every steering-enabled repository, saying nothing was absorbed. +func TestPostSteerReceipt_NotForAHeadOnlyMarker(t *testing.T) { + f := withFakeReceiptWriter(t) + + postSteerReceipt(context.Background(), receiptOpts(), + statuscomment.SteerMarker{HeadSHA: "abc123"}) + + assert.Empty(t, f.bodies, "a run that absorbed nothing has nothing to receipt") +} + +// TestPostSteerReceipt_NotForUnusableRunIDs: ids the marker would drop do +// not count as absorbing anything either. +func TestPostSteerReceipt_NotForUnusableRunIDs(t *testing.T) { + f := withFakeReceiptWriter(t) + + postSteerReceipt(context.Background(), receiptOpts(), + statuscomment.SteerMarker{ConsumedRunIDs: []int64{0, -1}, HeadSHA: "abc123"}) + + assert.Empty(t, f.bodies) +} + +// TestPostSteerReceipt_NotWithoutTheMintSwap: with no minting the captured +// job token is still in the environment the post-script inherits, so it is +// not an identity the sandbox lacks and must not sign a receipt. +func TestPostSteerReceipt_NotWithoutTheMintSwap(t *testing.T) { + f := withFakeReceiptWriter(t) + o := receiptOpts() + o.receiptToken = steerReceiptToken(o.jobToken, o.roleToken, false) + + postSteerReceipt(context.Background(), o, statuscomment.SteerMarker{ConsumedRunIDs: []int64{101}}) + + assert.Empty(t, f.bodies) +} + +func TestPostSteerReceipt_NotWhenNothingConsumed(t *testing.T) { + f := withFakeReceiptWriter(t) + postSteerReceipt(context.Background(), receiptOpts(), statuscomment.SteerMarker{}) + assert.Empty(t, f.bodies, "a run that absorbed nothing has nothing to receipt") +} + +func TestPostSteerReceipt_SkippedWithoutAJobToken(t *testing.T) { + f := withFakeReceiptWriter(t) + o := receiptOpts() + o.receiptToken = "" + postSteerReceipt(context.Background(), o, statuscomment.SteerMarker{ConsumedRunIDs: []int64{101}}) + assert.Empty(t, f.bodies) +} + +// TestPostSteerReceipt_GitLabPostsNothing: the GitLab job token cannot post +// notes, so there is no receipt to write and the skip check stays fail-open. +func TestPostSteerReceipt_GitLabPostsNothing(t *testing.T) { + f := withFakeReceiptWriter(t) + o := receiptOpts() + o.forgePlatform = "gitlab" + postSteerReceipt(context.Background(), o, statuscomment.SteerMarker{ConsumedRunIDs: []int64{101}}) + assert.Empty(t, f.bodies) +} + +// TestPostSteerReceipt_NilCommentDoesNotPanic: this path runs inside a +// defer on an already-successful run, so a nil dereference would take that +// run down. The live client never returns (nil, nil), but the interface +// this code depends on does not promise it. +func TestPostSteerReceipt_NilCommentDoesNotPanic(t *testing.T) { + prev := steerReceiptClientFn + t.Cleanup(func() { steerReceiptClientFn = prev }) + steerReceiptClientFn = func(string) steerReceiptWriter { return nilReturningWriter{} } + + assert.NotPanics(t, func() { + postSteerReceipt(context.Background(), receiptOpts(), + statuscomment.SteerMarker{ConsumedRunIDs: []int64{101}}) + }) +} + +// TestPostSteerReceipt_FailureIsBestEffort: a failed post costs one queued +// run that redoes finished work. Failing the run instead would throw away +// work that succeeded. +func TestPostSteerReceipt_FailureIsBestEffort(t *testing.T) { + f := withFakeReceiptWriter(t) + f.err = errors.New("403 Resource not accessible by integration") + + assert.NotPanics(t, func() { + postSteerReceipt(context.Background(), receiptOpts(), + statuscomment.SteerMarker{ConsumedRunIDs: []int64{101}}) + }) + assert.Empty(t, f.bodies) +} + +// TestShouldPostSteerReceipt: a receipt claims the work is done, so only an +// outright success may leave one. Every other outcome would turn a wasted +// run into a dropped update. +func TestShouldPostSteerReceipt(t *testing.T) { + assert.True(t, shouldPostSteerReceipt(nil, nil, false, false, false, false)) + assert.False(t, shouldPostSteerReceipt(errors.New("agent failed"), nil, false, false, false, false), "failure") + assert.False(t, shouldPostSteerReceipt(nil, context.Canceled, false, false, false, false), "cancellation") + assert.False(t, shouldPostSteerReceipt(nil, nil, true, false, false, false), "skipped") + assert.False(t, shouldPostSteerReceipt(nil, nil, false, false, false, true), "output not read back") +} + +// TestShouldPostSteerReceipt_WithheldPostScriptPublishesNothing covers +// --no-post-script on a harness that configures one. The run succeeds and the +// agent reports no error, so every other gate passes, but the step that +// publishes the work never ran — receipting it would tell the queued run to +// skip work nobody shipped. +func TestShouldPostSteerReceipt_WithheldPostScriptPublishesNothing(t *testing.T) { + assert.False(t, shouldPostSteerReceipt(nil, nil, false, false, true, false), + "a run whose post-script was withheld published nothing to receipt") +} + +// TestShouldPostSteerReceipt_TranscriptErrorWithheldTheOutput is the review's +// critical finding. An agent that exits 0 while its transcript reports an +// error has its post-script skipped — and the post-script is what publishes +// the work. With no validation loop nothing turns that into a non-nil +// runErr, so every other condition here reads like a clean success: the +// status comment says so too, and always has. +// +// For a status comment that is survivable, because it only reports. A +// receipt instructs the queued run to do nothing, so the same state would +// drop the update instead of merely wasting a run — the one direction this +// check must never fail in. +func TestShouldPostSteerReceipt_TranscriptErrorWithheldTheOutput(t *testing.T) { + assert.False(t, shouldPostSteerReceipt(nil, nil, false, true, false, false), + "the post-script was withheld, so nothing was published to receipt") +} + +// TestShouldPostSteerReceipt_UnreadOutputPublishedNothing: the sandbox left +// Ready after the agent finished, so its output was never read back. A +// post-script that tolerates missing output exits 0 and the run succeeds, +// yet nothing of the agent's was published. An output directory that was +// read and found empty stays eligible — the post-script judges that case. +func TestShouldPostSteerReceipt_UnreadOutputPublishedNothing(t *testing.T) { + assert.False(t, shouldPostSteerReceipt(nil, nil, false, false, false, true), + "the output was never read back, so nothing was published to receipt") +} + +// TestRunAgentReceiptSeesTheOutputExtraction pins what no unit test can reach +// inside runAgent: the receipt defer passes outputExtractFailed, and inside +// the iteration loop the flag is reset once and then assigned from the output +// extraction's error, in that order. The receipt therefore sees the last +// iteration that reached extraction. +func TestRunAgentReceiptSeesTheOutputExtraction(t *testing.T) { + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "run.go", nil, 0) + require.NoError(t, err) + + var body *ast.BlockStmt + for _, d := range file.Decls { + if fn, ok := d.(*ast.FuncDecl); ok && fn.Name.Name == "runAgent" { + body = fn.Body + } + } + require.NotNil(t, body, "runAgent not found in run.go") + + passed := false + var loops []*ast.ForStmt + var resets, sets []*ast.AssignStmt + ast.Inspect(body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.ForStmt: + loops = append(loops, x) + case *ast.CallExpr: + if id, ok := x.Fun.(*ast.Ident); ok && id.Name == "shouldPostSteerReceipt" { + last, ok := x.Args[len(x.Args)-1].(*ast.Ident) + passed = ok && last.Name == "outputExtractFailed" + } + case *ast.AssignStmt: + lhs, ok := x.Lhs[0].(*ast.Ident) + if !ok || lhs.Name != "outputExtractFailed" { + return true + } + switch rhs := x.Rhs[0].(type) { + case *ast.Ident: + if rhs.Name == "false" { + resets = append(resets, x) + } + case *ast.BinaryExpr: + errID, okX := rhs.X.(*ast.Ident) + nilID, okY := rhs.Y.(*ast.Ident) + if okX && okY && errID.Name == "extractErr" && rhs.Op == token.NEQ && nilID.Name == "nil" { + sets = append(sets, x) + } + } + require.Equal(t, token.ASSIGN, x.Tok, "outputExtractFailed must be assigned, not redeclared") + } + return true + }) + require.True(t, passed, "the receipt defer must pass outputExtractFailed to shouldPostSteerReceipt") + require.Len(t, resets, 1, "outputExtractFailed must be reset exactly once") + require.Len(t, sets, 1, "outputExtractFailed must be assigned extractErr != nil exactly once") + + var loop *ast.ForStmt + for _, l := range loops { + if l.Body.Pos() <= sets[0].Pos() && sets[0].End() <= l.Body.End() && + (loop == nil || l.Pos() > loop.Pos()) { + loop = l + } + } + require.NotNil(t, loop, "the extraction assignment must sit inside the iteration loop") + assert.True(t, loop.Body.Pos() <= resets[0].Pos() && resets[0].End() <= loop.Body.End(), + "the reset must sit inside the same loop as the extraction assignment") + assert.Less(t, resets[0].Pos(), sets[0].Pos(), "the reset must come before the extraction assignment") +} + +// The check must fail open in every direction: a false "already handled" +// silently drops the work, a false "not handled" costs one run. +func TestSteerAlreadyHandled_FailsOpen(t *testing.T) { + t.Run("nil client", func(t *testing.T) { + got, err := steerAlreadyHandled(context.Background(), nil, roleReader(), "org/repo", 7, 999) + require.NoError(t, err) + assert.False(t, got) + }) + + t.Run("no run id", func(t *testing.T) { + got, err := steerAlreadyHandled(context.Background(), fakeMarkerReader{}, roleReader(), "org/repo", 7, 0) + require.NoError(t, err) + assert.False(t, got) + }) + + t.Run("malformed repo", func(t *testing.T) { + _, err := steerAlreadyHandled(context.Background(), fakeMarkerReader{}, roleReader(), "norepo", 7, 999) + require.Error(t, err) + }) + + t.Run("the receipt login cannot be resolved", func(t *testing.T) { + _, err := steerAlreadyHandled(context.Background(), + fakeMarkerReader{loginErr: errors.New("403")}, roleReader(), "org/repo", 7, 999) + require.Error(t, err) + }) + + t.Run("the role login cannot be resolved", func(t *testing.T) { + // Without it the two identities cannot be shown to differ, and that + // difference is the whole control. + _, err := steerAlreadyHandled(context.Background(), + fakeMarkerReader{login: "github-actions[bot]"}, + fakeMarkerReader{loginErr: errors.New("403")}, "org/repo", 7, 999) + require.Error(t, err) + }) + + t.Run("the timeline cannot be read", func(t *testing.T) { + _, err := steerAlreadyHandled(context.Background(), + fakeMarkerReader{login: "github-actions[bot]", listErr: errors.New("500")}, + roleReader(), "org/repo", 7, 999) + require.Error(t, err) + }) +} + +func TestCheckSteerAlreadyHandled_OffPaths(t *testing.T) { + // Each case must short-circuit before the timeline read. Returning false + // is not enough on its own — a failed read returns false too, after a + // warning and a live API call — so every case also asserts that nothing + // was printed. That is what makes these cases fail if their guard goes. + cases := []struct { + name string + mut func(t *testing.T, o *steerOpts) + }{ + {"steering explicitly disabled", func(_ *testing.T, o *steerOpts) { + o.harness = steerHarness(false) + }}, + {"outside GitHub Actions", func(t *testing.T, _ *steerOpts) { + t.Setenv("GITHUB_ACTIONS", "") + }}, + {"no receipt token", func(_ *testing.T, o *steerOpts) { o.receiptToken = "" }}, + {"gitlab", func(_ *testing.T, o *steerOpts) { o.forgePlatform = "gitlab" }}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var out strings.Builder + o := baseOpts(t) + o.printer = ui.New(&out) + tc.mut(t, &o) + + assert.False(t, checkSteerAlreadyHandled(context.Background(), o)) + assert.Empty(t, out.String(), + "the guard must return before anything tries to read the timeline") + }) + } +} + +func TestCheckSteerAlreadyHandled_ReadsTheMarker(t *testing.T) { + o := baseOpts(t) + prev := steerMarkerClientFn + t.Cleanup(func() { steerMarkerClientFn = prev }) + // One fake per credential: the check resolves both logins and refuses to + // skip unless they differ. + steerMarkerClientFn = func(token string) steerMarkerReader { + if token == o.roleToken { + return fakeMarkerReader{login: "fullsend[bot]"} + } + return fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{ + {Author: "github-actions[bot]", Body: ""}, + }} + } + assert.True(t, checkSteerAlreadyHandled(context.Background(), o)) +} + +// TestSteerAlreadyHandled_IgnoresAnEditedReceipt pins that a receipt's body +// counts only as the job token wrote it. Editing a comment keeps its author, +// and an identity with write access can edit another's comment, so an edited +// receipt could name any queued run. +func TestSteerAlreadyHandled_IgnoresAnEditedReceipt(t *testing.T) { + edited := forge.IssueComment{ + Author: "github-actions[bot]", + Body: "", + CreatedAt: "2026-09-25T10:00:00Z", + UpdatedAt: "2026-09-25T10:05:00Z", + } + c := fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{edited}} + got, err := steerAlreadyHandled(context.Background(), c, roleReader(), "org/repo", 7, 999) + require.NoError(t, err) + assert.False(t, got, "an edited receipt must not skip the queued run") + + genuine := edited + genuine.UpdatedAt = genuine.CreatedAt + c = fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{genuine}} + got, err = steerAlreadyHandled(context.Background(), c, roleReader(), "org/repo", 7, 999) + require.NoError(t, err) + assert.True(t, got, "the same receipt, never edited, is honoured") +} + +// TestCheckSteerAlreadyHandled_ManualRerunRuns pins that a re-run always +// runs. It keeps its run id, so the receipt that consumed its first attempt +// still names it; a person pressing re-run asked for the work. +func TestCheckSteerAlreadyHandled_ManualRerunRuns(t *testing.T) { + var out strings.Builder + o := baseOpts(t) + o.printer = ui.New(&out) + prev := steerMarkerClientFn + t.Cleanup(func() { steerMarkerClientFn = prev }) + steerMarkerClientFn = func(token string) steerMarkerReader { + if token == o.roleToken { + return fakeMarkerReader{login: "fullsend[bot]"} + } + return fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{ + {Author: "github-actions[bot]", Body: ""}, + }} + } + + t.Setenv("GITHUB_RUN_ATTEMPT", "1") + assert.True(t, checkSteerAlreadyHandled(context.Background(), o), "the first attempt skips") + + t.Setenv("GITHUB_RUN_ATTEMPT", "2") + assert.False(t, checkSteerAlreadyHandled(context.Background(), o), "a re-run does the work") + assert.Contains(t, out.String(), "run attempt 2 is a manual re-run") +} + +// TestCheckSteerAlreadyHandled_ReadsWithTheJobToken pins the credential the +// skip check authenticates against. The reader resolves the receipt author +// from whichever token it is handed, so handing it the ROLE token would make +// it trust the App login — the identity the agent's own output is posted +// under — and the whole control would be inverted while every +// steerAlreadyHandled test kept passing, since those inject the client +// directly. +func TestCheckSteerAlreadyHandled_ReadsWithTheJobToken(t *testing.T) { + o := baseOpts(t) + prev := steerMarkerClientFn + t.Cleanup(func() { steerMarkerClientFn = prev }) + + var gotTokens []string + steerMarkerClientFn = func(token string) steerMarkerReader { + gotTokens = append(gotTokens, token) + if token == o.roleToken { + return fakeMarkerReader{login: "fullsend[bot]"} + } + return fakeMarkerReader{login: "github-actions[bot]"} + } + checkSteerAlreadyHandled(context.Background(), o) + + require.NotEmpty(t, gotTokens) + assert.Equal(t, o.receiptToken, gotTokens[0], + "the receipt author is resolved from the receipt credential, not the agent's") + assert.Contains(t, gotTokens, o.roleToken, + "and the agent's own identity is resolved too, so the two can be compared") +} + +// writeProviderDef writes one provider definition file into dir. +func writeProviderDef(t *testing.T, dir, file, body string) { + t.Helper() + require.NoError(t, os.MkdirAll(dir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, file), []byte(body), 0o600)) +} + +const workflowTokenProviderDef = "name: github-packages\ntype: fullsend-github-packages\ncredentials:\n GITHUB_TOKEN: \"${GH_WORKFLOW_TOKEN}\"\n" + +// TestSteerReceiptsHonoured pins when a receipt can be trusted. A provider +// that expands the workflow token hands it to a sandbox, where the agent can +// recover it and forge a receipt (ADR 0114). +func TestSteerReceiptsHonoured(t *testing.T) { + tests := []struct { + name string + files map[string]string + noDir bool + want bool + }{ + {name: "missing directory", noDir: true, want: true}, + {name: "providers that do not read the token", files: map[string]string{ + "github.yaml": "name: github\ntype: github\ncredentials:\n GITHUB_TOKEN: \"${GH_TOKEN}\"\n", + }, want: true}, + {name: "braced reference", files: map[string]string{"github-packages.yaml": workflowTokenProviderDef}, want: false}, + {name: "bare reference", files: map[string]string{ + "npm.yaml": "name: npm\ntype: generic\ncredentials:\n TOKEN: $GH_WORKFLOW_TOKEN\n", + }, want: false}, + {name: "unreadable definition", files: map[string]string{"broken.yaml": "name: [unclosed\n"}, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := filepath.Join(t.TempDir(), "providers") + if !tt.noDir { + require.NoError(t, os.MkdirAll(dir, 0o755)) + } + for f, body := range tt.files { + writeProviderDef(t, dir, f, body) + } + got, reason := steerReceiptsHonoured(dir) + assert.Equal(t, tt.want, got) + assert.Equal(t, tt.want, reason == "", "a refusal names its reason") + }) + } + + got, _ := steerReceiptsHonoured("") + assert.False(t, got, "an unknown location refuses") +} + +// TestCheckSteerAlreadyHandled_WorkflowTokenProviderRefusesTheSkip pins that +// the refusal is repository-wide. The definition belongs to a harness other +// than this run's, because a code-stage agent can forge a receipt that a +// queued review run would read. The receipt here would otherwise skip. +func TestCheckSteerAlreadyHandled_WorkflowTokenProviderRefusesTheSkip(t *testing.T) { + var out strings.Builder + o := baseOpts(t) + o.printer = ui.New(&out) + require.Empty(t, o.harness.Providers, "this run's harness declares no provider") + writeProviderDef(t, o.providersDir, "github-packages.yaml", workflowTokenProviderDef) + + prev := steerMarkerClientFn + t.Cleanup(func() { steerMarkerClientFn = prev }) + steerMarkerClientFn = func(token string) steerMarkerReader { + if token == o.roleToken { + return fakeMarkerReader{login: "fullsend[bot]"} + } + return fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{ + {Author: "github-actions[bot]", Body: ""}, + }} + } + + assert.False(t, checkSteerAlreadyHandled(context.Background(), o)) + assert.Contains(t, out.String(), + `Not skipping on a steer receipt: provider "github-packages" delivers GH_WORKFLOW_TOKEN to a sandbox`) +} + +func TestCheckSteerAlreadyHandled_FailureFallsThrough(t *testing.T) { + o := baseOpts(t) + prev := steerMarkerClientFn + t.Cleanup(func() { steerMarkerClientFn = prev }) + steerMarkerClientFn = func(string) steerMarkerReader { + return fakeMarkerReader{loginErr: errors.New("403")} + } + assert.False(t, checkSteerAlreadyHandled(context.Background(), o), + "an unreadable timeline must not silently drop the work") +} + +func TestSteerMarkerFrom_OnlyAcknowledgedDeliveriesCount(t *testing.T) { + delivered := []steerwatch.DeliveredSteer{ + {MessageID: 101, RunIDs: []int64{101}}, + {MessageID: 102, RunIDs: []int64{102}}, + } + + // The runtime acknowledged the first message only — it died before + // acking the second. + m := steerMarkerFrom(delivered, "abc123", []agentruntime.SteerResult{{FollowUpRunID: 101, Mode: "live"}}) + + assert.Equal(t, []int64{101}, m.ConsumedRunIDs, + "an unacknowledged delivery must not make the queued run skip its work") + assert.Equal(t, "abc123", m.HeadSHA) +} + +func TestSteerMarkerFrom_AckVouchesForTheWholeBatch(t *testing.T) { + // One poll accepted three follow-ups and folded them into one message + // named after the newest; the ack is per message, so a plain id + // intersection would drop all but that newest one. + delivered := []steerwatch.DeliveredSteer{{MessageID: 103, RunIDs: []int64{101, 102, 103}}} + + m := steerMarkerFrom(delivered, "", []agentruntime.SteerResult{{FollowUpRunID: 103}}) + assert.Equal(t, []int64{101, 102, 103}, m.ConsumedRunIDs) +} + +func TestSteerMarkerFrom_NoAcksMeansNoMarkerEntries(t *testing.T) { + delivered := []steerwatch.DeliveredSteer{{MessageID: 101, RunIDs: []int64{101}}} + assert.Empty(t, steerMarkerFrom(delivered, "abc", nil).ConsumedRunIDs) +} + +func TestSteerMarkerFrom_NothingDelivered(t *testing.T) { + m := steerMarkerFrom(nil, "abc", []agentruntime.SteerResult{{FollowUpRunID: 101}}) + assert.Empty(t, m.ConsumedRunIDs) + assert.Equal(t, "abc", m.HeadSHA) +} + +func TestSteerMarker_NilSessionIsEmpty(t *testing.T) { + var s *steerSession + assert.Empty(t, s.marker([]agentruntime.SteerResult{{FollowUpRunID: 1}}).ConsumedRunIDs) + assert.Empty(t, s.seenRunIDs()) +} + +func TestSteerMarkerForStatus(t *testing.T) { + m := statuscomment.SteerMarker{ConsumedRunIDs: []int64{101}, HeadSHA: "abc"} + + assert.Equal(t, m, steerMarkerForStatus("success", m)) + + // A run that absorbed an update and then failed produced no output for + // it; a receipt would make the queued run skip work nobody did. + for _, status := range []string{"failure", "cancelled", "skipped", ""} { + t.Run(status, func(t *testing.T) { + got := steerMarkerForStatus(status, m) + assert.Empty(t, got.ConsumedRunIDs) + assert.Empty(t, got.HeadSHA) + }) + } +} + +func TestShippedSteerMarker(t *testing.T) { + absorbed := statuscomment.SteerMarker{ConsumedRunIDs: []int64{101}, HeadSHA: "aaa"} + + // Iteration 1 absorbed run 101 and failed validation; iteration 2 + // absorbed nothing and passed. The retry never saw 101, so no receipt + // ships and the queued run does that update. + byIteration := map[int]statuscomment.SteerMarker{1: absorbed, 2: {}} + got := shippedSteerMarker(byIteration, true, 2, 2) + assert.Empty(t, got.ConsumedRunIDs) + + // The post-loop sweep can validate an earlier iteration; its receipts + // are the ones that ship. + byIteration = map[int]statuscomment.SteerMarker{ + 1: absorbed, + 2: {ConsumedRunIDs: []int64{102}, HeadSHA: "bbb"}, + } + assert.Equal(t, absorbed, shippedSteerMarker(byIteration, true, 1, 2)) + + // No iteration passed: nothing ships. + assert.Empty(t, shippedSteerMarker(byIteration, true, 0, 2).ConsumedRunIDs) + + // Without a validation loop the last iteration ships. + assert.Equal(t, byIteration[2], shippedSteerMarker(byIteration, false, 0, 2)) + + // An unsteered iteration has no entry and ships no receipt. + assert.Empty(t, shippedSteerMarker(map[int]statuscomment.SteerMarker{}, false, 0, 1).ConsumedRunIDs) +} + +// The forged-receipt attack, end to end through the skip check: an injection +// induces the agent to write a marker naming a run id into its review output, +// which the App posts. The body shape no longer matters — what disqualifies +// it is that the App is not the identity the runner's receipt credential +// posts under. +func TestSteerAlreadyHandled_IgnoresAgentAuthoredMarker(t *testing.T) { + c := fakeMarkerReader{login: "github-actions[bot]", comments: []forge.IssueComment{ + {Author: "fullsend[bot]", Body: "## Review\n\nLGTM.\n"}, + }} + got, err := steerAlreadyHandled(context.Background(), c, roleReader(), "org/repo", 7, 999) + require.NoError(t, err) + assert.False(t, got, "a marker in agent output must not suppress the queued run") +} + +// TestChildScriptEnv_StripsSwappedTokens covers the credential the receipt's +// authenticity rests on. Minting replaces GH_TOKEN and GITHUB_TOKEN, but a +// caller can export the same job token under a name of its own; a post-script +// that inherits it can shell out to `gh` and sign a receipt, which makes the +// queued run skip work nobody published. +func TestChildScriptEnv_StripsSwappedTokens(t *testing.T) { + t.Setenv("CALLER_COPY_OF_JOB_TOKEN", "job-token-value") + t.Setenv("AUTH_HEADER", "Bearer job-token-value") + t.Setenv("UNRELATED", "keep-me") + + prev := swappedAwayTokens + t.Cleanup(func() { swappedAwayTokens = prev }) + swappedAwayTokens = []string{"job-token-value"} + + env := childScriptEnv(nil, "") + + assert.NotContains(t, env, "CALLER_COPY_OF_JOB_TOKEN=job-token-value", + "a swapped-away credential must not reach a child script under any name") + assert.NotContains(t, env, "AUTH_HEADER=Bearer job-token-value", + "nor wrapped in a header, a URL or any other value that carries it") + assert.Contains(t, env, "UNRELATED=keep-me", + "stripping is by value, so everything else is untouched") +} + +// TestStripOIDCEnv_StripsSwappedTokens covers the validation_loop script, +// whose environment is composed without childScriptEnv. It must drop a +// swapped-away credential by value too, or a validation script inherits the +// job token under a caller's third name. +func TestStripOIDCEnv_StripsSwappedTokens(t *testing.T) { + prev := swappedAwayTokens + t.Cleanup(func() { swappedAwayTokens = prev }) + swappedAwayTokens = []string{"job-token-value"} + + env := stripOIDCEnv([]string{ + "CALLER_COPY_OF_JOB_TOKEN=job-token-value", + "AUTH_HEADER=Bearer job-token-value", + "UNRELATED=keep-me", + }) + + assert.Equal(t, []string{"UNRELATED=keep-me"}, env, + "a swapped-away credential must not reach a validation script under any name") +} + +// TestChildScriptEnv_StripsNothingWithoutAMint is the other direction: with no +// swap there is no receipt either, and the job token is the only credential a +// post-script has. Stripping it would break every unminted run. +func TestChildScriptEnv_StripsNothingWithoutAMint(t *testing.T) { + t.Setenv("GH_TOKEN", "job-token-value") + + prev := swappedAwayTokens + t.Cleanup(func() { swappedAwayTokens = prev }) + swappedAwayTokens = nil + + assert.Contains(t, childScriptEnv(nil, ""), "GH_TOKEN=job-token-value") +} + +// TestMintAgentToken_SwapsBothTokenSpellings pins the swap the receipt's +// authenticity rests on. GH_TOKEN alone is not enough: a caller that also +// exports GITHUB_TOKEN would leave the job token in the environment a +// post-script inherits, and a post-script that holds it can sign a receipt. +func TestMintAgentToken_SwapsBothTokenSpellings(t *testing.T) { + origMint := statusMintToken + t.Cleanup(func() { statusMintToken = origMint }) + statusMintToken = func(context.Context, mintclient.MintRequest) (*mintclient.MintResult, error) { + return &mintclient.MintResult{Token: "ghs_role_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "job-token-value") + t.Setenv("GITHUB_TOKEN", "job-token-value") + + prev := swappedAwayTokens + t.Cleanup(func() { swappedAwayTokens = prev }) + swappedAwayTokens = nil + + minted, cleanup, err := mintAgentToken(context.Background(), "coder", "https://mint.example.com", "", ui.New(io.Discard)) + require.NoError(t, err) + require.True(t, minted) + + assert.Equal(t, "ghs_role_token", os.Getenv("GH_TOKEN")) + assert.Equal(t, "ghs_role_token", os.Getenv("GITHUB_TOKEN"), + "the job token must not survive under the second spelling either") + assert.Contains(t, swappedAwayTokens, "job-token-value", + "what was swapped away is recorded so childScriptEnv can strip it by value") + + cleanup() + assert.Equal(t, "job-token-value", os.Getenv("GITHUB_TOKEN"), "cleanup restores it") + assert.Empty(t, swappedAwayTokens, "and stops stripping it") +} + +// TestMintAgentToken_NestedRemintKeepsTheJobToken covers the sequence a stage +// with its own privilege level produces: mint, remint around the script, +// restore. The inner restore must not forget the ORIGINAL job token, which is +// still swapped away — a post-script inheriting a third-name copy of it could +// otherwise sign a receipt. +func TestMintAgentToken_NestedRemintKeepsTheJobToken(t *testing.T) { + origMint := statusMintToken + t.Cleanup(func() { statusMintToken = origMint }) + var nth int + statusMintToken = func(context.Context, mintclient.MintRequest) (*mintclient.MintResult, error) { + nth++ + return &mintclient.MintResult{Token: fmt.Sprintf("ghs_role_%d", nth), ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "job-token-value") + t.Setenv("GITHUB_TOKEN", "job-token-value") + t.Setenv("CALLER_COPY_OF_JOB_TOKEN", "job-token-value") + + prev := swappedAwayTokens + t.Cleanup(func() { swappedAwayTokens = prev }) + swappedAwayTokens = nil + + _, outer, err := mintAgentToken(context.Background(), "coder", "https://mint.example.com", "", ui.New(io.Discard)) + require.NoError(t, err) + t.Cleanup(outer) + + // The stage remints at its own level and restores when its script ends. + _, inner, err := mintAgentTokenAtLevel(context.Background(), "coder", "https://mint.example.com", "", "read", ui.New(io.Discard)) + require.NoError(t, err) + inner() + + assert.Contains(t, swappedAwayTokens, "job-token-value", + "the inner restore must not forget a credential the outer mint is still hiding") + assert.NotContains(t, childScriptEnv(nil, ""), "CALLER_COPY_OF_JOB_TOKEN=job-token-value", + "a third-name copy of the job token must still be stripped after a nested remint") +} diff --git a/internal/forge/forge.go b/internal/forge/forge.go index ce7300f079..e51cb54300 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -509,6 +509,9 @@ type PullRequestReview struct { State string // "APPROVED", "CHANGES_REQUESTED", "COMMENTED", "DISMISSED" Body string SubmittedAt string + // CommitID is the head the review was submitted against. Empty when the + // forge does not report it. + CommitID string // AuthorIsApp is the forge's own verdict on the reviewer, as on // IssueComment.AuthorIsApp. AuthorIsApp bool diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 174c61262c..44bffa7ede 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -3374,6 +3374,7 @@ func (c *LiveClient) ListPullRequestReviews(ctx context.Context, owner, repo str State string `json:"state"` Body string `json:"body"` SubmittedAt string `json:"submitted_at"` + CommitID string `json:"commit_id"` } if err := decodeJSON(resp, &raw); err != nil { return nil, fmt.Errorf("decoding pull request reviews page %d: %w", page, err) @@ -3387,6 +3388,7 @@ func (c *LiveClient) ListPullRequestReviews(ctx context.Context, owner, repo str State: r.State, Body: r.Body, SubmittedAt: r.SubmittedAt, + CommitID: r.CommitID, AuthorIsApp: isAppUserType(r.User.Type), }) } diff --git a/internal/forge/github/github_comment_test.go b/internal/forge/github/github_comment_test.go index bc4d27023a..2f03a354fd 100644 --- a/internal/forge/github/github_comment_test.go +++ b/internal/forge/github/github_comment_test.go @@ -519,6 +519,7 @@ func TestListPullRequestReviews(t *testing.T) { "state": "APPROVED", "body": "LGTM", "submitted_at": "2026-01-01T00:00:00Z", + "commit_id": "abc123", }, }) })) @@ -533,6 +534,7 @@ func TestListPullRequestReviews(t *testing.T) { assert.Equal(t, "reviewer", reviews[0].User) assert.Equal(t, "APPROVED", reviews[0].State) assert.Equal(t, "LGTM", reviews[0].Body) + assert.Equal(t, "abc123", reviews[0].CommitID) } func TestAddIssueReaction(t *testing.T) { diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index fa82e98956..8d7f69b8c3 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -1822,13 +1822,19 @@ func ExtractOutputFiles(sandboxName, remoteDir, localDir string) ([]string, erro } defer root.Close() - stdout, _, _, err := Exec(sandboxName, + stdout, stderr, exitCode, err := Exec(sandboxName, fmt.Sprintf("find %s -type f 2>/dev/null || true", remoteDir), 10*time.Second, ) if err != nil { return nil, fmt.Errorf("listing output files: %w", err) } + // The listing ends in `|| true`, so a non-zero exit came from openshell + // itself — a sandbox that is not ready, say — not from find. Reporting it + // as no output would let a run that published nothing claim a receipt. + if exitCode != 0 { + return nil, fmt.Errorf("listing output files: openshell exited %d: %s", exitCode, strings.TrimSpace(stderr)) + } trimmed := strings.TrimSpace(stdout) if trimmed == "" { @@ -1837,11 +1843,13 @@ func ExtractOutputFiles(sandboxName, remoteDir, localDir string) ([]string, erro lines := strings.Split(trimmed, "\n") var extracted []string + named := 0 for _, remotePath := range lines { remotePath = strings.TrimSpace(remotePath) if remotePath == "" { continue } + named++ relPath := strings.TrimPrefix(remotePath, remoteDir) relPath = strings.TrimPrefix(relPath, "/") @@ -1871,5 +1879,11 @@ func ExtractOutputFiles(sandboxName, remoteDir, localDir string) ([]string, erro extracted = append(extracted, localPath) } + // Each copy is its own openshell call, so the sandbox can stop answering + // after the listing. Output that was listed but never copied is not an + // empty output directory. + if named > 0 && len(extracted) == 0 { + return nil, fmt.Errorf("copying output files: %d listed, none copied", named) + } return extracted, nil } diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go index 5a7ad3af06..8eae6c4a1b 100644 --- a/internal/sandbox/sandbox_test.go +++ b/internal/sandbox/sandbox_test.go @@ -2323,3 +2323,65 @@ func TestPhase_ReadsTheAnchoredField(t *testing.T) { require.NoError(t, err) assert.Equal(t, "Stopped", phase) } + +// stubOpenshell installs an openshell stub on PATH that prints stdoutText and +// stderrText and exits with exitCode. +func stubOpenshell(t *testing.T, stdoutText, stderrText string, exitCode int) { + t.Helper() + binDir := t.TempDir() + script := "#!/bin/sh\n" + + "printf '%s' " + shellQuote(stdoutText) + "\n" + + "printf '%s' " + shellQuote(stderrText) + " >&2\n" + + fmt.Sprintf("exit %d\n", exitCode) + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// TestExtractOutputFiles_OpenshellFailureIsAnError: the listing ends in +// `|| true`, so a non-zero exit is openshell's own — a sandbox that is not +// ready. Reading that as "no output" would let a run that published nothing +// post a steer receipt. +func TestExtractOutputFiles_OpenshellFailureIsAnError(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell stub") + } + stubOpenshell(t, "", "sandbox is not ready", 1) + + got, err := ExtractOutputFiles("sb", "/sandbox/output", t.TempDir()) + require.Error(t, err) + assert.Contains(t, err.Error(), "sandbox is not ready") + assert.Empty(t, got) +} + +// TestExtractOutputFiles_EmptyOutputIsNotAnError: a sandbox that answered and +// holds no output files is a genuinely empty result, not a failure. +func TestExtractOutputFiles_EmptyOutputIsNotAnError(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell stub") + } + stubOpenshell(t, "", "", 0) + + got, err := ExtractOutputFiles("sb", "/sandbox/output", t.TempDir()) + require.NoError(t, err) + assert.Empty(t, got) +} + +// TestExtractOutputFiles_ListedButNoneCopiedIsAnError: each copy is its own +// openshell call, so the sandbox can stop answering after the listing. Files +// that were listed but never copied are not an empty output directory. +func TestExtractOutputFiles_ListedButNoneCopiedIsAnError(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell stub") + } + binDir := t.TempDir() + script := "#!/bin/sh\n" + + "if [ \"$2\" = exec ]; then printf '%s\\n' /sandbox/output/agent-result.json; exit 0; fi\n" + + "echo 'sandbox is not ready' >&2\nexit 1\n" + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + + got, err := ExtractOutputFiles("sb", "/sandbox/output", t.TempDir()) + require.Error(t, err) + assert.Contains(t, err.Error(), "1 listed, none copied") + assert.Empty(t, got) +} diff --git a/internal/statuscomment/statuscomment.go b/internal/statuscomment/statuscomment.go index 253dcf9837..7fceb428fe 100644 --- a/internal/statuscomment/statuscomment.go +++ b/internal/statuscomment/statuscomment.go @@ -33,6 +33,10 @@ var startBodyRe = regexp.MustCompile(`🤖 (.+?) · Started (\d{1,2}:\d{2} [AP]M const terminalTag = "" +// statusMarkerPrefix is the invariant part of the per-run status marker +// buildMarker writes. Used to recognise the runner's own status comments. +const statusMarkerPrefix = "", runID), nil + return statusMarkerPrefix + runID + " -->", nil } func mustBuildMarker(runID string) string { diff --git a/internal/statuscomment/steermarker.go b/internal/statuscomment/steermarker.go new file mode 100644 index 0000000000..9c65de1f4c --- /dev/null +++ b/internal/statuscomment/steermarker.go @@ -0,0 +1,195 @@ +package statuscomment + +import ( + "fmt" + "regexp" + "sort" + "strconv" + "strings" + + "github.com/fullsend-ai/fullsend/internal/tracker" +) + +// The steer marker records what a settled run absorbed, so the follow-up +// run that is still queued behind it can tell whether its own event was +// already handled (ADR 0113). The runner posts it as its own comment under +// the job token; a copy also rides on the terminal status comment, for a +// reader, but the skip check does not honour that one — see +// LatestSteerMarker. +// +// Shape: ``. +// `consumed` lists the follow-up workflow run ids the settled run took as +// steers; `head` is the work item head the run finished on (empty for +// issues, which have no head). + +// steerMarkerPrefix is the opening of a steer marker. +const steerMarkerPrefix = "`) + +// SteerMarker is the parsed content of one steer marker. +type SteerMarker struct { + // ConsumedRunIDs are the follow-up workflow runs the settled run + // absorbed, ascending and deduplicated. + ConsumedRunIDs []int64 + // HeadSHA is the work item head the run settled on. Empty for issues. + HeadSHA string +} + +// Consumed reports whether runID appears in the marker. +func (m SteerMarker) Consumed(runID int64) bool { + for _, id := range m.ConsumedRunIDs { + if id == runID { + return true + } + } + return false +} + +// ConsumedRuns returns the run ids this marker actually records: sorted, +// deduplicated, and with the unusable ones dropped. +// +// It is the single answer to "did this run absorb anything", which both the +// rendered marker and the receipt decision depend on. Reading +// ConsumedRunIDs directly gets that wrong, because a slice of nothing but +// zeroes is non-empty and records nothing. +func (m SteerMarker) ConsumedRuns() []int64 { + ids := make([]int64, 0, len(m.ConsumedRunIDs)) + seen := make(map[int64]bool, len(m.ConsumedRunIDs)) + for _, id := range m.ConsumedRunIDs { + if id <= 0 || seen[id] { + continue + } + seen[id] = true + ids = append(ids, id) + } + sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) + return ids +} + +// BuildSteerMarker renders the marker line. It returns "" when there is +// nothing to record, so a run that absorbed no steers adds no marker and +// the status comment is byte-for-byte what it is today. +// +// A head-only marker IS rendered: on the status comment the head a run +// settled on is worth recording even when nothing was absorbed. The +// standalone receipt does not follow that rule — see postSteerReceipt. +// +// Run ids are sorted and deduplicated so the same set always renders the +// same string; a non-hex head is dropped rather than emitted, because the +// marker is HTML in a comment body and must not carry arbitrary text. +func BuildSteerMarker(m SteerMarker) string { + ids := m.ConsumedRuns() + + head := m.HeadSHA + if !isHexOnly(head) { + head = "" + } + if len(ids) == 0 && head == "" { + return "" + } + + parts := make([]string, 0, len(ids)) + for _, id := range ids { + parts = append(parts, strconv.FormatInt(id, 10)) + } + return fmt.Sprintf("%sconsumed=%s head=%s -->", steerMarkerPrefix, strings.Join(parts, ","), head) +} + +// ParseSteerMarker extracts the steer marker from a comment body. It +// returns ok=false when the body carries no marker. A malformed run id is +// skipped rather than failing the parse: the skip check must degrade to +// "not consumed" (do the work) and never to "consumed" (skip the work). +func ParseSteerMarker(body string) (SteerMarker, bool) { + match := steerMarkerRe.FindStringSubmatch(body) + if match == nil { + return SteerMarker{}, false + } + var m SteerMarker + for _, field := range strings.Split(match[1], ",") { + if field == "" { + continue + } + id, err := strconv.ParseInt(field, 10, 64) + if err != nil || id <= 0 { + continue + } + m.ConsumedRunIDs = append(m.ConsumedRunIDs, id) + } + m.HeadSHA = match[2] + return m, true +} + +// LatestSteerMarker returns the steer marker on the last comment written by +// author that carries one. comments must be in timeline order, oldest first. +// +// author is the login of the JOB TOKEN the runner holds — on GitHub Actions, +// the identity `GITHUB_TOKEN` posts under. It is resolved by the caller from +// the token itself rather than hardcoded, since the login differs between +// github.com and GHES. +// +// Authorship is the whole of the check. The job token is swapped out of the +// environment before the sandbox is created, so nothing inside it holds the +// credential — neither the agent nor a post-script shelling out to `gh`, both +// of which post as the App. An App-authored marker therefore never passes, +// whatever its body looks like. +// +// What this proves, stated exactly: the comment came from a workflow job +// token OF THIS REPOSITORY — not that it came from this run, or even from +// fullsend. Every job's default GITHUB_TOKEN in a repository posts under the +// same login, so any other workflow there could write a comment carrying +// this syntax and it would be honoured. That is a maintainer-controlled +// boundary — a repository's own workflows can already do anything to it — +// and it is deliberately not narrowed further: corroborating the marker +// against the Actions API would not help, because the run id it names is +// public. +// +// The boundary that would matter: a job token that leaves the runner's +// process could post a receipt this function would honour. A provider that +// hands the token to a sandbox does exactly that (ADR 0114), so the caller +// refuses to consult receipts at all while one is configured; otherwise it +// takes a compromise of the runner. +// +// The author comparison ignores case, as GitHub logins do, so the login the +// token resolves to matches however the timeline spells it. +func LatestSteerMarker(comments []tracker.Comment, author string) (SteerMarker, bool) { + if author == "" { + return SteerMarker{}, false + } + for i := len(comments) - 1; i >= 0; i-- { + if !strings.EqualFold(comments[i].Author, author) { + continue + } + if m, ok := ParseSteerMarker(string(comments[i].Body)); ok { + return m, true + } + } + return SteerMarker{}, false +} + +// fullsendMarkerOpen matches any HTML comment opening the fullsend marker +// namespace, however the whitespace and case fall. The steer marker's own +// parser is stricter than this on purpose: neutralization must cover +// everything that could ever match a marker parser, not just what one +// matches today. +var fullsendMarkerOpen = regexp.MustCompile(`(?is)", + }, + { + name: "consumed only (issue, no head)", + in: SteerMarker{ConsumedRunIDs: []int64{42}}, + want: "", + }, + { + name: "ids sorted and deduplicated", + in: SteerMarker{ConsumedRunIDs: []int64{9, 3, 9, 7}, HeadSHA: "deadbeef"}, + want: "", + }, + { + name: "non-positive ids dropped", + in: SteerMarker{ConsumedRunIDs: []int64{0, -1, 5}, HeadSHA: "aa"}, + want: "", + }, + { + name: "non-hex head dropped so the marker cannot carry arbitrary text", + in: SteerMarker{ConsumedRunIDs: []int64{5}, HeadSHA: "-->