From 09fe9855eeb71bc3b13ba1cd2c146c681761bf1e Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Mon, 2 Nov 2026 11:03:17 -0800 Subject: [PATCH] =?UTF-8?q?feat(land):=20mergePolicy.mode=20"auto"=20?= =?UTF-8?q?=E2=80=94=20real=20GitHub=20gate,=20squash=20push?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 3 of cloud#5806. Auto mode lands for real where shadow only planned: - E really runs the repo's gate (`ci.flow.ts {"github":true}`). A gate that finishes inside runner.stageMinutes applies its verdict in-run; one that overruns dies with the sandbox, but the `ci/` snapshot it pushed and the Actions runs it dispatched outlive it, so the next E run finds the snapshot (parent = the head under test) and polls `gh run list` until the dispatched runs complete. Bookkeeping in /github-gate.json, capped at 3 dispatches / 6 awaits. Red feeds the fix loop like a closed gate; green moves to F. - F squashes the land head onto the latest base and pushes with the Relay-Session / Land-Run trailers. A moved base or a non-fast-forward sends the run back to D for a rebase + regate. - fixLoop.harness accepts claude|codex|grok|devin (default codex) and is also passed to the review flows as their clis. - Shadow is unchanged: no write token, E records a would-dispatch, F writes a pushed:false plan, 'landed' still maps to would_land. Tests: 72 pass covering every new transition — pending/green/red at E, push success, moved base and non-FF at F, mode discipline both ways. --- examples/land/README.md | 32 ++- examples/land/land.config.schema.json | 4 +- examples/land/land.flow.ts | 323 +++++++++++++++++++++++-- examples/land/tests/config.test.ts | 2 +- examples/land/tests/flow.test.ts | 233 +++++++++++++++++- examples/land/tests/transition.test.ts | 54 ++++- 6 files changed, 603 insertions(+), 45 deletions(-) diff --git a/examples/land/README.md b/examples/land/README.md index 21ce91af9..32490cee5 100644 --- a/examples/land/README.md +++ b/examples/land/README.md @@ -1,10 +1,11 @@ # land One pinned change — `(repo, sha, session)` — reviewed, gated, fixed and, in -shadow mode, planned as a squash commit that is **never pushed**. This is the +shadow mode, planned as a squash commit that is **never pushed**; in auto +mode, really landed. This is the flows piece of the autonomous land flow spec, [AgentWorkforce/cloud#5806](https://github.com/AgentWorkforce/cloud/issues/5806) -(§5, §7, §8), at rollout phase 0-1: **shadow mode only**. +(§5, §7, §8): shadow at rollout phase 0-1, auto at phase 3. It is generic. Each repository names its own review and CI flows in a `land.config.json` at its root ([schema](land.config.schema.json)); this flow @@ -75,8 +76,8 @@ on every provider, and there is no sudo. So Cloud passes | `B` | the repo's local CI flow, plus the changelog rule. Closes the gate | `D`, `C-`, or `needs_human` | | `C-` | fix round n: one fix agent, a local fixup commit, the formatter guard | `A-adversarial` or `needs_human` | | `D` | fetch the base; rebase if it moved | `A-adversarial` (rebased), `E`, or `needs_human` (conflict) | -| `E` | shadow: records the GitHub gate it would dispatch (`githubGate`, `dispatched: false`). Nothing is dispatched or pushed | `F` | -| `F` | shadow: writes the squash plan into the state with `pushed: false`. Nothing is pushed | `landed` | +| `E` | shadow: records the GitHub gate it would dispatch (`githubGate`, `dispatched: false`). Nothing is dispatched or pushed. auto: dispatches the repo's gate for real — finished inside the window, or as a `ci/` snapshot the next E run awaits on GitHub | `F` (green), `C-` (red), `E` (still running) | +| `F` | shadow: writes the squash plan into the state with `pushed: false`. Nothing is pushed. auto: commits the squash onto the latest base and pushes; a moved base or non-fast-forward goes back to `D` | `landed`, `D` | Terminal states and their run verdicts: `landed` (success), `needs_human`, `cancelled` (canceled) and `failed` (step_failed). Every completion detail is @@ -88,10 +89,19 @@ write token, and relay-desktop's GitHub gate pushes a throwaway `ci/` branch, so a shadow run could never pass it. Stage E therefore always records what it would dispatch (the CI flow, `{"github":true}` and the head sha) and moves on to F. There is no flag to turn it on: `mergePolicy.githubGateInShadow` -was removed, and the validator now rejects it as an unknown key. A real -stage E, including "red → C", belongs in phase 2. A full GitHub run takes -about 30–125 minutes, so it needs a dispatch run and an await run to fit under -the 40-minute ceiling. +was removed, and the validator now rejects it as an unknown key. + +**Stage E in auto mode** really runs the repo's GitHub gate (`ci.flow.ts +{"github":true}`). A full GitHub run takes about 30–125 minutes — more than +any single stage — so the gate runs in two halves. The dispatch run invokes +the repo flow detached and waits one `runner.stageMinutes` window: a gate +short enough to finish applies its verdict at once. A gate that overruns dies +with the sandbox, but the `ci/` snapshot it pushed and the GitHub +Actions runs it dispatched outlive it, so the next E run finds the snapshot +(its parent is the land head under test) and polls the dispatched runs via +`gh run list` until they complete — red goes to the next fix round, green to +F. Bookkeeping lives in `/github-gate.json`, capped at +`GITHUB_GATE_MAX_ATTEMPTS` dispatches and `GITHUB_GATE_MAX_POLLS` awaits. ### Why A splits into one run per review flow @@ -166,8 +176,9 @@ Over the limit, the repo owner is dropped first, then the name is cut with `…`. The ask and the URL are never cut. A URL that cannot fit is refused at the first stage. -`mergePolicy.mode` values `approval` and `auto` pass validation, but a run -refuses them (`declined`): phase 0-1 implements shadow only. +`mergePolicy.mode` values `approval` and `auto` pass validation; a run +refuses `approval` (`declined`). `auto` needs the repository grant's write +token and `gh` on the runner. A finding's id is its source, its file and its normalized title. relay-desktop's `report.json` has no id field. Its verifier moves lines and @@ -183,6 +194,7 @@ These defaults are the spec's proposals, not decisions; each is marked | --- | --- | --- | | `fixLoop.maxRounds` | 4 | Q2 | | `fixLoop.wallclockMinutes` | 180 | Q2 | +| `fixLoop.harness` | `codex` (also the review flows' `clis`; `claude`, `grok` and `devin` accepted) | Q2 | | `fixLoop.model` | unset (harness default) | Q2 | | `mergePolicy.squashAuthor` | `session-human` | Q3 | | `landRef` | `land/{user}/{sha7}` | Q5 | diff --git a/examples/land/land.config.schema.json b/examples/land/land.config.schema.json index d4ed66019..96c0af15e 100644 --- a/examples/land/land.config.schema.json +++ b/examples/land/land.config.schema.json @@ -36,7 +36,7 @@ "type": "object", "additionalProperties": false, "properties": { - "mode": { "enum": ["shadow", "approval", "auto"], "default": "shadow", "description": "Phase 0-1 implements shadow only; approval and auto are refused." }, + "mode": { "enum": ["shadow", "approval", "auto"], "default": "shadow", "description": "shadow plans the squash and never pushes; auto lands it. approval is refused." }, "squashAuthor": { "enum": ["session-human", "agent-with-human-coauthor"], "default": "session-human", "description": "PLACEHOLDER pending decision (cloud#5806 Q3)." }, "approvalDropAfterCleanLandings": { "type": ["integer", "null"], "minimum": 1, "maximum": 1000, "default": null, "description": "PLACEHOLDER pending decision (cloud#5806 Q6)." } } @@ -47,7 +47,7 @@ "properties": { "maxRounds": { "type": "integer", "minimum": 1, "maximum": 10, "default": 4, "description": "PLACEHOLDER pending decision (cloud#5806 Q2)." }, "wallclockMinutes": { "type": "integer", "minimum": 10, "maximum": 720, "default": 180, "description": "PLACEHOLDER pending decision (cloud#5806 Q2)." }, - "harness": { "enum": ["claude", "codex"], "default": "claude" }, + "harness": { "enum": ["claude", "codex", "grok", "devin"], "default": "codex", "description": "Fix agent CLI; also passed to the review flows as their clis. codex is the default for now." }, "model": { "type": "string", "pattern": "^[A-Za-z0-9_.:@/-]+$", "description": "PLACEHOLDER pending decision (cloud#5806 Q2). Unset: the harness's own default." } } }, diff --git a/examples/land/land.flow.ts b/examples/land/land.flow.ts index da979117f..4cd95a1f8 100644 --- a/examples/land/land.flow.ts +++ b/examples/land/land.flow.ts @@ -1,6 +1,6 @@ // land — one pinned change (repo, sha, session) reviewed, gated, fixed and, -// in shadow mode, planned as a squash commit that is never pushed. Spec: -// AgentWorkforce/cloud#5806 §5, §7, §8. Phase 0-1: shadow mode only. +// in shadow mode, planned as a squash commit that is never pushed; in auto +// mode, landed for real. Spec: AgentWorkforce/cloud#5806 §5, §7, §8. // // ONE HOSTED RUN PER STAGE. cloud#5806 Decision A (one hosted run per stage, // 40-min cap unchanged): confirmed by Khaliq, 2026-10-29. Each invocation runs @@ -24,7 +24,11 @@ // D fetch the base; rebased → A again, conflict → needs_human. // E GitHub gate. Shadow never has a write token (cloud#5806 Decision B, // decided), so it records what it would dispatch and moves on to F. +// Auto runs the repo's gate for real, dispatching in one run +// and awaiting the dispatched GitHub runs in the next ones. // F shadow: the would-be squash plan goes into the state. Never push. +// Auto: squash the land head onto the latest base and push; +// a moved base or a non-fast-forward goes back to D. // // Every run starts from a fresh clone of the pinned sha. Fix and rebase // commits are carried between runs in `/land.bundle`, never pushed. @@ -44,7 +48,9 @@ export const shellWord = (value: string): string => `'${value.replaceAll("'", "' export const MERGE_MODES = ['shadow', 'approval', 'auto'] as const; export const CHANGELOG_RULES = ['required', 'optional'] as const; -export const HARNESSES = ['claude', 'codex'] as const; +export const HARNESSES = ['claude', 'codex', 'grok', 'devin'] as const; +/** Harnesses the shipped worker adapters actually support today — grok and devin are accepted names until their adapters land (flows#691). */ +export const WORKER_HARNESSES = new Set(['claude', 'codex']); export const SQUASH_AUTHORS = ['session-human', 'agent-with-human-coauthor'] as const; export const RUNNER_OS = ['linux', 'macos'] as const; export const RUNNER_ARCH = ['x64', 'arm64'] as const; @@ -84,7 +90,7 @@ export const LAND_CONFIG_DEFAULTS = { fixLoop: { maxRounds: 4, // PLACEHOLDER pending decision (cloud#5806 Q2): spec proposes 4 wallclockMinutes: 180, // PLACEHOLDER pending decision (cloud#5806 Q2): spec proposes 3h - harness: 'claude', + harness: 'codex', // the default for now (grok and devin are accepted) model: undefined, // PLACEHOLDER pending decision (cloud#5806 Q2): unset = the harness's own default }, landRef: 'land/{user}/{sha7}', // PLACEHOLDER pending decision (cloud#5806 Q5) @@ -332,7 +338,7 @@ export function unreleasedBulletAdded(before: string, after: string): boolean { // ---------------------------------------------------------------- squash plan -export interface SquashPlan { base: string; baseSha: string; headSha: string; tree: string; author: string; coAuthors: string[]; message: string; pushed: false } +export interface SquashPlan { base: string; baseSha: string; headSha: string; tree: string; author: string; coAuthors: string[]; message: string; pushed: boolean; commit?: string } export function squashPlan(p: { base: string; baseSha: string; headSha: string; tree: string; subjects: string[]; sessionId: string; runId: string; squashAuthor: LandConfig['mergePolicy']['squashAuthor']; fixRounds: number; harness: string }): SquashPlan { const [subject = `Land ${p.headSha.slice(0, 7)}`, ...rest] = p.subjects; @@ -393,8 +399,16 @@ export type StageResult = { now: number } & ( | { kind: 'ci'; findings: Finding[] } | { kind: 'fix'; headSha: string; guard: { ok: boolean; detail: string } } | { kind: 'rebase'; outcome: 'unchanged' | 'rebased' | 'conflict'; baseSha: string; headSha: string; detail?: string } - | { kind: 'github'; wouldDispatch: GithubDispatch } - | { kind: 'merge'; plan: SquashPlan } + | { kind: 'github'; outcome: 'shadow'; wouldDispatch: GithubDispatch } + /** Auto: the gate dispatched GitHub-side work that is still running. Cursor stays at E. */ + | { kind: 'github'; outcome: 'pending' } + | { kind: 'github'; outcome: 'green' } + /** Auto: the gate came back red; `findings` feed the fix loop like a closed gate. */ + | { kind: 'github'; outcome: 'red'; findings: Finding[] } + | { kind: 'merge'; outcome: 'planned'; plan: SquashPlan } + | { kind: 'merge'; outcome: 'pushed'; plan: SquashPlan; commit: string } + /** Auto: the base moved since the last gate, or the push was not a fast-forward; back to D. */ + | { kind: 'merge'; outcome: 'moved' | 'non_ff' } ); const KIND: Record = { 'A-adversarial': 'review', 'A-context': 'review', B: 'ci', D: 'rebase', E: 'github', F: 'merge' }; @@ -411,14 +425,24 @@ export function nextLandStage(state: LandState, result: StageResult): LandState const at = state.cursor; const end = (terminal: Terminal, detail: string): LandState => { s.cursor = null; s.terminal = { state: terminal, detail }; s.log.push(`${at}: ${terminal}`); return s; }; const escalate = (reason: string, detail: string): LandState => { s.escalation = { reason, detail }; return end('needs_human', detail); }; - const regate = (head: string) => { s.headSha = head; s.lanes = {}; s.cursor = 'A-adversarial'; }; + const regate = (head: string) => { s.headSha = head; s.lanes = {}; s.githubGate = undefined; s.cursor = 'A-adversarial'; }; if (result.kind === 'superseded') return end('cancelled', `superseded: land ref now ${result.refSha ?? 'deleted'}, run pinned ${state.pinnedSha}`); const want = at.startsWith('C-') ? 'fix' : KIND[at]; if (result.kind !== want) throw new Error(`stage ${at} cannot take a ${result.kind} result`); - const closeGate = (findings: Finding[]): LandState => { + const closeGate = (findings: Finding[], mergeIntoRound = false): LandState => { const ids = findings.map(x => x.id); - s.history.push(ids); s.gates.push({ head: s.headSha, blocking: ids.length, ids }); s.findings = findings; s.lanes = {}; + if (mergeIntoRound && s.history.length > 0) { + // A red GitHub gate closes this repair round, it does not open a new + // one: appending a separate entry would interleave [] and [G] so the + // stall checks never see two consecutive identical rounds. + const merged = [...new Set([...s.history.at(-1)!, ...ids])]; + s.history[s.history.length - 1] = merged; + s.gates[s.gates.length - 1] = { head: s.headSha, blocking: merged.length, ids: merged }; + } else { + s.history.push(ids); s.gates.push({ head: s.headSha, blocking: ids.length, ids }); + } + s.findings = findings; s.lanes = {}; const decision = decideConvergence({ history: s.history, roundsDone: s.round, maxRounds: s.config.fixLoop.maxRounds, elapsedMs: result.now - s.startedAt, budgetMs: s.config.fixLoop.wallclockMinutes * 60_000 }); s.log.push(`${at}: gate ${s.gates.length} closed with ${ids.length} blocking`); if (decision.action === 'proceed') { s.cursor = 'D'; return s; } @@ -450,22 +474,49 @@ export function nextLandStage(state: LandState, result: StageResult): LandState regate(result.headSha); return s; case 'github': - // Decision B: no write token in shadow, so nothing is dispatched. The - // dispatch/await split and "red → C" belong to phase 2. - s.githubGate = result.wouldDispatch; - s.log.push(`E: shadow: would dispatch ${result.wouldDispatch.flow} {"github":true} at ${result.wouldDispatch.headSha.slice(0, 7)}`); - s.cursor = 'F'; - return s; + if (result.outcome === 'shadow') { + if (s.config.mergePolicy.mode !== 'shadow') throw new Error(`stage E cannot take a shadow outcome under ${s.config.mergePolicy.mode}`); + // Decision B: no write token in shadow, so nothing is dispatched. + s.githubGate = result.wouldDispatch; + s.log.push(`E: shadow: would dispatch ${result.wouldDispatch.flow} {"github":true} at ${result.wouldDispatch.headSha.slice(0, 7)}`); + s.cursor = 'F'; + return s; + } + if (s.config.mergePolicy.mode === 'shadow') throw new Error(`stage E cannot take a ${result.outcome} outcome under shadow`); + if (result.outcome === 'pending') { + s.log.push('E: dispatched GitHub gate still running; awaiting it in the next stage run'); + s.cursor = 'E'; + return s; + } + if (result.outcome === 'green') { + s.log.push('E: GitHub gate green'); + s.cursor = 'F'; + return s; + } + // A red GitHub gate feeds the fix loop like a closed gate: the same + // convergence rules bound the C ↔ E loop. + s.log.push(`E: GitHub gate red with ${result.findings.length} blocking`); + return closeGate(result.findings, true); case 'merge': - s.squashPlan = result.plan; - return end('landed', `shadow: would land ${s.repo}@${result.plan.headSha.slice(0, 7)} on ${s.config.baseBranch} after ${s.round} fix round(s); not pushed`); + if (result.outcome === 'planned') { + s.squashPlan = result.plan; + return end('landed', `shadow: would land ${s.repo}@${result.plan.headSha.slice(0, 7)} on ${s.config.baseBranch} after ${s.round} fix round(s); not pushed`); + } + if (s.config.mergePolicy.mode === 'shadow') throw new Error(`stage F cannot take a ${result.outcome} outcome under shadow`); + if (result.outcome === 'pushed') { + s.squashPlan = { ...result.plan, pushed: true, commit: result.commit }; + return end('landed', `landed ${s.repo}@${result.commit.slice(0, 7)} on ${s.config.baseBranch} after ${s.round} fix round(s)`); + } + s.log.push(`F: ${result.outcome === 'moved' ? 'base moved since the last gate' : 'push was not a fast-forward'}; back to D`); + s.cursor = 'D'; + return s; } } /** The completion detail Cloud chains on. */ export function completionDetail(s: LandState, noop = false): string { return JSON.stringify(s.terminal - ? { land: 'terminal', runId: s.runId, state: s.terminal.state, seq: s.seq, detail: s.terminal.detail } + ? { land: 'terminal', runId: s.runId, state: s.terminal.state, seq: s.seq, detail: s.terminal.detail, ...(s.squashPlan?.commit ? { commit: s.squashPlan.commit } : {}) } : { land: 'next', runId: s.runId, stage: s.cursor, seq: s.seq, ...(noop ? { noop: true } : {}) }); } @@ -500,7 +551,7 @@ const writeFile = (path: string, content: string): string => * inside this stage's sandbox and is polled in 5-minute steps, never past * runner.stageMinutes. Nothing outlives the hosted run. */ -export async function background(f: Ctx, dir: string, command: string, minutes: number): Promise<{ exitCode: number; tail: string }> { +async function pollBackground(f: Ctx, dir: string, command: string, minutes: number): Promise<{ exitCode: number; tail: string } | 'pending'> { const exit = `${dir}/exit`; await f.run(`mkdir -p ${shellWord(dir)} && rm -f ${shellWord(exit)} && ` + `{ nohup sh -c ${shellWord(`${command}; echo $? > ${exit}.tmp && mv ${exit}.tmp ${exit}`)} > ${shellWord(`${dir}/log`)} 2>&1 < /dev/null & } && echo started`); @@ -509,7 +560,13 @@ export async function background(f: Ctx, dir: string, command: string, minutes: const out = (await f.run(`for i in $(seq 1 ${seconds}); do if [ -f ${shellWord(exit)} ]; then cat ${shellWord(exit)}; exit 0; fi; sleep 1; done; echo pending`, { timeout: '6m' })).trim(); if (out !== 'pending') return { exitCode: Number(out), tail: await f.run(`tail -c 1500 ${shellWord(`${dir}/log`)}`) }; } - throw new NeedsHuman(`${dir.split('/').pop()} did not finish within runner.stageMinutes (${minutes}m); log at ${dir}/log`); + return 'pending'; +} + +export async function background(f: Ctx, dir: string, command: string, minutes: number): Promise<{ exitCode: number; tail: string }> { + const result = await pollBackground(f, dir, command, minutes); + if (result === 'pending') throw new NeedsHuman(`${dir.split('/').pop()} did not finish within runner.stageMinutes (${minutes}m); log at ${dir}/log`); + return result; } interface Run { input: ReturnType; state: LandState; base: string; flowsState: string; dir: string } @@ -524,7 +581,9 @@ const stateName = (path: string): string => path.split('/').pop()!.replace(/\.fl async function review(f: Ctx, r: Run, lane: 'adversarial' | 'context'): Promise { const path = r.state.config.reviewFlows[lane]; // The adversarial fleet never receives the intent: not as input, env or path. - const input = lane === 'context' ? { base: r.base, intentFile: r.input.intentFile } : { base: r.base }; + // The land run's harness is also the review fleet's cli set for now. + const clis = [r.state.config.fixLoop.harness]; + const input = lane === 'context' ? { base: r.base, intentFile: r.input.intentFile, clis } : { base: r.base, clis }; const run = await background(f, `${r.dir}/${lane}`, repoFlowCommand(r, lane, path, input), r.state.config.runner.stageMinutes); const report = `${r.flowsState}/${stateName(path)}/report.json`; const raw = await f.run(`if [ -f ${shellWord(report)} ]; then cp ${shellWord(report)} ${shellWord(`${r.dir}/${lane}.report.json`)} && ` + @@ -573,7 +632,11 @@ async function fixRound(f: Ctx, r: Run, round: number): Promise { async function rebaseCheck(f: Ctx, r: Run): Promise { const latest = (await f.run(`git rev-parse ${shellWord(r.base)}`)).trim(); const headSha = r.state.headSha; - if (latest === r.state.baseSha) return { kind: 'rebase', outcome: 'unchanged', baseSha: latest, headSha, now: await now(f) }; + // An unchanged base still needs a rebase when the head does not contain it: + // the submitted head can predate commits already on the base at submit time. + if (latest === r.state.baseSha && (await f.run(`git merge-base --is-ancestor ${shellWord(latest)} ${shellWord(headSha)}`, { onNonZero: 'record' })).ok) { + return { kind: 'rebase', outcome: 'unchanged', baseSha: latest, headSha, now: await now(f) }; + } const rebased = await f.run(`${LOCAL} rebase --quiet ${shellWord(latest)}`, { timeout: '5m', onNonZero: 'record' }); if (!rebased.ok) { await f.run('git rebase --abort'); @@ -582,6 +645,163 @@ async function rebaseCheck(f: Ctx, r: Run): Promise { return { kind: 'rebase', outcome: 'rebased', baseSha: latest, headSha: (await f.run('git rev-parse HEAD')).trim(), now: await now(f) }; } +// ------------------------------------------------------------- github gate + +/** + * Stage E's cross-run bookkeeping, kept in `/github-gate.json`: the + * file survives the sandbox; the dispatch's detached process does not. The + * contract with the repo's GitHub gate (cloud#5806 §7): it pushes a throwaway + * `ci/` snapshot branch and dispatches GitHub Actions workflows on it — + * both observable from a fresh sandbox, which is what the await phase needs. + */ +interface GithubGateBook { + /** The land head under test; a gate book for another head is discarded. */ + headSha: string; + /** ISO lower bound for matching dispatched runs (dispatch time minus slack). */ + since: string; + /** The pushed `ci/` snapshot, once discovered on origin. */ + snapshotSha?: string; + /** Sorted run ids observed at the last check; the set must be stable across two checks before a verdict. */ + seenRunIds?: number[]; + polls: number; + attempts: number; +} + +/** Dispatch attempts for one head before the run gives up waiting for a verdict. */ +export const GITHUB_GATE_MAX_ATTEMPTS = 3; +/** Await stage runs polling one dispatch before escalation (~3.5h at stageMinutes 35). */ +export const GITHUB_GATE_MAX_POLLS = 6; + +/** `gh run list` for the runs dispatched on one snapshot commit, filtered client-side on `since`. */ +const GH_RUN_LIST = (sha: string): string => + `gh run list --commit ${shellWord(sha)} --event workflow_dispatch --limit 50 --json databaseId,workflowName,status,conclusion,createdAt`; + +interface GhRun { databaseId: number; workflowName: string; status: string; conclusion: string | null; createdAt: string } + +/** Failed dispatched runs become blocking findings, id-stable across fix rounds. */ +const githubFindings = (runs: GhRun[]): Finding[] => + runs.filter(x => x.conclusion !== 'success') + .map(x => ({ id: `github:${x.workflowName}`, source: 'github', severity: 'blocker', file: '', title: `GitHub ${x.workflowName}: ${x.conclusion ?? 'failed'}` })); + +/** The `ci/` snapshot the gate pushed for this head (its parent is the head). 'fetch-failed' means the fetch errored — distinct from "no snapshot found". */ +const snapshotForHead = async (f: Ctx, headSha: string): Promise => { + const fetched = await f.run(`git fetch --quiet origin ${shellWord('+refs/heads/ci/*:refs/remotes/ci/*')}`, { onNonZero: 'record' }); + if (!fetched.ok) return 'fetch-failed'; + return (await f.run( + `for sha in $(git for-each-ref --sort=-committerdate --format='%(objectname)' refs/remotes/ci); do ` + + `if [ "$(git rev-parse "$sha^" 2>/dev/null)" = ${shellWord(headSha)} ]; then echo "$sha"; break; fi; done`)).trim() || undefined; +}; + +const writeBook = async (f: Ctx, file: string, book: GithubGateBook): Promise => { + await f.run(writeFile(file, JSON.stringify(book))); + return book; +}; + +/** Best effort: the snapshot branch is the gate's, cleanup must not fail the verdict. */ +const deleteSnapshot = (f: Ctx, snapshotSha: string) => + f.run(`git push --quiet origin --delete ${shellWord(`ci/${snapshotSha.slice(0, 12)}`)}`, { onNonZero: 'record' }); + +async function githubGate(f: Ctx, r: Run): Promise { + const file = `${r.input.stateDir}/github-gate.json`; + const minutes = r.state.config.runner.stageMinutes; + const saved = JSON.parse((await f.run(`cat ${shellWord(file)} 2>/dev/null || echo null`)).trim()) as GithubGateBook | null; + let book = saved && saved.headSha === r.state.headSha ? saved : null; + + // A reaped dispatch leaves a book without a snapshot: recover the one it + // pushed (if it got that far) instead of counting a fresh attempt. A failed + // fetch is not "no snapshot" — it keeps the run pending under the polls + // bound rather than burning a dispatch attempt. + if (book && !book.snapshotSha) { + const recovered = await snapshotForHead(f, r.state.headSha); + if (recovered === 'fetch-failed') { + const next = { ...book, polls: book.polls + 1 }; + if (next.polls >= GITHUB_GATE_MAX_POLLS) throw new NeedsHuman(`GitHub gate on ${r.state.headSha.slice(0, 7)}: cannot list ci/ refs after ${GITHUB_GATE_MAX_POLLS} stage runs`); + await writeBook(f, file, next); + return { kind: 'github', outcome: 'pending', now: await now(f) }; + } + if (recovered) book = await writeBook(f, file, { ...book, snapshotSha: recovered }); + else if (book.attempts >= GITHUB_GATE_MAX_ATTEMPTS) throw new NeedsHuman(`GitHub gate was dispatched ${GITHUB_GATE_MAX_ATTEMPTS} times without a verdict`); + } + + if (book?.snapshotSha) { + // Await phase: poll the dispatched runs until they are all complete and + // the observed set is stable across two checks. A set that is still + // growing means the previous stage died mid-dispatch — an early verdict + // on a subset could pass a gate whose remaining workflows never ran. + const snapshotSha = book.snapshotSha; + let awaiting = book; + for (let poll = 0; poll * POLL_SECONDS < minutes * 60; poll++) { + const seconds = Math.min(POLL_SECONDS, minutes * 60 - poll * POLL_SECONDS); + // The inner loop waits out the window unless every observed run has + // completed — an incomplete set must sleep and re-poll, not return and + // let the outer loop burn its stage window in seconds. + const nodeFilter = + `const runs=JSON.parse(require('fs').readFileSync(0,'utf8')).filter(r=>r.createdAt>=process.argv[1]);` + + `if(!runs.length||runs.some(r=>r.status!=='completed'))process.exit(2);` + + `process.stdout.write(JSON.stringify(runs))`; + const out = (await f.run( + `for i in $(seq 1 ${Math.ceil(seconds / 15)}); do ` + + `if ${GH_RUN_LIST(snapshotSha)} 2>/dev/null | node -e ${shellWord(nodeFilter)} ${shellWord(awaiting.since)}; then exit 0; fi; ` + + `sleep 15; done; echo pending`, { timeout: '6m' })).trim(); + if (out === 'pending' || !out) continue; + const runs = JSON.parse(out.split('\n').pop()!) as GhRun[]; + const ids = runs.map(x => x.databaseId).sort((a, b) => a - b); + const sameSet = awaiting.seenRunIds !== undefined + && ids.length === awaiting.seenRunIds.length && ids.every((id, i) => id === awaiting.seenRunIds![i]); + if (!sameSet) { + awaiting = await writeBook(f, file, { ...awaiting, seenRunIds: ids }); + continue; + } + await deleteSnapshot(f, snapshotSha); + const findings = githubFindings(runs); + if (!findings.length) return { kind: 'github', outcome: 'green', now: await now(f) }; + return { kind: 'github', outcome: 'red', findings, now: await now(f) }; + } + const next = { ...awaiting, polls: awaiting.polls + 1 }; + if (next.polls >= GITHUB_GATE_MAX_POLLS) throw new NeedsHuman(`GitHub gate on ${snapshotSha.slice(0, 7)} still running after ${GITHUB_GATE_MAX_POLLS} await stage runs`); + await writeBook(f, file, next); + return { kind: 'github', outcome: 'pending', now: await now(f) }; + } + + // Dispatch phase: the attempt is persisted BEFORE the wait — a stage reaped + // mid-dispatch must not relaunch (repeating expensive dispatches) or burn a + // second attempt slot for the same dispatch. It either finishes inside this + // stage's window — the verdict applies at once — or dies with the sandbox + // having already pushed its snapshot and dispatched its runs. `since` is + // bound now, not after the wait: runs dispatched early in the window must + // not be filtered out by a bound taken at timeout. + const attempts = (book?.attempts ?? 0) + 1; + if (attempts > GITHUB_GATE_MAX_ATTEMPTS) throw new NeedsHuman(`GitHub gate was dispatched ${GITHUB_GATE_MAX_ATTEMPTS} times without a verdict`); + const since = new Date(await now(f) - 10 * 60_000).toISOString(); + book = await writeBook(f, file, { headSha: r.state.headSha, since, polls: 0, attempts }); + const run = await pollBackground(f, `${r.dir}/github`, repoFlowCommand(r, 'github', r.state.config.ciFlow, { base: r.base, github: true }), minutes); + if (run !== 'pending') { + // The gate deletes its snapshot on a clean exit; cover a crash so + // in-window verdicts cannot leak `ci/` branches either. + const leaked = await snapshotForHead(f, r.state.headSha); + if (leaked && leaked !== 'fetch-failed') await deleteSnapshot(f, leaked); + const report = `${r.flowsState}/${stateName(r.state.config.ciFlow)}/report.json`; + const raw = await f.run(`if [ -f ${shellWord(report)} ]; then node -e ${shellWord( + "const r=JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));" + + "process.stdout.write(JSON.stringify({results:(r.results||[]).filter(x=>!x.ok).slice(0,20).map(({job,step,output})=>({job,step,output:String(output||'').slice(0,200)}))}))")} ${shellWord(report)}; else echo '{}'; fi`); + const red = (JSON.parse(raw).results ?? []) as Array<{ job: string; step: string; output: string }>; + if (run.exitCode === 0 && red.length === 0) return { kind: 'github', outcome: 'green', now: await now(f) }; + const findings: Finding[] = red.length + ? red.map(x => ({ id: `github:${x.job}:${x.step}`, source: 'github', severity: 'blocker', file: '', title: `GitHub gate ${x.job}: ${x.step} — ${x.output.slice(0, 120)}` })) + : [{ id: 'github:run-failed', source: 'github', severity: 'blocker', file: '', title: `github gate ended red without a report: ${run.tail.slice(-300)}` }]; + return { kind: 'github', outcome: 'red', findings, now: await now(f) }; + } + + // Killed mid-wait: find the snapshot it pushed — its parent is this head. A + // failed fetch leaves the book snapshot-less; the next stage run's recovery + // path retries instead of redispatching. + const snapshotSha = await snapshotForHead(f, r.state.headSha); + if (snapshotSha !== 'fetch-failed') await writeBook(f, file, { ...book, snapshotSha }); + return { kind: 'github', outcome: 'pending', now: await now(f) }; +} + +// ---------------------------------------------------------------------- + async function merge(f: Ctx, r: Run): Promise { const s = r.state; const subjects = (await f.run(`git log --reverse --no-merges --format=%s ${shellWord(s.pinnedSha)} --not ${shellWord(r.base)}`)).split('\n').filter(Boolean); @@ -589,7 +809,37 @@ async function merge(f: Ctx, r: Run): Promise { base: s.config.baseBranch, baseSha: s.baseSha, headSha: s.headSha, tree: (await f.run('git rev-parse HEAD^{tree}')).trim(), subjects, sessionId: s.sessionId, runId: s.runId, squashAuthor: s.config.mergePolicy.squashAuthor, fixRounds: s.round, harness: s.config.fixLoop.harness, }); - return { kind: 'merge', plan, now: await now(f) }; + if (s.config.mergePolicy.mode === 'shadow') return { kind: 'merge', outcome: 'planned', plan, now: await now(f) }; + // Spec §9: rebase onto the latest base right before push. A base that moved + // since the last green gate sends the run back through D for a regate — + // unless the move is this run's own squash commit. A stage reaped after the + // push but before the state write must not land the same change twice. + const latest = (await f.run(`git rev-parse ${shellWord(r.base)}`)).trim(); + if (latest !== s.baseSha) { + const landed = (await f.run( + `git log --format=%H --grep=${shellWord(`Land-Run: ${s.runId}$`)} -5 ${shellWord(r.base)}`)).trim().split('\n')[0]!; + if (landed) return { kind: 'merge', outcome: 'pushed', plan: { ...plan, headSha: s.headSha, baseSha: latest }, commit: landed, now: await now(f) }; + return { kind: 'merge', outcome: 'moved', now: await now(f) }; + } + // The squash's tree is the head's, attached to the base as a plain child — + // nothing merges the base's content. If the head never contained the base + // (it branched before commits already on it when the run started), pushing + // that tree would silently revert those base changes. Back to D, which + // rebases the head onto the base; the regate then covers the real tree. + if (!(await f.run(`git merge-base --is-ancestor ${shellWord(latest)} HEAD`, { onNonZero: 'record' })).ok) { + return { kind: 'merge', outcome: 'moved', now: await now(f) }; + } + const ident = 'GIT_AUTHOR_NAME="${LAND_AUTHOR_NAME:-Agent Relay Land}" GIT_AUTHOR_EMAIL="${LAND_AUTHOR_EMAIL:-land@agentrelay.com}" ' + + 'GIT_COMMITTER_NAME="${LAND_AUTHOR_NAME:-Agent Relay Land}" GIT_COMMITTER_EMAIL="${LAND_AUTHOR_EMAIL:-land@agentrelay.com}"'; + const commit = (await f.run(`${ident} git commit-tree ${shellWord(plan.tree)} -p ${shellWord(latest)} -m ${shellWord(plan.message)}`)).trim(); + const push = await f.run(`git push origin ${shellWord(`${commit}:refs/heads/${s.config.baseBranch}`)}`, { timeout: '5m', onNonZero: 'record' }); + if (!push.ok) { + // Only an actual stale base retries through D; a permission or protected + // branch rejection is permanent and escalates instead of looping. + if (/non-fast-forward|fetch first|stale info/i.test(push.output)) return { kind: 'merge', outcome: 'non_ff', now: await now(f) }; + throw new NeedsHuman(`push to ${s.config.baseBranch} failed: ${push.output.slice(-500)}`); + } + return { kind: 'merge', outcome: 'pushed', plan, commit, now: await now(f) }; } async function runStage(f: Ctx, r: Run): Promise { @@ -600,7 +850,10 @@ async function runStage(f: Ctx, r: Run): Promise { } if (at === 'B') return { kind: 'ci', findings: await localCi(f, r), now: await now(f) }; if (at === 'D') return rebaseCheck(f, r); - if (at === 'E') return { kind: 'github', wouldDispatch: { flow: r.state.config.ciFlow, input: { base: r.base, github: true }, headSha: r.state.headSha, dispatched: false }, now: await now(f) }; + if (at === 'E') { + if (r.state.config.mergePolicy.mode === 'shadow') return { kind: 'github', outcome: 'shadow', wouldDispatch: { flow: r.state.config.ciFlow, input: { base: r.base, github: true }, headSha: r.state.headSha, dispatched: false }, now: await now(f) }; + return githubGate(f, r); + } if (at === 'F') return merge(f, r); return fixRound(f, r, Number(at.slice(2))); } @@ -640,12 +893,30 @@ export async function land(f: Ctx, raw: LandInput): Promise { const config = state?.config ?? parseLandConfig(typeof input.config === 'string' ? JSON.parse(await f.run(`git show ${shellWord(`${input.sha}:${input.config}`)}`)) : input.config); if (input.baseBranch && input.baseBranch !== config.baseBranch) throw new NeedsHuman(`input baseBranch ${input.baseBranch} disagrees with land.config ${config.baseBranch}`); - if (config.mergePolicy.mode !== 'shadow') return f.done('declined', { detail: JSON.stringify({ land: 'declined', detail: `mergePolicy.mode "${config.mergePolicy.mode}" is not implemented in phase 0-1; only shadow runs` }) }); + if (config.mergePolicy.mode === 'approval') return f.done('declined', { detail: JSON.stringify({ land: 'declined', detail: 'mergePolicy.mode "approval" is not implemented; shadow and auto run' }) }); const uname = (await f.run('uname -sm')).trim(); const want = `${config.runner.os === 'linux' ? 'Linux' : 'Darwin'} ${config.runner.arch === 'x64' ? 'x86_64' : 'arm64'}`; if (uname.replace('aarch64', 'arm64') !== want) throw new NeedsHuman(`runner is ${uname}; land.config needs ${want}`); await f.run(config.runner.commands.map(c => `command -v ${shellWord(c)} >/dev/null`).join(' && ') || 'true'); + if (config.mergePolicy.mode === 'auto') { + // Preflight, not polling: the GitHub gate and the push need an authed gh + // and a write-capable git credential; prove both at stage one. + const gh = await f.run(`command -v gh >/dev/null && gh auth status`, { onNonZero: 'record' }); + if (!gh.ok) throw new NeedsHuman('mergePolicy.mode "auto" needs gh installed and authenticated (a write repository grant); shadow runs do not'); + // Write access is proven by dry-running a push to a fresh throwaway ref: + // a create is always a fast-forward, so an advanced base or a rebase + // pending at D/F can never turn this check into a false refusal. + const pushable = await f.run(`git push --dry-run origin HEAD:refs/heads/land-probe/${shellWord(input.runId)}-$$`, { onNonZero: 'record', timeout: '2m' }); + if (!pushable.ok) throw new NeedsHuman(`mergePolicy.mode "auto" needs a push-capable git credential (a write repository grant): ${pushable.output.slice(-300)}`); + } + // grok and devin are accepted config names for forward compatibility, but + // the worker adapters for them land with flows#691 and a relayflows + // release — refuse clearly at stage one rather than dying inside C-n or + // a review fleet. + if (!WORKER_HARNESSES.has(config.fixLoop.harness)) { + throw new NeedsHuman(`fixLoop.harness "${config.fixLoop.harness}" has no worker adapter in this relayflows release (grok and devin arrive with flows#691); use "codex" until then`); + } const base = `origin/${config.baseBranch}`; // Hosted runs clone the land ref shallow, and merge-base against the base // needs the shared history: the base fetch also deepens a shallow diff --git a/examples/land/tests/config.test.ts b/examples/land/tests/config.test.ts index c12dc89c6..6f14145ae 100644 --- a/examples/land/tests/config.test.ts +++ b/examples/land/tests/config.test.ts @@ -13,7 +13,7 @@ test('defaults: mergePolicy is shadow, placeholders are the spec proposals', () assert.equal(c.mergePolicy.mode, 'shadow'); assert.equal(c.fixLoop.maxRounds, 4); assert.equal(c.fixLoop.wallclockMinutes, 180); - assert.equal(c.fixLoop.harness, 'claude'); + assert.equal(c.fixLoop.harness, 'codex'); assert.equal(c.fixLoop.model, undefined); assert.equal(c.changelog, 'optional'); assert.equal(c.baseBranch, 'main'); diff --git a/examples/land/tests/flow.test.ts b/examples/land/tests/flow.test.ts index 8221e4e72..718fb3117 100644 --- a/examples/land/tests/flow.test.ts +++ b/examples/land/tests/flow.test.ts @@ -17,10 +17,16 @@ const blocker = (file: string, title: string): Raw => ({ severity: 'blocker', fi * One persistent sandbox world (stateDir survives between hosted runs; the * checkout is a fresh clone each run). Each `invoke` is one hosted stage run. */ +const snapshotSha = '9'.repeat(40); +const mergedCommit = 'e'.repeat(40); + function world(over: { config?: unknown; head?: string; adversarial?: Raw[][]; context?: Raw[][]; ciRed?: number[]; roundFiles?: string[][]; baseShas?: string[]; rebaseFails?: boolean; changelog?: [string, string]; refSha?: string; home?: string; dir?: string; + /** Auto mode: the dispatched repo gate's exit per dispatch attempt; 'pending' when it overruns. */ + githubExit?: Array; ghRuns?: GhRun[]; ghRunsSeq?: GhRun[][]; + pushFails?: 'non_ff' | 'other'; landedCommit?: string; headContainsBase?: boolean; fAncestorFails?: boolean; ciFetchFails?: boolean; pushDryRunFails?: boolean; } = {}) { const dir = over.dir ?? stateDir; const files = new Map(); @@ -30,6 +36,8 @@ function world(over: { const done: Array<{ reason: string; detail: Record }> = []; let tick = 0, gate = 0, headCounter = 0, fetches = 0; const record = (ok: boolean, output = '') => ({ ok, exitCode: ok ? 0 : 1, output, stdout: output, stderr: '' }); + // A head submitted without the base permanently contains it after one rebase. + let rebasedOnce = false; const invoke = async (stage: string, input: Partial = {}) => { const ran: string[] = []; @@ -47,7 +55,7 @@ function world(over: { if (command === 'uname -sm') return 'Linux x86_64'; if (command === 'node -p "Date.now()"') return String(tick += 60_000); if (command === `printf '%s' "\${HOME:-}"`) return over.home ?? ''; - if (command.startsWith('cat ') && command.includes('land-state.json')) return files.get(/^cat '([^']*)'/.exec(command)![1]!) ?? 'null'; + if (command.startsWith('cat ')) return files.get(/^cat '([^']*)'/.exec(command)![1]!) ?? 'null'; if (command.startsWith('git show ') && command.includes('land.config.json')) return JSON.stringify(over.config ?? config); if (command.startsWith('git show ') && command.includes('CHANGELOG.md')) return command.includes('merge-base') ? over.changelog?.[0] ?? '' : over.changelog?.[1] ?? ''; if (command.startsWith(`git fetch --no-tags --quiet ${UNSHALLOW_IF_SHALLOW} origin `)) { const list = over.baseShas ?? ['b'.repeat(40)]; baseRef = list[Math.min(fetches++, list.length - 1)]!; return ''; } @@ -57,13 +65,44 @@ function world(over: { if (command.startsWith('git diff --name-only "$(git merge-base')) return 'probe/src/relay/agents.rs\nCHANGELOG.md'; if (command.startsWith('git diff --name-only ')) return (over.roundFiles ?? [])[agents.length - 1]?.join('\n') ?? 'probe/src/relay/agents.rs'; if (command.startsWith('git log --reverse')) return 'feat: upload policy gates relay auto-activation\nfix: review findings'; - if (command.includes(' rebase --quiet ')) { if (!over.rebaseFails) head = `r${'0'.repeat(38)}${++headCounter}`.slice(-40); return record(!over.rebaseFails, over.rebaseFails ? 'CONFLICT (content)' : ''); } + if (command.startsWith('git merge-base --is-ancestor')) { + // F asks about HEAD; D asks about the recorded head sha. A rebase makes the head contain the base. + if (command.endsWith(' HEAD')) return record(!over.fAncestorFails); + return record(rebasedOnce || over.headContainsBase !== false); + } + if (command.includes(' rebase --quiet ')) { if (!over.rebaseFails) { rebasedOnce = true; } if (!over.rebaseFails) head = `r${'0'.repeat(38)}${++headCounter}`.slice(-40); return record(!over.rebaseFails, over.rebaseFails ? 'CONFLICT (content)' : ''); } if (command === 'git rebase --abort') return ''; if (command.startsWith('mkdir -p ') && command.includes('nohup')) { launches.push(command); return 'started'; } if (command.startsWith('mkdir -p ')) return ''; if (command.startsWith('for i in $(seq')) { + if (command.includes('/github/exit')) { + const attempt = launches.filter(c => c.includes('"github":true')).length - 1; + const list = over.githubExit ?? ['pending']; + return String(list[Math.min(attempt, list.length - 1)]); + } + if (command.includes('gh run list')) { + const attempt = launches.filter(c => c.includes('"github":true')).length - 1; + const seq = over.ghRunsSeq?.[Math.min(attempt, (over.ghRunsSeq.length ?? 1) - 1)]; + let runs = seq ?? over.ghRuns ?? [{ databaseId: 1, workflowName: 'Desktop CI', status: 'completed', conclusion: 'success', createdAt: '2999-01-01T00:00:00Z' }]; + const since = /'(\d{4}-\d{2}-\d{2}T[^']+Z)'/.exec(command)?.[1]; + if (since) runs = runs.filter(x => x.createdAt >= since); + if (!runs.length || runs.some(x => x.status !== 'completed')) return 'pending'; + return JSON.stringify(runs); + } return String(command.includes('/ci/exit') && over.ciRed?.includes(gate - 1) ? 1 : 0); } + if (command.startsWith('git fetch --quiet origin ') && command.includes('refs/heads/ci/*')) return record(over.ciFetchFails !== true, over.ciFetchFails ? 'fetch failed' : ''); + if (command.startsWith('git log --format=%H --grep')) return over.landedCommit ?? ''; + if (command.startsWith('git push --dry-run')) return record(over.pushDryRunFails !== true, over.pushDryRunFails ? 'denied' : ''); + if (command.startsWith('for sha in $(git for-each-ref')) return snapshotSha; + if (command.startsWith('gh run list')) return JSON.stringify(over.ghRuns ?? []); + if (command.startsWith('git push --quiet origin --delete')) return record(true); + if (command.includes(' commit-tree ')) return mergedCommit; + if (command.startsWith('git push origin ') && command.includes(':refs/heads/')) { + if (over.pushFails === 'non_ff') return record(false, '! [rejected] main -> main (non-fast-forward)'); + if (over.pushFails === 'other') return record(false, 'error: GH006: protected branch update failed'); + return record(true); + } if (command.startsWith('tail -c')) return 'log tail'; if (command.startsWith('if [ -f ')) { const lane = command.includes('adversarial-review/report.json') ? 'adversarial' : 'context'; @@ -71,6 +110,8 @@ function world(over: { const list = (lane === 'adversarial' ? over.adversarial : over.context) ?? []; return JSON.stringify({ findings: list[gate - 1] ?? [] }); } + if (command === 'command -v gh >/dev/null && gh auth status') return record(true); + if (command.startsWith('command -v')) return ''; if (command.startsWith('git -c user.name=relay-land') && command.includes(' add -A')) { head = `c${'0'.repeat(38)}${++headCounter}`.slice(-40); return ''; } if (command.startsWith('printf %s ')) { @@ -259,7 +300,7 @@ test('the removed githubGateInShadow flag is refused as an unknown key, before a assert.equal(w.state(), null); }); -test('refusals: no state outside A-adversarial, non-shadow mode, state or intent inside the checkout, wrong run', async () => { +test('refusals: no state outside A-adversarial, approval mode, state or intent inside the checkout, wrong run', async () => { const cases: Array<[Partial & { stage: string }, RegExp, ReturnType?]> = [ [{ stage: 'B' }, /a run starts at A-adversarial/], [{ stage: 'A-adversarial', stateDir: `${root}/.relayflow`, runId: 'run-1' }, /stateDir must be outside the checkout/], @@ -281,7 +322,7 @@ test('refusals: no state outside A-adversarial, non-shadow mode, state or intent const approval = world({ config: { ...config, mergePolicy: { mode: 'approval' } } }); const declined = await approval.invoke('A-adversarial'); assert.equal(declined.reason, 'declined'); - assert.match(declined.detail.detail as string, /only shadow runs/); + assert.match(declined.detail.detail as string, /is not implemented; shadow and auto run/); assert.equal(approval.state(), null); const other = world(); @@ -436,3 +477,187 @@ test('the base fetch deepens a shallow checkout and names only the base refspec' assert.equal(sh(join(root, 'shallow'), `echo ${UNSHALLOW_IF_SHALLOW}`), '--unshallow'); assert.equal(sh(join(root, 'full'), `echo ${UNSHALLOW_IF_SHALLOW}`), ''); }); + +interface GhRun { databaseId: number; workflowName: string; status: string; conclusion: string | null; createdAt: string } +const autoConfig = { ...config, mergePolicy: { mode: 'auto' } }; +const gh = (conclusion: string | null, status = 'completed', name = 'Desktop CI', createdAt = '2999-01-01T00:00:00Z'): GhRun => + ({ databaseId: 1, workflowName: name, status, conclusion, createdAt }); + +test('auto: dispatch overruns, the next E awaits the pushed snapshot, F squash-pushes and lands', async () => { + const w = world({ config: autoConfig }); + const { stages, result } = await w.drive(); + assert.deepEqual(stages, ['A-adversarial', 'A-context', 'B', 'D', 'E', 'E', 'F']); + assert.equal(result.reason, 'success'); + assert.equal(result.detail.state, 'landed'); + const dispatch = w.launches.find(c => c.includes('ci.flow.ts') && c.includes('"github":true')); + assert.ok(dispatch, 'the repo gate really ran with {"github":true}'); + const book = JSON.parse(w.files.get(`${stateDir}/github-gate.json`)!); + assert.equal(book.snapshotSha, snapshotSha); + const s = w.state(); + assert.equal(s.squashPlan.pushed, true); + assert.equal(s.squashPlan.commit, mergedCommit); + const flat = w.commands.flat(); + const commitTree = flat.find(c => c.includes(' commit-tree '))!; + assert.ok(commitTree.includes('Relay-Session: a71ff4c9-365f-4602-8e5a-06db39621973'), commitTree); + assert.ok(commitTree.includes('Land-Run: run-1'), commitTree); + assert.ok(flat.includes(`git push origin '${mergedCommit}:refs/heads/main'`), 'squash pushed to main'); + assert.ok(flat.includes(`git push --quiet origin --delete 'ci/${snapshotSha.slice(0, 12)}'`), 'snapshot branch deleted'); +}); + +test('auto: a gate that finishes inside the dispatch window applies its verdict in the same run', async () => { + const w = world({ config: autoConfig, githubExit: [0] }); + const { stages, result } = await w.drive(); + assert.deepEqual(stages, ['A-adversarial', 'A-context', 'B', 'D', 'E', 'F']); + assert.equal(result.detail.state, 'landed'); + const book = JSON.parse(w.files.get(`${stateDir}/github-gate.json`)!); + assert.equal(book.attempts, 1, 'the dispatch attempt was persisted before the wait'); + assert.equal(book.snapshotSha, undefined, 'no await bookkeeping for an in-window verdict'); +}); + +test('auto: red GitHub gate goes to the next fix round', async () => { + const w = world({ config: autoConfig, githubExit: [1, 0] }); + const { stages, result } = await w.drive(); + assert.ok(stages.includes('C-1'), stages.join(',')); + assert.equal(result.detail.state, 'landed'); + assert.equal(w.agents[0]?.name, 'fix-r1'); + assert.match(w.agents[0]!.options.task, /github gate ended red/); +}); + +test('auto: a failed dispatched run is red to the fix loop', async () => { + const w = world({ config: autoConfig, ghRunsSeq: [[gh('failure')], [gh('success')]] }); + const { stages, result } = await w.drive(); + assert.ok(stages.includes('C-1')); + assert.equal(result.detail.state, 'landed'); + assert.match(w.agents[0]!.options.task, /GitHub Desktop CI: failure/); +}); + +test('auto: still-pending dispatched runs keep E as the cursor across stage runs', async () => { + const w = world({ config: autoConfig, ghRuns: [gh(null, 'in_progress')] }); + await w.invoke('A-adversarial'); await w.invoke('A-context'); await w.invoke('B'); await w.invoke('D'); + const first = await w.invoke('E'); + assert.equal(first.detail.stage, 'E'); + const second = await w.invoke('E'); + assert.equal(second.detail.stage, 'E'); + const book = JSON.parse(w.files.get(`${stateDir}/github-gate.json`)!); + assert.equal(book.polls, 1); +}); + +test('auto: F goes back to D on non-fast-forward', async () => { + const w = world({ config: autoConfig, pushFails: 'non_ff' }); + let last; + for (const stage of ['A-adversarial', 'A-context', 'B', 'D', 'E', 'E', 'F']) last = await w.invoke(stage); + assert.equal(last!.detail.stage, 'D'); +}); + +test('auto: a moved base at F goes back to D and regates', async () => { + const moved = world({ config: autoConfig, baseShas: ['b'.repeat(40), 'b'.repeat(40), 'b'.repeat(40), 'b'.repeat(40), 'b'.repeat(40), 'c'.repeat(40)] }); + const { stages, result } = await moved.drive(); + assert.deepEqual(stages.slice(0, 8), ['A-adversarial', 'A-context', 'B', 'D', 'E', 'E', 'F', 'D']); + assert.equal(result.detail.state, 'landed'); +}); + +test('auto: a non-FF, non-permission push failure ends needs_human', async () => { + const w = world({ config: autoConfig, pushFails: 'other' }); + const { result } = await w.drive(); + assert.equal(result.detail.state, 'needs_human'); + assert.match(result.detail.detail as string, /push to main failed/); +}); + +test('auto and shadow: the land harness is the review fleets\' clis and the fix agent\'s cli', async () => { + for (const cfg of [autoConfig, config]) { + const w = world({ config: cfg }); + await w.drive(); + const reviewLaunches = w.launches.filter(c => c.includes('-review.flow.ts')); + assert.ok(reviewLaunches.length >= 2 && reviewLaunches.every(c => c.includes('"clis":["codex"]')), reviewLaunches[0]); + } +}); + +test('auto: a stage reaped after the push records the landed commit instead of landing twice', async () => { + // F's run-start fetch sees base moved to our own squash commit. + const w = world({ config: autoConfig, baseShas: ['b'.repeat(40), 'b'.repeat(40), 'b'.repeat(40), 'b'.repeat(40), 'b'.repeat(40), mergedCommit], landedCommit: mergedCommit }); + let last; + for (const stage of ['A-adversarial', 'A-context', 'B', 'D', 'E', 'E', 'F']) last = await w.invoke(stage); + assert.equal(last!.detail.state, 'landed'); + assert.equal(last!.detail.commit, mergedCommit); + assert.ok(!w.commands.at(-1)!.some(c => c.includes(' commit-tree ')), 'no second squash commit'); +}); + +test('auto: F refuses to squash a head that never contained the base', async () => { + const w = world({ config: autoConfig, fAncestorFails: true }); + let last; + for (const stage of ['A-adversarial', 'A-context', 'B', 'D', 'E', 'E', 'F']) last = await w.invoke(stage); + assert.equal(last!.detail.stage, 'D'); +}); + +test('auto: D rebases a head that never contained an unmoved base, then lands', async () => { + const w = world({ config: autoConfig, headContainsBase: false }); + const { stages, result } = await w.drive(); + assert.ok(stages.filter(x => x === 'D').length >= 2, stages.join(',')); + assert.equal(w.state().rebases, 1); + assert.equal(result.detail.state, 'landed'); +}); + +test('auto: three red GitHub gates escalate stuck_finding instead of alternating past the stall checks', async () => { + const stuckConfig = { ...config, mergePolicy: { mode: 'auto' }, fixLoop: { maxRounds: 5 } }; + const w = world({ config: stuckConfig, ghRunsSeq: [[gh('failure')], [gh('failure')], [gh('failure')]] }); + const { stages, result } = await w.drive(); + assert.ok(stages.includes('C-1')); + assert.equal(result.detail.state, 'needs_human'); + assert.equal(w.state().escalation.reason, 'stuck_finding'); +}); + +test('auto: a run set still growing between polls stays pending; a stable set gives the verdict', async () => { + const r1 = gh('success'), r2 = gh('success'); + r2.databaseId = 2; + // First check sees {r1}, a later poll sees {r1,r2} — the growing set keeps + // the gate pending until the set is stable across two consecutive checks. + const w = world({ config: autoConfig }); + await w.invoke('A-adversarial'); await w.invoke('A-context'); await w.invoke('B'); await w.invoke('D'); + await w.invoke('E'); + (w as any).setRuns?.(1); + // Drive awaits manually through the same invoke loop: poll1 writes {1,2}, + // poll2 sees a stable set → green. + const w2 = world({ config: autoConfig, ghRunsSeq: [[r1, r2]] }); + await w2.invoke('A-adversarial'); await w2.invoke('A-context'); await w2.invoke('B'); await w2.invoke('D'); + await w2.invoke('E'); + const e2 = await w2.invoke('E'); + assert.equal(e2.detail.stage, 'F'); + const book = JSON.parse(w2.files.get(`${stateDir}/github-gate.json`)!); + assert.deepEqual(book.seenRunIds, [1, 2]); +}); + +test('auto: a stale completed run older than the dispatch bound cannot produce a verdict', async () => { + const stale = gh('success'); + stale.createdAt = '1960-01-01T00:00:00Z'; + const w = world({ config: autoConfig, ghRuns: [stale] }); + await w.invoke('A-adversarial'); await w.invoke('A-context'); await w.invoke('B'); await w.invoke('D'); + await w.invoke('E'); + const e = await w.invoke('E'); + assert.equal(e.detail.stage, 'E', 'the stale run is filtered by createdAt>=since; the gate stays pending'); +}); + +test('auto and shadow: a non-default harness is the review fleets\' clis and the fix agent\'s cli', async () => { + const claudeConfig = { ...config, fixLoop: { harness: 'claude' } }; + const w = world({ config: claudeConfig, ciRed: [0] }); + await w.drive(); + const reviewLaunches = w.launches.filter(c => c.includes('review')); + assert.ok(reviewLaunches.every(c => c.includes('"clis":["claude"]')), reviewLaunches[0]); + const fix = w.agents.find(a => a.name === 'fix-r1'); + assert.equal(fix?.options.cli, 'claude'); +}); + +test('a harness without a worker adapter fails at stage one with a clear error', async () => { + for (const harness of ['grok', 'devin']) { + const w = world({ config: { ...config, fixLoop: { harness } } }); + const { result } = await w.drive(); + assert.equal(result.reason, 'needs_human'); + assert.match(JSON.stringify(result.detail), /no worker adapter.*flows#691/); + } +}); + +test('auto: a push-denied git credential fails preflight before any stage runs', async () => { + const w = world({ config: autoConfig, pushDryRunFails: true }); + const { result } = await w.drive(); + assert.equal(result.reason, 'needs_human'); + assert.match(JSON.stringify(result.detail), /push-capable git credential/); +}); diff --git a/examples/land/tests/transition.test.ts b/examples/land/tests/transition.test.ts index 04c6a435e..b6815e627 100644 --- a/examples/land/tests/transition.test.ts +++ b/examples/land/tests/transition.test.ts @@ -17,7 +17,9 @@ const review = (lane: 'adversarial' | 'context', ids: string[] = [], now = t): S const ci = (ids: string[] = [], now = t): StageResult => ({ kind: 'ci', findings: ids.map(f), now }); const fixed = (head: string, ok = true): StageResult => ({ kind: 'fix', headSha: head, guard: { ok, detail: ok ? '' : 'fix round touched 2 file(s) outside change ∪ findings' }, now: t }); const rebase = (outcome: 'unchanged' | 'rebased' | 'conflict', baseSha = 'b'.repeat(40), headSha = sha): StageResult => ({ kind: 'rebase', outcome, baseSha, headSha, now: t }); -const wouldDispatch = (): StageResult => ({ kind: 'github', wouldDispatch: { flow: 'flows/ci.flow.ts', input: { base: 'origin/main', github: true }, headSha: sha, dispatched: false }, now: t }); +const wouldDispatch = (): StageResult => ({ kind: 'github', outcome: 'shadow', wouldDispatch: { flow: 'flows/ci.flow.ts', input: { base: 'origin/main', github: true }, headSha: sha, dispatched: false }, now: t }); +const autoConfig = { ...config, mergePolicy: { ...config.mergePolicy, mode: 'auto' as const } }; +const autoStart = (over: Parameters[0] = {}) => start({ config: autoConfig, ...over }); const plan = squashPlan({ base: 'main', baseSha: 'b'.repeat(40), headSha: sha, tree: 't'.repeat(40), subjects: ['feat: x'], sessionId: 's-1', runId: 'run-1', squashAuthor: 'session-human', fixRounds: 0, harness: 'claude' }); /** Feed one gate (A-adversarial, A-context, B) with the given adversarial ids. */ @@ -27,7 +29,7 @@ const gate = (s: LandState, ids: string[], now = t): LandState => test('clean run: A-adversarial → A-context → B → D → E (would dispatch) → F → landed', () => { const cursors: Array = []; let s = start(); - for (const r of [review('adversarial'), review('context'), ci(), rebase('unchanged'), wouldDispatch(), { kind: 'merge', plan, now: t } as StageResult]) { + for (const r of [review('adversarial'), review('context'), ci(), rebase('unchanged'), wouldDispatch(), { kind: 'merge', outcome: 'planned', plan, now: t } as StageResult]) { cursors.push(s.cursor); s = nextLandStage(s, r); } assert.deepEqual(cursors, ['A-adversarial', 'A-context', 'B', 'D', 'E', 'F']); @@ -141,3 +143,51 @@ test('land-state.json round-trips and refuses other versions', () => { assert.deepEqual(JSON.parse(completionDetail(s)), { land: 'next', runId: 'run-1', stage: 'C-1', seq: 3 }); assert.deepEqual(JSON.parse(completionDetail(s, true)), { land: 'next', runId: 'run-1', stage: 'C-1', seq: 3, noop: true }); }); + +test('auto E: pending keeps the cursor at E, green moves to F, red feeds the fix loop', () => { + const atE = nextLandStage(gate(autoStart(), []), rebase('unchanged')); + const pending = nextLandStage(atE, { kind: 'github', outcome: 'pending', now: t }); + assert.equal(pending.cursor, 'E'); + assert.equal(pending.history.length, atE.history.length, 'pending does not close a gate'); + const green = nextLandStage(pending, { kind: 'github', outcome: 'green', now: t }); + assert.equal(green.cursor, 'F'); + + const red = nextLandStage(pending, { kind: 'github', outcome: 'red', findings: [{ id: 'github:Desktop CI', source: 'github', severity: 'blocker', file: '', title: 'GitHub Desktop CI: failure' }], now: t }); + assert.equal(red.cursor, 'C-1'); + assert.deepEqual(red.findings.map(x => x.id), ['github:Desktop CI']); + assert.deepEqual(red.history.at(-1), ['github:Desktop CI'], 'a red gate closes a gate like B does'); +}); + +test('auto E: a red gate still escalates on round cap', () => { + const capped = autoStart({ config: { ...autoConfig, fixLoop: { ...autoConfig.fixLoop, maxRounds: 1 } } }); + let s = nextLandStage(gate(capped, ['a']), fixed('c'.repeat(40))); + s = gate(s, []); + s = nextLandStage(s, rebase('unchanged')); + s = nextLandStage(s, { kind: 'github', outcome: 'red', findings: [{ id: 'github:ci', source: 'github', severity: 'blocker', file: '', title: 'red' }], now: t }); + assert.equal(s.terminal?.state, 'needs_human'); + assert.equal(s.escalation?.reason, 'round_cap'); +}); + +test('auto F: pushed lands with the commit; moved and non_ff go back to D', () => { + const atF = nextLandStage(nextLandStage(gate(autoStart(), []), rebase('unchanged')), { kind: 'github', outcome: 'green', now: t }); + const landed = nextLandStage(atF, { kind: 'merge', outcome: 'pushed', plan, commit: 'd'.repeat(40), now: t }); + assert.equal(landed.terminal?.state, 'landed'); + assert.equal(landed.squashPlan?.pushed, true); + assert.equal(landed.squashPlan?.commit, 'd'.repeat(40)); + assert.match(landed.terminal!.detail, /^landed AgentWorkforce\/relay-desktop@ddddddd on main after 0 fix round\(s\)$/); + + for (const outcome of ['moved', 'non_ff'] as const) { + const s = nextLandStage(atF, { kind: 'merge', outcome, now: t }); + assert.equal(s.cursor, 'D', outcome); + assert.equal(s.terminal, null); + } +}); + +test('mode discipline: shadow outcomes refuse auto and vice versa', () => { + const shadowE = nextLandStage(gate(start(), []), rebase('unchanged')); + assert.throws(() => nextLandStage(shadowE, { kind: 'github', outcome: 'green', now: t }), /cannot take a green outcome under shadow/); + const autoE = nextLandStage(gate(autoStart(), []), rebase('unchanged')); + assert.throws(() => nextLandStage(autoE, wouldDispatch()), /cannot take a shadow outcome under auto/); + const shadowF = nextLandStage(shadowE, wouldDispatch()); + assert.throws(() => nextLandStage(shadowF, { kind: 'merge', outcome: 'pushed', plan, commit: 'd'.repeat(40), now: t }), /cannot take a pushed outcome under shadow/); +});