From eef9219535742dc259d743702d399c1ff76937cb Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 18 Sep 2026 09:46:09 -0400 Subject: [PATCH 1/5] feat(dispatch)!: never cancel the agent run in flight on a work-item update Every stage job in reusable-dispatch.yml ran in a concurrency group keyed on the work item with cancel-in-progress: true, so a second push, comment, label or title edit cancelled the run already working on the item and a fresh run started over: sandbox provisioning and bootstrap before the model read a line, then the whole item again from cold. On a review minutes from posting that is the entire spend lost, and a spaced burst of pushes produces a review of every intermediate state, each superseded before anyone reads it. ADR 0106 (serialize agent runs and coalesce subsequent events, Accepted) decided for preserve-and-coalesce and states that the reusable workflows must move to cancel-in-progress: false. This is that change on GitHub. All seven stage jobs, the matrix fan-out included, now carry the literal false, so the run in flight finishes and the last run to queue waits as the single pending run GitHub keeps per group. That is normally but not necessarily the newest event, since a stage job queues only after route completes; either way the pending run works from the item's current state, which is the agent's side of the bargain. The value is identical on every job on purpose: one role cancelling while another queues on the same item is harder to reason about than either behaviour alone. The workflow header records what the trade gives up: ADR 0063 counted per-stage cancellation as a layer against duplicate poll dispatch, and that layer is gone everywhere, leaving the poller's lock and agent idempotency. queue: max is not used because it is incompatible with cancel-in-progress and N pending full runs is the failure mode this exists to remove. The alignment test pinned six of the seven jobs and asserted a Go bool, which cannot tell a literal boolean from the quoted string that would silently turn the value into an expression. It now pins all seven with the YAML node's tag and value, and fails on any job in the workflow it was not told about, so an eighth stage job cannot ship with its concurrency unchecked. The per-repo shim's header comment, and its generated copy in this repository, described per-role cancel-in-progress groups; both now describe the preserved run, and the scaffold test pins the new wording. BREAKING CHANGE: Every repository stops cancelling the agent run in flight when a newer event arrives on the same work item, on the release that carries this. There is no opt-out. A run may now finish on input the work item has already moved past; the pending run that follows works from current state and corrects it. Repositories that relied on the newest event superseding an older run will see both run to completion instead. Assisted-by: Claude Signed-off-by: Wayne Sun --- .github/workflows/fullsend.yaml | 5 +- .github/workflows/reusable-dispatch.yml | 42 ++++++++++---- .../templates/shim-per-repo.yaml | 5 +- internal/scaffold/scaffold_test.go | 3 +- .../scaffold/workflow_call_alignment_test.go | 55 ++++++++++++++++--- 5 files changed, 88 insertions(+), 22 deletions(-) diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml index 11d46287ea..c228221cf1 100644 --- a/.github/workflows/fullsend.yaml +++ b/.github/workflows/fullsend.yaml @@ -15,8 +15,9 @@ # which determines the stage and runs the agent inline (ADR 62). # Adding a new stage requires only a job in reusable-dispatch.yml — zero changes to this repo. # -# Concurrency: per-role cancel-in-progress groups live in reusable-dispatch.yml -# stage jobs with -agent- suffix. Roles operate independently (#2452). +# Concurrency: per-role groups (fullsend-{stage}-...) live in reusable-dispatch.yml +# stage jobs. A newer event never cancels the run in flight; it waits as the single +# pending run (ADR 0106). Roles operate independently (#2452). name: fullsend on: diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 150b5c402b..cc074ad0ea 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -14,9 +14,31 @@ # caller-provided matrix. This enables reuse without extracting separate workflows # while preserving ADR 62's inlining decision. # -# Concurrency: each stage job declares a per-role cancel-in-progress group -# (fullsend-{stage}-…). Roles operate independently — review dispatches do -# not cancel triage, code, fix, etc. +# Concurrency: each stage job declares a per-role group (fullsend-{stage}-...). +# Roles operate independently: a review dispatch does not cancel triage, code, +# fix, and so on. +# +# A second event on the same work item never cancels the run already working +# on it. Every stage job carries cancel-in-progress: false, so the run in +# flight finishes and one run waits behind it: GitHub Actions keeps a single +# pending run per group, the last one to queue, which is normally but not +# necessarily the newest event, since a stage job queues only after route +# completes. Either way the pending run works from the work item's current +# state rather than the state that dispatched it. That reconciliation is the +# agent's side of the bargain, and is why the runner exports +# FULLSEND_RUN_HEAD_SHA and FULLSEND_RUN_STARTED_AT (ADR 0106). +# +# What that gives up: ADR 0063 names per-stage cancel-in-progress as the second +# of two layers protecting poll dispatch from duplicate side effects, and that +# layer is now gone everywhere, leaving the first — the poller's own lock — +# plus whatever idempotency the agent has. The duplicate-poll case is where +# this costs most: two duplicate dispatches are the same work rather than a +# newer state superseding an older one, so both run to completion instead of +# one replacing the other. +# +# queue: max is deliberately not used. The default already keeps one pending +# run per group, which is the coalescing ADR 0106 asks for, and N pending full +# runs is the failure mode preserving the active run exists to remove. # # Flow: shim (per-repo) → reusable-dispatch.yml (route + inlined stage logic) # Or: custom poller → reusable-dispatch.yml (pre-computed matrix → harness-run) @@ -656,7 +678,7 @@ jobs: runs-on: ${{ inputs.runner_image }} concurrency: group: fullsend-triage-${{ github.repository }}-${{ github.event.issue.number || github.event.pull_request.number }} - cancel-in-progress: true + cancel-in-progress: false permissions: actions: write contents: read @@ -767,7 +789,7 @@ jobs: runs-on: ${{ inputs.runner_image }} concurrency: group: fullsend-code-${{ github.repository }}-${{ github.event.issue.number || github.event.pull_request.number }} - cancel-in-progress: true + cancel-in-progress: false permissions: actions: write contents: write @@ -908,7 +930,7 @@ jobs: runs-on: ${{ inputs.runner_image }} concurrency: group: fullsend-review-${{ github.repository }}-${{ github.event.pull_request.number || github.event.issue.number }} - cancel-in-progress: true + cancel-in-progress: false permissions: actions: write contents: read @@ -1038,7 +1060,7 @@ jobs: runs-on: ${{ inputs.runner_image }} concurrency: group: fullsend-fix-${{ github.repository }}-${{ github.event.pull_request.number || github.event.issue.number }} - cancel-in-progress: true + cancel-in-progress: false permissions: actions: write contents: write @@ -1320,7 +1342,7 @@ jobs: runs-on: ${{ inputs.runner_image }} concurrency: group: fullsend-retro-${{ github.repository }}-${{ github.event.pull_request.number || github.event.issue.number }} - cancel-in-progress: true + cancel-in-progress: false permissions: actions: write contents: read @@ -1432,7 +1454,7 @@ jobs: runs-on: ${{ inputs.runner_image }} concurrency: group: fullsend-prioritize-${{ github.repository }}-${{ github.event.issue.number || github.event.pull_request.number }} - cancel-in-progress: true + cancel-in-progress: false permissions: actions: write contents: read @@ -1691,7 +1713,7 @@ jobs: matrix: ${{ fromJSON(inputs.matrix != '' && inputs.matrix || (needs.harness-dispatch.outputs.matrix != '' && needs.harness-dispatch.outputs.matrix || '{"include":[]}')) }} concurrency: group: fullsend-harness-${{ matrix.agent }}-${{ github.repository }}-${{ matrix.status_repo }}-${{ matrix.status_number }} - cancel-in-progress: true + cancel-in-progress: false runs-on: ${{ inputs.runner_image }} permissions: actions: write diff --git a/internal/scaffold/fullsend-repo/templates/shim-per-repo.yaml b/internal/scaffold/fullsend-repo/templates/shim-per-repo.yaml index 2bd85b0495..aebd7bd42a 100644 --- a/internal/scaffold/fullsend-repo/templates/shim-per-repo.yaml +++ b/internal/scaffold/fullsend-repo/templates/shim-per-repo.yaml @@ -13,8 +13,9 @@ # which determines the stage and runs the agent inline (ADR 62). # Adding a new stage requires only a job in reusable-dispatch.yml — zero changes to this repo. # -# Concurrency: per-role cancel-in-progress groups live in reusable-dispatch.yml -# stage jobs with -agent- suffix. Roles operate independently (#2452). +# Concurrency: per-role groups (fullsend-{stage}-...) live in reusable-dispatch.yml +# stage jobs. A newer event never cancels the run in flight; it waits as the single +# pending run (ADR 0106). Roles operate independently (#2452). name: fullsend on: diff --git a/internal/scaffold/scaffold_test.go b/internal/scaffold/scaffold_test.go index 3817b0bb4a..91594f75eb 100644 --- a/internal/scaffold/scaffold_test.go +++ b/internal/scaffold/scaffold_test.go @@ -170,7 +170,8 @@ func TestShimPerRepoTemplateContent(t *testing.T) { // Per-role concurrency lives in reusable-dispatch.yml, not a monolithic shim group (#2452). assert.NotContains(t, s, "fullsend-dispatch-${{") assert.NotRegexp(t, `(?m)^\s+concurrency:`, s) - assert.Contains(t, s, "per-role cancel-in-progress groups live in reusable-dispatch.yml") + assert.Contains(t, s, "per-role groups (fullsend-{stage}-...) live in reusable-dispatch.yml") + assert.Contains(t, s, "A newer event never cancels the run in flight") // Permissions assertions (YAML-parsed, not string-contains) — #5785 var pr struct { diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 4331a52196..ccfc00dcd2 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -49,8 +49,11 @@ type callerJob struct { } type jobConcurrency struct { - Group string `yaml:"group"` - CancelInProgress bool `yaml:"cancel-in-progress"` + Group string `yaml:"group"` + // CancelInProgress is a Node, not a bool, so the assertions below can + // check the YAML tag: Node.Value cannot tell a literal boolean from the + // quoted string that would silently make the value an expression. + CancelInProgress yaml.Node `yaml:"cancel-in-progress"` } // reusableStageWorkflow includes workflow-level concurrency on reusable agent workflows. @@ -143,6 +146,14 @@ var dispatchStageConcurrencyExpectations = map[string]stageConcurrencyExpectatio groupPrefix: "fullsend-prioritize-", groupMust: []string{"github.repository", "github.event.issue.number", "github.event.pull_request.number"}, }, + // The matrix fan-out is a stage job too, and carries the same + // cancel-in-progress expression, so it is pinned here alongside the six + // built-in stages. Its group is keyed by matrix identity rather than by + // the event payload, because a poller supplies the work item. + "harness-run": { + groupPrefix: "fullsend-harness-", + groupMust: []string{"matrix.agent", "github.repository", "matrix.status_repo", "matrix.status_number"}, + }, } // stepDeclRe matches a YAML step declaration line: " - name: ". @@ -681,6 +692,21 @@ func TestReusableDispatchStageConcurrency(t *testing.T) { var caller callerWorkflow require.NoError(t, yaml.Unmarshal(content, &caller)) + // Every job is either a stage job pinned in the expectations or a job + // named here as not running an agent. A job that is neither fails, so an + // eighth stage job cannot ship with its concurrency unchecked: the loop + // below only visits the stages the map already knows. + nonStageJobs := map[string]bool{"route": true, "harness-dispatch": true} + for name := range caller.Jobs { + if nonStageJobs[name] { + continue + } + _, pinned := dispatchStageConcurrencyExpectations[name] + assert.True(t, pinned, "job %q is in reusable-dispatch.yml but not in "+ + "dispatchStageConcurrencyExpectations: pin its concurrency there, or list "+ + "it in nonStageJobs if it does not run an agent", name) + } + for stage, expect := range dispatchStageConcurrencyExpectations { t.Run(stage, func(t *testing.T) { job, ok := caller.Jobs[stage] @@ -691,8 +717,14 @@ func TestReusableDispatchStageConcurrency(t *testing.T) { assert.Contains(t, job.Concurrency.Group, fragment, "job %q concurrency group should reference %q", stage, fragment) } - assert.True(t, job.Concurrency.CancelInProgress, - "job %q should cancel in-progress runs when a newer dispatch arrives", stage) + assert.Equal(t, "false", job.Concurrency.CancelInProgress.Value, + "job %q must never cancel the run in flight when a newer event "+ + "arrives on the same work item (ADR 0106). A new stage job must "+ + "be added to dispatchStageConcurrencyExpectations, or its "+ + "concurrency is unpinned", stage) + assert.Equal(t, "!!bool", job.Concurrency.CancelInProgress.Tag, + "job %q cancel-in-progress must stay a literal boolean — a quoted "+ + "string or an expression would reintroduce a conditional", stage) }) } } @@ -715,8 +747,11 @@ func TestReusableAgentWorkflowConcurrency(t *testing.T) { assert.Contains(t, wf.Concurrency.Group, fragment, "reusable-%s.yml concurrency group should reference %q", stage, fragment) } - assert.True(t, wf.Concurrency.CancelInProgress, + assert.Equal(t, "true", wf.Concurrency.CancelInProgress.Value, "reusable-%s.yml should cancel in-progress runs", stage) + assert.Equal(t, "!!bool", wf.Concurrency.CancelInProgress.Tag, + "reusable-%s.yml cancel-in-progress must stay a literal boolean, "+ + "not the string \"true\" — Node.Value cannot tell them apart", stage) callerExpect := thinCallerConcurrencyExpectations[stage] assert.NotEqual(t, callerExpect.groupPrefix, expect.groupPrefix, @@ -743,8 +778,11 @@ func TestThinCallerStageConcurrency(t *testing.T) { assert.Contains(t, wf.Concurrency.Group, fragment, "%s concurrency group should reference %q", path, fragment) } - assert.True(t, wf.Concurrency.CancelInProgress, + assert.Equal(t, "true", wf.Concurrency.CancelInProgress.Value, "%s should cancel in-progress runs when a newer dispatch arrives", path) + assert.Equal(t, "!!bool", wf.Concurrency.CancelInProgress.Tag, + "%s cancel-in-progress must stay a literal boolean, not the string "+ + "\"true\" — Node.Value cannot tell them apart", path) }) } } @@ -1300,8 +1338,11 @@ func TestShimLabeledEventFiltering(t *testing.T) { `fullsend-dispatch-\$\{\{\s*github\.event\.issue\.number\s*\|\|\s*github\.event\.pull_request\.number\s*\}\}-\$\{\{\s*github\.event\.action\s*==\s*'labeled'\s*&&\s*format\('label-\{0\}',\s*github\.event\.label\.name\)\s*\|\|\s*'dispatch'\s*\}\}`, job.Concurrency.Group, "%s concurrency group must match full label-aware structure", tc.name) - assert.False(t, job.Concurrency.CancelInProgress, + assert.Equal(t, "false", job.Concurrency.CancelInProgress.Value, "%s concurrency group must have cancel-in-progress: false", tc.name) + assert.Equal(t, "!!bool", job.Concurrency.CancelInProgress.Tag, + "%s cancel-in-progress must stay a literal boolean, not the string "+ + "\"false\" — Node.Value cannot tell them apart", tc.name) }) } From 166d7883e5600e0bdf23935c1d344671cbd8ebd9 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 18 Sep 2026 09:46:48 -0400 Subject: [PATCH 2/5] feat(run): export the run facts after .env.d and env.sandbox Now that a newer event no longer cancels the run in flight, a run can outlive the state it was dispatched on, and the agent has to be able to tell whether the work item moved under it before it writes its result. The runner exports two run facts into the sandbox: FULLSEND_RUN_HEAD_SHA, the pull or merge request's head at run start and empty for an issue, and FULLSEND_RUN_STARTED_AT, RFC 3339 UTC. The head is empty rather than absent on an issue run so an agent can skip its re-check on an empty value, which it cannot do for a variable that is not there. The start is captured at the top of runAgent, before harness resolution, token minting and env expansion, each of which takes real time. It is still the runner's own clock rather than the workflow run's server-side created_at, and the gap runs one way: an agent re-checking against it sees a narrower window than the run spans, never a wider one. Both lines are emitted after .env.d is sourced and after the env.sandbox block, and both keys are added to reservedSandboxKeys. Position is what protects them: the reserved-key check drops an env.sandbox entry with either name but says nothing about .env.d, so a harness env file sourced above the line would otherwise overwrite them. The iteration-env source stays last because it re-reads a file rewritten before every iteration. That ordering is behaviour, so the script assembly moves out of bootstrapEnv into buildEnvScriptLines and a test pins the run facts after the .env.d line rather than at the end. The SHA is single-quoted with internal quotes escaped, the way every other exported value is, rather than trusting its shape. GITHUB_SHA is not a fallback for the head: on pull_request_target it is the base branch, and a base SHA presented as the head would report a head move on every run. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/cli/run.go | 141 +++++++++++++++++++++++++++----- internal/cli/run_test.go | 8 +- internal/cli/runfacts_test.go | 150 ++++++++++++++++++++++++++++++++++ 3 files changed, 275 insertions(+), 24 deletions(-) create mode 100644 internal/cli/runfacts_test.go diff --git a/internal/cli/run.go b/internal/cli/run.go index 20cb1a664b..c8c599b084 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -506,6 +506,20 @@ func newRunCmd() *cobra.Command { } func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRepo, fullsendBinary string, envFiles []string, noPostScript bool, debug string, forgeFlag string, eventFile string, rFlags resolveFlags, sOpts statusOpts, printer *ui.Printer, keepSandbox bool, oFlags runOverrideFlags) (runErr error) { + // Captured first, before harness resolution, token minting and env + // expansion, each of which can take real time — a mint call retries over + // the network. Anything on the work item after this instant is activity + // the agent must reconcile against, and a later capture would classify + // some of it as predating the run. + // + // This is still not the honest baseline. The run was dispatched before + // this process started, so the true start is the workflow run's + // server-side created_at, which costs an API call to read; no host clock + // inside this process can reach it. The gap runs one way: an agent + // re-checking against this value sees a narrower window than the run + // spans, never a wider one. + runStartedAt := time.Now().UTC() + printer.Banner(Version()) printer.Blank() printer.Header("Running agent: " + agentName) @@ -1973,7 +1987,8 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep printer.StepFail("Failed to bootstrap sandbox") return err } - if err := bootstrapEnv(sandboxName, remoteRepositoryDir, h, rt.EnvExports(), fetchEnvVal); err != nil { + if err := bootstrapEnv(sandboxName, remoteRepositoryDir, h, rt.EnvExports(), + runFacts{headSHA: runHeadSHA(forgePlatform), startedAt: runStartedAt}, fetchEnvVal); err != nil { printer.StepFail("Failed to bootstrap sandbox") return err } @@ -2941,6 +2956,8 @@ var reservedSandboxKeys = map[string]bool{ "FULLSEND_TIMEOUT_MINUTES": true, "FULLSEND_ITERATION_DEADLINE": true, "TRACEPARENT": true, + "FULLSEND_RUN_HEAD_SHA": true, + "FULLSEND_RUN_STARTED_AT": true, // OPENAI_API_KEY is reserved through oidcDenyKeys (merged by init()). // GH_WORKFLOW_TOKEN is reserved through providerOnlyKeys (merged by init()). } @@ -3147,8 +3164,48 @@ func runTerminalError(hasLoop, validationPassed, timedOut bool, runCount int, el return nil } -func bootstrapEnv(sandboxName, remoteRepositoryDir string, h *harness.Harness, runtimeEnvExports []string, fetchEnv ...fetchServiceEnv) error { +// runFacts is what the work item looked like when this run started. It is +// exported into the sandbox so an agent can tell, before it writes its +// result, whether the item moved under it — which it must do because the run +// in flight is no longer cancelled when a newer event arrives. +type runFacts struct { + // headSHA is the work item's head at run start; empty for issues. + headSHA string + // startedAt is when the run started, in UTC. + startedAt time.Time +} + +func bootstrapEnv(sandboxName, remoteRepositoryDir string, h *harness.Harness, runtimeEnvExports []string, facts runFacts, fetchEnv ...fetchServiceEnv) error { remoteEnvFile := sandbox.SandboxWorkspace + "/.env" + + content := strings.Join(buildEnvScriptLines(sandboxName, remoteRepositoryDir, h, runtimeEnvExports, facts, fetchEnv...), "\n") + "\n" + + tmpFile, err := os.CreateTemp("", "fullsend-env-*.sh") + if err != nil { + return fmt.Errorf("creating temp env file: %w", err) + } + defer os.Remove(tmpFile.Name()) + + if _, err := tmpFile.WriteString(content); err != nil { + tmpFile.Close() + return fmt.Errorf("writing temp env file: %w", err) + } + tmpFile.Close() + + if err := sandbox.UploadFile(sandboxName, tmpFile.Name(), remoteEnvFile); err != nil { + return fmt.Errorf("copying .env file to sandbox: %w", err) + } + + return uploadHostFiles(sandboxName, h) +} + +// buildEnvScriptLines assembles the sandbox .env script. +// +// The ORDER of these lines is behaviour, not formatting: later exports win, +// and .env.d is sourced in the middle, so anything that must outrank a +// harness-supplied env file has to come after it. There is a test pinning +// that for the run facts. +func buildEnvScriptLines(sandboxName, remoteRepositoryDir string, h *harness.Harness, runtimeEnvExports []string, facts runFacts, fetchEnv ...fetchServiceEnv) []string { outputDir := sandbox.SandboxWorkspace + "/output" var lines []string @@ -3214,29 +3271,30 @@ func bootstrapEnv(sandboxName, remoteRepositoryDir string, h *harness.Harness, r // overriding a single var from a shared host_files .env file. lines = append(lines, buildSandboxEnvLines(h)...) + // Expose this run's baseline so the agent can re-check, once, whether the + // work item moved under it before it writes its result. + // + // After .env.d, for the same reason env.sandbox is: a file sourced from + // .env.d would otherwise overwrite these. reservedSandboxKeys stops an + // env.sandbox entry shadowing them, but it says nothing about .env.d, so + // position is what actually protects them. It does not close every route — + // a host_files entry whose dest is the runner's own .env replaces the file + // wholesale — and that gap is repo-wide rather than specific to these two + // keys; see the tracking issue. + lines = append(lines, buildRunFactsEnvLines(facts)...) + // Runner-owned budget, deadline, and TRACEPARENT come after every // harness-controlled entry so none of them can shadow the values (#7042). + // This stays the last line: unlike the static exports above it sources a + // file rewritten before every iteration, so it must be re-read after + // everything else. lines = append(lines, iterationEnvSourceLine()) - content := strings.Join(lines, "\n") + "\n" - - tmpFile, err := os.CreateTemp("", "fullsend-env-*.sh") - if err != nil { - return fmt.Errorf("creating temp env file: %w", err) - } - defer os.Remove(tmpFile.Name()) - - if _, err := tmpFile.WriteString(content); err != nil { - tmpFile.Close() - return fmt.Errorf("writing temp env file: %w", err) - } - tmpFile.Close() - - if err := sandbox.UploadFile(sandboxName, tmpFile.Name(), remoteEnvFile); err != nil { - return fmt.Errorf("copying .env file to sandbox: %w", err) - } + return lines +} - // Copy host files into the sandbox. +// uploadHostFiles copies the harness's host_files into the sandbox. +func uploadHostFiles(sandboxName string, h *harness.Harness) error { for _, hf := range h.HostFiles { // Use safeExpandEnv instead of os.ExpandEnv to refuse OIDC // credential vars in host_files src path expansion (#5832). @@ -5351,6 +5409,49 @@ func extractMapString(m map[string]any, keys ...string) string { return "" } +// runHeadSHA returns the work item's head at run start, or "" when the run +// is not against a pull or merge request. +// +// GITHUB_SHA is deliberately not a fallback: on pull_request_target it is the +// base branch, and a base SHA presented as the head would make an agent +// report a head move on every run. +func runHeadSHA(forgePlatform string) string { + if forgePlatform == "gitlab" { + return os.Getenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA") + } + if sha := os.Getenv("PR_HEAD_SHA"); sha != "" { + return sha + } + return prHeadSHAFromEventPath(os.Getenv("GITHUB_EVENT_PATH")) +} + +// buildRunFactsEnvLines exports this run's baseline into the sandbox. +// +// The lines are emitted after the .env.d sourcing and the env.sandbox block, +// so neither can shadow the values. They are runner-owned lines rather than +// env.sandbox entries or ${VAR} references: reservedSandboxKeys drops these +// keys from env.sandbox, and a ${FULLSEND_RUN_*} reference would hard-fail +// ValidateRunnerEnvWith on a host that does not define it. +func buildRunFactsEnvLines(facts runFacts) []string { + // The SHA is forge-supplied. Anything that is not a hex object name is + // exported empty, which the agent reads as "no head", as for an issue + // run. It is still single-quoted like every other exported value here. + head := facts.headSHA + if !gitObjectNameRe.MatchString(head) { + head = "" + } + return []string{ + fmt.Sprintf("export FULLSEND_RUN_STARTED_AT='%s'", facts.startedAt.UTC().Format(time.RFC3339)), + fmt.Sprintf("export FULLSEND_RUN_HEAD_SHA='%s'", strings.ReplaceAll(head, "'", "'\\''")), + } +} + +// gitObjectNameRe matches a hex git object name, abbreviated or full +// (SHA-1 or SHA-256). The 7-64 range is deliberately looser than postreview's +// hexSHARe: tightening it would export a real head as empty and skip the +// agent's moved-head re-check. +var gitObjectNameRe = regexp.MustCompile(`^[0-9a-fA-F]{7,64}$`) + // prHeadSHAFromEventPath extracts pull_request.head.sha from the event // payload embedded in a workflow_dispatch event file. For workflow_dispatch // events, the file contains {"inputs": {"event_payload": ""}}. diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 71a923792c..3fb57c238d 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -3804,7 +3804,7 @@ func TestBootstrapEnv_IncludesFetchServiceVars(t *testing.T) { h := &harness.Harness{Agent: "agents/test.md"} fEnv := fetchServiceEnv{addr: "127.0.0.1:54321", token: "deadbeef"} - err := bootstrapEnv("nonexistent-sandbox", "/workspace/repo", h, nil, fEnv) + err := bootstrapEnv("nonexistent-sandbox", "/workspace/repo", h, nil, runFacts{}, fEnv) // Expected to fail at sandbox.UploadFile — we just verify the fetch // env var code path was reached (coverage) and the error is from upload. @@ -3815,7 +3815,7 @@ func TestBootstrapEnv_IncludesFetchServiceVars(t *testing.T) { func TestBootstrapEnv_SkipsFetchVarsWhenEmpty(t *testing.T) { h := &harness.Harness{Agent: "agents/test.md"} - err := bootstrapEnv("nonexistent-sandbox", "/workspace/repo", h, nil) + err := bootstrapEnv("nonexistent-sandbox", "/workspace/repo", h, nil, runFacts{}) require.Error(t, err) assert.Contains(t, err.Error(), "copying .env file to sandbox") @@ -3837,7 +3837,7 @@ func TestBootstrapEnv_ValidationLoopSchemaPrecedence(t *testing.T) { }, } - err := bootstrapEnv("nonexistent-sandbox", "/workspace/repo", h, nil) + err := bootstrapEnv("nonexistent-sandbox", "/workspace/repo", h, nil, runFacts{}) // Expected to fail at sandbox operations — the schema code path is // exercised before the failure. @@ -3852,7 +3852,7 @@ func TestBootstrapEnv_ValidationLoopSchemaFallback(t *testing.T) { }, } - err := bootstrapEnv("nonexistent-sandbox", "/workspace/repo", h, nil) + err := bootstrapEnv("nonexistent-sandbox", "/workspace/repo", h, nil, runFacts{}) require.Error(t, err) assert.Contains(t, err.Error(), "copying .env file to sandbox") diff --git a/internal/cli/runfacts_test.go b/internal/cli/runfacts_test.go new file mode 100644 index 0000000000..ca4132c956 --- /dev/null +++ b/internal/cli/runfacts_test.go @@ -0,0 +1,150 @@ +package cli + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/harness" +) + +func TestBuildRunFactsEnvLines(t *testing.T) { + at := time.Date(2026, 9, 4, 8, 30, 0, 0, time.UTC) + + t.Run("exports both facts", func(t *testing.T) { + lines := buildRunFactsEnvLines(runFacts{headSHA: "abc1234", startedAt: at}) + assert.Equal(t, []string{ + "export FULLSEND_RUN_STARTED_AT='2026-09-04T08:30:00Z'", + "export FULLSEND_RUN_HEAD_SHA='abc1234'", + }, lines) + }) + + t.Run("an issue run exports an empty head rather than omitting it", func(t *testing.T) { + // The agent skips its re-check on an empty value, so the variable + // must exist and be empty rather than be absent. + lines := buildRunFactsEnvLines(runFacts{startedAt: at}) + assert.Contains(t, lines, "export FULLSEND_RUN_HEAD_SHA=''") + }) + + t.Run("the start is normalised to UTC", func(t *testing.T) { + east := time.FixedZone("UTC+5", 5*60*60) + lines := buildRunFactsEnvLines(runFacts{startedAt: at.In(east)}) + assert.Contains(t, lines, "export FULLSEND_RUN_STARTED_AT='2026-09-04T08:30:00Z'") + }) + + t.Run("a head that is not a hex object name is exported empty", func(t *testing.T) { + for _, head := range []string{"a'; rm -rf /; '", "abc123", "main", strings.Repeat("a", 65)} { + lines := buildRunFactsEnvLines(runFacts{headSHA: head, startedAt: at}) + assert.Contains(t, lines, "export FULLSEND_RUN_HEAD_SHA=''", "head %q", head) + } + }) + + t.Run("full SHA-1 and SHA-256 heads are exported as given", func(t *testing.T) { + for _, head := range []string{strings.Repeat("a", 40), strings.Repeat("B", 64)} { + lines := buildRunFactsEnvLines(runFacts{headSHA: head, startedAt: at}) + assert.Contains(t, lines, "export FULLSEND_RUN_HEAD_SHA='"+head+"'") + } + }) +} + +func TestRunHeadSHA(t *testing.T) { + t.Run("gitlab reads the merge request source sha", func(t *testing.T) { + t.Setenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", "gl123") + assert.Equal(t, "gl123", runHeadSHA("gitlab")) + }) + + t.Run("github prefers the explicit PR_HEAD_SHA", func(t *testing.T) { + t.Setenv("PR_HEAD_SHA", "gh123") + assert.Equal(t, "gh123", runHeadSHA("github")) + }) + + t.Run("github falls back to the dispatched event payload", func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "event.json") + require.NoError(t, os.WriteFile(path, + []byte(`{"inputs":{"event_payload":"{\"pull_request\":{\"head\":{\"sha\":\"ev123\"}}}"}}`), 0o600)) + t.Setenv("PR_HEAD_SHA", "") + t.Setenv("GITHUB_EVENT_PATH", path) + assert.Equal(t, "ev123", runHeadSHA("github")) + }) + + t.Run("an issue run has no head", func(t *testing.T) { + t.Setenv("PR_HEAD_SHA", "") + t.Setenv("GITHUB_EVENT_PATH", "") + assert.Empty(t, runHeadSHA("github")) + }) +} + +func TestRunHeadSHA_NeverFallsBackToTheBaseSHA(t *testing.T) { + // On pull_request_target GITHUB_SHA is the base branch. Presenting it as + // the head would make an agent report a head move on every run. + t.Setenv("PR_HEAD_SHA", "") + t.Setenv("GITHUB_EVENT_PATH", "") + t.Setenv("GITHUB_SHA", "base000") + assert.Empty(t, runHeadSHA("github")) +} + +func TestRunFactsKeysAreReserved(t *testing.T) { + // Reserved so a harness env.sandbox entry cannot shadow the baseline the + // agent's re-check depends on. + assert.True(t, reservedSandboxKeys["FULLSEND_RUN_HEAD_SHA"]) + assert.True(t, reservedSandboxKeys["FULLSEND_RUN_STARTED_AT"]) +} + +// The order of .env is behaviour, not formatting: later entries win, so what +// a value outranks is decided by where it sits. +// +// Two runner-owned groups depend on that. The run facts must follow .env.d +// and env.sandbox, because reservedSandboxKeys stops an env.sandbox entry +// shadowing them but says nothing about a harness host_files file landing in +// .env.d. The iteration source line must be genuinely last, because the file +// it reads is rewritten before every iteration and carries the budget and +// deadline; anything emitted after it would be stale by an iteration. +// +// The whole order is asserted rather than the individual pairs: a change +// that moved iteration sourcing above .env.d would satisfy every pairwise +// claim about the run facts while silently letting a harness env file +// overwrite the budget. +func TestEnvScriptOrderIsPinned(t *testing.T) { + h := &harness.Harness{ + Agent: "agents/test.md", + Env: &harness.EnvConfig{Sandbox: map[string]string{"SOME_VAR": "x"}}, + } + lines := buildEnvScriptLines("", "/workspace/repo", h, nil, + runFacts{headSHA: "abc1234", startedAt: time.Now()}) + + idx := func(substr string) int { + t.Helper() + for i, l := range lines { + if strings.Contains(l, substr) { + return i + } + } + t.Fatalf("no line containing %q in:\n%s", substr, strings.Join(lines, "\n")) + return -1 + } + + envD := idx("/.env.d/*.env") + sandboxVar := idx("export SOME_VAR=") + headSHA := idx("export FULLSEND_RUN_HEAD_SHA=") + startedAt := idx("export FULLSEND_RUN_STARTED_AT=") + iterSource := idx(iterationEnvFile) + + // .env.d → env.sandbox → both run facts → iteration source. + assert.Greater(t, sandboxVar, envD, "env.sandbox must override a shared host_files .env") + assert.Greater(t, headSHA, sandboxVar, "FULLSEND_RUN_HEAD_SHA must outrank env.sandbox and .env.d") + assert.Greater(t, startedAt, sandboxVar, "FULLSEND_RUN_STARTED_AT must outrank env.sandbox and .env.d") + assert.Greater(t, iterSource, headSHA, "the iteration file is sourced after the run facts") + assert.Greater(t, iterSource, startedAt, "the iteration file is sourced after the run facts") + + // Last outright, not merely after the entries checked above: the file is + // rewritten per iteration, so anything emitted later would be stale. + require.NotEmpty(t, lines) + assert.Equal(t, iterationEnvSourceLine(), lines[len(lines)-1], + "the iteration source line must be the final entry in .env") +} From 2bf2e9e32042ef8c3eca46f67333439494f17d19 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 18 Sep 2026 09:47:12 -0400 Subject: [PATCH 3/5] fix(run): report a GitLab merge request head on ordinary MR pipelines On GitLab the head was read from CI_MERGE_REQUEST_SOURCE_BRANCH_SHA alone. GitLab's predefined-variables reference says that variable is empty in merge request pipelines and present only in merged results pipelines, so on an ordinary merge request pipeline the run exported no head at all, the signal reserved for issue runs, and an agent could not notice the branch moving underneath it. CI_COMMIT_SHA fills the gap, but only when the pipeline carries the merge request's own variables: in a merged results pipeline it is the merge result commit rather than the source head, and on a branch pipeline it is the branch. The fallback is therefore gated on CI_MERGE_REQUEST_IID rather than on the pipeline source string, since only a pipeline with the merge request's variables has CI_COMMIT_SHA on the source branch, whatever its source says. In a merged results pipeline the first variable is populated, so the fallback is never reached there. fullsend's own GitLab agent job does not carry those variables. Since #7322 the cron poller raises every agent run as an API pipeline on the protected branch and passes the merge request's IID as STATUS_IID, and CI_COMMIT_SHA is the protected branch's commit. STATUS_IID is deliberately not accepted as "a merge request is known": pairing it with CI_COMMIT_SHA would tell the agent the head moved on every run, the same failure GITHUB_SHA is refused for on GitHub. On that path the head stays empty until the poller passes the source branch's SHA as a pipeline variable of its own, which is a follow-up and is recorded in the function comment and the run reference. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/cli/run.go | 23 +++++++++++++++++- internal/cli/runfacts_test.go | 46 ++++++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index c8c599b084..a73a2b2cd6 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -5417,7 +5417,7 @@ func extractMapString(m map[string]any, keys ...string) string { // report a head move on every run. func runHeadSHA(forgePlatform string) string { if forgePlatform == "gitlab" { - return os.Getenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA") + return gitlabMergeRequestHeadSHA() } if sha := os.Getenv("PR_HEAD_SHA"); sha != "" { return sha @@ -5425,6 +5425,27 @@ func runHeadSHA(forgePlatform string) string { return prHeadSHAFromEventPath(os.Getenv("GITHUB_EVENT_PATH")) } +// gitlabMergeRequestHeadSHA returns the source-branch head of the merge +// request this run was dispatched for, or "" when the run is not against one. +// +// - Merged results pipeline: CI_MERGE_REQUEST_SOURCE_BRANCH_SHA is the head. +// CI_COMMIT_SHA there is the merge-result commit, so it is never used. +// - Ordinary merge request pipeline: that variable is empty, and +// CI_COMMIT_SHA is the source head. CI_MERGE_REQUEST_IID marks this case, +// whatever CI_PIPELINE_SOURCE says. +// - fullsend's poller pipelines (#7322): no CI_MERGE_REQUEST_* variable, and +// CI_COMMIT_SHA is the protected branch. The head is left empty, as for an +// issue run, rather than reported as moving on every run. +func gitlabMergeRequestHeadSHA() string { + if sha := os.Getenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA"); sha != "" { + return sha + } + if os.Getenv("CI_MERGE_REQUEST_IID") != "" { + return os.Getenv("CI_COMMIT_SHA") + } + return "" +} + // buildRunFactsEnvLines exports this run's baseline into the sandbox. // // The lines are emitted after the .env.d sourcing and the env.sandbox block, diff --git a/internal/cli/runfacts_test.go b/internal/cli/runfacts_test.go index ca4132c956..bf5263e941 100644 --- a/internal/cli/runfacts_test.go +++ b/internal/cli/runfacts_test.go @@ -53,11 +53,55 @@ func TestBuildRunFactsEnvLines(t *testing.T) { } func TestRunHeadSHA(t *testing.T) { - t.Run("gitlab reads the merge request source sha", func(t *testing.T) { + // The source-branch SHA is set only in merged results pipelines, so the + // CI_COMMIT_SHA fallback carries the ordinary merge request pipeline where + // it is empty. What gates that fallback is CI_MERGE_REQUEST_IID rather + // than the pipeline source: only a pipeline carrying the merge request's + // own variables has CI_COMMIT_SHA on the source branch. fullsend's + // poller-raised agent pipeline carries none of them and knows the merge + // request through STATUS_IID alone, so it reports no head at all. + t.Run("gitlab prefers the merge request source sha", func(t *testing.T) { t.Setenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", "gl123") + // Present too, and must lose: in a merged results pipeline this is + // the merge-result commit, not the source head. + t.Setenv("CI_COMMIT_SHA", "merge-result-sha") + t.Setenv("CI_MERGE_REQUEST_IID", "42") + t.Setenv("CI_PIPELINE_SOURCE", "merge_request_event") assert.Equal(t, "gl123", runHeadSHA("gitlab")) }) + t.Run("gitlab falls back on an ordinary merge request pipeline", func(t *testing.T) { + t.Setenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", "") + t.Setenv("CI_MERGE_REQUEST_IID", "42") + t.Setenv("CI_PIPELINE_SOURCE", "merge_request_event") + t.Setenv("CI_COMMIT_SHA", "gl456") + assert.Equal(t, "gl456", runHeadSHA("gitlab"), + "an empty source-branch SHA must not be reported as no head at all") + }) + + t.Run("gitlab reports no head when only the poller knows the merge request", func(t *testing.T) { + // The shape fullsend produces since #7322: an API pipeline on the + // protected branch with the MR IID passed as STATUS_IID and no + // CI_MERGE_REQUEST_* variable. CI_COMMIT_SHA is that branch, not the + // merge request's head, so there is no head to report. + t.Setenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", "") + t.Setenv("CI_MERGE_REQUEST_IID", "") + t.Setenv("STATUS_IID", "42") + t.Setenv("CI_PIPELINE_SOURCE", "api") + t.Setenv("CI_COMMIT_SHA", "main-sha") + assert.Empty(t, runHeadSHA("gitlab"), + "the protected branch's commit is not the merge request's head") + }) + + t.Run("gitlab reports no head off a merge request", func(t *testing.T) { + t.Setenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", "") + t.Setenv("CI_MERGE_REQUEST_IID", "") + t.Setenv("CI_PIPELINE_SOURCE", "push") + t.Setenv("CI_COMMIT_SHA", "branch-sha") + assert.Empty(t, runHeadSHA("gitlab"), + "a branch pipeline has no merge request head, and its commit sha is not one") + }) + t.Run("github prefers the explicit PR_HEAD_SHA", func(t *testing.T) { t.Setenv("PR_HEAD_SHA", "gh123") assert.Equal(t, "gh123", runHeadSHA("github")) From 8b9e3d07fef4ef6b5739636706a2d064f6b735ed Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 18 Sep 2026 09:47:32 -0400 Subject: [PATCH 4/5] docs: describe the preserved run and the run baseline it needs The run reference gains a Run baseline section: the two variables, what each holds, that the head is empty rather than absent on an issue run and today on GitLab's poller-raised pipeline, that the start is the runner's own clock and the gap it leaves runs one way, and why the export position after .env.d and env.sandbox is what protects the values. The custom-agent guide and bring-your-own-agent list the variables beside the budget ones and point at that section, and the CLI internals diagram shows where in the env script they land. The CI-workflows conventions record that every stage job in reusable-dispatch.yml carries cancel-in-progress: false, that the value must stay identical across jobs, and what the trade gives up against duplicate poll dispatch. The fix-agent page no longer says a /fs-fix comment cancels the run in flight: it waits as the single pending run and works from the PR's current state. The custom-agent workflow example switches to false and drops the sentence that promised the switch once ADR 0106 was implemented. Assisted-by: Claude Signed-off-by: Wayne Sun --- docs/agents/fix.md | 6 +++-- docs/cli/run.md | 28 ++++++++++++++++++++++ docs/contributing/ci-workflows.md | 2 ++ docs/glossary.md | 4 ++-- docs/guides/dev/cli-internals.md | 2 ++ docs/guides/user/bring-your-own-agent.md | 7 ++++++ docs/guides/user/building-custom-agents.md | 21 ++++++++++------ docs/reference/harness-reference.md | 2 +- 8 files changed, 60 insertions(+), 12 deletions(-) diff --git a/docs/agents/fix.md b/docs/agents/fix.md index 67e21e9bcd..c124cc2a97 100644 --- a/docs/agents/fix.md +++ b/docs/agents/fix.md @@ -102,8 +102,10 @@ The fix agent enforces iteration caps to prevent infinite review-fix loops: `needs-human` label. - When the cap is exceeded, the run fails before the sandbox starts and the status comment shows the escalation message (a human can still `/fs-fix`). -- Each `/fs-fix` comment cancels any in-flight fix run for the same PR and - starts a new one. +- A `/fs-fix` comment while a fix run is already in flight for the same PR does + not cancel it: that run finishes, and the new dispatch waits as the single + pending run (normally but not necessarily the newest event), then works from + the PR's current state ([ADR 0106](../ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md)). ## How it helps diff --git a/docs/cli/run.md b/docs/cli/run.md index 047124e7d8..eaa6e335df 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -277,6 +277,34 @@ variables is deployed. | `clearing stale iteration deadline (iteration N): ...` | The write failed and the previous iteration's file could not be removed either. The run stops rather than let the agent read a stale deadline. | Same as above. | | `FULLSEND_ITERATION_DEADLINE` unset inside the agent | The agent's shell was started without sourcing `/sandbox/workspace/.env`. | Runtimes that fullsend ships always source it; a custom command must do the same. | +## Run baseline + +Alongside the budget, the runner tells the agent what the work item looked like when the run +began. Two more environment variables, set on every runtime (claude, pi, codex): + +| Variable | Value | +|---|---| +| `FULLSEND_RUN_HEAD_SHA` | The work item's head as the event that dispatched the run carried it. Empty on an issue run, which has no head, and today on GitLab, where the poller-raised agent pipeline does not carry the merge request's head. A value that is not a hex object name is exported empty | +| `FULLSEND_RUN_STARTED_AT` | When the run started, RFC 3339 UTC | + +The two are not sampled at the same instant. The head is frozen when the run is dispatched, before +it queues; the start is the runner's own clock at the top of `fullsend run`, after the +concurrency-group wait, which can now last a whole predecessor run, and after the job steps that +precede the command. The gap runs one way. An agent re-checking against the start looks at a +narrower window than the run spans, never a wider one, so it can miss activity that landed while the +run queued or the job was starting but cannot invent any; a head comparison has no such gap. + +The head is empty rather than absent on an issue run — an agent that re-checks it skips the check +on an empty value, which it cannot do for a variable that is not there at all. + +Both are written after the harness's `.env.d` files are sourced and after `env.sandbox` is +applied, so a harness cannot shadow the baseline its own agent's re-check depends on. Position is +what protects them: the reserved-key check drops an `env.sandbox` entry with either name, but says +nothing about `.env.d`. + +Both are captured once, at run start, and are not rewritten between validation-loop iterations, +unlike the deadline above. + ## OpenAI credentials on pi and codex A `fullsend-openai` provider (`providers: [openai]` on the harness, `openai/` models on pi or codex) diff --git a/docs/contributing/ci-workflows.md b/docs/contributing/ci-workflows.md index a230f88dc8..9134221b0d 100644 --- a/docs/contributing/ci-workflows.md +++ b/docs/contributing/ci-workflows.md @@ -26,6 +26,8 @@ Conventions for GitHub Actions workflows under `.github/workflows/`. Follow thes ``` Hybrid workflows that combine `workflow_call` with direct triggers like `pull_request_target` or `push` (e.g., `e2e.yml`, `functional-tests.yml`) may still use `${{ github.workflow }}` in the branch of their concurrency expression that handles direct triggers — the `workflow_call` invocations in these cases come from a thin caller that shares the same concurrency intent. - Never cancel in-progress runs on the default branch (`refs/heads/main`). Gate `cancel-in-progress` when the workflow triggers on `push` to `main`. +- **Agent stage jobs never cancel the run in flight.** Every stage job in `reusable-dispatch.yml` carries `cancel-in-progress: false`. A newer event on the same work item leaves the run already working on it alone; GitHub keeps one pending run per group, the last to queue, normally but not necessarily the newest event, which then works from the item's current state rather than its own event ([ADR 0106](../ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md)). Keep the value identical across every stage job — one role cancelling while another queues on the same item is harder to reason about than either behaviour on its own. The rule covers the dispatch path through `reusable-dispatch.yml`. The scheduler-driven prioritize lane (`prioritize.yml` → `reusable-prioritize.yml`, installed per-repo as well) and the deprecated per-org path ([ADR 0044](../ADRs/0044-deprecate-per-org-installation-mode.md)) still cancel in flight. The trade: [ADR 0063](../ADRs/0063-polling-based-work-discovery.md) counted per-stage cancellation as a layer against duplicate poll dispatch, and that layer is gone, leaving the poller's lock and agent idempotency. +- **Where that trade bites.** The duplicate-poll case is the least comfortable one: two duplicate dispatches are the same work rather than a newer state superseding an older one, so both run to completion instead of one replacing the other. **Why:** A hardcoded prefix like `my-workflow-${{ github.workflow }}` is redundant — `github.workflow` already resolves to the workflow `name:` field. The duplication creates a confusing group key and wastes characters. The reusable-workflow exception exists because GitHub resolves `github.workflow` from the caller's context, so a reusable workflow using it would share a concurrency group with its caller. diff --git a/docs/glossary.md b/docs/glossary.md index 401a8c3baa..314227affb 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -140,8 +140,8 @@ watermark-based deduplication at 5–60 minute intervals reconciliation backstop. [ADR 0106](ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md) additionally adopts preserve-and-coalesce scheduling at the execution-platform -layer: after implementation, an active run finishes while later matching -events collapse into one pending follow-up run. +layer. On GitHub Actions an active run now finishes while later matching events +collapse into one pending follow-up run. See [architecture.md](architecture.md) (building block 1). ### Default Agent diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index ccd70719fe..17420f0a6b 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -471,6 +471,8 @@ Vendoring commit messages use title + body (upload and stale delete). `github st │ │ ├── FULLSEND_FETCH_URL=... (if allow_runtime_fetch)│ │ │ │ ├── FULLSEND_FETCH_TOKEN= (if above)│ │ │ │ ├── sources .env.d/*.env files │ │ +│ │ ├── FULLSEND_RUN_HEAD_SHA + │ │ +│ │ │ FULLSEND_RUN_STARTED_AT │ │ │ │ └── sources .fullsend/iteration.env │ │ │ │ (FULLSEND_TIMEOUT_MINUTES + │ │ │ │ FULLSEND_ITERATION_DEADLINE + │ │ diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index 24d39736b3..d62ca408fd 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -227,6 +227,13 @@ and `TRACEPARENT` (this iteration's agent-span W3C trace context, so runtime tel Fullsend trace; empty when telemetry produced no valid span context). Write the result before the deadline — see [`fullsend run` § Budget and deadline](../../cli/run.md#budget-and-deadline). +It also carries what the work item looked like when the run began: `FULLSEND_RUN_HEAD_SHA` (the head +the dispatching event carried, empty for an issue and today on GitLab's poller-raised pipeline) and +`FULLSEND_RUN_STARTED_AT` (RFC 3339 UTC). The start is the runner's own clock at the top of +`fullsend run`, after the concurrency wait and the job steps that precede the command, so activity +from that gap falls before it — see +[`fullsend run` § Run baseline](../../cli/run.md#run-baseline). + Network access (which APIs the agent can reach) is controlled by provider profiles or inline `network_policies`. The six built-in profiles (`vertex-ai`, `github`, `github-ro`, `github-artifacts`, `gitleaks`, `package-registries`) use framework-known `type` values (e.g. `fullsend-vertex-ai`, `fullsend-github`), but — like a fully custom provider type — still need a matching `openshell.profiles` entry (or one inherited via `base:` composition) to be imported; only the profile's `type` value is framework-known, not its import path. When defining a fully custom provider type, reference a remote provider definition together with a matching `openshell.profiles` entry (see [Remote providers and profiles](customizing-agents.md#remote-providers-and-profiles)). For endpoints not covered by providers, inline `network_policies` in the policy YAML also work. Providers are the pattern used by fullsend's built-in agents, but custom agents can use whichever approach fits. **Next steps:** [Register your agent](#registering-your-agent) so dispatch discovers it, then [write a CEL trigger](cel-triggers-reference.md#writing-cel-triggers) to control when it runs. To iterate on your agent locally before registering, see [Testing locally](#testing-locally). diff --git a/docs/guides/user/building-custom-agents.md b/docs/guides/user/building-custom-agents.md index e0bb43bf06..18aec776c9 100644 --- a/docs/guides/user/building-custom-agents.md +++ b/docs/guides/user/building-custom-agents.md @@ -79,6 +79,12 @@ Environment variables set by the runner, present in every agent's shell: - `TRACEPARENT` — W3C trace context of this iteration's agent span, so runtime telemetry can join the Fullsend trace; empty when telemetry produced no valid span context (see [`fullsend run` § Budget and deadline](../../cli/run.md#budget-and-deadline)) +- `FULLSEND_RUN_HEAD_SHA` — the work item's head as the dispatching event carried it; empty for an issue + and today on GitLab's poller-raised pipeline +- `FULLSEND_RUN_STARTED_AT` — when the run started, RFC 3339 UTC. This is the runner's own clock + at the top of `fullsend run`, after the concurrency wait and the job steps that precede the + command, so activity from that gap falls before it + (see [`fullsend run` § Run baseline](../../cli/run.md#run-baseline)) ## Process @@ -500,7 +506,7 @@ on: concurrency: group: my-agent-${{ inputs.issue_key || 'unknown' }} - cancel-in-progress: true + cancel-in-progress: false jobs: run: @@ -578,12 +584,13 @@ jobs: path: ${{ github.workspace }}/output ``` -This example reflects the currently deployed cancellation policy. Under -[ADR 0106](../../ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md), -the platform will change subject-scoped agent workflows to -`cancel-in-progress: false` once preserve-and-coalesce scheduling is -implemented. Until that migration lands, keep the setting aligned with the -reusable workflow that invokes the agent. +This example matches the platform's scheduling: subject-scoped agent workflows +run with `cancel-in-progress: false`, so a newer event on the same work item +waits as the single pending run and works from current state instead of +cancelling the run in flight +([ADR 0106](../../ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md), +which the reusable dispatch workflow implements). Keep the setting aligned with +the reusable workflow that invokes the agent. ### Critical workflow steps diff --git a/docs/reference/harness-reference.md b/docs/reference/harness-reference.md index 2b2b4d7dc3..377df5d1e0 100644 --- a/docs/reference/harness-reference.md +++ b/docs/reference/harness-reference.md @@ -152,7 +152,7 @@ Most fields are self-explanatory from the inline comments above. This section ex **`validation_loop.max_iterations`** — The maximum number of agent runs in one invocation (default 1). A second run happens only when the agent finished and its output failed validation; an iteration the runner killed at `timeout_minutes` is not retried. See [`fullsend run` § Budget and deadline](../cli/run.md#budget-and-deadline) and [ADR 0105](../ADRs/0105-timed-out-iteration-ends-the-run.md). -**`timeout_minutes`** — Wall-clock budget for one agent iteration, default 30. The runner ends the iteration and sweeps the processes the agent left running in the sandbox (best effort) when it is spent, and a killed iteration ends the run with `agent timed out after without completing (timeout: )` unless its output validates anyway. Before every iteration the runner writes the budget as `FULLSEND_TIMEOUT_MINUTES`, the kill time as `FULLSEND_ITERATION_DEADLINE` (Unix seconds), and the current agent span as `TRACEPARENT` into the agent's environment — see [`fullsend run` § Budget and deadline](../cli/run.md#budget-and-deadline). Those names are reserved: an `env.sandbox` entry with any of them is dropped. +**`timeout_minutes`** — Wall-clock budget for one agent iteration, default 30. The runner ends the iteration and sweeps the processes the agent left running in the sandbox (best effort) when it is spent, and a killed iteration ends the run with `agent timed out after without completing (timeout: )` unless its output validates anyway. Before every iteration the runner writes the budget as `FULLSEND_TIMEOUT_MINUTES`, the kill time as `FULLSEND_ITERATION_DEADLINE` (Unix seconds), and the current agent span as `TRACEPARENT` into the agent's environment — see [`fullsend run` § Budget and deadline](../cli/run.md#budget-and-deadline). These names, and the run baseline's `FULLSEND_RUN_HEAD_SHA` and `FULLSEND_RUN_STARTED_AT` ([`fullsend run` § Run baseline](../cli/run.md#run-baseline)), are reserved: an `env.sandbox` entry with any of them is dropped. **`security.fail_mode`** — Determines what happens when a pre-run security scan finds issues or fails to complete. `closed` (default): the run aborts on scan failure or critical findings. `open`: the run continues with a warning. Omitting the `security` block is equivalent to `fail_mode: closed`. From 3733389431a79aff9ef45f2cc1c4a2bd45c7f96d Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 18 Sep 2026 09:47:33 -0400 Subject: [PATCH 5/5] docs(adr): annotate ADR 0106 and ADR 0063 with the GitHub implementation ADR 0106 decided preserve-and-coalesce and said the reusable workflows must move to cancel-in-progress: false. The change that does so carried its own ADR for a while; with 0106 Accepted on main that record was redundant, so none is added, and 0106 gets the one annotation the ADR rules allow: a short update note under the GitHub Actions paragraph of its Decision naming the pull request, the workflow setting and the two run facts, with a link to the run reference for the detail. ADR 0063's existing update note already says 0106 replaces automatic cancellation. It now also says that on GitHub the per-stage cancellation it counted as a second layer against duplicate poll dispatch is gone, and that the duplicate-poll case is where the trade is least favourable. The architecture overview's serialization bullet gains the GitHub shape: every stage job with cancel-in-progress: false, the last run to queue waiting as the single pending run, and the runner exporting the run facts, pointing at the run reference rather than at a second ADR. Assisted-by: Claude Signed-off-by: Wayne Sun --- docs/ADRs/0063-polling-based-work-discovery.md | 8 +++++++- ...ialize-agent-runs-and-coalesce-subsequent-events.md | 10 ++++++++++ docs/architecture.md | 6 ++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/ADRs/0063-polling-based-work-discovery.md b/docs/ADRs/0063-polling-based-work-discovery.md index 5c58e619fe..c795d3b50b 100644 --- a/docs/ADRs/0063-polling-based-work-discovery.md +++ b/docs/ADRs/0063-polling-based-work-discovery.md @@ -364,7 +364,13 @@ event-driven dispatch already assumes under `cancel-in-progress`. > **Update (2026-09):** [ADR 0106](0106-serialize-agent-runs-and-coalesce-subsequent-events.md) > replaces automatic cancellation with serialized runs and platform-native > pending-run coalescing. Source-native locks and agent idempotency remain -> defense in depth for duplicate dispatch and side effects. +> defense in depth for duplicate dispatch and side effects. On GitHub, every +> stage job in `reusable-dispatch.yml` now carries `cancel-in-progress: false`, +> so layer 2 above is gone, and the duplicate-poll case is where that trade is +> least favourable, because two duplicate dispatches are the same work rather +> than a newer state superseding an older one. The mentions below of GHA +> concurrency as a mitigation for stale-lock races and as the primary safety net +> for same-item re-dispatch describe the cancelling behaviour and no longer hold. Property keys are namespaced by target repo to avoid collisions when multiple repos poll the same Jira project: diff --git a/docs/ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md b/docs/ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md index 1bc7cd27f8..2556f4b223 100644 --- a/docs/ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md +++ b/docs/ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md @@ -114,6 +114,16 @@ MUST derive compatible harness-and-entity identities, but a synchronous `workflow_call` caller and callee MUST retain distinct group-name prefixes so the child does not wait on the parent that is waiting for it. +> **Update (2026-09):** Active-run preservation is implemented on GitHub +> Actions by [#7007](https://github.com/fullsend-ai/fullsend/pull/7007): every +> stage job in `reusable-dispatch.yml` carries `cancel-in-progress: false`, and +> the runner exports `FULLSEND_RUN_HEAD_SHA` and `FULLSEND_RUN_STARTED_AT` so a +> run can tell whether the subject moved under it +> ([`fullsend run` § Run baseline](../cli/run.md#run-baseline)). Keying the +> serialization scope on the canonical subject identity is still pending: +> `harness-run` keys on the item number +> ([#7475](https://github.com/fullsend-ai/fullsend/issues/7475)). + On GitLab CI/CD, a subject-scoped `resource_group` serializes agent jobs. `workflow:auto_cancel:on_new_commit: none` and a non-interruptible agent job preserve active work, while the resource group's `newest_first` process mode diff --git a/docs/architecture.md b/docs/architecture.md index 97df94091a..e7c36512cd 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -314,6 +314,12 @@ The existing design principle is that [the repo is the coordinator](problems/age over other comments and content discovered during reconciliation remains a separate decision ([ADR 0106](ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md)). + On GitHub this is every stage job in `reusable-dispatch.yml` running with + `cancel-in-progress: false`, so the last run to queue, normally but not + necessarily the newest event, waits as the single pending run and works from + current state, and the runner exporting `FULLSEND_RUN_HEAD_SHA` and + `FULLSEND_RUN_STARTED_AT` so an agent can see what moved beneath it + ([`fullsend run` § Run baseline](cli/run.md#run-baseline)). - Dispatch runs no follow-up stage after an agent. Every run publishes the `fullsend-` artifact, and users who want to act on a result chain their own workflow on the shim's `workflow_run` event