From f15f5662fce3b62658743aa59855d807f5ee614a Mon Sep 17 00:00:00 2001 From: garrytan Date: Mon, 26 Oct 2026 00:57:30 +0000 Subject: [PATCH] feat(ship-queue): require a current /ship receipt before READY, train build and train merge Garry, 2026-10-25: use the gstack ship skill before merging PRs. ready printed SHIP_RECEIPT: none as information and returned ok, so the pool was READY'd without /ship. Now ready, train build (dry run included) and verify --train refuse with QUEUE_RECEIPT_MISSING or QUEUE_RECEIPT_STALE from the PR body alone; verify accepts the receipt written for the pinned head when the current head is its stamp commit. gstack-ship-receipt result is /ship's terminal step (GSTACK_RESULT: skill=ship, run dir with the head and receipt), unattended /ship may update an existing PR's body, and INSTALL_UNVERIFIED with no verdict names the project directory to install from (GSTA-85). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CHANGELOG.md | 16 ++++ bin/gstack-doctor-components.sh | 2 + bin/gstack-install-verdict.sh | 1 + bin/gstack-ship-queue | 4 +- bin/gstack-ship-receipt | 63 +++++++++++++++- bin/gstack-skill-start | 6 +- docs/ship-policy.md | 38 +++++++++- docs/troubleshooting.md | 32 ++++++++ docs/unattended.md | 37 ++++++++-- lib/install-verdict.ts | 5 +- lib/result-codes-release.ts | 11 +++ lib/ship-queue-train-github.ts | 6 +- lib/ship-queue-train-verify.ts | 9 ++- lib/ship-queue-train.ts | 3 + lib/ship-queue.ts | 12 +-- lib/ship-receipt.ts | 32 ++++++++ ship/SKILL.md | 19 ++++- ship/SKILL.md.tmpl | 19 ++++- ship/sections/handoff.md | 3 +- ship/sections/handoff.md.tmpl | 3 +- ship/sections/pr-body.md | 5 +- ship/sections/pr-body.md.tmpl | 5 +- test/fixtures/golden/agy-ship-SKILL.md | 19 ++++- test/fixtures/golden/claude-ship-SKILL.md | 19 ++++- test/fixtures/golden/codex-ship-SKILL.md | 20 ++++- test/fixtures/golden/factory-ship-SKILL.md | 20 ++++- test/gstack-ship-queue.test.ts | 27 +++++-- test/gstack-ship-receipt.test.ts | 44 +++++++++++ test/gstack-skill-start.test.ts | 13 +++- test/helpers/carve-guards.ts | 4 +- test/helpers/ship-queue-train-fixture.ts | 18 ++++- test/install-verdict.test.ts | 13 ++++ test/ship-queue-train.test.ts | 85 +++++++++++++++++++++- 33 files changed, 560 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb48cbce1..a8bc051ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [Unreleased] + +**The merge queue now refuses a PR that never ran /ship.** Garry, 2026-10-25: "we should really be using the gstack ship skill before merging PRs." `gstack-ship-queue ready` printed `SHIP_RECEIPT: none in the PR body` as information and returned ok, so every PR in the pool was READY'd without a /ship run. The receipt /ship writes into the PR body is now a precondition at every queue step, with no flag around it. + +### Changed +- **`gstack-ship-queue ready`** refuses with `QUEUE_RECEIPT_MISSING` when the PR body has no valid ```gstack-ship-receipt``` block and with `QUEUE_RECEIPT_STALE` when the receipt's `head` is not the head being READY'd (or its `pr` is another PR). The informational `SHIP_RECEIPT:` line still prints in the block. +- **`gstack-ship-queue train build`** refuses a pin whose PR has no current receipt with the same codes, naming the PR, before any write, push or dispatch, `--dry-run` included. **`verify --train`** refuses the slot the same way before `MERGE_CONDITION`, and accepts a receipt written for the slot's pinned head when the current head is its stamp commit (the stamp changes only stamp files, or merges main into the pin from slot 2 on), since no /ship runs on a stamp. +- **`gstack-ship-receipt result`** (new) is /ship's terminal step: it binds the posted receipt to HEAD, writes `/ship/runs/-/{run.json,ship-receipt.md}` and prints `GSTACK_RESULT: skill=ship status=complete run=`, or `status=refused run=-` with the receipt code, so a parent's merge check reads `run.json` instead of parsing the PR body. The ship skill's new Step 22 runs it after the pr-body and handoff sections. +- **Unattended /ship may update an existing PR's body.** `gstack-skill-start`'s unattended block and `UNATTENDED_SHIP:` line, the ship skill's Step 18 and `docs/unattended.md` now say: when an open PR for the branch exists and HEAD is its pushed head, Step 18 takes the pr-body section's existing-PR path (body with the receipt first, and title); it never runs `pr-create` and never pushes a commit; anything else takes the handoff section. Before this the block said the receipt lived only in `.gstack/tmp/ship-receipt.md` while rule 22 and `ready` read it from the PR body. +- **`INSTALL_UNVERIFIED` with no verdict names the directory to install from.** An installer run from the skill's own folder records a verdict for no project, so /ship launched from the project found none and the fix said only "run the installer on this machine" (GSTA-85). Both twins (`lib/install-verdict.ts`, `bin/gstack-install-verdict.sh`) now say `run … scripts/install.sh --for ship from : the verdict is keyed by the project directory the installer runs in`. +- **Docs:** `docs/ship-policy.md#ship-before-ready` (the lane runs /ship before every READY and after every push; the stamp keeps the pin's receipt), the two codes in `docs/troubleshooting.md`, `docs/unattended.md` (/ship now prints the result line), and the ship skill's pr-body section says what refuses without a receipt. +- **Gate edit (size budgets):** `test/helpers/carve-guards.ts` raises ship's `maxSkeletonBytes` 81,000 → 82,000 and `maxSizeRatio` 1.6690 → 1.6760 for Step 22 and the Step 18 routing, both written as tight as they go (measured skeleton 81,711, union 314,204; the 2026-10-14 tightening had left 2 bytes of headroom). No threshold, trial count or case kind changed. + +### Tests +- `test/ship-queue-train.test.ts`: READY, train build (dry run and live) and verify --train refuse a missing, invalid, other-head and other-PR receipt and admit the current one; the pinned-head receipt admits a stamp commit. `test/gstack-ship-queue.test.ts` covers the per-PR READY block. `test/gstack-ship-receipt.test.ts` covers `result` from a PR and from the handoff file. The train fixture's `openPr` now writes a receipt for the head it opens (`shipped: false` leaves the body empty). `test/install-verdict.test.ts` pins the GSTA-85 fix in both twins; `test/gstack-skill-start.test.ts` pins the new unattended /ship block. + ## [1.91.224.0] - 2026-10-25 **`/context-restore` now says when commits landed after a checkpoint was saved, instead of offering finished steps as the plan.** `/context-save` recorded the branch, a timestamp and the modified files, but not the commit, so a checkpoint saved before a step was committed came back with that step still listed under Remaining Work. Ported from #3316 by @soyames, with their commit kept. diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index 9d37b08e6..eb470c992 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -277,6 +277,8 @@ gstack_result_anchor() { QUEUE_TRAIN_REBUILD_REFUSED) printf '%s' 'queue-train-rebuild-refused' ;; QUEUE_TRAIN_TREE_MISMATCH) printf '%s' 'queue-train-tree-mismatch' ;; QUEUE_TRAIN_FROZEN) printf '%s' 'queue-train-frozen' ;; + QUEUE_RECEIPT_MISSING) printf '%s' 'queue-receipt-missing' ;; + QUEUE_RECEIPT_STALE) printf '%s' 'queue-receipt-stale' ;; READY_SCREEN_CHOICE_REQUIRED) printf '%s' 'ready-screen-choice-required' ;; PREGATE_TIMING_ASSERTION) printf '%s' 'pregate-timing-assertion' ;; APPROVAL_CLASSES_INVALID) printf '%s' 'approval-classes-invalid' ;; diff --git a/bin/gstack-install-verdict.sh b/bin/gstack-install-verdict.sh index e500344a8..a1ecd5773 100644 --- a/bin/gstack-install-verdict.sh +++ b/bin/gstack-install-verdict.sh @@ -131,6 +131,7 @@ gstack_install_admission() { fix="run the Capy skill installer (scripts/install.sh --for $skill) on this machine, then launch with the GSTACK_LAUNCH line it prints" if [ ! -f "$file" ]; then detail="no install verdict at $file for $src" + fix="run the Capy skill installer (scripts/install.sh --for $skill) from ${project:-this directory}: the verdict is keyed by the project directory the installer runs in, so a run from the skill's own folder does not cover ${project:-it}; then launch with the GSTACK_LAUNCH line it prints" else trailer=$(gstack_install_verdict_field "$file" trailer) v_head=$(gstack_install_verdict_field "$file" head) diff --git a/bin/gstack-ship-queue b/bin/gstack-ship-queue index c62dddf54..a5f852d10 100755 --- a/bin/gstack-ship-queue +++ b/bin/gstack-ship-queue @@ -4,6 +4,7 @@ * step (field list 2, W1; docs/ship-policy.md#run-a-shared-merge-queue). * * gstack-ship-queue ready --pr [--pregate ] [--gate-exit --gate-log ] + * (refused with QUEUE_RECEIPT_MISSING|STALE unless the PR body carries /ship's receipt for HEAD) * gstack-ship-queue stamp --pr --version --expect-gated --expect-base * [--expect-order ] [--allow-repo-commands] [--gate-exit --gate-log ] * gstack-ship-queue verify --pr (--gated | --record ) [--receipt ] @@ -33,7 +34,8 @@ import { attemptFile, listAttempts, prepareGateAhead, recordGateAhead, type Queu const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (docs/ship-policy.md#run-a-shared-merge-queue) ready --pr [--pregate ] [--gate-exit --gate-log ] - READY # STAMP_VERSION=, CI at that head, PREGATE, gate state + READY # STAMP_VERSION=, CI at that head, PREGATE, gate state, + SHIP_RECEIPT (refused unless the PR body carries /ship's receipt for that head) stamp --pr --version --expect-gated --expect-base [--expect-order ] [--allow-repo-commands] [--gate-exit --gate-log ] restamp, commit and prove: QUEUE_STAMP: head= gated= tree= receipt= diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index a5ce43fa5..85423da0f 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -10,11 +10,14 @@ * [--out ] [--body ] [--json] * gstack-ship-receipt read --pr [--repo ] [--json] * gstack-ship-receipt read --body [--json] + * gstack-ship-receipt result (--pr [--repo ] | --body ) [--head ] [--out ] [--json] * gstack-ship-receipt census --repo --since [--cohort ] [--limit ] [--json] * * `write` validates against `gstack-artifact schema ship-receipt`, prints the * fenced block (and SHIP_RECEIPT: on stderr), writes it to --out, * and with --body makes it the first section of that PR body file. + * `result` is /ship's terminal step: it binds the receipt to HEAD, writes the + * run record under /ship/runs/ and prints GSTACK_RESULT: skill=ship. * Query commands: no GSTACK_RESULT line. Logic: lib/ship-receipt.ts. */ import { spawnSync } from 'node:child_process'; @@ -27,15 +30,20 @@ import { readPregateFile, verifyPregate } from '../lib/pregate/index'; import { resolveBaseBranch } from '../lib/ship-policy'; import { approvalForReceipt } from '../lib/approval-citations'; import { - computeCensus, extractReceipt, missingIssueLines, orderReceipt, placeReceiptFirst, receiptIssuesFrom, receiptSummaryLine, renderCensus, renderReceiptBlock, - validateReceipt, type CensusPr, + bindReceipt, computeCensus, extractReceipt, missingIssueLines, orderReceipt, placeReceiptFirst, receiptIssuesFrom, receiptSummaryLine, renderCensus, + renderReceiptBlock, validateReceipt, type CensusPr, } from '../lib/ship-receipt'; +import { resolveStateRoot } from '../lib/state-root'; const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt) write [flags] compose, validate and print the block; --body puts it first in that PR body read --pr [--repo ] parse the block from the PR body through gh (RECEIPT_MISSING / RECEIPT_INVALID) read --body parse the block from a file + result --pr [--repo ] | --body [--head ] [--out ] + /ship's terminal line: binds the receipt to HEAD (QUEUE_RECEIPT_MISSING / QUEUE_RECEIPT_STALE), + writes /ship/runs/-/{run.json,ship-receipt.md} and prints + GSTACK_RESULT: skill=ship status=complete run= (refused: status=refused run=-) census --repo --since [--cohort ] the P7 adoption number over merged PRs (deduplicated by run and thread) @@ -182,6 +190,56 @@ function cmdRead(rest: string[], json: boolean): number { return EXIT.ok; } +/** + * /ship's terminal line (docs/unattended.md#the-terminal-line). The receipt in + * the PR body (or the handoff file) must bind to HEAD: then the run record + * goes under /ship/runs/ with the head, the PR and the receipt, and + * the last stdout line is GSTACK_RESULT: skill=ship status=complete run=. + * A missing or stale receipt is status=refused run=- (exit 3), so a parent + * never has to parse the PR body to know whether /ship finished at this head. + */ +function cmdResult(rest: string[], json: boolean): number { + const bodyFile = flag(rest, '--body'); + const pr = flag(rest, '--pr'); + const repoRoot = git(['rev-parse', '--show-toplevel']); + const head = flag(rest, '--head') ?? (repoRoot ? git(['rev-parse', 'HEAD'], repoRoot) : undefined); + const refused = (code: 'QUEUE_RECEIPT_MISSING' | 'QUEUE_RECEIPT_STALE', message: string) => { + process.stderr.write(resultLineWithDocs('gstack-ship-receipt result', code, message) + '\n'); + process.stdout.write(json ? JSON.stringify({ skill: 'ship', status: 'refused', run: '-', code, message }) + '\n' : 'GSTACK_RESULT: skill=ship status=refused run=-\n'); + return EXIT.refused; + }; + if (!head) { process.stderr.write('gstack-ship-receipt result: --head is required outside a git repository\n'); return EXIT.usage; } + let body: string; + let source: string; + if (bodyFile) { + if (!fs.existsSync(bodyFile)) return refused('QUEUE_RECEIPT_MISSING', `${bodyFile} does not exist; /ship did not write its receipt`); + body = fs.readFileSync(bodyFile, 'utf8'); + source = path.resolve(bodyFile); + } else if (pr) { + const repo = flag(rest, '--repo'); + const r = gh(['pr', 'view', pr, ...(repo ? ['--repo', repo] : []), '--json', 'body']); + if (!r.ok) { process.stderr.write(`gstack-ship-receipt result: gh pr view failed: ${r.err}\n`); return EXIT.fail; } + try { body = JSON.parse(r.out).body ?? ''; } catch { process.stderr.write('gstack-ship-receipt result: gh returned no JSON body\n'); return EXIT.fail; } + source = `PR #${pr}${repo ? ` (${repo})` : ''}`; + } else { process.stderr.write(`gstack-ship-receipt result: --pr or --body is required\n${HELP}\n`); return EXIT.usage; } + const bound = bindReceipt(body, pr ?? String(extractReceipt(body).receipt?.pr ?? '-'), [head]); + if (!bound.ok) return refused(bound.code, bound.message.replace(/^PR #-'s /, "the receipt's ")); + const stamp = new Date().toISOString().replace(/[:.]/g, '-'); + const dir = flag(rest, '--out') ?? path.join(resolveStateRoot(), 'ship', 'runs', `${stamp}-${head.slice(0, 12)}`); + fs.mkdirSync(dir, { recursive: true }); + const receiptPath = path.join(dir, 'ship-receipt.md'); + fs.writeFileSync(receiptPath, renderReceiptBlock(bound.receipt)); + const run = { + schema_version: 1, skill: 'ship', status: 'complete', head, pr: bound.receipt.pr ?? (pr ? Number(pr) : null), base: bound.receipt.base, version: bound.receipt.version ?? null, + queue_mode: bound.receipt.queue_mode ?? null, session_kind: bound.receipt.session_kind ?? process.env.GSTACK_SESSION_KIND ?? null, + receipt: receiptPath, receipt_source: source, branch: repoRoot ? git(['rev-parse', '--abbrev-ref', 'HEAD'], repoRoot) ?? null : null, created_at: new Date().toISOString(), + }; + fs.writeFileSync(path.join(dir, 'run.json'), JSON.stringify(run, null, 2) + '\n'); + process.stderr.write(bound.line + '\n'); + process.stdout.write(json ? JSON.stringify({ ...run, run: dir }) + '\n' : `GSTACK_RESULT: skill=ship status=complete run=${dir}\n`); + return EXIT.ok; +} + function sinceDate(repo: string, since: string): string | undefined { if (/^\d{4}-\d{2}-\d{2}/.test(since)) return since.slice(0, 10); const local = git(['log', '-1', '--format=%cI', since]); @@ -214,6 +272,7 @@ function main(argv: string[]): number { if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; } if (cmd === 'write') return cmdWrite(rest, json); if (cmd === 'read') return cmdRead(rest, json); + if (cmd === 'result') return cmdResult(rest, json); if (cmd === 'census') return cmdCensus(rest, json); process.stderr.write(`gstack-ship-receipt: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; diff --git a/bin/gstack-skill-start b/bin/gstack-skill-start index 81ccda14d..f83ef59d0 100755 --- a/bin/gstack-skill-start +++ b/bin/gstack-skill-start @@ -322,7 +322,7 @@ echo "GSTACK_PLAN_MODE: $GSTACK_PLAN_MODE" # GSTACK_SESSION_KIND=spawned override must light this up too. [ "$_SESSION_KIND" = "spawned" ] && echo "SPAWNED_SESSION: true" || true [ "$_SESSION_KIND" = "unattended" ] && echo "UNATTENDED_SESSION: true" || true -[ "$_SESSION_KIND" = "unattended" ] && [ "$SKILL_NAME" = "ship" ] && echo "UNATTENDED_SHIP: no push, no PR; Step 18 takes the handoff section; receipt at .gstack/tmp/ship-receipt.md" || true +[ "$_SESSION_KIND" = "unattended" ] && [ "$SKILL_NAME" = "ship" ] && echo "UNATTENDED_SHIP: no push, no new PR; an open PR at HEAD gets its body updated (pr-body section, receipt first), else Step 18 takes the handoff section; receipt at .gstack/tmp/ship-receipt.md; end with gstack-ship-receipt result" || true # --------------------------------------------------------------------------- # Artifacts sync (the former "Artifacts Sync (skill start)" fence, verbatim @@ -648,13 +648,13 @@ if [ "$_SESSION_KIND" = "unattended" ]; then case "$SKILL_NAME" in autoplan) _UA_RECORD="This skill writes a run directory through gstack-autoplan (plan.md, review-record.md, tasks.jsonl, decisions.jsonl, findings.jsonl, timing.json, run.json, gate.json): append each recommended choice to decisions.jsonl with kind \"auto\" and each pending one with kind \"approval\" and status \"pending\". The final approval gate is written as a gate list (gstack-gate render) and this run ENDS there with \`GSTACK_RESULT: skill=autoplan status=gate_pending run=\`." ;; eval-plan) _UA_RECORD="This run ENDS at the Step 4 spend approval, left pending, with \`GSTACK_RESULT: skill=eval-plan status=gate_pending run=\`, where is the pilot's --out directory. No helper writes a gate.json for this skill yet, so the parent reads the pilot report and spend ledger in ." ;; - ship) _UA_RECORD="$_UA_NONE The parent reads the ship receipt from .gstack/tmp/ship-receipt.md when nothing was pushed, and from the PR body (\`gstack-ship-receipt read --pr --json\`) only once a PR exists." ;; + ship) _UA_RECORD="This skill ends with \`gstack-ship-receipt result\` (Step 22), which writes /ship/runs/-/run.json and prints \`GSTACK_RESULT: skill=ship status=complete run=\`; a run that stops earlier prints \`GSTACK_RESULT: skill=ship status=refused run=-\` itself. The one publication allowed here: when an open PR for this branch exists and HEAD is its pushed head, update that PR's body with the receipt through the pr-body section's existing-PR path (never pr-create, never a push); otherwise the handoff section writes the receipt to .gstack/tmp/ship-receipt.md and the parent reads it there." ;; review) _UA_RECORD="$_UA_NONE The parent reads the review-log rows (\`gstack-review-read\`)." ;; qa) _UA_RECORD="$_UA_NONE The parent reads the \`qa-report-*.md\` file." ;; *) _UA_RECORD="$_UA_NONE The parent reads this skill's own record (docs/unattended.md)." ;; esac _emit_block unattended-session < … It refuses (`QUEUE_NOT_READY`) when the working tree has tracked edits, HEAD is not the PR's pushed head, CI at that exact head is not green, or the pregate -result is not a current pass. Send the block as printed. +result is not a current pass, and (`QUEUE_RECEIPT_MISSING`, +`QUEUE_RECEIPT_STALE`) when the PR body carries no /ship receipt for that +head: /ship runs before every READY ([details](#ship-before-ready)). Send the +block as printed. **2. Lane behind another PR: gate ahead.** Gate the tree the queue will have once the predecessor lands, while it is still open: @@ -304,6 +307,33 @@ are mirrored to origin as git notes on `refs/notes/gstack-trains` before any remote effect, so a lost machine loses nothing: `train status` on a clean state root rebuilds them. `GSTACK_SHIP_QUEUE_NOW` pins the clock for tests. + +**0. Lane: /ship before READY.** Every READY follows a /ship run on the branch +at the head being READY'd, including a re-READY after a push (Garry, +2026-10-25: "we should really be using the gstack ship skill before merging +PRs"). /ship runs the tests, both reviews, the gate-integrity list and the docs +audit, and ends by writing its receipt into the PR body +(`gstack-ship-receipt write --pr … --body `, posted with +`gstack-post pr-body`). Under `queue_mode: stamp-at-merge` it bumps no version +and never merges or merges main into the branch; the train still stamps at the +slot. The queue enforces this at every step from the PR body alone: + +- `ready` refuses with `QUEUE_RECEIPT_MISSING` when the body has no valid + receipt and with `QUEUE_RECEIPT_STALE` when the receipt's `head` is not the + head being READY'd (or its `pr` is another PR); the informational + `SHIP_RECEIPT:` line still prints. There is no flag around it. +- `train build` refuses a pin whose PR has no current receipt with the same + codes, naming the PR, before anything is written, pushed or dispatched, + `--dry-run` included. +- `verify --train` refuses the slot with the same codes before printing + `MERGE_CONDITION`. + +**The stamp keeps the pin's receipt.** The slot's stamp commit changes only +stamp files (and, from slot 2 on, merges main into the pin), so no /ship runs +on it: the receipt written for the pinned head stays the binding one. `verify +--train` accepts a receipt whose `head` is either the slot's pinned head or +the current head; any other head is `QUEUE_RECEIPT_STALE`. + **1. Lane: READY with a screen choice.** Under a train policy READY needs an explicit choice: @@ -350,8 +380,10 @@ has waited `fill_hours` (`QUEUE_TRAIN_WAITING`); `--urgent` dispatches a one-PR train at once. The same pins on the same base return the live train instead of a second one; `train build --train ` resumes a train from its record. Refusals, all before any spend: `QUEUE_TRAIN_UNTRUSTED` (a fork -head), `QUEUE_TRAIN_MOVED` (a head moved from its pin), `QUEUE_NOT_READY` (no -READY receipt at that head), `QUEUE_TRAIN_CONFLICT` (the printed +head), `QUEUE_TRAIN_MOVED` (a head moved from its pin), +`QUEUE_RECEIPT_MISSING` and `QUEUE_RECEIPT_STALE` (the PR body has no /ship +receipt for the pin; see [/ship before READY](#ship-before-ready)), +`QUEUE_NOT_READY` (no READY receipt at that head), `QUEUE_TRAIN_CONFLICT` (the printed `QUEUE_TRAIN_CONFLICT: train stopped at # (conflicts: ) after merging #,#; nothing dispatched, no branch pushed; fix: …` line names the build without that PR) and `QUEUE_TRAIN_FREE_RED` (free tests red, diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f9ca4cef2..1f43b0929 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -4021,6 +4021,38 @@ trains and other trains' merges are refused until a repair lands. @`). The freeze clears when verify finds main's tree after that merge in a green record; `NEXT:` then builds a train of the PRs still unmerged. + +### `QUEUE_RECEIPT_MISSING` + +**Meaning.** The PR body carries no valid ```gstack-ship-receipt``` block, so +/ship never ran on this branch (or its receipt was lost when the body was +rewritten). `gstack-ship-queue ready` refuses to READY it, `train build` +refuses the pin by PR number before any write, push or dispatch (dry run +included), and `verify --train` refuses the slot. The block still prints the +informational `SHIP_RECEIPT: none in the PR body` (or `invalid`) line. There +is no flag that skips this check (Garry, 2026-10-25: use the gstack ship skill +before merging PRs; [ship-policy.md](ship-policy.md#ship-before-ready)). + +**Fix.** Run /ship on the branch. Unattended, it ends by writing the receipt +into the PR body (`gstack-ship-receipt write --pr … --body `, then +`gstack-post pr-body`). Then rerun `gstack-ship-queue ready --pr +--screen|--no-screen` and send the new READY block. + + +### `QUEUE_RECEIPT_STALE` + +**Meaning.** The PR body's ship receipt is valid but names another head than +the one being READY'd or merged (a push after /ship, a receipt copied from +another PR, or a `pr` field for another PR), so the receipt does not cover +what would merge. The one accepted difference is a train slot's stamp: when +the current head is the pinned head's stamp commit (same tree modulo stamp +files, or the pin with main merged in at slot 2 and later), the receipt +written for the pinned head is the binding one and `verify --train` accepts it. + +**Fix.** Rerun /ship on the current head so the receipt names it, then rerun +`gstack-ship-queue ready --pr --screen|--no-screen`. A lane never stamps +to fix this: the stamp comes only when the slot is called. + ### `READY_SCREEN_CHOICE_REQUIRED` diff --git a/docs/unattended.md b/docs/unattended.md index 249ff535c..ba1b06b9b 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -80,7 +80,31 @@ Not every workflow writes this line or a run directory today: record), not a run directory. - **A refused launch.** Any skill whose install check refuses it at startup prints `GSTACK_RESULT: skill= status=refused run=-` and stops. -- **Every other workflow skill** (`/ship`, `/review`, `/qa`, `/design-review`, +- **`/ship`** ends with `gstack-ship-receipt result --pr ` (or `--body + .gstack/tmp/ship-receipt.md` after the handoff section). It binds the + receipt to the branch head, writes `/ship/runs/-/` + (`run.json` with `head`, `pr`, `base`, `version`, `queue_mode`, + `session_kind`, `receipt` as the path of the copied `ship-receipt.md`, and + `receipt_source`) and prints `GSTACK_RESULT: skill=ship status=complete + run=`. A receipt that is missing or names another head prints + `GSTACK_RESULT: skill=ship status=refused run=-` with `QUEUE_RECEIPT_MISSING` + or `QUEUE_RECEIPT_STALE` on stderr (exit 3); a run that stops before + publication prints the same refused line itself. A parent's merge check is + then mechanical: take `run=` from the last result line, read + `run.json`, and compare its `head` to the PR head. `gstack-ship-queue ready`, + `train build` and `verify --train` make the same comparison from the PR body + ([ship-policy.md](ship-policy.md#ship-before-ready)), which is why an + unattended /ship may update the body of a PR that already exists: when an + open PR for the branch exists and HEAD is its pushed head, Step 18 takes the + pr-body section's existing-PR path and posts the body (receipt first) and + title through `gstack-post`. That is the one publication the unattended + rules allow; it never runs `pr-create`, never pushes a commit, and a branch + with no open PR, or whose PR head is not HEAD, takes the handoff section. + When the run committed anything (a CHANGELOG entry, generated tests), the + parent pushes those commits itself, then reruns the receipt write, the body + post and `result` at the pushed head: a receipt for an unpushed head is + `QUEUE_RECEIPT_STALE` to the queue. +- **Every other workflow skill** (`/review`, `/qa`, `/design-review`, `/spec`, `/land-and-deploy` and the rest) gets the session rules above (no prompts, approvals stay pending, nothing published), but has no step that writes a run directory or prints the line, so a parent should not wait for @@ -88,14 +112,15 @@ Not every workflow writes this line or a run directory today: helper writes its `gate.json` yet (`gstack-gate` renders and parses a gate list; it does not create one). `/cso` skips the shared startup, so these session rules do not reach it at all. Read each skill's own record instead: - the review-log rows (`gstack-review-read`) for `/review`, the - `qa-report-*.md` file for `/qa`, and the ship receipt for `/ship`. When - the run did not push (an unattended run must not), read the receipt file in - the child's checkout with `gstack-ship-receipt read --body .gstack/tmp/ship-receipt.md --json`; + the review-log rows (`gstack-review-read`) for `/review` and the + `qa-report-*.md` file for `/qa`. For a `/ship` run from before the result + line, read the receipt instead: when the run did not push (an unattended run + must not), read the receipt file in the child's checkout with + `gstack-ship-receipt read --body .gstack/tmp/ship-receipt.md --json`; use `gstack-ship-receipt read --pr --json` only once a PR exists. In both cases compare the receipt's `head` to the branch SHA (`git rev-parse HEAD` in the child's checkout): `read` does not check that the receipt is current, so - an older PR's receipt reads as valid. + an older PR's receipt reads as valid; `result` does. Every workflow command shares one exit table: `0` ok, `1` fail, `2` usage, `3` refused or needs a flag. Error lines end with a result code in parentheses, diff --git a/lib/install-verdict.ts b/lib/install-verdict.ts index a08a8a265..3eb92a057 100644 --- a/lib/install-verdict.ts +++ b/lib/install-verdict.ts @@ -141,7 +141,10 @@ export function verdictProblem(skill: string, gstackRoot: string, env: Env, bunP const file = findInstallVerdict(src, project, env); const v = readInstallVerdict(file); const problem = (detail: string): VerdictProblem => ({ detail, code: 'INSTALL_UNVERIFIED' }); - if (!v) return problem(`no install verdict at ${file} for ${src}`); + if (!v) { + return { ...problem(`no install verdict at ${file} for ${src}`), + fix: `run the Capy skill installer (scripts/install.sh --for ${skill}) from ${project ?? 'this directory'}: the verdict is keyed by the project directory the installer runs in, so a run from the skill's own folder does not cover ${project ?? 'it'}; then launch with the GSTACK_LAUNCH line it prints` }; + } if (!v.ok) return problem(`the install verdict says: ${v.trailer}`); if (v.checkout !== src) return problem(`the install verdict is for checkout ${v.checkout}, not ${src}`); const head = spawnSync('git', ['-C', src, 'rev-parse', 'HEAD'], { encoding: 'utf8', timeout: 10_000 }).stdout?.trim() ?? ''; diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts index 96ed5fed2..e2d0edaa4 100644 --- a/lib/result-codes-release.ts +++ b/lib/result-codes-release.ts @@ -132,6 +132,17 @@ export const RELEASE_RESULT_CODES = { summary: 'a train stopped partway through publication, so main holds a prefix no gate covered on its own; ordinary trains are refused until a repair lands', fix: 'admit one repair PR at its exact head (train build --repair --prs @); the freeze clears when verify finds main’s tree after that merge in a green record', }, + // CREW rule 22 (Garry, 2026-10-25): /ship runs before every READY; the queue refuses a PR whose body has no current receipt. + QUEUE_RECEIPT_MISSING: { + anchor: 'queue-receipt-missing', + summary: 'the PR body carries no valid /ship receipt, so the PR was never shipped through gstack and cannot be READY’d, admitted to a train or merged', + fix: 'run /ship on the branch (unattended it writes the receipt with gstack-ship-receipt write --pr --body …), then gstack-ship-queue ready again; there is no flag to skip this', + }, + QUEUE_RECEIPT_STALE: { + anchor: 'queue-receipt-stale', + summary: 'the PR body’s /ship receipt is for another head than the one being READY’d or merged (a push after /ship, or a receipt copied from another PR)', + fix: 'rerun /ship on the current head so the receipt names it, then gstack-ship-queue ready again; a slot’s stamp commit keeps the receipt written for its pinned head', + }, READY_SCREEN_CHOICE_REQUIRED: { anchor: 'ready-screen-choice-required', summary: 'the base policy turns trains on, so READY needs an explicit screen choice: --screen (pay for a diff-relevant screen now) or --no-screen', diff --git a/lib/ship-queue-train-github.ts b/lib/ship-queue-train-github.ts index 82f12820f..b96c359f8 100644 --- a/lib/ship-queue-train-github.ts +++ b/lib/ship-queue-train-github.ts @@ -9,7 +9,7 @@ import * as path from 'node:path'; import type { Exec, RunSummary } from '../scripts/eval-bg'; import type { QueueContext } from './ship-queue'; -export interface PrInfo { headRefOid: string; isCrossRepository: boolean; state: string; headRefName: string } +export interface PrInfo { headRefOid: string; isCrossRepository: boolean; state: string; headRefName: string; body: string } export interface RunInfo { databaseId: number; status: string; conclusion: string | null; url: string; headSha: string; event: string; displayTitle: string } export interface CheckInfo { status: string; conclusion: string | null } @@ -33,10 +33,10 @@ export function repoSlug(ctx: QueueContext): string | null { } export function prInfo(ctx: QueueContext, pr: string): PrInfo | { error: string } { - const r = ctx.gh(['pr', 'view', pr, '--json', 'headRefOid,isCrossRepository,state,headRefName']); + const r = ctx.gh(['pr', 'view', pr, '--json', 'headRefOid,isCrossRepository,state,headRefName,body']); const p = json>(r); if (!p?.headRefOid) return { error: `cannot read PR #${pr} through gh (${(r.err ?? r.out).trim().slice(0, 120) || 'no headRefOid'})` }; - return { headRefOid: p.headRefOid, isCrossRepository: p.isCrossRepository !== false, state: p.state ?? 'OPEN', headRefName: p.headRefName ?? '' }; + return { headRefOid: p.headRefOid, isCrossRepository: p.isCrossRepository !== false, state: p.state ?? 'OPEN', headRefName: p.headRefName ?? '', body: p.body ?? '' }; } const RUN_FIELDS = 'databaseId,status,conclusion,url,headSha,event,displayTitle'; diff --git a/lib/ship-queue-train-verify.ts b/lib/ship-queue-train-verify.ts index 7f2db14fb..6504d036e 100644 --- a/lib/ship-queue-train-verify.ts +++ b/lib/ship-queue-train-verify.ts @@ -17,7 +17,8 @@ import { randomBytes } from 'node:crypto'; import { DISPATCH_INPUTS, awaitNonceRun, dispatchWorkflow, makeNonce } from '../scripts/eval-bg'; import type { QueueContext } from './ship-queue'; import { git } from './ship-queue-gate'; -import { checkRun, execFor, repoSlug } from './ship-queue-train-github'; +import { bindReceipt } from './ship-receipt'; +import { checkRun, execFor, prInfo, repoSlug } from './ship-queue-train-github'; import { activeFreeze, attemptsOf, nowIso, persist, trainFile, type FreezeRecord, type TrainRecord } from './ship-queue-train-record'; import { effect, fetchBase, fetchTrainBranch, findTrain, frozenLines, nextFor, outFailed, outOk, outRefused, pinList, prsArgs, save, trainEnv, type TrainEnv, type TrainOut, @@ -132,7 +133,11 @@ export async function verifyTrain(ctx: QueueContext, o: { pr: string; train: str const pinned = head === t.slots[i]!.head ? { same: true, detail: 'the pinned head' } : sameModuloStamps(env, t.slots[i]!.head, head); const stampOnly = pinned.same ? pinned : mergedIn(env, t, i, head, main); if (!stampOnly.same) return stopped(env, t, 'QUEUE_TRAIN_MOVED', `#${o.pr} moved past its pinned head ${t.slots[i]!.head.slice(0, 12)} and is not T${after.index} modulo stamps (${head.slice(0, 12)}: ${stampOnly.detail}; against the pin it ${pinned.detail})`, main, lines); - return outOk([...lines, `main: ${main} = T${before.index} (${pre.detail})`, `head: ${head} (${stampOnly.detail})`, + const info = prInfo(ctx, o.pr); + if ('error' in info) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: info.error }, lines, `${Q} verify --pr ${o.pr} --train ${t.nonce}`, run); + const shipped = bindReceipt(info.body, o.pr, [t.slots[i]!.head, head]); + if (!shipped.ok) return outRefused({ code: shipped.code, message: shipped.message }, [...lines, shipped.line], `#${o.pr}'s lane runs /ship and READYs again; then ${Q} train build --prs `, run); + return outOk([...lines, `main: ${main} = T${before.index} (${pre.detail})`, `head: ${head} (${stampOnly.detail})`, `${shipped.line} (binds ${shipped.head === t.slots[i]!.head ? 'the pinned head' : 'the current head'})`, `VERIFY_TRAIN: #${o.pr} may merge as slot ${i + 1} of train ${t.nonce} (green run ${gate.run?.id ?? '-'}, ${env.train.full_gate_check} success)`, `MERGE_CONDITION: sha=${head}`], `merge #${o.pr} with expected head ${head.slice(0, 12)} (gstack-restamp stamps at merge), then ${Q} verify --pr ${o.pr} --train ${t.nonce}`, run); } diff --git a/lib/ship-queue-train.ts b/lib/ship-queue-train.ts index 60e7be402..c9a66b010 100644 --- a/lib/ship-queue-train.ts +++ b/lib/ship-queue-train.ts @@ -21,6 +21,7 @@ import type { ResultStatus } from './headless-artifacts'; import { versionAtRef, versionFiles } from './restamp'; import type { LoadedPolicy, ShipPolicy, TrainPolicy } from './ship-policy'; import { loadBasePolicy, type QueueContext } from './ship-queue'; +import { bindReceipt } from './ship-receipt'; import { git, sha256, withIndex, type QueueFailure } from './ship-queue-gate'; import { asRun, execFor, newestBranchRun, prInfo, remoteBranchSha, repoSlug, runView, checkRun } from './ship-queue-train-github'; import { @@ -293,6 +294,8 @@ function admitSlots(env: TrainEnv, pins: Array<{ pr: string; sha: string }>): { if (!info.headRefOid.startsWith(p.sha) || fetched !== info.headRefOid) { return outRefused({ code: 'QUEUE_TRAIN_MOVED', message: `PR #${p.pr} moved: pinned ${p.sha.slice(0, 12)}, head is now ${info.headRefOid.slice(0, 12)}` }, [], `ask #${p.pr}'s lane for READY on ${info.headRefOid.slice(0, 12)}, then ${Q} train build --prs `, 'none'); } + const shipped = bindReceipt(info.body, p.pr, [info.headRefOid]); + if (!shipped.ok) return outRefused({ code: shipped.code, message: shipped.message }, [shipped.line], `#${p.pr}'s lane runs /ship, then ${Q} ready --pr ${p.pr} --screen|--no-screen; then ${Q} train build --prs `, 'none'); const ready = loadReady(env.repo.keys, p.pr, info.headRefOid); if (!ready) return outRefused({ code: 'QUEUE_NOT_READY', message: `no READY receipt for #${p.pr} at ${info.headRefOid.slice(0, 12)} (local state or ${'refs/notes/gstack-trains'})` }, [], `the lane runs ${Q} ready --pr ${p.pr} --screen|--no-screen`, 'none'); slots.push({ pr: p.pr, head: info.headRefOid, ready_at: ready.ready_at, screen: ready.screen }); diff --git a/lib/ship-queue.ts b/lib/ship-queue.ts index 574a17517..151b5d55b 100644 --- a/lib/ship-queue.ts +++ b/lib/ship-queue.ts @@ -5,8 +5,9 @@ * so every step ends in a line a coordinator can act on: * * ready READY # STAMP_VERSION= plus head, base, - * CI at that exact head, the PREGATE line and the gate state; - * refused when the tree is not the pushed PR head. + * CI at that exact head, the PREGATE line, the gate state and the + * /ship receipt; refused when the tree is not the pushed PR head + * or the PR body carries no receipt for it (QUEUE_RECEIPT_*). * stamp preflight (gated head equals HEAD modulo stamps, base, policy, * gate record under full_e2e), restamp, commit, tree receipt, * each stage journaled; QUEUE_STAMP: head= gated= @@ -23,7 +24,7 @@ import * as path from 'node:path'; import { readPregateFile, verifyPregate, PREGATE_OUT_REL } from './pregate/index'; import { ensureTmpExcluded, restamp, versionAtRef } from './restamp'; import type { ResultCodeName } from './result-codes'; -import { extractReceipt, receiptSummaryLine } from './ship-receipt'; +import { bindReceipt } from './ship-receipt'; import { isUnavailable, loadPolicyFromBase, type LoadedPolicy } from './ship-policy'; import { QUEUE_DIR_REL, applyStampPatch, commitForTree, currentAttempt, git, listAttempts, recomputeMergeTree, sha256, writeJsonAtomic, @@ -141,7 +142,7 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate pregateLine = `PREGATE: ${read.file.verdict} tree=${read.file.tree.slice(0, 12)} head=${(read.file.head ?? '').slice(0, 12)} checks=${read.file.checks.length}${v.ok ? '' : ` — ${v.message} (${v.code})`}`; } else pregateLine = `PREGATE: unreadable (${read.errors[0]?.message ?? 'invalid'})`; } - const receipt = extractReceipt(info.body ?? ''); + const receipt = bindReceipt(info.body ?? '', o.pr, [head]); const attempt = currentAttempt(ctx.repoRoot, o.pr); const lines = [ `READY #${o.pr} ${head} STAMP_VERSION=${version}`, @@ -152,13 +153,14 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate `ci: ${ci.line}`, pregateLine, gateLine(policy, attempt), - receipt.found && receipt.receipt && !receipt.errors.length ? receiptSummaryLine(receipt.receipt) : `SHIP_RECEIPT: ${receipt.found ? 'invalid' : 'none'} in the PR body`, + receipt.line, ]; const gate = policy.policy.full_e2e ? gateEvidence(ctx, o.pr, head, attempt, o.gateExit, o.gateLog) : null; if (gate) lines.push(gate.line); if (!ci.green) return fail({ code: 'QUEUE_NOT_READY', message: `CI is not green at ${head.slice(0, 12)}: ${ci.line}` }, lines, run); if (!pregateOk) return fail({ code: 'QUEUE_NOT_READY', message: `the pregate result is not a current pass: ${pregateLine}` }, lines, run); if (gate && !gate.ok) return fail({ code: 'QUEUE_GATE_MISSING', message: `full_e2e is set and no passing gate is bound to ${head.slice(0, 12)}: ${gate.line}` }, lines, run); + if (!receipt.ok) return fail({ code: receipt.code, message: receipt.message }, lines, run); return { ok: true, lines, run }; } diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index 9350b4169..64858bf89 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -49,6 +49,38 @@ export function extractReceipt(body: string): { found: boolean; receipt?: ShipRe } } +export type ReceiptBindingCode = 'QUEUE_RECEIPT_MISSING' | 'QUEUE_RECEIPT_STALE'; +export type ReceiptBinding = + | { ok: true; receipt: ShipReceipt; head: string; line: string } + | { ok: false; code: ReceiptBindingCode; message: string; line: string }; + +/** + * The /ship receipt a PR body must carry before READY, train build or a train + * merge (CREW rule 22; docs/ship-policy.md#ship-before-ready): a valid block + * whose `head` is one of the accepted heads. `accepted` is the head being + * READY'd, or the slot's pinned head beside the current head when the current + * head is the pin's stamp commit (the stamp changes only stamp files, so the + * receipt written for the pin stays the binding one). `line` is the + * informational `SHIP_RECEIPT:` line the READY block prints either way. + */ +export function bindReceipt(body: string, pr: string, accepted: readonly string[]): ReceiptBinding { + const ex = extractReceipt(body); + if (!ex.found) return { ok: false, code: 'QUEUE_RECEIPT_MISSING', message: `PR #${pr}'s body carries no ship receipt`, line: 'SHIP_RECEIPT: none in the PR body' }; + if (!ex.receipt || ex.errors.length) { + const why = ex.errors[0] ? `${ex.errors[0].message} at ${ex.errors[0].path}` : 'invalid'; + return { ok: false, code: 'QUEUE_RECEIPT_MISSING', message: `PR #${pr}'s ship receipt is invalid (${why})`, line: 'SHIP_RECEIPT: invalid in the PR body' }; + } + const r = ex.receipt; + const line = receiptSummaryLine(r); + const head = accepted.find(h => h === r.head || (r.head.length >= 12 && h.startsWith(r.head))); + if (!head) { + const want = accepted.map(h => h.slice(0, 12)).join(' or '); + return { ok: false, code: 'QUEUE_RECEIPT_STALE', message: `PR #${pr}'s ship receipt is for ${r.head.slice(0, 12)}, not the head ${want} being merged`, line }; + } + if (r.pr !== undefined && String(r.pr) !== pr) return { ok: false, code: 'QUEUE_RECEIPT_STALE', message: `PR #${pr}'s ship receipt names pr=${r.pr}, not this PR`, line }; + return { ok: true, receipt: r, head, line }; +} + /** The block becomes the first section of the body: an existing block is replaced in place at the top, prose follows. */ export function placeReceiptFirst(body: string, receipt: ShipReceipt): string { const block = renderReceiptBlock(receipt); diff --git a/ship/SKILL.md b/ship/SKILL.md index 24d4cfafb..2a7f04a63 100644 --- a/ship/SKILL.md +++ b/ship/SKILL.md @@ -1154,7 +1154,9 @@ Lookup failure or ambiguous matches **STOP** for resolution, never mean no PR. Save the result for Step 19's recheck. The pr-body section prepares the title from that result, then publishes; -`--no-pr` or an automation lane takes the handoff section. +`--no-pr` or an automation lane takes the handoff section. Unattended +(`UNATTENDED_SHIP:` echoed): an open PR at HEAD takes the pr-body section's +existing-PR path (body and title only, never `pr-create` or a push); else handoff. > **STOP.** Before preparing the title and creating or updating the PR/MR with the verified documentation outcome (Steps 18-19), Read `~/.claude/skills/gstack/ship/sections/pr-body.md` and execute it > in full. Do not work from memory — that section is the source of truth for this step. @@ -1206,6 +1208,21 @@ The marker or enabled question_tuning suppresses it; remove the marker to re-ena --- +## Step 22: Terminal line (every run) + +The last line printed is the result line a parent greps (docs/unattended.md): + +```bash +~/.claude/skills/gstack/bin/gstack-ship-receipt result --pr # handoff: --body .gstack/tmp/ship-receipt.md +``` + +It binds the receipt to HEAD, writes `/ship/runs/-/` and prints +`GSTACK_RESULT: skill=ship status=complete run=`. `QUEUE_RECEIPT_STALE`: HEAD moved after +the receipt; rewrite, repost, rerun. A run that STOPs earlier ends with the literal +`GSTACK_RESULT: skill=ship status=refused run=-` after its reason. + +--- + ## Section self-check (before you finish) List the applicable Section index entries and confirm each Read. If you worked from diff --git a/ship/SKILL.md.tmpl b/ship/SKILL.md.tmpl index fcff6bc33..833cba84e 100644 --- a/ship/SKILL.md.tmpl +++ b/ship/SKILL.md.tmpl @@ -624,7 +624,9 @@ Lookup failure or ambiguous matches **STOP** for resolution, never mean no PR. Save the result for Step 19's recheck. The pr-body section prepares the title from that result, then publishes; -`--no-pr` or an automation lane takes the handoff section. +`--no-pr` or an automation lane takes the handoff section. Unattended +(`UNATTENDED_SHIP:` echoed): an open PR at HEAD takes the pr-body section's +existing-PR path (body and title only, never `pr-create` or a push); else handoff. {{SECTION:pr-body}} @@ -674,6 +676,21 @@ The marker or enabled question_tuning suppresses it; remove the marker to re-ena --- +## Step 22: Terminal line (every run) + +The last line printed is the result line a parent greps (docs/unattended.md): + +```bash +~/.claude/skills/gstack/bin/gstack-ship-receipt result --pr # handoff: --body .gstack/tmp/ship-receipt.md +``` + +It binds the receipt to HEAD, writes `/ship/runs/-/` and prints +`GSTACK_RESULT: skill=ship status=complete run=`. `QUEUE_RECEIPT_STALE`: HEAD moved after +the receipt; rewrite, repost, rerun. A run that STOPs earlier ends with the literal +`GSTACK_RESULT: skill=ship status=refused run=-` after its reason. + +--- + ## Section self-check (before you finish) List the applicable Section index entries and confirm each Read. If you worked from diff --git a/ship/sections/handoff.md b/ship/sections/handoff.md index 046f585e2..31449cca5 100644 --- a/ship/sections/handoff.md +++ b/ship/sections/handoff.md @@ -20,7 +20,8 @@ automation lane, an unattended parent said so). Nothing here publishes. (a `requires-remote` lane, an open gate finding, an unverified claim) or `none`. `issues:` its lines, unpromoted candidates and lookup failures. Full thread ids (`jam_…`) cross-thread. -3. Skip Steps 19 and 21. Run Step 20 with `"version":null` when NO_VERSION applied. +3. Skip Steps 19 and 21. Run Step 20 with `"version":null` when NO_VERSION applied, then + Step 22 with `--body .gstack/tmp/ship-receipt.md`. ### Multi-lane runs diff --git a/ship/sections/handoff.md.tmpl b/ship/sections/handoff.md.tmpl index 3c39b9674..64aa8eaa9 100644 --- a/ship/sections/handoff.md.tmpl +++ b/ship/sections/handoff.md.tmpl @@ -18,7 +18,8 @@ automation lane, an unattended parent said so). Nothing here publishes. (a `requires-remote` lane, an open gate finding, an unverified claim) or `none`. `issues:` its lines, unpromoted candidates and lookup failures. Full thread ids (`jam_…`) cross-thread. -3. Skip Steps 19 and 21. Run Step 20 with `"version":null` when NO_VERSION applied. +3. Skip Steps 19 and 21. Run Step 20 with `"version":null` when NO_VERSION applied, then + Step 22 with `--body .gstack/tmp/ship-receipt.md`. ### Multi-lane runs diff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.md index 256fa1af1..17fbc0c40 100644 --- a/ship/sections/pr-body.md +++ b/ship/sections/pr-body.md @@ -206,7 +206,10 @@ per-lane counts (`{"":{"pass":N,"fail":N,"skip":N}}`) to Add `--receipt .gstack/tmp/tree-receipt.json` only when Step 16 wrote it (gate-ahead). New PR/MR: omit `--pr`, then rerun with the number after creation and repost the body. -Its `SHIP_RECEIPT:` line opens the completion message. `RECEIPT_INVALID` names the bad +Its `SHIP_RECEIPT:` line opens the completion message. The posted receipt is what +`gstack-ship-queue ready`, `train build` and `verify --train` check (`QUEUE_RECEIPT_MISSING`, +`QUEUE_RECEIPT_STALE`, no flag around them): /ship runs before every READY and after any +later push. `RECEIPT_INVALID` names the bad field: fix that input file and rerun; nothing was written. `ISSUE_LINKS_MISSING`: add the named line under `## Issues` and rerun. `PREGATE_STALE` means rerun `gstack-pregate` on the stamped tree; `PREGATE_REMOTE_UNCLEARED` needs diff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmpl index d886dae1d..83dfc7c11 100644 --- a/ship/sections/pr-body.md.tmpl +++ b/ship/sections/pr-body.md.tmpl @@ -189,7 +189,10 @@ per-lane counts (`{"":{"pass":N,"fail":N,"skip":N}}`) to Add `--receipt .gstack/tmp/tree-receipt.json` only when Step 16 wrote it (gate-ahead). New PR/MR: omit `--pr`, then rerun with the number after creation and repost the body. -Its `SHIP_RECEIPT:` line opens the completion message. `RECEIPT_INVALID` names the bad +Its `SHIP_RECEIPT:` line opens the completion message. The posted receipt is what +`gstack-ship-queue ready`, `train build` and `verify --train` check (`QUEUE_RECEIPT_MISSING`, +`QUEUE_RECEIPT_STALE`, no flag around them): /ship runs before every READY and after any +later push. `RECEIPT_INVALID` names the bad field: fix that input file and rerun; nothing was written. `ISSUE_LINKS_MISSING`: add the named line under `## Issues` and rerun. `PREGATE_STALE` means rerun `gstack-pregate` on the stamped tree; `PREGATE_REMOTE_UNCLEARED` needs diff --git a/test/fixtures/golden/agy-ship-SKILL.md b/test/fixtures/golden/agy-ship-SKILL.md index 6cc30d0b4..75c9c3983 100644 --- a/test/fixtures/golden/agy-ship-SKILL.md +++ b/test/fixtures/golden/agy-ship-SKILL.md @@ -1149,7 +1149,9 @@ Lookup failure or ambiguous matches **STOP** for resolution, never mean no PR. Save the result for Step 19's recheck. The pr-body section prepares the title from that result, then publishes; -`--no-pr` or an automation lane takes the handoff section. +`--no-pr` or an automation lane takes the handoff section. Unattended +(`UNATTENDED_SHIP:` echoed): an open PR at HEAD takes the pr-body section's +existing-PR path (body and title only, never `pr-create` or a push); else handoff. > **STOP.** Before preparing the title and creating or updating the PR/MR with the verified documentation outcome (Steps 18-19), Read `sections/pr-body.md` relative to the installed `gstack-ship` SKILL.md directory and execute it > in full. Do not work from memory — that section is the source of truth for this step. @@ -1201,6 +1203,21 @@ The marker or enabled question_tuning suppresses it; remove the marker to re-ena --- +## Step 22: Terminal line (every run) + +The last line printed is the result line a parent greps (docs/unattended.md): + +```bash +~/.gemini/antigravity-cli/skills/gstack/bin/gstack-ship-receipt result --pr # handoff: --body .gstack/tmp/ship-receipt.md +``` + +It binds the receipt to HEAD, writes `/ship/runs/-/` and prints +`GSTACK_RESULT: skill=ship status=complete run=`. `QUEUE_RECEIPT_STALE`: HEAD moved after +the receipt; rewrite, repost, rerun. A run that STOPs earlier ends with the literal +`GSTACK_RESULT: skill=ship status=refused run=-` after its reason. + +--- + ## Section self-check (before you finish) List the applicable Section index entries and confirm each Read. If you worked from diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md index 24d4cfafb..2a7f04a63 100644 --- a/test/fixtures/golden/claude-ship-SKILL.md +++ b/test/fixtures/golden/claude-ship-SKILL.md @@ -1154,7 +1154,9 @@ Lookup failure or ambiguous matches **STOP** for resolution, never mean no PR. Save the result for Step 19's recheck. The pr-body section prepares the title from that result, then publishes; -`--no-pr` or an automation lane takes the handoff section. +`--no-pr` or an automation lane takes the handoff section. Unattended +(`UNATTENDED_SHIP:` echoed): an open PR at HEAD takes the pr-body section's +existing-PR path (body and title only, never `pr-create` or a push); else handoff. > **STOP.** Before preparing the title and creating or updating the PR/MR with the verified documentation outcome (Steps 18-19), Read `~/.claude/skills/gstack/ship/sections/pr-body.md` and execute it > in full. Do not work from memory — that section is the source of truth for this step. @@ -1206,6 +1208,21 @@ The marker or enabled question_tuning suppresses it; remove the marker to re-ena --- +## Step 22: Terminal line (every run) + +The last line printed is the result line a parent greps (docs/unattended.md): + +```bash +~/.claude/skills/gstack/bin/gstack-ship-receipt result --pr # handoff: --body .gstack/tmp/ship-receipt.md +``` + +It binds the receipt to HEAD, writes `/ship/runs/-/` and prints +`GSTACK_RESULT: skill=ship status=complete run=`. `QUEUE_RECEIPT_STALE`: HEAD moved after +the receipt; rewrite, repost, rerun. A run that STOPs earlier ends with the literal +`GSTACK_RESULT: skill=ship status=refused run=-` after its reason. + +--- + ## Section self-check (before you finish) List the applicable Section index entries and confirm each Read. If you worked from diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.md index bbadb86ec..a4f52d763 100644 --- a/test/fixtures/golden/codex-ship-SKILL.md +++ b/test/fixtures/golden/codex-ship-SKILL.md @@ -1177,7 +1177,9 @@ Lookup failure or ambiguous matches **STOP** for resolution, never mean no PR. Save the result for Step 19's recheck. The pr-body section prepares the title from that result, then publishes; -`--no-pr` or an automation lane takes the handoff section. +`--no-pr` or an automation lane takes the handoff section. Unattended +(`UNATTENDED_SHIP:` echoed): an open PR at HEAD takes the pr-body section's +existing-PR path (body and title only, never `pr-create` or a push); else handoff. > **STOP.** Before preparing the title and creating or updating the PR/MR with the verified documentation outcome (Steps 18-19), Read `sections/pr-body.md` relative to the installed `gstack-ship` SKILL.md directory and execute it > in full. Do not work from memory — that section is the source of truth for this step. @@ -1231,6 +1233,22 @@ The marker or enabled question_tuning suppresses it; remove the marker to re-ena --- +## Step 22: Terminal line (every run) + +The last line printed is the result line a parent greps (docs/unattended.md): + +```bash +[ -d "${GSTACK_ROOT:-/-}/bin" ]&&[ -d "$GSTACK_ROOT/lib" ]||{ _r=$(git rev-parse --show-toplevel 2>/dev/null)/.agents/skills/gstack;[ -d "$_r/bin" ]||_r=${CODEX_HOME:-~/.codex}/skills/gstack;[ -d "$_r/bin" ]||{ echo "gstack: no install found (tried $_r). Fix: ./setup --host codex from your gstack checkout; ./setup --status shows it.">&2;exit 1;};GSTACK_ROOT=$_r;} +$GSTACK_ROOT/bin/gstack-ship-receipt result --pr # handoff: --body .gstack/tmp/ship-receipt.md +``` + +It binds the receipt to HEAD, writes `/ship/runs/-/` and prints +`GSTACK_RESULT: skill=ship status=complete run=`. `QUEUE_RECEIPT_STALE`: HEAD moved after +the receipt; rewrite, repost, rerun. A run that STOPs earlier ends with the literal +`GSTACK_RESULT: skill=ship status=refused run=-` after its reason. + +--- + ## Section self-check (before you finish) List the applicable Section index entries and confirm each Read. If you worked from diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.md index a59827a30..7a6f9426e 100644 --- a/test/fixtures/golden/factory-ship-SKILL.md +++ b/test/fixtures/golden/factory-ship-SKILL.md @@ -1158,7 +1158,9 @@ Lookup failure or ambiguous matches **STOP** for resolution, never mean no PR. Save the result for Step 19's recheck. The pr-body section prepares the title from that result, then publishes; -`--no-pr` or an automation lane takes the handoff section. +`--no-pr` or an automation lane takes the handoff section. Unattended +(`UNATTENDED_SHIP:` echoed): an open PR at HEAD takes the pr-body section's +existing-PR path (body and title only, never `pr-create` or a push); else handoff. > **STOP.** Before preparing the title and creating or updating the PR/MR with the verified documentation outcome (Steps 18-19), Read `sections/pr-body.md` relative to the installed `gstack-ship` SKILL.md directory and execute it > in full. Do not work from memory — that section is the source of truth for this step. @@ -1212,6 +1214,22 @@ The marker or enabled question_tuning suppresses it; remove the marker to re-ena --- +## Step 22: Terminal line (every run) + +The last line printed is the result line a parent greps (docs/unattended.md): + +```bash +[ -d "${GSTACK_ROOT:-/-}/bin" ]&&[ -d "$GSTACK_ROOT/lib" ]||{ _r=$(git rev-parse --show-toplevel 2>/dev/null)/.factory/skills/gstack;[ -d "$_r/bin" ]||_r=~/.factory/skills/gstack;[ -d "$_r/bin" ]||{ echo "gstack: no install found (tried $_r). Fix: ./setup --host factory from your gstack checkout; ./setup --status shows it.">&2;exit 1;};GSTACK_ROOT=$_r;} +$GSTACK_ROOT/bin/gstack-ship-receipt result --pr # handoff: --body .gstack/tmp/ship-receipt.md +``` + +It binds the receipt to HEAD, writes `/ship/runs/-/` and prints +`GSTACK_RESULT: skill=ship status=complete run=`. `QUEUE_RECEIPT_STALE`: HEAD moved after +the receipt; rewrite, repost, rerun. A run that STOPs earlier ends with the literal +`GSTACK_RESULT: skill=ship status=refused run=-` after its reason. + +--- + ## Section self-check (before you finish) List the applicable Section index entries and confirm each Read. If you worked from diff --git a/test/gstack-ship-queue.test.ts b/test/gstack-ship-queue.test.ts index 2422c2ae7..edf31105e 100644 --- a/test/gstack-ship-queue.test.ts +++ b/test/gstack-ship-queue.test.ts @@ -20,6 +20,7 @@ import { applyStampPatch } from '../lib/ship-queue-gate'; import type { TreeReceipt } from '../lib/tree-receipt'; import { BASE_POLICY, BIN, cleanup, makeFixtureRepo, makePr, mergeMain, mergeToMain, restamp, runBin, type FixtureRepo } from './helpers/restamp-fixture'; import { coordinatorClone, ghQueueShim } from './helpers/ship-queue-fixture'; +import { shippedBody } from './helpers/ship-queue-train-fixture'; const repos: FixtureRepo[] = []; const fixture = (policy?: Record, prefix?: string) => { const r = makeFixtureRepo({ ...(policy ? { policy } : {}), ...(prefix ? { prefix } : {}) }); repos.push(r); return r; }; @@ -258,7 +259,7 @@ describe('ready', () => { const repo = fixture(); const head = makePr(repo, 'pr-a'); const pregate = pregateFor(repo, head); - const shim = (prHead: string, checks: unknown) => ghQueueShim(repo, { prs: { '1': { headRefOid: prHead, url: 'https://github.com/o/r/pull/1', body: 'no receipt' } }, checks: { [head]: checks } }); + const shim = (prHead: string, checks: unknown, body = shippedBody('1', head)) => ghQueueShim(repo, { prs: { '1': { headRefOid: prHead, url: 'https://github.com/o/r/pull/1', body } }, checks: { [head]: checks } }); const ok = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], shim(head, green)); expect(ok.status).toBe(EXIT.ok); const lines = ok.out.split('\n'); @@ -266,8 +267,20 @@ describe('ready', () => { expect(lines.slice(1, 9)).toEqual([ 'pr: https://github.com/o/r/pull/1', `head: ${head}`, 'version: unstamped', `base: origin/main@${repo.git('rev-parse', 'origin/main')}`, `ci: green at ${head.slice(0, 12)} (passed=1 failed=0 pending=0 skipped=1)`, expect.stringMatching(/^PREGATE: pass tree=[0-9a-f]{12} head=[0-9a-f]{12} checks=1$/), - 'gate: command=none full_e2e=no gate-ahead=none', 'SHIP_RECEIPT: none in the PR body', + 'gate: command=none full_e2e=no gate-ahead=none', `SHIP_RECEIPT: pr=1 head=${head.slice(0, 12)} version=- base=main`, ]); + const unshipped = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], shim(head, green, 'no receipt')); + expect(unshipped.status).toBe(EXIT.refused); + expect(unshipped.out).toContain('SHIP_RECEIPT: none in the PR body'); + expect(unshipped.err).toMatch(/PR #1's body carries no ship receipt; fix: run \/ship on the branch .*\(QUEUE_RECEIPT_MISSING\)/); + const broken = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], shim(head, green, '```gstack-ship-receipt\n{"schema_version":1}\n```\n')); + expect(broken.status).toBe(EXIT.refused); + expect(broken.out).toContain('SHIP_RECEIPT: invalid in the PR body'); + expect(broken.err).toMatch(/ship receipt is invalid \(.*head.*\).*\(QUEUE_RECEIPT_MISSING\)/); + const stale = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], shim(head, green, shippedBody('1', 'e'.repeat(40)))); + expect(stale.status).toBe(EXIT.refused); + expect(stale.out).toContain(`SHIP_RECEIPT: pr=1 head=eeeeeeeeeeee version=- base=main`); + expect(stale.err).toMatch(new RegExp(`PR #1's ship receipt is for eeeeeeeeeeee, not the head ${head.slice(0, 12)} being merged.*\\(QUEUE_RECEIPT_STALE\\)`)); const unpushed = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], shim('f'.repeat(40), green)); expect(unpushed.status).toBe(EXIT.refused); expect(unpushed.err).toMatch(/is not PR #1's pushed head ffffffffffff.*\(QUEUE_NOT_READY\)/); @@ -276,9 +289,9 @@ describe('ready', () => { fs.appendFileSync(path.join(repo.work, 'pr-a.txt'), 'more\n'); repo.git('commit', '-qam', 'more'); const moved = repo.git('rev-parse', 'HEAD'); - const stale = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], ghQueueShim(repo, { prs: { '1': { headRefOid: moved, body: '' } }, checks: { [moved]: green } })); - expect(stale.status).toBe(EXIT.refused); - expect(stale.out).toMatch(/^PREGATE: pass .* \(PREGATE_STALE\)$/m); + const stalePregate = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], ghQueueShim(repo, { prs: { '1': { headRefOid: moved, body: shippedBody('1', moved) } }, checks: { [moved]: green } })); + expect(stalePregate.status).toBe(EXIT.refused); + expect(stalePregate.out).toMatch(/^PREGATE: pass .* \(PREGATE_STALE\)$/m); fs.appendFileSync(path.join(repo.work, 'pr-a.txt'), 'dirty\n'); expect(queue(repo, ['ready', '--pr', '1'], shim(moved, green)).err).toMatch(/uncommitted tracked changes: pr-a\.txt.*\(QUEUE_NOT_READY\)/); }, 180_000); @@ -330,7 +343,7 @@ describe('full_e2e gate evidence (review #3235 P1-1)', () => { const tree = runBin(repo, 'gstack-wtree', []).out.trim(); const pregate = path.join(repo.root, 'pregate.json'); fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree, head, verdict: 'pass', checks: [{ id: 'unit', status: 'pass' }] })); - const gh = ghQueueShim(repo, { prs: { '1': { headRefOid: head, body: '' } }, checks: { [head]: { check_runs: [{ status: 'completed', conclusion: 'success' }] } } }); + const gh = ghQueueShim(repo, { prs: { '1': { headRefOid: head, body: shippedBody('1', head) } }, checks: { [head]: { check_runs: [{ status: 'completed', conclusion: 'success' }] } } }); const missing = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], gh); expect(missing.status).toBe(EXIT.refused); expect(missing.out).toContain(`gate-evidence: missing for ${head.slice(0, 12)}`); @@ -352,7 +365,7 @@ describe('ready reads all of CI at the head (review #3235 P1-5)', () => { const tree = runBin(repo, 'gstack-wtree', []).out.trim(); const pregate = path.join(repo.root, 'pregate.json'); fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree, head, verdict: 'pass', checks: [{ id: 'unit', status: 'pass' }] })); - const gh = ghQueueShim(repo, { prs: { '1': { headRefOid: head, body: '' } }, checks: { [head]: checks }, ...(statuses ? { statuses: { [head]: statuses } } : {}) }); + const gh = ghQueueShim(repo, { prs: { '1': { headRefOid: head, body: shippedBody('1', head) } }, checks: { [head]: checks }, ...(statuses ? { statuses: { [head]: statuses } } : {}) }); return { r: queue(repo, ['ready', '--pr', '1', '--pregate', pregate], gh), at: head.slice(0, 12) }; } diff --git a/test/gstack-ship-receipt.test.ts b/test/gstack-ship-receipt.test.ts index c345cbbe1..8bec45350 100644 --- a/test/gstack-ship-receipt.test.ts +++ b/test/gstack-ship-receipt.test.ts @@ -147,6 +147,50 @@ describe('gstack-ship-receipt read', () => { }); }); +describe('gstack-ship-receipt result (/ship terminal line, GBRA-108)', () => { + test('binds the receipt to HEAD, writes the run record with the head and the receipt path, and ends with GSTACK_RESULT: skill=ship; a missing or stale receipt is status=refused run=-', () => { + const repo = fixture(); + const head = repo.git('rev-parse', 'HEAD'); + const state = path.join(repo.root, 'state'); + const env = { ...ghShim(repo, { + 5: { body: placeReceiptFirst('Prose.\n', { schema_version: 1, pr: 5, head, base: 'main', queue_mode: 'stamp-at-merge' } as any) }, + 6: { body: placeReceiptFirst('Prose.\n', { schema_version: 1, pr: 6, head: 'b'.repeat(40), base: 'main' } as any) }, + 7: { body: 'No receipt here.\n' }, + }), GSTACK_STATE_ROOT: state, GSTACK_SESSION_KIND: 'unattended' }; + const ok = runBin(repo, 'gstack-ship-receipt', ['result', '--pr', '5'], env); + expect(ok.status).toBe(EXIT.ok); + const last = ok.out.trim().split('\n').at(-1)!; + const m = /^GSTACK_RESULT: skill=ship status=complete run=(.+)$/.exec(last); + expect(m).not.toBeNull(); + const dir = m![1]!; + expect(dir.startsWith(path.join(state, 'ship', 'runs'))).toBe(true); + expect(dir.endsWith(`-${head.slice(0, 12)}`)).toBe(true); + const run = JSON.parse(fs.readFileSync(path.join(dir, 'run.json'), 'utf8')); + expect(run).toMatchObject({ schema_version: 1, skill: 'ship', status: 'complete', head, pr: 5, base: 'main', queue_mode: 'stamp-at-merge', receipt: path.join(dir, 'ship-receipt.md'), receipt_source: 'PR #5' }); + expect(extractReceipt(fs.readFileSync(run.receipt, 'utf8')).receipt).toMatchObject({ pr: 5, head }); + expect(ok.err.trim()).toBe(`SHIP_RECEIPT: pr=5 head=${head.slice(0, 12)} version=- base=main`); + + const stale = runBin(repo, 'gstack-ship-receipt', ['result', '--pr', '6'], env); + expect(stale.status).toBe(EXIT.refused); + expect(stale.out.trim()).toBe('GSTACK_RESULT: skill=ship status=refused run=-'); + expect(stale.err).toMatch(new RegExp(`PR #6's ship receipt is for bbbbbbbbbbbb, not the head ${head.slice(0, 12)} being merged.*\\(QUEUE_RECEIPT_STALE; https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#queue-receipt-stale\\)`)); + const missing = runBin(repo, 'gstack-ship-receipt', ['result', '--pr', '7', '--json'], env); + expect(missing.status).toBe(EXIT.refused); + expect(JSON.parse(missing.out)).toMatchObject({ skill: 'ship', status: 'refused', run: '-', code: 'QUEUE_RECEIPT_MISSING' }); + + const bodyFile = path.join(repo.work, '.gstack/tmp/ship-receipt.md'); + fs.mkdirSync(path.dirname(bodyFile), { recursive: true }); + fs.writeFileSync(bodyFile, renderReceiptBlock({ schema_version: 1, head, base: 'main' } as any)); + const handoff = runBin(repo, 'gstack-ship-receipt', ['result', '--body', bodyFile, '--out', path.join(repo.root, 'run-out')], env); + expect(handoff.status).toBe(EXIT.ok); + expect(handoff.out.trim()).toBe(`GSTACK_RESULT: skill=ship status=complete run=${path.join(repo.root, 'run-out')}`); + expect(JSON.parse(fs.readFileSync(path.join(repo.root, 'run-out', 'run.json'), 'utf8'))).toMatchObject({ head, pr: null, receipt_source: bodyFile, session_kind: 'unattended' }); + expect(runBin(repo, 'gstack-ship-receipt', ['result', '--body', path.join(repo.root, 'absent.md')], env).status).toBe(EXIT.refused); + expect(runBin(repo, 'gstack-ship-receipt', ['result'], env).status).toBe(EXIT.usage); + expect(fs.readdirSync(path.join(state, 'ship', 'runs')).length).toBe(1); + }); +}); + describe('gstack-ship-receipt census (P7)', () => { const prs = [ { number: 1, mergedAt: '2026-10-02T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '2/3', run: 'run-a', thread: 'jam_1' } as any) }, diff --git a/test/gstack-skill-start.test.ts b/test/gstack-skill-start.test.ts index 63f1f9999..ee47487a8 100644 --- a/test/gstack-skill-start.test.ts +++ b/test/gstack-skill-start.test.ts @@ -401,8 +401,11 @@ describe('gstack-skill-start behavior', () => { expect(evalPlan).toContain('`GSTACK_RESULT: skill=eval-plan status=gate_pending run=`'); expect(evalPlan).toContain('No helper writes a gate.json'); expect(evalPlan).not.toContain('gate list'); + const ship = blocks.ship; + expect(ship).toContain('`GSTACK_RESULT: skill=ship status=complete run=`'); + expect(ship).toContain('`GSTACK_RESULT: skill=ship status=refused run=-`'); + expect(ship).not.toContain('writes no run directory'); const records: Record = { - ship: 'gstack-ship-receipt read --pr --json', review: 'gstack-review-read', qa: 'qa-report-*.md', investigate: "this skill's own record (docs/unattended.md)", @@ -418,12 +421,14 @@ describe('gstack-skill-start behavior', () => { } }, 60_000); - test('unattended /ship alone prints the UNATTENDED_SHIP status line naming the receipt file (GSTA-88)', () => { - const line = /^UNATTENDED_SHIP: no push, no PR; Step 18 takes the handoff section; receipt at \.gstack\/tmp\/ship-receipt\.md$/gm; + test('unattended /ship alone prints the UNATTENDED_SHIP status line naming the receipt file, the existing-PR body update and the result line (GSTA-88, rule 22)', () => { + const line = /^UNATTENDED_SHIP: no push, no new PR; an open PR at HEAD gets its body updated \(pr-body section, receipt first\), else Step 18 takes the handoff section; receipt at \.gstack\/tmp\/ship-receipt\.md; end with gstack-ship-receipt result$/gm; const ship = runStart(['--skill', 'ship'], { GSTACK_SESSION_KIND: 'unattended' }); expect(ship.match(line)).toHaveLength(1); expect((ship.match(/^GSTACK_INSTRUCTION_BEGIN: (\S+)/gm) ?? []).map((h) => h.replace(/^GSTACK_INSTRUCTION_BEGIN: /, ''))).toEqual(['unattended-session']); - expect(ship).toContain('.gstack/tmp/ship-receipt.md when nothing was pushed'); + expect(ship).toContain('`GSTACK_RESULT: skill=ship status=complete run=`'); + expect(ship).toContain("update that PR's body with the receipt through the pr-body section's existing-PR path (never pr-create, never a push)"); + expect(ship).toContain('the handoff section writes the receipt to .gstack/tmp/ship-receipt.md'); for (const skill of ['review', 'qa', 'autoplan']) { expect(runStart(['--skill', skill], { GSTACK_SESSION_KIND: 'unattended' })).not.toContain('UNATTENDED_SHIP'); } diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.ts index ff3ff4203..611b64727 100644 --- a/test/helpers/carve-guards.ts +++ b/test/helpers/carve-guards.ts @@ -155,7 +155,7 @@ export const CARVE_GUARDS: Record = { }, behavioral: 'external', externalTest: 'test/skill-e2e-ship-section-loading.test.ts', - maxSkeletonBytes: 81_000, // + v2.0 {{ASIDE_RESEARCH}} (Aside first, WebSearch fallback); measured 78_275. + gate integrity (HONEST_WORK_GATE_INTEGRITY W3): Step 16 stage 4 ZERO-RUN/unknown receipt rows, stage 5 honesty inventory, Step 17 open-gate ready-PR gate; measured 80,540 (2026-10-10). + maxSkeletonBytes: 82_000, // + v2.0 {{ASIDE_RESEARCH}} (Aside first, WebSearch fallback); measured 78_275. + gate integrity (HONEST_WORK_GATE_INTEGRITY W3): Step 16 stage 4 ZERO-RUN/unknown receipt rows, stage 5 honesty inventory, Step 17 open-gate ready-PR gate; measured 80,540 (2026-10-10). + rule 22 / GBRA-108 (2026-10-25): Step 22's terminal line (gstack-ship-receipt result, the GSTACK_RESULT line a parent greps) and Step 18's unattended routing (an open PR at HEAD gets its body updated, else handoff), both written as tight as they go after the 2026-10-14 tightening left 2 bytes of headroom; measured 81,711. minUnionBytes: 181_000, // token-reduction Phases 1-2 (v1.69.x branch); measured union 201,464 mustContain: ['VERSION', 'CHANGELOG', 'review', 'merge', 'PR'], // v1.58.5.0: pre-push-guard install (#2077) stacks on the shared first-run-guidance preamble. @@ -168,7 +168,7 @@ export const CARVE_GUARDS: Record = { // wave's headline capability) grows the union to 1.195x. Deliberate: // the section is on-demand (loads only for Apple store targets), so // per-invocation cost for non-iOS ships is one manifest line. - maxSizeRatio: 1.6690, // Shared advisory identity/dedup + critical-severity validation: 248,065 union bytes / 187,706 baseline = 1.3216 (2026-09-17). + test value bar in the lazy Step 7 section (value cards, weak paths, gate table, base control, machine checks; ~13.6KB): measured 1.396 (2026-09-29). + W1 guarded state-root resolution (`eval gstack-paths; : "${GSTACK_STATE_ROOT:?…}"`) in the Context Recovery preamble, the eureka log and each state-writing bash block; measured 1.401 (2026-09-30). + the shared QA review step's plan-check timing rule (plan checks and their revalidation run on --timeout-ms after smoke expiry); measured 1.4022 (2026-09-30). + the shared TEST_BOOTSTRAP owned-change undo rules (s03 H1-H3, M1) and the value-bar coverage wording (s03 M2/M3); measured 1.4044 (2026-10-02). + severe fix wave ship-review lane: G1 NO_VERSION dispatch, title and CHANGELOG arms (versionless repos ship without inventing a version), F1 parent-side plan binding before the audit dispatch (binding, docs/designs candidates, exact not-run line) and D3's data-not-instructions line; +2,126 union bytes, measured 1.4135 (2026-10-03). + INV-1 consumer lines (outside review `unverified`/`unavailable` is missing coverage in the readiness note and PR body); measured 1.4148 (2026-10-03). + v1.91.19.0 severe fix wave: verdict-form outside-review callers with sandbox preflight and first-use notice (INV-1/B1/Q2), P0/P1 gate and unverified wording, bound-plan discovery (F1), visible LEARNINGS failures (B5), carved external pointers; measured 267,752 / 187,706 = 1.4264 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 267,874 / 187,706 = 1.4271 (2026-10-04). + Oct 6 fix wave: quota_exhausted preflight branch (#3051) and quoted-heredoc issue template (#3046); measured 268,199 / 187,706 = 1.4288 (2026-10-06). + Step 10's inline no-PR check before the Greptile dispatch (#3020); measured 268,655 / 187,706 = 1.4313 (2026-10-06). + Oct 6 fix wave A3/CEO-12: free text reaches commands only through agent-written mktemp files (mktemp block, write rule, path rebuild and refusal at each posting, prompt and brief site); measured 275,422 / 187,706 = 1.4673 (2026-10-06). Combined Oct 6 wave head (B free-text files + D measure loop + A rework): measured 280,363 / 187,706 = 1.4936 (2026-10-06). + gate-once push rule (no second paid gate after a CI push); measured 280,573 / 187,706 = 1.4947 (2026-10-06). + the measurement bar's decision step (exit-code branches for MEETS, MEETS-qualified, needs-classify with the qualifying and fix-round classes, EXTEND once; the measure prose was tightened to offset most of it); measured 281,058 / 187,706 = 1.4973 (2026-10-06). + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 281,438 / 187,706 = 1.4994 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; measured 281,556 / 187,706 = 1.5000 (2026-10-07). + Oct 7 wave B4: /ship publishes through gstack-post (title prepared in a file in the pr-body section, compose block plus gstack-post exit-code branches replacing the two scans); measured 281,894 / 187,706 = 1.5018 (2026-10-07). + B2 early Greptile PR (lazy Step 6.5 section: detect, public-repo consent, push, provisional title file, open; Step 10's bounded wait; the stop-leaves-the-draft rule); measured 286,626 / 187,706 = 1.5270 (2026-10-07). B3, the classifier, B4 and B2 merged: measured 287,128 / 187,706 = 1.5297 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; measured 281,370 / 187,706 = 1.4990 (2026-10-07). Merged with the guard area: measured 287,440 / 187,706 = 1.5313 (2026-10-07). + Oct 8 wave: the defensive-security framing and fixture summary mode reach the security specialist and the Red Team (stated once in the dispatch, referenced by the Red Team); measured 288,783 / 187,706 = 1.5385 (2026-10-08). + gate integrity (HONEST_WORK_GATE_INTEGRITY W3): the shared GATE_SCAN_BLOCK in the core checklist (2.5) and after Step 7's child, the four-option gate question and record fields in 9.4, tests_ran states in Step 5, Gate edits and per-lane counts in the PR body with draft-while-open; measured 300,143 / 187,706 = 1.5990 (2026-10-10). + Honest Work wave merged (W2/W3 gate integrity in review/ship, W4 kernel + DONE line in every tier-2+ skill, W5/W7 in spec/ship): re-measured on the integrated tree (2026-10-10). + Oct 10 multi-agent wave PR E2 (ship/sections/handoff.md: the no-PR automation handoff, with its Section-index row and STOP pointer in the skeleton), offset by tightening Steps 1–3, 12, 14–17 and 20–21 prose so the skeleton stays under 81,000 bytes (80,997); C-pregate landed 1,123 union bytes in tests.md in between; measured 308,619 / 187,706 = 1.6442 on the integrated tree (2026-10-10). + next-wave Lane D (GBRA-40 item 12): the pr-body Issue links step (promotion candidates and `fix #N`, owner-confirmed Supersedes/credit, `--author` for app-identity gh, lookup failures, ISSUE_LINKS_MISSING) and the handoff's issue-links run, with the `## Issues` placeholder shortened; Step 15's `Fixes:` trailer rule offset by tightening Step 15 so the skeleton stays at 80,998; measured 309,483 / 187,706 = 1.6488 (2026-10-14). + GSTA-61 Capy merge asks: the on-demand capy-pr section (What changed with before/after images, Why, Approvals; loads only when Step 19 prints CAPY_PR: on, so a non-Capy ship pays one manifest line and the three-line CAPY_PR check); measured 313,265 / 187,706 = 1.6689 (2026-10-20). + maxSizeRatio: 1.6760, // Shared advisory identity/dedup + critical-severity validation: 248,065 union bytes / 187,706 baseline = 1.3216 (2026-09-17). + test value bar in the lazy Step 7 section (value cards, weak paths, gate table, base control, machine checks; ~13.6KB): measured 1.396 (2026-09-29). + W1 guarded state-root resolution (`eval gstack-paths; : "${GSTACK_STATE_ROOT:?…}"`) in the Context Recovery preamble, the eureka log and each state-writing bash block; measured 1.401 (2026-09-30). + the shared QA review step's plan-check timing rule (plan checks and their revalidation run on --timeout-ms after smoke expiry); measured 1.4022 (2026-09-30). + the shared TEST_BOOTSTRAP owned-change undo rules (s03 H1-H3, M1) and the value-bar coverage wording (s03 M2/M3); measured 1.4044 (2026-10-02). + severe fix wave ship-review lane: G1 NO_VERSION dispatch, title and CHANGELOG arms (versionless repos ship without inventing a version), F1 parent-side plan binding before the audit dispatch (binding, docs/designs candidates, exact not-run line) and D3's data-not-instructions line; +2,126 union bytes, measured 1.4135 (2026-10-03). + INV-1 consumer lines (outside review `unverified`/`unavailable` is missing coverage in the readiness note and PR body); measured 1.4148 (2026-10-03). + v1.91.19.0 severe fix wave: verdict-form outside-review callers with sandbox preflight and first-use notice (INV-1/B1/Q2), P0/P1 gate and unverified wording, bound-plan discovery (F1), visible LEARNINGS failures (B5), carved external pointers; measured 267,752 / 187,706 = 1.4264 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 267,874 / 187,706 = 1.4271 (2026-10-04). + Oct 6 fix wave: quota_exhausted preflight branch (#3051) and quoted-heredoc issue template (#3046); measured 268,199 / 187,706 = 1.4288 (2026-10-06). + Step 10's inline no-PR check before the Greptile dispatch (#3020); measured 268,655 / 187,706 = 1.4313 (2026-10-06). + Oct 6 fix wave A3/CEO-12: free text reaches commands only through agent-written mktemp files (mktemp block, write rule, path rebuild and refusal at each posting, prompt and brief site); measured 275,422 / 187,706 = 1.4673 (2026-10-06). Combined Oct 6 wave head (B free-text files + D measure loop + A rework): measured 280,363 / 187,706 = 1.4936 (2026-10-06). + gate-once push rule (no second paid gate after a CI push); measured 280,573 / 187,706 = 1.4947 (2026-10-06). + the measurement bar's decision step (exit-code branches for MEETS, MEETS-qualified, needs-classify with the qualifying and fix-round classes, EXTEND once; the measure prose was tightened to offset most of it); measured 281,058 / 187,706 = 1.4973 (2026-10-06). + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 281,438 / 187,706 = 1.4994 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; measured 281,556 / 187,706 = 1.5000 (2026-10-07). + Oct 7 wave B4: /ship publishes through gstack-post (title prepared in a file in the pr-body section, compose block plus gstack-post exit-code branches replacing the two scans); measured 281,894 / 187,706 = 1.5018 (2026-10-07). + B2 early Greptile PR (lazy Step 6.5 section: detect, public-repo consent, push, provisional title file, open; Step 10's bounded wait; the stop-leaves-the-draft rule); measured 286,626 / 187,706 = 1.5270 (2026-10-07). B3, the classifier, B4 and B2 merged: measured 287,128 / 187,706 = 1.5297 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; measured 281,370 / 187,706 = 1.4990 (2026-10-07). Merged with the guard area: measured 287,440 / 187,706 = 1.5313 (2026-10-07). + Oct 8 wave: the defensive-security framing and fixture summary mode reach the security specialist and the Red Team (stated once in the dispatch, referenced by the Red Team); measured 288,783 / 187,706 = 1.5385 (2026-10-08). + gate integrity (HONEST_WORK_GATE_INTEGRITY W3): the shared GATE_SCAN_BLOCK in the core checklist (2.5) and after Step 7's child, the four-option gate question and record fields in 9.4, tests_ran states in Step 5, Gate edits and per-lane counts in the PR body with draft-while-open; measured 300,143 / 187,706 = 1.5990 (2026-10-10). + Honest Work wave merged (W2/W3 gate integrity in review/ship, W4 kernel + DONE line in every tier-2+ skill, W5/W7 in spec/ship): re-measured on the integrated tree (2026-10-10). + Oct 10 multi-agent wave PR E2 (ship/sections/handoff.md: the no-PR automation handoff, with its Section-index row and STOP pointer in the skeleton), offset by tightening Steps 1–3, 12, 14–17 and 20–21 prose so the skeleton stays under 81,000 bytes (80,997); C-pregate landed 1,123 union bytes in tests.md in between; measured 308,619 / 187,706 = 1.6442 on the integrated tree (2026-10-10). + next-wave Lane D (GBRA-40 item 12): the pr-body Issue links step (promotion candidates and `fix #N`, owner-confirmed Supersedes/credit, `--author` for app-identity gh, lookup failures, ISSUE_LINKS_MISSING) and the handoff's issue-links run, with the `## Issues` placeholder shortened; Step 15's `Fixes:` trailer rule offset by tightening Step 15 so the skeleton stays at 80,998; measured 309,483 / 187,706 = 1.6488 (2026-10-14). + GSTA-61 Capy merge asks: the on-demand capy-pr section (What changed with before/after images, Why, Approvals; loads only when Step 19 prints CAPY_PR: on, so a non-Capy ship pays one manifest line and the three-line CAPY_PR check); measured 313,265 / 187,706 = 1.6689 (2026-10-20). + rule 22 / GBRA-108 (2026-10-25): Step 22 terminal line and Step 18 unattended routing in the skeleton, the pr-body section's receipt-check sentence and the handoff's Step 22 pointer; measured 314,204 / 187,706 = 1.6739. }, 'plan-ceo-review': { skill: 'plan-ceo-review', diff --git a/test/helpers/ship-queue-train-fixture.ts b/test/helpers/ship-queue-train-fixture.ts index 9769d9419..c1ab1072b 100644 --- a/test/helpers/ship-queue-train-fixture.ts +++ b/test/helpers/ship-queue-train-fixture.ts @@ -13,7 +13,9 @@ import { spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import type { ShipReceipt } from '../../lib/headless-artifacts'; import { TRAIN_KEYS_VERSION } from '../../lib/ship-policy'; +import { orderReceipt, renderReceiptBlock } from '../../lib/ship-receipt'; import { BASE_POLICY, makeFixtureRepo, runBin, type FixtureRepo } from './restamp-fixture'; export const TRAIN_BLOCK = { @@ -58,8 +60,18 @@ export function repoKey(fx: TrainFixture): string { return createHash('sha256').update(norm).digest('hex').slice(0, 16); } -/** A same-repo PR: a branch from origin/main touching `file`, published as refs/pull//head (and /merge), known to the gh shim. */ -export function openPr(fx: TrainFixture, pr: string, opts: { file?: string; text?: string; changelog?: boolean | ((text: string) => string); cross?: boolean; from?: string } = {}): string { +/** The PR body /ship leaves behind: the receipt block first (lib/ship-receipt.ts), bound to `head`, then prose. */ +export function shippedBody(pr: string, head: string, extra: Partial = {}): string { + return renderReceiptBlock(orderReceipt({ schema_version: 1, pr: Number(pr), head, base: 'main', queue_mode: 'stamp-at-merge', ...extra })) + `\n## What changed\n\n#${pr} change\n`; +} + +/** Set a shimmed PR's body (`shippedBody` for a receipt bound to another head, '' for none). */ +export function setPrBody(fx: TrainFixture, pr: string, body: string): void { + fx.write(d => { d.prs[pr] = { ...(d.prs[pr] as Record), body }; }); +} + +/** A same-repo PR: a branch from origin/main touching `file`, published as refs/pull//head (and /merge), known to the gh shim with a /ship receipt for its head (`shipped: false` leaves the body empty). */ +export function openPr(fx: TrainFixture, pr: string, opts: { file?: string; text?: string; changelog?: boolean | ((text: string) => string); cross?: boolean; from?: string; shipped?: boolean } = {}): string { const { repo } = fx; repo.git('checkout', '-q', opts.from ?? 'origin/main', '-B', `pr-${pr}`); const file = opts.file ?? `pr-${pr}.txt`; @@ -73,7 +85,7 @@ export function openPr(fx: TrainFixture, pr: string, opts: { file?: string; text repo.git('commit', '-q', '-m', `feat #${pr}`); const head = repo.git('rev-parse', 'HEAD'); repo.git('push', '-q', '-f', 'origin', `HEAD:refs/pull/${pr}/head`, `HEAD:refs/pull/${pr}/merge`); - fx.write(d => { d.prs[pr] = { headRefOid: head, isCrossRepository: !!opts.cross, state: 'OPEN', headRefName: `pr-${pr}`, url: `https://github.com/fixture/repo/pull/${pr}`, body: '' }; }); + fx.write(d => { d.prs[pr] = { headRefOid: head, isCrossRepository: !!opts.cross, state: 'OPEN', headRefName: `pr-${pr}`, url: `https://github.com/fixture/repo/pull/${pr}`, body: opts.shipped === false ? '' : shippedBody(pr, head) }; }); return head; } diff --git a/test/install-verdict.test.ts b/test/install-verdict.test.ts index 5729b55b0..172ecfa72 100644 --- a/test/install-verdict.test.ts +++ b/test/install-verdict.test.ts @@ -110,6 +110,19 @@ describe('install verdict keyed by (checkout, project): both twins', () => { expect(both('review', b, { GSTACK_STATE_ROOT: legacySr })).toMatchObject({ refuse: false, status: 'ok' }); }); + test("GSTA-85: an installer run from the skill's own folder (no project) leaves /ship from the project with no verdict; both twins name the project directory to run the installer from", () => { + const sr = tmp(); + const env = { GSTACK_STATE_ROOT: sr }; + const proj = project('lane'); + writeVerdict(sr, { project: '', bun_path: BUN, bun_version: '1.4.2', schema_version: 2, for: 'ship' }); + const r = both('ship', proj, env); + expect(r).toMatchObject({ refuse: true, status: 'verdict', code: 'INSTALL_UNVERIFIED' }); + expect(r.detail).toBe(`no install verdict at ${installVerdictPath(REAL, sr, proj)} for ${REAL}`); + const fix = `fix: run the Capy skill installer (scripts/install.sh --for ship) from ${proj}: the verdict is keyed by the project directory the installer runs in, so a run from the skill's own folder does not cover ${proj}; then launch with the GSTACK_LAUNCH line it prints (INSTALL_UNVERIFIED)`; + expect(r.line).toContain(fix); + expect(bashAdmit('ship', proj, { _GH: sr, ...env }).line).toContain(fix); + }); + test('a running Bun other than the recorded one refuses with BUN_RESOLUTION_DRIFT and names both', () => { const sr = tmp(); const a = project('a'); diff --git a/test/ship-queue-train.test.ts b/test/ship-queue-train.test.ts index 08dd50033..8bf91f174 100644 --- a/test/ship-queue-train.test.ts +++ b/test/ship-queue-train.test.ts @@ -19,7 +19,7 @@ import { TRAIN_HELP } from '../lib/ship-queue-train-cli'; import { BASE_POLICY, cleanup, runBin } from './helpers/restamp-fixture'; import { coordinatorClone } from './helpers/ship-queue-fixture'; import { - COMPLETE, FAIL, GREEN_GATE, PASS, RED_GATE, TRAIN_BLOCK, TRAIN_POLICY, dispatches, githubOrigin, line, nonceOf, openPr, queue, readyReceipt, repoKey, trainFixture, trainJson, urlKey, + COMPLETE, FAIL, GREEN_GATE, PASS, RED_GATE, TRAIN_BLOCK, TRAIN_POLICY, dispatches, githubOrigin, line, nonceOf, openPr, queue, readyReceipt, repoKey, setPrBody, shippedBody, trainFixture, trainJson, urlKey, type Rule, type TrainFixture, } from './helpers/ship-queue-train-fixture'; @@ -151,6 +151,30 @@ describe('ready under a train policy: the screen choice', () => { expect(fs.existsSync(path.join(fx.state, 'ship-queue', 'ready'))).toBe(false); }, 120_000); + test('rule 22: READY needs the /ship receipt for this head in the PR body; none or another head refuses before any receipt is written, with no flag around it', () => { + const { fx, head, pregate } = readyFixture(); + setPrBody(fx, '1', '## What changed\n\nno /ship ran\n'); + const none = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen']); + expect(none.status).toBe(EXIT.refused); + expect(none.out).toContain('SHIP_RECEIPT: none in the PR body'); + expect(none.err).toMatch(/PR #1's body carries no ship receipt; fix: run \/ship on the branch .*there is no flag to skip this \(QUEUE_RECEIPT_MISSING\)/); + expect(next(none.out)).toBe('NEXT: fix the refusal, then gstack-ship-queue ready --pr 1 --screen|--no-screen'); + const other = 'd'.repeat(40); + setPrBody(fx, '1', shippedBody('1', other)); + const stale = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen']); + expect(stale.status).toBe(EXIT.refused); + expect(stale.out).toContain(`SHIP_RECEIPT: pr=1 head=dddddddddddd version=- base=main`); + expect(stale.err).toMatch(new RegExp(`PR #1's ship receipt is for dddddddddddd, not the head ${head.slice(0, 12)} being merged; fix: rerun /ship .*\\(QUEUE_RECEIPT_STALE\\)`)); + setPrBody(fx, '1', shippedBody('2', head)); + expect(queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen']).err).toMatch(/PR #1's ship receipt names pr=2, not this PR.*\(QUEUE_RECEIPT_STALE\)/); + expect(fs.existsSync(path.join(fx.state, 'ship-queue', 'ready'))).toBe(false); + setPrBody(fx, '1', shippedBody('1', head, { version: '1.2.4.0', session_kind: 'unattended' })); + const ok = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen']); + expect(ok.status).toBe(EXIT.ok); + expect(line(ok.out, 'SHIP_RECEIPT:')).toBe(`SHIP_RECEIPT: pr=1 head=${head.slice(0, 12)} version=1.2.4.0 base=main session_kind=unattended`); + expect(fs.existsSync(path.join(fx.state, 'ship-queue', 'ready', repoKey(fx), `1-${head}.json`))).toBe(true); + }, 120_000); + test('--screen dispatches one screen with the PR, its merge SHA and the policy; a repeat adopts it; a broad screen never adopts the narrow one', () => { const { fx, head, pregate } = readyFixture(); const dry = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--screen', '--dry-run']); @@ -309,6 +333,35 @@ describe('train build', () => { expect(dispatches(fx, 'evals.yml').length).toBe(1); }, 180_000); + test('rule 22: a pin whose PR body has no current /ship receipt is refused by name before any write, push or dispatch, dry run included; the pinned-head receipt admits it', () => { + const fx = make(); + const h1 = openPr(fx, '1'); + const h2 = openPr(fx, '2', { shipped: false }); + readyReceipt(fx, '1', h1); + readyReceipt(fx, '2', h2); + fx.write(d => { d.rules['evals.yml'] = GREEN_GATE; }); + const refsBefore = remoteRefs(fx); + for (const args of [['--dry-run'], []]) { + const r = queue(fx, ['train', 'build', '--prs', `1@${h1},2@${h2}`, ...args]); + expect(r.status).toBe(EXIT.refused); + expect(r.err).toMatch(/PR #2's body carries no ship receipt; fix: run \/ship on the branch .*\(QUEUE_RECEIPT_MISSING\)/); + expect(r.out).toContain('SHIP_RECEIPT: none in the PR body'); + expect(next(r.out)).toBe("NEXT: #2's lane runs /ship, then gstack-ship-queue ready --pr 2 --screen|--no-screen; then gstack-ship-queue train build --prs "); + expect(result(r.out)).toBe('GSTACK_RESULT: skill=ship-queue status=refused run=none'); + } + setPrBody(fx, '2', shippedBody('2', 'a'.repeat(40))); + const stale = queue(fx, ['train', 'build', '--prs', `1@${h1},2@${h2}`, '--dry-run']); + expect(stale.status).toBe(EXIT.refused); + expect(stale.err).toMatch(new RegExp(`PR #2's ship receipt is for aaaaaaaaaaaa, not the head ${h2.slice(0, 12)} being merged.*\\(QUEUE_RECEIPT_STALE\\)`)); + expect(remoteRefs(fx)).toBe(refsBefore); + expect(dispatches(fx)).toEqual([]); + expect(fs.existsSync(path.join(fx.state, 'ship-queue', 'trains'))).toBe(false); + setPrBody(fx, '2', shippedBody('2', h2)); + const ok = queue(fx, ['train', 'build', '--prs', `1@${h1},2@${h2}`]); + expect(ok.status).toBe(EXIT.ok); + expect(dispatches(fx).length).toBe(2); + }, 180_000); + test('free tests red, cancelled, missing or on another SHA refuse with QUEUE_TRAIN_FREE_RED before any paid dispatch', () => { const fx = make(); const h1 = openPr(fx, '1'); @@ -596,6 +649,36 @@ describe('verify, freeze, repair and clear', () => { expect(JSON.parse(fs.readFileSync(freezeFile, 'utf8')).cleared_at).toBe('2026-10-18T12:00:00.000Z'); expect(queue(fx, ['train', 'status']).out).not.toContain('QUEUE_TRAIN_FROZEN'); }, 300_000); + test("rule 22: verify --train binds the receipt to the pinned head when the current head is its stamp commit; a receipt for another head refuses the slot and merges nothing", () => { + const fx = make(); + const { h1, nonce } = twoPrTrain(fx); + expect(queue(fx, ['train', 'verdict', '--train', nonce]).status).toBe(EXIT.ok); + const coord = coordinatorClone(fx.repo); + const v = () => queue(fx, ['verify', '--pr', '1', '--train', nonce], {}, coord); + const { repo } = fx; + repo.git('checkout', '-q', '-B', 'lane1', h1); + fs.writeFileSync(path.join(repo.work, 'VERSION'), '1.2.4.0\n'); + repo.git('commit', '-qam', 'v1.2.4.0 stamp'); + const stamped = repo.git('rev-parse', 'HEAD'); + repo.git('push', '-q', '-f', 'origin', `${stamped}:refs/pull/1/head`); + const ok = v(); + expect(ok.status).toBe(EXIT.ok); + expect(ok.out).toContain(`head: ${stamped} (same modulo stamps (1 stamp file(s)))`); + expect(ok.out).toContain(`SHIP_RECEIPT: pr=1 head=${h1.slice(0, 12)} version=- base=main (binds the pinned head)`); + expect(line(ok.out, 'MERGE_CONDITION:')).toBe(`MERGE_CONDITION: sha=${stamped}`); + setPrBody(fx, '1', shippedBody('1', 'b'.repeat(40))); + const stale = v(); + expect(stale.status).toBe(EXIT.refused); + expect(stale.err).toMatch(new RegExp(`PR #1's ship receipt is for bbbbbbbbbbbb, not the head ${h1.slice(0, 12)} or ${stamped.slice(0, 12)} being merged.*\\(QUEUE_RECEIPT_STALE\\)`)); + expect(stale.out).not.toContain('MERGE_CONDITION:'); + expect(next(stale.out)).toBe("NEXT: #1's lane runs /ship and READYs again; then gstack-ship-queue train build --prs "); + expect(trainJson(fx, nonce).merged).toEqual([]); + setPrBody(fx, '1', ''); + expect(v().err).toContain('(QUEUE_RECEIPT_MISSING)'); + setPrBody(fx, '1', shippedBody('1', stamped)); + expect(v().out).toContain(`SHIP_RECEIPT: pr=1 head=${stamped.slice(0, 12)} version=- base=main (binds the current head)`); + }, 300_000); + test('from slot 2 on, a head that merges main into the pin verifies when its tree is the slot\'s prefix modulo stamps', () => { const fx = make(); const { h2, nonce } = twoPrTrain(fx);