From 45ee345030ec421f2c331ab4e1a1ac48f507a2dc Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 16 Nov 2026 10:46:26 +0800 Subject: [PATCH 01/62] Stable release cut no longer waits on the Windows nightly (GST-2815) (#4400) * Stable release cut no longer waits on the Windows nightly (GST-2815) The nightly Windows free suite is documented as never gating, but the daily cut refused any commit carrying its red or unfinished check runs, so stable stayed behind v1.99.5.0 while shard 4 kept timing out. The cut now sets that workflow's check runs aside by workflow path, like its own job. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Type the expected green verdict in the nightly test as a literal Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../stable-cut-ignores-windows-nightly.md | 1 + crew/scripts/release-cut.ts | 13 ++++--- crew/test/release-cut.test.ts | 34 ++++++++++++++++++- docs/releases.md | 5 ++- docs/support-tiers.md | 2 +- 5 files changed, 48 insertions(+), 7 deletions(-) create mode 100644 changelog.d/stable-cut-ignores-windows-nightly.md diff --git a/changelog.d/stable-cut-ignores-windows-nightly.md b/changelog.d/stable-cut-ignores-windows-nightly.md new file mode 100644 index 00000000000..e932e4ee0fa --- /dev/null +++ b/changelog.d/stable-cut-ignores-windows-nightly.md @@ -0,0 +1 @@ +- **The stable release no longer waits on the nightly Windows tests (GST-2815).** The nightly Windows free suite never blocks a pull request, but the daily stable cut still treated its red or unfinished results as a reason to skip a commit, so stable stopped moving while one Windows shard kept timing out. The cut now sets that workflow's check runs aside, matched by workflow file, the same way it ignores its own job. Every other check, the required `free-tests` check and the release-gate evidence still block exactly as before. diff --git a/crew/scripts/release-cut.ts b/crew/scripts/release-cut.ts index 167b7b3fa1f..b3942387c0b 100755 --- a/crew/scripts/release-cut.ts +++ b/crew/scripts/release-cut.ts @@ -23,6 +23,8 @@ * workflow produced itself (CUT_WORKFLOW: the jobs of a workflow run whose path * is that file; a job's id is its check run's id) are set aside, running or * finished: a cut lands its own job on main's head, the commit it may cut. + * Check runs from NEVER_GATING_WORKFLOWS (the nightly Windows free suite, which + * docs/support-tiers.md says never blocks) are set aside the same way. * Matching by job, not check suite, keeps check runs other workflows create * through the API, which GitHub files under any github-actions suite on the * commit. When the workflow runs cannot be read, nothing is set aside. @@ -77,6 +79,8 @@ export const REQUIRED_CHECK = 'free-tests'; export const BACKSTOP_CHECK = 'main-backstop'; export const NOTES_REF = 'refs/notes/gstack-trains'; export const CUT_WORKFLOW = '.github/workflows/weekly-release.yml'; +/** Workflows documented as never gating (docs/support-tiers.md): their check runs are set aside like the cut's own, matched the same way. */ +export const NEVER_GATING_WORKFLOWS: readonly string[] = ['.github/workflows/windows-free-tests.yml']; const NOTES_LOCAL = 'refs/notes/gstack-trains-release'; const RED = new Set(['failure', 'timed_out', 'cancelled', 'action_required', 'startup_failure', 'stale']); export const WINDOW_DAYS = 7; @@ -127,12 +131,13 @@ export function gateVerdict(gh: Gh, repo: string, sha: string, o: GateOptions = if (runs.some(c => c.status !== 'completed' || RED.has(c.conclusion ?? ''))) { const wf = parseJson(gh(['api', '--paginate', '--slurp', `repos/${repo}/actions/runs?head_sha=${sha}&per_page=100`])); const wfRuns = (Array.isArray(wf) ? wf : wf ? [wf] : []) as Array<{ workflow_runs?: Array<{ id?: number; path?: string }> }>; - const own = new Set(); - for (const w of wfRuns.flatMap(p => p.workflow_runs ?? []).filter(w => w.path === CUT_WORKFLOW && typeof w.id === 'number')) { + const asideWorkflows = new Set([CUT_WORKFLOW, ...NEVER_GATING_WORKFLOWS]); + const aside = new Set(); + for (const w of wfRuns.flatMap(p => p.workflow_runs ?? []).filter(w => asideWorkflows.has(w.path ?? '') && typeof w.id === 'number')) { const jobs = parseJson(gh(['api', '--paginate', '--slurp', `repos/${repo}/actions/runs/${w.id}/jobs?filter=all&per_page=100`])); - for (const p of (Array.isArray(jobs) ? jobs : jobs ? [jobs] : []) as Array<{ jobs?: Array<{ id?: number }> }>) for (const j of p.jobs ?? []) if (typeof j.id === 'number') own.add(j.id); + for (const p of (Array.isArray(jobs) ? jobs : jobs ? [jobs] : []) as Array<{ jobs?: Array<{ id?: number }> }>) for (const j of p.jobs ?? []) if (typeof j.id === 'number') aside.add(j.id); } - runs = runs.filter(c => !(typeof c.id === 'number' && own.has(c.id))); + runs = runs.filter(c => !(typeof c.id === 'number' && aside.has(c.id))); } let via = backstop; for (const name of [required, backstop]) { diff --git a/crew/test/release-cut.test.ts b/crew/test/release-cut.test.ts index 7abf1470957..a8c1a68302e 100644 --- a/crew/test/release-cut.test.ts +++ b/crew/test/release-cut.test.ts @@ -13,7 +13,7 @@ import * as path from 'node:path'; import { bunIsolationArgs } from '../../lib/bun-isolation'; import { gitFixtureTemplate, rebindGitDir } from '../../test/helpers/git-fixture-template'; import { - BACKSTOP_CHECK, CUT_WORKFLOW, FLOOR_HOURS, NOTES_CAP, NOTES_REF, REQUIRED_CHECK, SCHEDULED_GRACE_HOURS, changelogEntries, compareVersions, cutRelease, describePlan, floorStatus, + BACKSTOP_CHECK, CUT_WORKFLOW, FLOOR_HOURS, NEVER_GATING_WORKFLOWS, NOTES_CAP, NOTES_REF, REQUIRED_CHECK, SCHEDULED_GRACE_HOURS, changelogEntries, compareVersions, cutRelease, describePlan, floorStatus, gateVerdict, gitIn, planRelease, readTrainNotes, releaseNotes, sanitizeReason, stableMovedAt, verifyRegression, verifySecurity, type Gh, type Git, type TrainEvidence, } from '../scripts/release-cut'; @@ -346,6 +346,38 @@ describe('release-cut: the cut sets aside its own check runs (GST-2463)', () => .toEqual({ green: false, why: 'red check runs: Cut the release', pending: false }); }); + // Value: protects=check runs from the never-gating Windows nightly (timed out, cancelled, failed or still running) never keep a gated commit out of the + // cut, while a red required check, a red or running check run from any other workflow, a same-named job outside the nightly and a missing gate still + // refuse; fails_when=the nightly's shard 4 timeout holds stable (0326b144 behind a GREEN release gate, 6 nights), or the exclusion is keyed on the check + // name and swallows another workflow's red run; why_new=only the cut's own workflow was set aside; seam=gh is faked with the check-runs, actions/runs + // and jobs payload shapes; no_claim=a live workflow run + test('gateVerdict: the never-gating Windows nightly\'s red or running check runs are set aside; every other not-green signal still refuses (GST-2815)', () => { + const evidence = gatedBy(sha, '43668645294'); + const nightly = { id: 9100, path: '.github/workflows/windows-free-tests.yml', jobs: [71004, 71007] }; + expect(NEVER_GATING_WORKFLOWS).toContain(nightly.path); + const api = workflowRuns(sha, [ownWorkflow, nightly, { id: 555, path: '.github/workflows/evals.yml', jobs: [70555] }]); + const shard = (status: string, conclusion: string | null, id = 71004) => ({ id, name: 'windows-free-shard (4)', status, conclusion }) as CheckRun; + const aggregate = { id: 71007, name: 'windows-free-tests', status: 'completed', conclusion: 'failure' } as CheckRun; + const gated = { green: true, via: 'release gate run 43668645294' } as const; + for (const red of [shard('completed', 'timed_out'), shard('completed', 'cancelled'), shard('completed', 'failure')]) { + expect(gateVerdict(ghFor([...unbacked, red, aggregate], api), 'o/r', sha, { evidence })).toEqual(gated); + } + expect(gateVerdict(ghFor([...unbacked, shard('in_progress', null), { ...aggregate, status: 'queued', conclusion: null }], api), 'o/r', sha, { evidence })).toEqual(gated); + expect(gateVerdict(ghFor([...GREEN, shard('completed', 'timed_out')], api), 'o/r', sha)).toEqual({ green: true, via: BACKSTOP_CHECK }); + expect(gateVerdict(ghFor([{ name: REQUIRED_CHECK, status: 'completed', conclusion: 'failure' }, shard('completed', 'timed_out')], api), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: REQUIRED_CHECK + ' concluded failure', pending: false }); + expect(gateVerdict(ghFor([...unbacked, shard('completed', 'timed_out'), { id: 70555, name: 'quality', status: 'completed', conclusion: 'failure' } as CheckRun], api), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'red check runs: quality', pending: false }); + expect(gateVerdict(ghFor([...unbacked, shard('completed', 'timed_out', 80004)], api), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'red check runs: windows-free-shard (4)', pending: false }); + expect(gateVerdict(ghFor([...unbacked, shard('in_progress', null), { name: 'slices-report', status: 'queued', conclusion: null }], api), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'check runs still going: slices-report', pending: true }); + expect(gateVerdict(ghFor([...unbacked, shard('completed', 'timed_out')], api), 'o/r', sha)) + .toEqual({ green: false, why: 'no ' + BACKSTOP_CHECK + ' check run', pending: false }); + expect(gateVerdict(ghFor([...unbacked, shard('completed', 'timed_out')], {}), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'red check runs: windows-free-shard (4)', pending: false }); + }); + const note = (f: ReturnType, record: unknown, on: string) => { git(f.seed, 'notes', '--ref=' + NOTES_REF, 'add', '-f', '-m', JSON.stringify(record), on); git(f.seed, 'push', '-q', '-f', 'origin', NOTES_REF); diff --git a/docs/releases.md b/docs/releases.md index 43506b18bca..c6bca97282c 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -50,7 +50,10 @@ days or 200 first-parent commits. The cut's own job lands a check run on main's head, the very commit it may cut, so check runs from this workflow's own runs (its file path, `.github/workflows/weekly-release.yml`, matched by the job ids of those workflow runs) are set aside whether running or -failed; every other check run counts as above. The lookup needs the +failed. Check runs from the nightly Windows free suite +(`.github/workflows/windows-free-tests.yml`), which +[never blocks](support-tiers.md#windows-ci), are set aside the same way; +every other check run counts as above. The lookup needs the workflow's `actions: read` permission; when it cannot read those runs, nothing is set aside. The workflow runs no tests and no paid evals of its own; it only reads what the trains, the backstop and the release gate diff --git a/docs/support-tiers.md b/docs/support-tiers.md index 15b6d4614fc..fc00729bcfe 100644 --- a/docs/support-tiers.md +++ b/docs/support-tiers.md @@ -24,7 +24,7 @@ That is the whole promise. Other skills, optional parts such as `/cso`'s native ## Windows CI - `windows-smoke` is the required Windows check on pull requests. -- The six-shard Windows free suite (the `Windows Free Tests` workflow, `windows-free-tests`) runs nightly on main, or when someone starts it by hand, and never blocks a pull request. +- The six-shard Windows free suite (the `Windows Free Tests` workflow, `windows-free-tests`) runs nightly on main, or when someone starts it by hand, and never blocks a pull request. The stable release cut ignores its results too, so a red or unfinished nightly never holds a release. - A red nightly run gets a fix only when it shows an install, startup or core-workflow break. - Windows checks run by path (ship-90-90 plan D, approved 2026-11-03): `Windows Scoped Tests` runs a pull request's changed Windows-safe test files on one Windows job only when it touches path, file-name or process code (a red run blocks that pull request, like any failed check), and `Windows Setup E2E` runs only when install files change (a version-only `package.json` change doesn't count). From eb0aa51c1782717c46bf1846a2b33072456914fd Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 16 Nov 2026 10:50:17 +0800 Subject: [PATCH 02/62] Explain how to merge any PR with gstack's land command (GST-2744) (#4377) * Explain how to merge any PR with gstack's land command (GST-2744) docs/ship-policy.md opens its land section with the two policy keys a repo sets first, what land checks, a pinned gh pr merge fallback and four known traps; CONTRIBUTING.md points to it. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Show regate's required arguments in the migration trap (GST-2744) Review-Finding: p1/specialist-batched#1 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Add the changelog entry for the land merge guide (GST-2744) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CONTRIBUTING.md | 2 + changelog.d/land-normal-merge.md | 1 + docs/ship-policy.md | 121 +++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+) create mode 100644 changelog.d/land-normal-merge.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 42db0bdc3dd..4a189b6e91d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1085,3 +1085,5 @@ When you're happy with your skill edits: ``` This runs tests, reviews the diff, triages the comments of every review bot you configured (Greptile's with 2-tier escalation), manages TODOS.md, bumps the version, and opens a PR. See `ship/SKILL.md` for the full workflow. + +A maintainer then merges the PR with `gstack-ship-queue land`. To merge the same way in your own repository, even with one maintainer, see [Merge with land](docs/ship-policy.md#land-normal). diff --git a/changelog.d/land-normal-merge.md b/changelog.d/land-normal-merge.md new file mode 100644 index 00000000000..b76774f3abe --- /dev/null +++ b/changelog.d/land-normal-merge.md @@ -0,0 +1 @@ +- **The ship policy guide now explains how to merge any pull request with `gstack-ship-queue land`, even in a repository with one maintainer.** It names the two policy keys land needs before it will run, lists what land already checks, gives a pinned `gh pr merge` fallback for repositories that can't use land yet, and covers four common traps. CONTRIBUTING.md links to it. diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 8e85deb195a..1e602b175fa 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -2589,6 +2589,127 @@ tree, taking no lock and pushing nothing. ### `land --pin`: merge at the PR's own green head (`merge: direct`) + +#### Merge with land, even in a repo with one maintainer + +`gstack-ship-queue land --pr --pin ` is the normal way to merge a PR +in any repository that uses gstack, including one with a single maintainer and +nobody coordinating merges. Whoever merges runs it, with `` set to the +commit they reviewed. It merges that exact commit or nothing, and afterward it +checks that main holds what was reviewed. + +**Set two keys first.** Land reads `.gstack/ship-policy.json` from the base +branch and refuses with `QUEUE_NOT_READY` unless both are set +(`landDirect` in `lib/ship-queue-land-direct.ts`). Neither is on by default +(`DEFAULT_POLICY` in `lib/ship-policy.ts` has `merge: "train"` and +`changelog_fragments: null`), which is why land refuses in most repositories +until someone adds them: + +- `"merge": "direct"` tells gstack each PR merges on its own, at its own green + head. Land refuses under any other value. +- `"changelog_fragments"` makes each PR carry its changelog entry as a file in + `changelog.d/` instead of editing VERSION or CHANGELOG.md, so two PRs never + fight over the next version. `gstack-ship-queue ready` writes the READY note + land needs only when this key is set, so land refuses `merge: direct` + without it. + +The smallest policy that works: + +```json +{ + "merge": "direct", + "changelog_fragments": { "dir": "changelog.d" }, + "min_gstack_version": "1.95.0.0" +} +``` + +`min_gstack_version` is required because `merge` arrived in gstack 1.95.0.0, +and an older gstack has to refuse the file by name rather than misread it. +Every key you leave out keeps its default. Check the file with +`gstack-ship-policy validate`. Land reads the policy from the base branch, so +the PR that adds it merges by the [fallback](#land-fallback) below; land works +from the next PR on. With PRs already open, run `land --census` first +([migrating to fragments](#migrating-to-fragments)). + +**Each PR, start to finish:** + +```bash +/ship # review, tests, the changelog.d entry, the receipt in the PR body +gstack-pregate run --allow-repo-commands # once CI is green at the head +gstack-ship-queue ready --pr 42 --no-screen # records the READY note land looks for +gstack-ship-queue land --pr 42 --pin +``` + +Add `--allow-repo-commands` to `land` when the policy lists +`land.merged_checks` (below). Versions don't move per PR. When you want a +release, `gstack-release-stamp open` opens a release PR that sets the version +and folds the `changelog.d` entries into CHANGELOG.md, and you land it the +same way ([the release PR](#release-stamp)). + +**What land already checks, so you don't.** Before it merges, land refuses +unless: + +- the PR's head is still the pin (`QUEUE_LAND_PIN_MOVED`); +- the PR is open, targets the base branch, and comes from this repository, not + a fork; +- every check at the pin is green, with none pending; +- GitHub reports the PR `MERGEABLE` and `CLEAN`; +- the /ship receipt in the PR body and a READY note are both bound to the pin. + +After merging, it checks that main's tree is exactly the pin merged onto the +commit before it (`QUEUE_LAND_UNVERIFIED` otherwise). A script that reads +these before calling land adds nothing; read land's output instead. Every +check, with its refusal code, is in [the table below](#land-direct-contract). + + +**When a repo can't use land.** Check the receipt with the read-only half of +land, then merge pinned to the same commit: + +```bash +gstack-ship-queue verify --pr 42 --pin # receipt bound to , gate dispositions accepted; merges nothing +gh pr view 42 --json state,baseRefName,headRefOid,mergeable,mergeStateStatus +gh pr checks 42 # every check passed, none pending +gh pr merge 42 --squash --match-head-commit \ + --subject " (#42)" \ + --body "" +gh pr view 42 --json state,mergeCommit # MERGED, with its merge commit +``` + +`verify --pin` doesn't read CI or GitHub's merge state, so the two `gh` +reads replace those checks. `--match-head-commit` makes GitHub refuse the +merge if anyone pushed after you checked. Use `--merge` instead of +`--squash` where branch rules allow only merge commits. Keep the subject and +body plain: they become main's history. + + +**Known traps.** + +- **GitHub merge queues.** Land doesn't support them. With a queue on the base + branch, `gh pr merge` only queues the PR and can exit 0 even when the queue + later drops it, so confirm the PR reads `MERGED` instead of trusting the + exit code. +- **Migration collisions.** Two PRs can add the same migration number and both + pass CI, and land doesn't look at migrations. The check is + `gstack-pregate regate --against --bundle --pr ` + with the policy's `migrations` key set, which compares the branch's new + numbers with main and every open PR ([regate](pregate.md#regate)). +- **`bump`.** Without `changelog_fragments`, the default `bump: ask` stops + an unattended /ship at `BUMP_ANSWER_REQUIRED`, so a repo on the fallback + sets `"bump": "patch"`. With fragments a PR never writes a version and + `bump` only sizes the release (PATCH under `patch`, MICRO otherwise), and + `bump: never` is refused next to `changelog_fragments`, so drop it before + switching. +- **CI results belong to one commit.** Checks, the /ship receipt and the READY + note each name a sha, so after any push, a merge of main included, land + refuses until checks are green and `ready` has run at the new head (the + receipt itself can [carry across a base merge](#carrying-a-receipt-across-a-base-merge-or-a-test-only-fix)). + A `pull_request` CI run tests GitHub's merge commit rather than your branch, + so on a branch behind main `gstack-ci-carry` reports `tree_mismatch`: + dispatch the workflow on the branch (`gh workflow run --ref `). + + +#### Every check land makes + Under `"merge": "direct"` in the base policy, the Captain merges one READY PR at a time with `gstack-ship-queue land --pr --pin `, where `` is the head the READY names. There's no train and no stamp commit. GitHub's From 984a2683060ad9111ac74597449ce57228df883f Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 16 Nov 2026 10:51:22 +0800 Subject: [PATCH 03/62] Add guides for landing a fix in someone else's repo and running human playtests (GST-2757) (#4380) * Add guides for landing a fix in someone else's repo and running human playtests (GST-2757) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Use plain paths in the guides' changelog entry Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../guides-for-outside-fixes-and-playtests.md | 1 + .../howto-land-a-fix-in-someone-elses-repo.md | 53 +++++++++++++++++++ docs/howto-run-human-playtests.md | 53 +++++++++++++++++++ 3 files changed, 107 insertions(+) create mode 100644 changelog.d/guides-for-outside-fixes-and-playtests.md create mode 100644 docs/howto-land-a-fix-in-someone-elses-repo.md create mode 100644 docs/howto-run-human-playtests.md diff --git a/changelog.d/guides-for-outside-fixes-and-playtests.md b/changelog.d/guides-for-outside-fixes-and-playtests.md new file mode 100644 index 00000000000..6baed792a91 --- /dev/null +++ b/changelog.d/guides-for-outside-fixes-and-playtests.md @@ -0,0 +1 @@ +- **Two new short guides.** `docs/howto-land-a-fix-in-someone-elses-repo.md` covers reading the other project's rules, searching for the same fix first, running every guard their CI runs before you open, keeping the change small, and answering each review point in a new commit with the proof rerun. `docs/howto-run-human-playtests.md` covers asking about moments and where people would stop, and why a back-to-back pick between two builds measures the order they were played in, not the builds. diff --git a/docs/howto-land-a-fix-in-someone-elses-repo.md b/docs/howto-land-a-fix-in-someone-elses-repo.md new file mode 100644 index 00000000000..2ff29500049 --- /dev/null +++ b/docs/howto-land-a-fix-in-someone-elses-repo.md @@ -0,0 +1,53 @@ +# How to land a fix in someone else's repository + +You found a bug in a project you don't own, and you (or your agent) have a fix. Whether it +lands depends on the maintainers' rules, their CI and their reviewers, not on yours. This +guide is the order we work in: before you design, before you open the pull request, and +after each review. + +## Before you design + +1. **Read their rules.** Start with the root `AGENTS.md` or `CLAUDE.md`, then + `CONTRIBUTING.md` and the pull request template. Reviewers, people and bots alike, turn + those rules into findings, so a rule you skipped becomes a review round. +2. **Search for the same fix first.** Look at their main branch, open pull requests, + recently merged ones and issues for your symptom, and do it again right before any + public step, because a busy main moves daily. If someone is already fixing it, help + that fix with a test or a repro instead of opening a second one. A closed issue can + still be broken in a new way: link it ("Related: #N") and describe the new error. +3. **Read the history of the code you're changing.** `git log -p ` shows what the + owner chose on purpose. Reuse the mechanism the code already has before adding a new + one. +4. **Keep it small.** A short fix in the place the owner already maintains beats a large + rewrite that also fixes the bug. When a maintainer's smaller fix lands instead of + yours, that's a good outcome: close yours and say thanks. + +## Before you open the pull request + +1. **Run every guard their CI runs, on your final commit.** List them from + `.github/workflows/`, the `scripts` in `package.json`, a `Makefile` or whatever their + CI calls: lint, format, typecheck, size or line-count ratchets, boundary checks, and the + tests near your change. A guard you never ran is the easiest way to fail a first + review. Your own local review tools don't replace these; they miss repo-specific rules. +2. **Prove the fix.** Add one or two tests that fail on their main and pass with your + change, and say so in the description with the commands you ran. +3. **Follow their format.** Title style, description sections, "Allow edits by + maintainers" turned on. Don't edit their changelog, @-mention people or add trailers + unless their rules ask for it. + +## After each review + +1. **Sort the failing checks.** For each one, decide whether your change caused it or it + already fails on their main, and prove "already fails" by running it on main. Never + call a failure pre-existing without that run. +2. **Answer each review point in a new commit** on the same branch, so reviewers can see + exactly what changed. Don't force-push unless their rules ask for a squash. +3. **Rerun the proof on the new head:** the fail-then-pass test and the CI guards from + above. Evidence from the previous commit doesn't count. +4. **Update the description** so its evidence describes the current head. Reviewers read + the description, not the whole thread. +5. **Reply once per round,** after the push: map each point to the commit that fixes it, + or explain with a file and line why the point doesn't apply. + +These steps come from landing fixes in one outside project so far. Treat them as a +starting checklist and expect them to change as they meet more repositories. diff --git a/docs/howto-run-human-playtests.md b/docs/howto-run-human-playtests.md new file mode 100644 index 00000000000..cbc7c6212b7 --- /dev/null +++ b/docs/howto-run-human-playtests.md @@ -0,0 +1,53 @@ +# How to run a human playtest + +Models can't tell you whether a game is fun or whether a new person gets your app's first +screen. People can, but what they tell you depends on what you ask and on the order they +see things in. This note covers games, and it works the same for any product flow you +want a stranger to try. + +## Ask about moments, not opinions + +"It was boring" can't be fixed. "At minute 4 I had money and nothing to spend it on" +points straight at the thing to change. So set up each session to collect moments: + +- **Before they start,** ask three short questions: what device and browser they're on, + how often they play or use things like this, and one they've enjoyed lately. +- **While they play,** ask them to think out loud: what they're trying to do, what + confuses them, when they're bored. When they reach the point where they'd normally + stop, they say "I'd stop here" and keep going until the time is up, unless they're + stuck. Record the screen and their voice if they agree to it. +- **Afterwards,** open questions first, then specific ones: + 1. In one sentence, what is this and what were you trying to do? + 2. Your best moment and your worst moment: about when, and what happened? + 3. Where were you confused or stuck? + 4. Did your choices matter? Was anything at stake? + 5. Anything broken, hard to tap, hard to read or hard to scroll? Give the minute. + 6. If you could change one thing first, what would it be? + 7. Would you come back to it tomorrow? Yes, maybe or no. + +If you pay testers, reward specific, timestamped moments and bugs someone can reproduce, +not long answers. + +## Never pick a winner by playing two builds back to back + +Don't have each tester play build A, then build B, and ask which one they'd keep. The +order decides the answer: in the tests this note comes from, the build played second won +most of the picks, whichever build it was. Whether testers finished a session also +depended on which build they saw first. + +Give each tester one build. Compare builds across testers by where people said "I'd stop +here" and by the moments they reported. If one person must try both, randomize the order +and still decide from quit points and moments, never from the pick. + +## Turning what they said into fixes + +1. Pull the timestamped moments out of each session: where they'd quit, what confused + them, what delighted them, what broke. +2. Tag each complaint by area: the opening and how it teaches, controls, readability, + balance, stakes, pacing, bugs. +3. Count across testers. One tester's gripe is a note; the same gripe from three testers + is a fix. +4. Rank the list. Each item gets its clips or quotes and a proposed change, and a change + still has to show it helps before it ships. + +This note rests on one team's playtests so far. Expect it to change as more teams use it. From 2c0e07886b6636437f2b776cb58916f257893234 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 16 Nov 2026 10:53:22 +0800 Subject: [PATCH 04/62] Add a write-up checklist to ETHOS and the READY template (GST-2755) (#4381) * Add a write-up checklist to ETHOS and the READY template (GST-2755) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Fix a mid-sentence colon in the write-up checklist changelog note Review-Finding: p1/adversarial-native#1 reader=adversarial-native Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- ETHOS.md | 18 ++++++++++++++++++ captain/templates/READY.md | 4 ++++ changelog.d/write-up-checklist.md | 1 + 3 files changed, 23 insertions(+) create mode 100644 changelog.d/write-up-checklist.md diff --git a/ETHOS.md b/ETHOS.md index 5ef7a9aaa4e..bdb427660ac 100644 --- a/ETHOS.md +++ b/ETHOS.md @@ -282,11 +282,29 @@ reason, helping builders or letting others reproduce a published finding. None of this bends the rules above: no number is rounded in our favour and no caveat is dropped. +### Write-up checklist + +Before a post or write-up goes out, check three things. The second also holds for every +ready or status report. + +1. **The words match the page.** Every claim the text makes, the page it links makes too, + at the same strength. If the page says the other side won by a few points, the post + doesn't say "as good as". Readers repeat the post, not the page. +2. **Every number, "green" and "ready" names its source, read at the current head.** Give + the run id, commit, command or file it came from, and read it again on the tree you are + shipping. A number carried over from an earlier head, or taken from a list a tool + capped, is a guess until re-read; re-read it or mark it unverified. +3. **A fresh model reads it cold, once.** Give a model with none of the work's context the + finished text and the pages it links, and ask what the text claims and where it lost + the thread. Fix what it misread, then send. One read, not a loop. + **Anti-patterns:** - A speedup from one run on each side. - A pass rate without the trial count. - "Faster" with no theory of what changed. - A results file whose lesson, or whose null, sits under a page of run ids. +- A post that says more than the page it links. +- "Green" read from an earlier head. --- diff --git a/captain/templates/READY.md b/captain/templates/READY.md index ff4f5002fb7..d31cda187e6 100644 --- a/captain/templates/READY.md +++ b/captain/templates/READY.md @@ -51,6 +51,10 @@ tested. `none` means the lane looked for each of these and found none. A missing asked for as a follow-up message: it never holds a PR out of a train, does not stale READYs sent before the line existed, and needs no new `ready` or /ship run. +Every number, "green" and "ready" in the block names where it came from (a run id, a commit, +a command) and is read at the pinned head; anything carried over from an earlier head goes +under `Unverified:` until it is re-read ([ETHOS.md: write-up checklist](../../ETHOS.md#write-up-checklist)). + Optional lines a crew's rules file may require: ```text diff --git a/changelog.d/write-up-checklist.md b/changelog.d/write-up-checklist.md new file mode 100644 index 00000000000..230ebf5b039 --- /dev/null +++ b/changelog.d/write-up-checklist.md @@ -0,0 +1 @@ +- **A short write-up checklist in ETHOS.md.** Explain the Number now ends with three checks before a post or write-up goes out: its words match the page it links, every number, "green" and "ready" names its source and is read at the current head, and a fresh model reads it cold once. The READY template in `captain/templates/READY.md` points to the second check. Anything carried over from an earlier head goes under `Unverified:` until it is re-read. From fdf3f1e1b661b65bad6d78d41c006ce51991bc7f Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 16 Nov 2026 10:55:19 +0800 Subject: [PATCH 05/62] Make /eval-plan check judges, zeros, failure counts and decisions before results count (GST-2754) (#4384) * Make /eval-plan check judges, zeros, failure counts and decisions before results count (GST-2754) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Check zeros in every results table, apply Decisions and Scoring with stack: none, count only valid judge labels (GST-2754) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Describe the /eval-plan result checks in the skills guide (GST-2754) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-doctor-components.sh | 3 + bin/gstack-eval-plan | 50 ++++-- changelog.d/eval-plan-result-checks.md | 1 + docs/TESTING_INTERNALS.md | 31 ++++ docs/skills.md | 9 +- docs/troubleshooting.md | 64 +++++++- eval-plan/SKILL.md | 52 ++++++- eval-plan/SKILL.md.tmpl | 52 ++++++- lib/eval-plan-checks.ts | 121 +++++++++++++++ lib/eval-plan-report.ts | 79 +++++++--- lib/eval-plan.ts | 24 ++- lib/result-codes-eval.ts | 20 ++- test/eval-plan-no-gstack-arm.test.ts | 11 +- test/eval-plan-prereg-diagnostics.test.ts | 8 +- test/eval-plan-result-checks.test.ts | 180 ++++++++++++++++++++++ test/eval-plan-results.test.ts | 3 +- test/exercised-map.test.ts | 1 + test/fixtures/arm-benchmark/PREREG.md | 2 + test/fixtures/model-panel/PREREG.md | 2 + test/helpers/placeholder-allowlist.ts | 1 + test/pricing-eval-plan.test.ts | 4 +- 21 files changed, 643 insertions(+), 75 deletions(-) create mode 100644 changelog.d/eval-plan-result-checks.md create mode 100644 lib/eval-plan-checks.ts create mode 100644 test/eval-plan-result-checks.test.ts diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index 4a810df8abc..e65205dc075 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -413,6 +413,9 @@ gstack_result_anchor() { PREREG_DIAGNOSTIC_UNTESTED) printf '%s' 'prereg-diagnostic-untested' ;; PREREG_NO_GSTACK_ARM) printf '%s' 'prereg-no-gstack-arm' ;; EVAL_REPORT_NO_GSTACK_ROW) printf '%s' 'eval-report-no-gstack-row' ;; + EVAL_JUDGE_UNCHECKED) printf '%s' 'eval-judge-unchecked' ;; + EVAL_REPORT_UNPLANTED_ZERO) printf '%s' 'eval-report-unplanted-zero' ;; + EVAL_REPORT_NO_ANSWER_ONLY) printf '%s' 'eval-report-no-answer-only' ;; EVAL_ARM_DUPLICATE) printf '%s' 'eval-arm-duplicate' ;; OFFICE_HOURS_PROBE_REFUSED) printf '%s' 'office-hours-probe-refused' ;; TASKS_SUPERSEDE_REFUSED) printf '%s' 'tasks-supersede-refused' ;; diff --git a/bin/gstack-eval-plan b/bin/gstack-eval-plan index 4826b83e01b..4ea39ba6546 100755 --- a/bin/gstack-eval-plan +++ b/bin/gstack-eval-plan @@ -10,7 +10,8 @@ * gstack-eval-plan pilot settle --out --attempt --usd * gstack-eval-plan pilot release --out --attempt * gstack-eval-plan pilot report --out --total [--workers W] [--json] - * gstack-eval-plan results --check [--json] + * gstack-eval-plan results --check [--labels ] [--json] + * gstack-eval-plan judge --check --labels [--json] * gstack-eval-plan price-gate --gate-file | --gate "" [--plan-file ] [--base ] [--cap-usd N] * [--smoke-cap-usd N] [--allow-unpriced ""] [--out ] [--json] * @@ -27,13 +28,15 @@ * price-gate lint every arm's model against the base branch's * .gstack/eval-models.json (docs/eval-models.md; lib/eval-models.ts). Exit 0 ok, 1 fail (incomplete * prereg, failed check, exceeded cap, unpriced or stale gate), 2 usage, 3 refused. - * Logic: lib/eval-plan.ts; `results --check` in lib/eval-plan-report.ts. + * Logic: lib/eval-plan.ts; `results --check` in lib/eval-plan-report.ts; the result checks + * (decisions, scoring, judge labels) in lib/eval-plan-checks.ts. */ import * as fs from 'node:fs'; import * as path from 'node:path'; import { spawnSync } from 'node:child_process'; -import { armModel, checkPrereg, DEFAULT_TOKENS, PREREG_SECTIONS, dryRun, pilotReport, preregTemplate, priceGate, releasePilot, renderArms, renderDryRun, renderGatePrice, renderPilotReport, renderPreregDiagnostics, resolveArms, resolvePlanSource, runPreregDiagnostics, settlePilot, startPilot } from '../lib/eval-plan'; +import { armModel, checkPrereg, DEFAULT_TOKENS, dryRun, pilotReport, preregTemplate, priceGate, releasePilot, renderArms, renderDryRun, renderGatePrice, renderPilotReport, renderPreregDiagnostics, resolveArms, resolvePlanSource, runPreregDiagnostics, settlePilot, startPilot } from '../lib/eval-plan'; import { checkResults } from '../lib/eval-plan-report'; +import { checkJudgeLabels, renderJudgeLabels } from '../lib/eval-plan-checks'; import { checkModelRules, EVAL_SCOPES, type EvalScope, type ModelRulesCheck } from '../lib/eval-models'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { resultLine } from '../lib/result-codes'; @@ -43,8 +46,11 @@ import { SpendCapExceeded } from '../lib/spend-ledger'; const HELP = `gstack-eval-plan — preregistration, priced arms, $0 dry run, priced pilot (eval-plan/SKILL.md) prereg --check [--allow-repo-commands] [--json] - the required sections exist and are filled: Bars, Arms, Comparison, Decoys, Stop rules, - Held-out exposure, and No-gstack arm when the Comparison says stack: loaded; + the required sections exist and are filled: Bars, Decisions, Arms, Comparison, Scoring, + Decoys, Stop rules, Held-out exposure, and No-gstack arm when the Comparison says stack: loaded; + Decisions needs two or more "if : " lines with different actions; Scoring a + judge (none, or another model family with labels >= 40 and agreement >= 0.6) and, with two or + more arms, paired: yes, interval: 95% and mdd:; a frozen: date before 2026-11-15 skips both; an optional Diagnostics section's summarizer runs on its synthetic fixture only with --allow-repo-commands (else it is listed and exit 3) and every count must match prereg --init [--title ] write the template @@ -60,9 +66,13 @@ const HELP = `gstack-eval-plan — preregistration, priced arms, $0 dry run, pri settle unknown, and sit outside the cap and the projection until one settles a charge pilot settle --out dir --attempt id --usd pilot release --out dir --attempt id pilot report --out dir --total items [--workers W] [--json] spend table + per-arm extrapolation with a 95% band, then the approval ask - results --check [--json] + results --check [--labels labels.jsonl] [--json] one table in the results file has a filled row for every Arms identity, each no-gstack arm - beside its variants; reads text only (docs/TESTING_INTERNALS.md#no-gstack-arm) + beside its variants; a model judge's labels pass; a zero in any results table comes from a + Diagnostics counter with a planted case; a failures column has an answer-only column beside + it; reads text only (docs/TESTING_INTERNALS.md#result-checks) + judge --check --labels labels.jsonl [--json] + Cohen's kappa of the preregistered judge against {"id","human","judge"} hand labels price-gate --gate-file | --gate "" [--plan-file f] [--base b] [--cap-usd N] [--smoke-cap-usd N] [--allow-unpriced ""] [--out dir] [--json] price a paid gate from its GSTACK_EVAL_CALLS v1 call-plan file (--plan-file, else the base policy's price_file at HEAD); checks the gate/head/input binding, executes nothing, writes a @@ -126,11 +136,11 @@ function doPrereg(rest: string[]): number { const run = runnable && allowed ? runPreregDiagnostics(d, repoRoot) : null; if (rest.includes('--json')) process.stdout.write(JSON.stringify({ file, ...r, diagnostics_run: run }) + '\n'); else { - process.stdout.write(`PREREG: ${r.ok ? 'ok' : 'incomplete'} present=${r.present.length}/${PREREG_SECTIONS.length}${r.missing.length ? ` missing=${r.missing.join(',')}` : ''}${r.empty.length ? ` empty=${r.empty.join(',')}` : ''}${r.comparison.stack ? ` stack=${r.comparison.stack}` : ''}${r.no_gstack.required ? ` no_gstack_arm=${r.no_gstack.ok ? 'ok' : r.no_gstack.problems[0] === 'missing section' ? 'missing' : 'incomplete'}` : ''}${d ? ` diagnostics=${d.errors.length ? 'invalid' : d.expected.length}` : ''} file=${file}\n`); + process.stdout.write(`PREREG: ${r.ok ? 'ok' : 'incomplete'} present=${r.present.length}/${r.present.length + r.missing.length + r.empty.length}${r.missing.length ? ` missing=${r.missing.join(',')}` : ''}${r.empty.length ? ` empty=${r.empty.join(',')}` : ''}${r.comparison.stack ? ` stack=${r.comparison.stack}` : ''}${r.no_gstack.required ? ` no_gstack_arm=${r.no_gstack.ok ? 'ok' : r.no_gstack.problems[0] === 'missing section' ? 'missing' : 'incomplete'}` : ''}${d ? ` diagnostics=${d.errors.length ? 'invalid' : d.expected.length}` : ''}${r.grandfathered ? ` frozen=${r.frozen} result_checks=exempt` : ''} file=${file}\n`); if (runnable && !allowed) process.stdout.write(`PREREG_COMMAND: summarizer=${JSON.stringify(d.summarizer)} fixture=${d.fixture} cwd=${repoRoot}\n`); if (run) process.stdout.write(renderPreregDiagnostics(run)); } - const incomplete = [...r.missing.map(m => `missing ${m}`), ...r.empty.map(e => `empty ${e}`), ...r.comparison.errors.map(e => `comparison: ${e}`), ...(d?.errors ?? []).map(e => `diagnostics: ${e}`)]; + const incomplete = [...r.missing.map(m => `missing ${m}`), ...r.empty.map(e => `empty ${e}`), ...r.comparison.errors.map(e => `comparison: ${e}`), ...r.decisions.errors.map(e => `decisions: ${e}`), ...r.scoring.errors.map(e => `scoring: ${e}`), ...(d?.errors ?? []).map(e => `diagnostics: ${e}`)]; if (incomplete.length) process.stderr.write(resultLine('gstack-eval-plan prereg', 'PREREG_INCOMPLETE', incomplete.join('; ')) + '\n'); if (!r.no_gstack.ok) process.stderr.write(resultLine('gstack-eval-plan prereg', 'PREREG_NO_GSTACK_ARM', `no-gstack arm: ${r.no_gstack.problems.join('; ')}`) + '\n'); if (run && !run.ok) process.stderr.write(resultLine('gstack-eval-plan prereg', 'PREREG_DIAGNOSTIC_UNTESTED', run.error ?? run.rows.filter(row => row.status !== 'ok').map(row => `${row.name} ${row.status} (expected ${row.expected ?? 'undeclared'}, got ${row.got ?? 'none'})`).join('; ')) + '\n'); @@ -141,12 +151,27 @@ function doPrereg(rest: string[]): number { function doResults(rest: string[]): number { const prereg = flag(rest, '--check'); - const results = rest.filter(a => !a.startsWith('--') && a !== prereg)[0]; + const labels = flag(rest, '--labels'); + const results = rest.filter(a => !a.startsWith('--') && a !== prereg && a !== labels)[0]; if (!prereg || !results || !fs.existsSync(prereg) || !fs.existsSync(results)) return usage('results needs --check '); - const r = checkResults(fs.readFileSync(prereg, 'utf8'), fs.readFileSync(results, 'utf8')); + if (labels !== undefined && !fs.existsSync(labels)) return usage('results --labels needs an existing labels file'); + const r = checkResults(fs.readFileSync(prereg, 'utf8'), fs.readFileSync(results, 'utf8'), labels === undefined ? null : fs.readFileSync(labels, 'utf8')); if (rest.includes('--json')) process.stdout.write(JSON.stringify({ prereg, results, ...r }) + '\n'); else process.stdout.write(`RESULTS: ${r.ok ? 'ok' : 'incomplete'} no_gstack_rows=${r.no_gstack.filter(id => r.found.includes(id)).length}/${r.no_gstack.length} rows=${r.found.length}/${r.required.length} file=${results}\n`); - if (!r.ok) { process.stderr.write(resultLine('gstack-eval-plan results', 'EVAL_REPORT_NO_GSTACK_ROW', r.problems.join('; ')) + '\n'); return EXIT.fail; } + if (r.judge && !rest.includes('--json')) process.stdout.write(renderJudgeLabels(r.judge)); + for (const code of new Set(r.issues.map(i => i.code))) process.stderr.write(resultLine('gstack-eval-plan results', code, r.issues.filter(i => i.code === code).map(i => i.message).join('; ')) + '\n'); + return r.ok ? EXIT.ok : EXIT.fail; +} + +function doJudge(rest: string[]): number { + const prereg = flag(rest, '--check'); + const labels = flag(rest, '--labels'); + if (!prereg || !labels || !fs.existsSync(prereg) || !fs.existsSync(labels)) return usage('judge needs --check --labels '); + const { scoring } = checkPrereg(fs.readFileSync(prereg, 'utf8')); + if (!scoring.judge || scoring.judge.toLowerCase() === 'none') return usage('judge --check needs a preregistration whose ## Scoring names a judge model'); + const r = checkJudgeLabels(scoring, fs.readFileSync(labels, 'utf8')); + process.stdout.write(rest.includes('--json') ? JSON.stringify({ prereg, labels, ...r }) + '\n' : renderJudgeLabels(r)); + if (!r.ok) { process.stderr.write(resultLine('gstack-eval-plan judge', 'EVAL_JUDGE_UNCHECKED', r.problems.join('; ')) + '\n'); return EXIT.fail; } return EXIT.ok; } @@ -266,6 +291,7 @@ function main(argv: string[]): number { if (cmd === 'pilot') return doPilot(rest); if (cmd === 'price-gate') return doPriceGate(rest); if (cmd === 'results') return doResults(rest); + if (cmd === 'judge') return doJudge(rest); return usage(`unknown command ${cmd}`); } catch (e: any) { if (e instanceof SpendCapExceeded) { process.stderr.write(resultLine(`gstack-eval-plan ${cmd}`, 'EVAL_BUDGET_EXHAUSTED', e.message) + '\n'); return EXIT.fail; } diff --git a/changelog.d/eval-plan-result-checks.md b/changelog.d/eval-plan-result-checks.md new file mode 100644 index 00000000000..8613ccc0a10 --- /dev/null +++ b/changelog.d/eval-plan-result-checks.md @@ -0,0 +1 @@ +- `/eval-plan` now runs four result checks instead of leaving them to judgment. `prereg --check` requires a `## Decisions` section (what each possible result changes, at least two different actions) and a `## Scoring` section (a judge from another model family than every arm, checked against at least 40 hand labels at kappa 0.6 or better, and paired results with a 95% interval and the smallest detectable difference stated before the run). The new `judge --check --labels` scores the judge against hand labels, and `results --check` holds back a judged result without passing labels, a zero from a counter never shown to find a planted case, and a failures column with no answer-only column beside it. Preregistrations frozen before 2026-11-15 keep their rules. diff --git a/docs/TESTING_INTERNALS.md b/docs/TESTING_INTERNALS.md index c4abc8f9fca..65042c1da5c 100644 --- a/docs/TESTING_INTERNALS.md +++ b/docs/TESTING_INTERNALS.md @@ -2059,6 +2059,37 @@ it as the diagnostic. Candidate folders and git identity name a project, never the arm. The model panel (`test/skill-e2e-model-panel.test.ts`) runs a `#no-gstack` arm beside each model (GST-468, GST-469). +## Result checks + +`/eval-plan` runs four checks so that a number which cannot change a decision, or +which comes from an unchecked instrument, never leaves the run. Each one is a +refusal from `bin/gstack-eval-plan` (logic in `lib/eval-plan-checks.ts` and +`lib/eval-plan-report.ts`), not advice: + +| Check | When it runs | Refusal | +|---|---|---| +| `## Decisions`: one `if : ` line per possible result, at least two, with different actions | `prereg --check`, before anything is spent | `PREREG_INCOMPLETE` | +| `## Scoring`: `judge: none`, or a judge model from another family than every arm with `labels:` (40 or more) and `agreement:` (kappa 0.6 or more); with two or more arms, `paired: yes`, `interval: 95%` and `mdd:` stated before the run | `prereg --check` | `PREREG_INCOMPLETE` | +| The judge's Cohen's kappa against `{"id", "human", "judge"}` hand labels, at the preregistered count and bar | `judge --check` before the approval ask; `results --check --labels` before any number goes out | `EVAL_JUDGE_UNCHECKED` | +| A zero in any results table comes from a column named after a `## Diagnostics` counter whose synthetic fixture plants at least one case (expected 1 or more) | `results --check` | `EVAL_REPORT_UNPLANTED_ZERO` | +| A results table with a failures column also has an `answer-only` column: failures by the grader's own rule on the final answer | `results --check` | `EVAL_REPORT_NO_ANSWER_ONLY` | + +Why: in our own agent teams, a counter that never fired reported zero for one +model while an outside check with planted cases found every one, and a reported +rise in failures vanished once failures were counted by the grader's own rule. +A judge from the same family as the arm it grades, or one never compared with +people, gives numbers nobody can weigh. An eval whose every result leads to the +same action spends money to change nothing. + +Model families come from the model id (`claude` is Anthropic, `gpt` and `o` +models OpenAI, `gemini` Google, `grok` xAI), else its first word. A judge +whose labels are all one class has undefined agreement and is refused. + +A preregistration with a `frozen: YYYY-MM-DD` line before 2026-11-15 keeps the +rules it was frozen under: the PREREG line shows `result_checks=exempt` and +none of the four checks apply. Text frozen before a priced call is not edited +to meet a newer rule. + ## Frontier models under test Garry, 2026-11-01 (R54): "I think you are spending too much time with Haiku and diff --git a/docs/skills.md b/docs/skills.md index e45ad381ce0..8e2fc459fe9 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -966,7 +966,10 @@ You: /eval-plan how much will the retrieval eval cost before I run it? `bin/gstack-eval-plan prereg --init` writes the preregistration (question, bars, arms, decoys, stop rules, cap) and `--check` refuses to continue while a field is -blank (`PREREG_INCOMPLETE`). `arms` resolves the `eval-arms` model role against +blank (`PREREG_INCOMPLETE`), including the `## Decisions` and `## Scoring` +sections the [result checks](TESTING_INTERNALS.md#result-checks) require. +`judge --check --labels ` scores a model judge against hand +labels (`EVAL_JUDGE_UNCHECKED`). `arms` resolves the `eval-arms` model role against `lib/pricing.ts` and stops on an unpriced model (`EVAL_PRICE_MISSING`); `dry-run` runs every row through the stub model for $0 and flags malformed rows (`EVAL_DRY_RUN_FAILED`), and refuses a plan whose every arm is Haiku or Sonnet @@ -981,7 +984,9 @@ stays out of the projection until one of its attempts settles a real charge. A run stops at the first quota or rate-limit error on such an arm. `results --check ` refuses a finished results file unless one table holds a filled row for every arm, each `#no-gstack` row beside its -variants (`EVAL_REPORT_NO_GSTACK_ROW`); no number leaves the run before it passes. +variants (`EVAL_REPORT_NO_GSTACK_ROW`); it also checks a model judge's `--labels`, +unplanted zeros (`EVAL_REPORT_UNPLANTED_ZERO`) and failures columns without an +`answer-only` column (`EVAL_REPORT_NO_ANSWER_ONLY`); no number leaves the run before it passes. The skill's closing section lists the tier-3 items (instrument audit, steady state, sealed paths, off-machine persistence, memory preflight, power tables, QA soak) as `tier 3, after P7`; none of them run yet. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f14f21b3d1c..50c43ef6a8a 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -4763,12 +4763,19 @@ parentheses; grep the code. ### `PREREG_INCOMPLETE` **Meaning.** `gstack-eval-plan prereg --check ` found a required -preregistration section missing or empty: `## Bars`, `## Arms`, -`## Comparison`, `## Decoys`, `## Stop rules` or `## Held-out exposure` -(every held-out set the plan touches, its prior exposure and the reservation -on it). It also fires when `## Comparison` has no `stack:` line, a value other -than `loaded` or `none`, or `stack: none` without a `why:` line, and when a -`## Diagnostics` declaration is malformed. +preregistration section missing or empty: `## Bars`, `## Decisions`, +`## Arms`, `## Comparison`, `## Scoring`, `## Decoys`, `## Stop rules` or +`## Held-out exposure` (every held-out set the plan touches, its prior +exposure and the reservation on it). It also fires when `## Comparison` has no +`stack:` line, a value other than `loaded` or `none`, or `stack: none` without +a `why:` line, and when a `## Diagnostics` declaration is malformed. The +result checks add two more (`decisions:` and `scoring:` in the message): +`## Decisions` needs two or more `if : ` lines with different +actions, and `## Scoring` needs a `judge:` line, a model judge from another +model family than every arm with `labels:` of 40 or more and `agreement:` of +0.6 or more, and with two or more arms `paired: yes`, `interval: 95%` and +`mdd:`. A `frozen:` date before 2026-11-15 exempts both +([docs/TESTING_INTERNALS.md](TESTING_INTERNALS.md#result-checks)). **Fix.** Fill the named sections before any priced call. A plan that cannot name its stop rule or its held-out exposure is not preregistered; the pilot @@ -4808,6 +4815,51 @@ in one table, and rerun the check. Publish no number before it prints `RESULTS: ok`. A preregistration with `stack: none` needs no row. The rule is in [docs/TESTING_INTERNALS.md](TESTING_INTERNALS.md#no-gstack-arm). + +### `EVAL_JUDGE_UNCHECKED` + +**Meaning.** The preregistration's `## Scoring` names a model judge, and +`gstack-eval-plan judge --check` or `results --check` found no `--labels` +file, fewer labelled outputs than the preregistered count (at least 40), labels +that are all one class (agreement is undefined), a repeated id, or a Cohen's +kappa between the hand labels and the judge below the preregistered bar (at +least 0.6). Until it passes, the judge's numbers do not count. + +**Fix.** Label outputs by hand from development or calibration rows, never +held-out ones, as JSONL rows `{"id", "human", "judge"}`, covering every kind +of output the judge scores, and pass the file with `--labels`. A judge below +its bar is replaced or its prompt fixed and relabelled; the bar is not +lowered. The rule is in +[docs/TESTING_INTERNALS.md](TESTING_INTERNALS.md#result-checks). + + +### `EVAL_REPORT_UNPLANTED_ZERO` + +**Meaning.** `gstack-eval-plan results --check` found a zero (`0`, `0%`, +`0/N`) in a column of any results table, and the preregistration's +`## Diagnostics` declares no counter by that column's name with a planted +case (`expected` of 1 or more). A counter that never fires also reports zero, +so a zero from a counter nobody saw find anything proves nothing. + +**Fix.** Declare the counter under `## Diagnostics` with a synthetic fixture +that plants at least one case, run `prereg --check --allow-repo-commands` +until its `PREREG_DIAGNOSTIC:` line says ok, and name the results column after +the diagnostic. Otherwise leave the zero out of the report. The rule is in +[docs/TESTING_INTERNALS.md](TESTING_INTERNALS.md#result-checks). + + +### `EVAL_REPORT_NO_ANSWER_ONLY` + +**Meaning.** A table in the results file has a column counting failures and no +column headed `answer-only` beside it. A broad failure count (from +transcripts, tool errors or a second rule) can rise while failures counted by +the grader's own rule on the final answer do not move, and the two readings +must be read side by side. + +**Fix.** Add an `answer-only` column to the same table, counting failures by +the grader's rule on the final answer alone, and report both readings. The +rule is in [docs/TESTING_INTERNALS.md](TESTING_INTERNALS.md#result-checks). + ### `EVAL_ARM_DUPLICATE` diff --git a/eval-plan/SKILL.md b/eval-plan/SKILL.md index adca9139cf5..9f7d7ea0238 100644 --- a/eval-plan/SKILL.md +++ b/eval-plan/SKILL.md @@ -134,9 +134,11 @@ Write (or open) the preregistration file. Each section is required and must be f | Section | What it holds | |---|---| -| Bars | `lesson:` the public lesson the run is after, then one line per metric: name, pass bar, direction, what a miss means for the decision | +| Bars | `lesson:` the public lesson the run is after, then one line per metric: name, pass bar, direction | +| Decisions | one `if : ` line per way the run can come out, at least two, with different actions | | Arms | one line per arm: the arm identity first (`` or `#`), settings, per-item cost from Step 1b | | Comparison | `stack: loaded` when any arm loads gstack or another skill stack; otherwise `stack: none` and a `why:` line | +| Scoring | `judge: none` or the judge model with `labels:` and `agreement:`; with two or more arms, `paired: yes`, `interval: 95%`, `mdd:` | | Decoys | inputs the scorer must reject or score low; how many, how they were made, what a decoy pass proves | | Stop rules | the spend cap, a bar missed on the pilot, a scorer below its bar, `budget_exhausted`, the first quota or rate-limit error on a seat-metered arm | | Held-out exposure | every held-out set the plan touches: prior exposure (which runs, which models), the reservation on it | @@ -169,7 +171,22 @@ fixture is built to produce. The summarizer's last stdout line is one JSON objec Then run `prereg --check --allow-repo-commands`. Without the flag, the summarizer is listed and the check exits 3. Every `PREREG_DIAGNOSTIC:` line must say `ok`. `PREREG_DIAGNOSTIC_UNTESTED` (exit 1) means a count, a missing diagnostic or an -undeclared one does not match its definition. Fix that before you freeze. +undeclared one does not match its definition. Fix that before you freeze. Any count +the results may report as zero is declared here with a planted case: its fixture holds +at least one, so `expected` is 1 or more and the summarizer is shown to find it. + +**Result checks** (docs/TESTING_INTERNALS.md#result-checks). `prereg --check` runs them; +`PREREG_INCOMPLETE` names the line that fails: + +1. **Decisions before spend.** Each possible result names what we do differently. If + every result leads to the same action, the eval changes nothing: do not run it. +2. **A checked judge.** A model judge comes from another model family than every arm, + is checked against at least 40 hand-labelled outputs (never held-out rows) at a + kappa of 0.6 or better, and the comparison is paired with a 95% interval and its + smallest detectable difference stated now. + +A `frozen: YYYY-MM-DD` line before 2026-11-15 keeps the rules it was frozen under +(`result_checks=exempt`). ### Step 1b: Arms and their price @@ -284,6 +301,18 @@ the preregistration, when `status=budget_exhausted`, or when `verdict=exceeds`. ## Step 4: The approval ask +With a model judge, check it before asking. Label at least the preregistered number of +outputs by hand as `{"id", "human", "judge"}` JSONL (development or calibration rows), +then: + +```bash +~/.claude/skills/gstack/bin/gstack-eval-plan judge --check --labels +``` + +`JUDGE_AGREEMENT: ok` continues. `EVAL_JUDGE_UNCHECKED` (exit 1) means too few labels, +one class, or kappa below the bar: replace the judge or fix its prompt, then +relabel; never lower the bar. + Price every paid gate the plan names (a benchmark or eval command that spends) from the repo's call-plan file; nothing is executed (`docs/eval-calls.md` in gstack). The gate command is free text, so it reaches the pricer only as a file: @@ -309,7 +338,8 @@ Each `GATE_PRICE:` line goes into the ask. `EVAL_GATE_UNPRICED`, `EVAL_PLAN_STAL `--allow-unpriced ""` only on the owner's word. Present, in this order and nothing before it: the `PILOT_PROJECTION:` line, the spend -table, each gate's `GATE_PRICE:` line, the pilot's per-bar results, and the preregistration's stop rules. Then ask one +table, each gate's `GATE_PRICE:` line, the pilot's per-bar results, the `JUDGE_AGREEMENT:` +line, the preregistration's Decisions lines, and its stop rules. Then ask one question with the projection as the recommended option only when `verdict=within`: - A) Run `` items at the projected cost (recommended when within the cap) @@ -328,12 +358,20 @@ from the Arms section, each `#no-gstack` row beside its variants. Before leaves the run (a report, a READY block, a PR body), check it: ```bash -~/.claude/skills/gstack/bin/gstack-eval-plan results --check +~/.claude/skills/gstack/bin/gstack-eval-plan results --check [--labels ] ``` -`RESULTS: ok` lets the numbers go out. `EVAL_REPORT_NO_GSTACK_ROW` (exit 1) names the arm -whose filled row is missing from the table that holds the others; add it and rerun. A -preregistration with `stack: none` needs no row. +`RESULTS: ok` lets the numbers go out. Each refusal exits 1: + +- `EVAL_REPORT_NO_GSTACK_ROW` names the arm whose filled row is missing from the table + that holds the others; add it. A preregistration with `stack: none` needs no row. +- `EVAL_JUDGE_UNCHECKED`: a model judge's numbers count only with `--labels` passing. +- `EVAL_REPORT_UNPLANTED_ZERO`: a zero in any results table, in a column not named after + a Diagnostics counter with a planted case. Declare and run it, or report the zero as + unverified, outside the tables. +- `EVAL_REPORT_NO_ANSWER_ONLY`: a failures column needs an `answer-only` column beside + it (failures by the grader's own rule on the final answer); a broader count can rise + while that one stays flat. The results file opens with two or three plain takeaways ("We learned X. You should do X."): what works first, then what didn't, with its number. Cost appears only as part of a diff --git a/eval-plan/SKILL.md.tmpl b/eval-plan/SKILL.md.tmpl index 4472766b092..c51321370b4 100644 --- a/eval-plan/SKILL.md.tmpl +++ b/eval-plan/SKILL.md.tmpl @@ -56,9 +56,11 @@ Write (or open) the preregistration file. Each section is required and must be f | Section | What it holds | |---|---| -| Bars | `lesson:` the public lesson the run is after, then one line per metric: name, pass bar, direction, what a miss means for the decision | +| Bars | `lesson:` the public lesson the run is after, then one line per metric: name, pass bar, direction | +| Decisions | one `if : ` line per way the run can come out, at least two, with different actions | | Arms | one line per arm: the arm identity first (`` or `#`), settings, per-item cost from Step 1b | | Comparison | `stack: loaded` when any arm loads gstack or another skill stack; otherwise `stack: none` and a `why:` line | +| Scoring | `judge: none` or the judge model with `labels:` and `agreement:`; with two or more arms, `paired: yes`, `interval: 95%`, `mdd:` | | Decoys | inputs the scorer must reject or score low; how many, how they were made, what a decoy pass proves | | Stop rules | the spend cap, a bar missed on the pilot, a scorer below its bar, `budget_exhausted`, the first quota or rate-limit error on a seat-metered arm | | Held-out exposure | every held-out set the plan touches: prior exposure (which runs, which models), the reservation on it | @@ -91,7 +93,22 @@ fixture is built to produce. The summarizer's last stdout line is one JSON objec Then run `prereg --check --allow-repo-commands`. Without the flag, the summarizer is listed and the check exits 3. Every `PREREG_DIAGNOSTIC:` line must say `ok`. `PREREG_DIAGNOSTIC_UNTESTED` (exit 1) means a count, a missing diagnostic or an -undeclared one does not match its definition. Fix that before you freeze. +undeclared one does not match its definition. Fix that before you freeze. Any count +the results may report as zero is declared here with a planted case: its fixture holds +at least one, so `expected` is 1 or more and the summarizer is shown to find it. + +**Result checks** (docs/TESTING_INTERNALS.md#result-checks). `prereg --check` runs them; +`PREREG_INCOMPLETE` names the line that fails: + +1. **Decisions before spend.** Each possible result names what we do differently. If + every result leads to the same action, the eval changes nothing: do not run it. +2. **A checked judge.** A model judge comes from another model family than every arm, + is checked against at least 40 hand-labelled outputs (never held-out rows) at a + kappa of 0.6 or better, and the comparison is paired with a 95% interval and its + smallest detectable difference stated now. + +A `frozen: YYYY-MM-DD` line before 2026-11-15 keeps the rules it was frozen under +(`result_checks=exempt`). ### Step 1b: Arms and their price @@ -206,6 +223,18 @@ the preregistration, when `status=budget_exhausted`, or when `verdict=exceeds`. ## Step 4: The approval ask +With a model judge, check it before asking. Label at least the preregistered number of +outputs by hand as `{"id", "human", "judge"}` JSONL (development or calibration rows), +then: + +```bash +~/.claude/skills/gstack/bin/gstack-eval-plan judge --check --labels +``` + +`JUDGE_AGREEMENT: ok` continues. `EVAL_JUDGE_UNCHECKED` (exit 1) means too few labels, +one class, or kappa below the bar: replace the judge or fix its prompt, then +relabel; never lower the bar. + Price every paid gate the plan names (a benchmark or eval command that spends) from the repo's call-plan file; nothing is executed (`docs/eval-calls.md` in gstack). The gate command is free text, so it reaches the pricer only as a file: @@ -224,7 +253,8 @@ Each `GATE_PRICE:` line goes into the ask. `EVAL_GATE_UNPRICED`, `EVAL_PLAN_STAL `--allow-unpriced ""` only on the owner's word. Present, in this order and nothing before it: the `PILOT_PROJECTION:` line, the spend -table, each gate's `GATE_PRICE:` line, the pilot's per-bar results, and the preregistration's stop rules. Then ask one +table, each gate's `GATE_PRICE:` line, the pilot's per-bar results, the `JUDGE_AGREEMENT:` +line, the preregistration's Decisions lines, and its stop rules. Then ask one question with the projection as the recommended option only when `verdict=within`: - A) Run `` items at the projected cost (recommended when within the cap) @@ -243,12 +273,20 @@ from the Arms section, each `#no-gstack` row beside its variants. Before leaves the run (a report, a READY block, a PR body), check it: ```bash -~/.claude/skills/gstack/bin/gstack-eval-plan results --check +~/.claude/skills/gstack/bin/gstack-eval-plan results --check [--labels ] ``` -`RESULTS: ok` lets the numbers go out. `EVAL_REPORT_NO_GSTACK_ROW` (exit 1) names the arm -whose filled row is missing from the table that holds the others; add it and rerun. A -preregistration with `stack: none` needs no row. +`RESULTS: ok` lets the numbers go out. Each refusal exits 1: + +- `EVAL_REPORT_NO_GSTACK_ROW` names the arm whose filled row is missing from the table + that holds the others; add it. A preregistration with `stack: none` needs no row. +- `EVAL_JUDGE_UNCHECKED`: a model judge's numbers count only with `--labels` passing. +- `EVAL_REPORT_UNPLANTED_ZERO`: a zero in any results table, in a column not named after + a Diagnostics counter with a planted case. Declare and run it, or report the zero as + unverified, outside the tables. +- `EVAL_REPORT_NO_ANSWER_ONLY`: a failures column needs an `answer-only` column beside + it (failures by the grader's own rule on the final answer); a broader count can rise + while that one stays flat. The results file opens with two or three plain takeaways ("We learned X. You should do X."): what works first, then what didn't, with its number. Cost appears only as part of a diff --git a/lib/eval-plan-checks.ts b/lib/eval-plan-checks.ts new file mode 100644 index 00000000000..4491fc3962f --- /dev/null +++ b/lib/eval-plan-checks.ts @@ -0,0 +1,121 @@ +/** + * eval-plan-checks: the result checks /eval-plan runs on top of the section + * check (docs/TESTING_INTERNALS.md#result-checks). `## Decisions` names what + * each possible result changes before anything is spent; `## Scoring` names + * the judge and the statistics before the run; `judge --check` scores the + * judge against hand labels before its numbers count. A preregistration whose + * `frozen:` date is before RESULT_CHECKS_SINCE keeps the rules it was frozen + * under. Reads text only; executes nothing. + */ +export const RESULT_CHECKS_SINCE = '2026-11-15'; +export const JUDGE_MIN_LABELS = 40; +export const JUDGE_MIN_KAPPA = 0.6; + +const PLACEHOLDER = /^(?:|-+|—|n\/a|none|tbd|todo|\?)\.?$/i; +const keyValues = (body: string[]) => { + const kv: Record = {}; + for (const line of body) { + const m = /^\s*(?:[-*]\s+)?([a-z]+):(.*)$/i.exec(line); + if (m) kv[m[1]!.toLowerCase()] = m[2]!.trim().replace(/^`(.*)`$/, '$1'); + } + return kv; +}; +const firstNumber = (v: string | undefined) => { const m = /\d+(?:\.\d+)?/.exec(v ?? ''); return m ? Number(m[0]) : null; }; + +/** The `frozen: YYYY-MM-DD` line, when the preregistration states its freeze date. */ +export function frozenDate(text: string): string | null { + return /^\s*frozen:\s*(\d{4}-\d{2}-\d{2})\s*$/im.exec(text)?.[1] ?? null; +} +export const grandfathered = (text: string) => { const d = frozenDate(text); return d !== null && d < RESULT_CHECKS_SINCE; }; + +/** Model family for the judge rule: the lab behind a model id, else the id's first word. */ +export function modelFamily(model: string): string { + const id = model.split('#')[0]!.toLowerCase().split('/').pop()!; + const head = id.split(/[-_.:\s]|(?<=[a-z])(?=\d)/)[0]!; + const labs: Record = { claude: 'anthropic', gpt: 'openai', o: 'openai', codex: 'openai', gemini: 'google', gemma: 'google', grok: 'xai', llama: 'meta', muse: 'meta' }; + return labs[head] ?? head; +} + +export interface DecisionsCheck { outcomes: Array<{ result: string; action: string }>; errors: string[] } +/** `## Decisions`: one `if : ` line per possible result, at least two, and not all the same action. */ +export function checkDecisions(body: string[] | null): DecisionsCheck { + const outcomes: DecisionsCheck['outcomes'] = []; + for (const line of body ?? []) { + const m = /^\s*(?:[-*]\s+)?if\s+(.+?):\s*(.*)$/i.exec(line); + if (m) outcomes.push({ result: m[1]!.trim(), action: m[2]!.trim() }); + } + if (!body?.length) return { outcomes, errors: [] }; + const errors: string[] = []; + if (outcomes.length < 2) errors.push('needs one "if : " line per possible result, at least two'); + for (const o of outcomes) if (PLACEHOLDER.test(o.action)) errors.push(`if ${o.result}: names no action`); + const actions = new Set(outcomes.map(o => o.action.toLowerCase().replace(/\s+/g, ' '))); + if (outcomes.length >= 2 && actions.size === 1) errors.push('every result leads to the same action, so the eval changes nothing; do not run it'); + return { outcomes, errors }; +} + +export interface ScoringCheck { judge: string | null; labels: number | null; agreement: number | null; errors: string[] } +/** + * `## Scoring`: `judge: none` or the judge model; a model judge needs `labels:` + * (at least 40) and `agreement:` (a kappa bar of at least 0.6) and a family no + * arm shares. Two or more arms need `paired: yes`, `interval: 95%` and `mdd:`, + * the smallest difference the run can detect. + */ +export function checkScoring(body: string[] | null, arms: string[]): ScoringCheck { + if (!body?.length) return { judge: null, labels: null, agreement: null, errors: [] }; + const kv = keyValues(body); + const judge = kv.judge || null; + const labels = firstNumber(kv.labels); + const agreement = firstNumber(kv.agreement); + const errors: string[] = []; + if (!judge) errors.push('no judge: line (judge: none, or the judge model)'); + else if (judge.toLowerCase() !== 'none') { + if (labels === null || labels < JUDGE_MIN_LABELS) errors.push(`labels: needs at least ${JUDGE_MIN_LABELS} hand-labelled outputs the judge is checked against`); + if (agreement === null || agreement < JUDGE_MIN_KAPPA || agreement > 1) errors.push(`agreement: needs a kappa bar from ${JUDGE_MIN_KAPPA} to 1`); + const family = modelFamily(judge); + for (const arm of [...new Set(arms)]) if (modelFamily(arm) === family) errors.push(`judge ${judge} is the same model family (${family}) as arm ${arm}; use a judge from another family`); + } + if (new Set(arms).size >= 2) { + if (!/^yes\b/i.test(kv.paired ?? '')) errors.push('paired: yes (every comparison is reported on paired items)'); + if (firstNumber(kv.interval) !== 95) errors.push('interval: 95% (the interval every comparison is reported with)'); + if (PLACEHOLDER.test(kv.mdd ?? '')) errors.push('mdd: the smallest difference this run can detect, stated before the run'); + } + return { judge, labels, agreement, errors }; +} + +export interface JudgeLabelCheck { ok: boolean; judge: string; n: number; kappa: number | null; need_n: number; need_kappa: number; problems: string[] } + +/** Cohen's kappa over paired categorical labels; null when chance agreement is total (every label one class). */ +export function cohensKappa(pairs: Array<[string, string]>): number | null { + if (!pairs.length) return null; + const n = pairs.length; + const a = new Map(); const b = new Map(); + let agree = 0; + for (const [h, j] of pairs) { a.set(h, (a.get(h) ?? 0) + 1); b.set(j, (b.get(j) ?? 0) + 1); if (h === j) agree++; } + const pe = [...a.keys()].reduce((s, k) => s + (a.get(k)! / n) * ((b.get(k) ?? 0) / n), 0); + return pe === 1 ? null : (agree / n - pe) / (1 - pe); +} + +/** Score the preregistered judge against a JSONL file of `{"id", "human", "judge"}` rows. */ +export function checkJudgeLabels(scoring: ScoringCheck, labelsText: string): JudgeLabelCheck { + const need_n = Math.max(JUDGE_MIN_LABELS, scoring.labels ?? 0); + const need_kappa = Math.max(JUDGE_MIN_KAPPA, scoring.agreement ?? 0); + const problems: string[] = []; + const pairs: Array<[string, string]> = []; + const ids = new Set(); + labelsText.split('\n').forEach((line, i) => { + if (!line.trim()) return; + let row: { id?: unknown; human?: unknown; judge?: unknown } | null = null; + try { row = JSON.parse(line); } catch { row = null; } + if (!row || typeof row !== 'object' || ![row.id, row.human, row.judge].every(v => (typeof v === 'string' && v.trim() !== '') || typeof v === 'number' || typeof v === 'boolean')) { problems.push(`line ${i + 1}: needs {"id", "human", "judge"}, each a string, number or boolean`); return; } + if (ids.has(String(row.id))) { problems.push(`id ${String(row.id)} is labelled twice`); return; } + ids.add(String(row.id)); + pairs.push([String(row.human), String(row.judge)]); + }); + const kappa = cohensKappa(pairs); + if (pairs.length < need_n) problems.push(`${pairs.length} labelled outputs, needs ${need_n}`); + if (pairs.length && kappa === null) problems.push('every label is one class, so agreement is undefined; label outputs of every kind the judge scores'); + else if (kappa !== null && kappa < need_kappa) problems.push(`kappa ${kappa.toFixed(2)} is below the bar ${need_kappa}`); + return { ok: problems.length === 0, judge: scoring.judge ?? 'none', n: pairs.length, kappa, need_n, need_kappa, problems }; +} + +export const renderJudgeLabels = (c: JudgeLabelCheck) => `JUDGE_AGREEMENT: ${c.ok ? 'ok' : 'unchecked'} judge=${c.judge} n=${c.n}/${c.need_n} kappa=${c.kappa === null ? 'undefined' : c.kappa.toFixed(2)} bar=${c.need_kappa}\n`; diff --git a/lib/eval-plan-report.ts b/lib/eval-plan-report.ts index fef62483f8c..beabde88659 100644 --- a/lib/eval-plan-report.ts +++ b/lib/eval-plan-report.ts @@ -3,44 +3,77 @@ * A preregistration that says `stack: loaded` names its no-gstack arms; its * results file must hold one markdown table with a filled row for every Arms * identity, so each no-gstack row sits beside its variants - * (docs/TESTING_INTERNALS.md#no-gstack-arm). Reads text only; executes nothing. + * (docs/TESTING_INTERNALS.md#no-gstack-arm). The result checks + * (docs/TESTING_INTERNALS.md#result-checks) hold back a model judge's numbers + * until its hand labels pass, a zero from a counter never shown to find a + * planted case, and a failures column with no answer-only reading beside it. + * Reads text only; executes nothing. */ import { armIdentities, checkPrereg } from './eval-plan'; +import { checkJudgeLabels, type JudgeLabelCheck } from './eval-plan-checks'; +import type { ResultCodeName } from './result-codes'; -export interface ResultsCheck { ok: boolean; required: string[]; no_gstack: string[]; found: string[]; missing: string[]; problems: string[] } +export interface ResultsIssue { code: ResultCodeName; message: string } +export interface ResultsCheck { ok: boolean; required: string[]; no_gstack: string[]; found: string[]; missing: string[]; problems: string[]; issues: ResultsIssue[]; judge: JudgeLabelCheck | null } +export interface ResultTable { ids: Set; header: string[]; rows: string[][] } const PLACEHOLDER = /^(?:|-+|—|–|n\/a|tbd|todo|\?)$/i; +const ZERO = /^0(?:\.0+)?(?:%|\/\d+)?$/; +const plain = (c: string) => c.replace(/[`*]/g, '').trim(); const cellsOf = (line: string) => line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(c => c.trim()); const separator = (line: string | undefined) => !!line && /^\s*\|[\s:|-]+\|?\s*$/.test(line) && line.includes('-'); -/** The filled-row identities of each markdown table: first cell, backticks stripped, header and separator rows skipped. */ -export function resultTables(text: string): Array> { +/** Each markdown table: its header cells, data rows, and filled-row identities (first cell, backticks stripped). */ +export function resultTables(text: string): ResultTable[] { const lines = text.split('\n'); - const tables: Array> = []; - let current: Set | null = null; + const tables: ResultTable[] = []; + let current: ResultTable | null = null; lines.forEach((line, i) => { if (!/^\s*\|/.test(line)) { current = null; return; } - if (!current) { current = new Set(); tables.push(current); } - if (separator(line) || separator(lines[i + 1])) return; - const [first, ...rest] = cellsOf(line); - const id = (first ?? '').replace(/`/g, '').trim(); - if (id && rest.some(c => !PLACEHOLDER.test(c.replace(/`/g, '').trim()))) current.add(id); + if (!current) { current = { ids: new Set(), header: [], rows: [] }; tables.push(current); } + if (separator(line)) return; + if (separator(lines[i + 1])) { current.header = cellsOf(line).map(plain); return; } + const cells = cellsOf(line); + current.rows.push(cells.map(plain)); + const id = (cells[0] ?? '').replace(/`/g, '').trim(); + if (id && cells.slice(1).some(c => !PLACEHOLDER.test(c.replace(/`/g, '').trim()))) current.ids.add(id); }); return tables; } -export function checkResults(preregText: string, resultsText: string): ResultsCheck { +export function checkResults(preregText: string, resultsText: string, labelsText: string | null = null): ResultsCheck { const prereg = checkPrereg(preregText); - if (prereg.comparison.stack === 'none') return { ok: true, required: [], no_gstack: [], found: [], missing: [], problems: [] }; - const required = [...new Set(armIdentities(preregText))]; - const noGstack = prereg.no_gstack.arms; - const problems: string[] = []; - if (!prereg.ok) problems.push('the preregistration does not pass prereg --check'); + const issues: ResultsIssue[] = []; const tables = resultTables(resultsText); - const best = tables.reduce>((b, t) => (required.filter(id => t.has(id)).length > required.filter(id => b.has(id)).length ? t : b), new Set()); - const found = required.filter(id => best.has(id)); - const missing = required.filter(id => !best.has(id)); - if (!tables.length) problems.push('no markdown table in the results file'); - else for (const id of missing) problems.push(`no filled row for ${id} in the table that holds the other arms`); - return { ok: problems.length === 0, required, no_gstack: noGstack, found, missing, problems }; + const arms = [...new Set(armIdentities(preregText))]; + const required = prereg.comparison.stack === 'none' ? [] : arms; + const best = tables.reduce((b, t) => (!b || arms.filter(id => t.ids.has(id)).length > arms.filter(id => b.ids.has(id)).length ? t : b), null); + const found = required.filter(id => best?.ids.has(id)); + const missing = required.filter(id => !best?.ids.has(id)); + if (prereg.comparison.stack !== 'none') { + if (!prereg.ok) issues.push({ code: 'EVAL_REPORT_NO_GSTACK_ROW', message: 'the preregistration does not pass prereg --check' }); + if (!tables.length) issues.push({ code: 'EVAL_REPORT_NO_GSTACK_ROW', message: 'no markdown table in the results file' }); + else for (const id of missing) issues.push({ code: 'EVAL_REPORT_NO_GSTACK_ROW', message: `no filled row for ${id} in the table that holds the other arms` }); + } + let judge: JudgeLabelCheck | null = null; + if (!prereg.grandfathered) { + for (const [section, errors] of [['Decisions', prereg.decisions.errors], ['Scoring', prereg.scoring.errors]] as const) { + for (const e of errors) issues.push({ code: 'PREREG_INCOMPLETE', message: `## ${section}: ${e}` }); + } + if (prereg.scoring.judge && prereg.scoring.judge.toLowerCase() !== 'none') { + judge = labelsText === null ? null : checkJudgeLabels(prereg.scoring, labelsText); + if (!judge) issues.push({ code: 'EVAL_JUDGE_UNCHECKED', message: `the preregistration names judge ${prereg.scoring.judge}; pass --labels ` }); + else if (!judge.ok) issues.push({ code: 'EVAL_JUDGE_UNCHECKED', message: judge.problems.join('; ') }); + } + const planted = new Set((prereg.diagnostics?.expected ?? []).filter(e => e.count >= 1).map(e => e.name.toLowerCase())); + for (const t of tables) { + t.header.forEach((name, col) => { + if (col === 0 || planted.has(name.toLowerCase()) || !t.rows.some(r => ZERO.test(r[col] ?? ''))) return; + issues.push({ code: 'EVAL_REPORT_UNPLANTED_ZERO', message: `column "${name}" reports a zero, and no Diagnostics counter by that name was shown to find a planted case` }); + }); + const failures = t.header.filter(h => /\bfail/i.test(h) && !/answer[- ]only/i.test(h)); + if (failures.length && !t.header.some(h => /answer[- ]only/i.test(h))) issues.push({ code: 'EVAL_REPORT_NO_ANSWER_ONLY', message: `column "${failures[0]}" counts failures with no answer-only column beside it in the same table` }); + } + } + return { ok: issues.length === 0, required, no_gstack: prereg.no_gstack.arms, found, missing, problems: issues.map(i => i.message), issues, judge }; } diff --git a/lib/eval-plan.ts b/lib/eval-plan.ts index 258ee975a04..9b5580c1e5d 100644 --- a/lib/eval-plan.ts +++ b/lib/eval-plan.ts @@ -19,16 +19,19 @@ import { EXCLUDED_BILLING_CATEGORIES, estimateCostUsd, hasPricing, PRICING, pric import type { ResultCodeName } from './result-codes'; import type { ModelRulesCheck } from './eval-models'; import { readLedger, release, reserve, settle, SpendCapExceeded, summarize, type SpendLedger, type SpendSummary } from './spend-ledger'; +import { checkDecisions, checkScoring, frozenDate, grandfathered, type DecisionsCheck, type ScoringCheck } from './eval-plan-checks'; // --------------------------------------------------------------------------- // preregistration // --------------------------------------------------------------------------- -export const PREREG_SECTIONS = ['Bars', 'Arms', 'Comparison', 'Decoys', 'Stop rules', 'Held-out exposure'] as const; +export const PREREG_SECTIONS = ['Bars', 'Decisions', 'Arms', 'Comparison', 'Scoring', 'Decoys', 'Stop rules', 'Held-out exposure'] as const; +/** Sections added with the result checks; a preregistration frozen before them (`frozen:` before RESULT_CHECKS_SINCE) is not asked for them. */ +const RESULT_CHECK_SECTIONS: readonly string[] = ['Decisions', 'Scoring']; /** `## Comparison`: `stack: loaded` when any arm loads gstack or another skill stack, `stack: none` with a `why:` otherwise. */ export interface ComparisonCheck { stack: 'loaded' | 'none' | null; why: string | null; errors: string[] } /** `## No-gstack arm`, required when `stack: loaded`: one `#no-gstack` Arms line per model, the inputs, prompt, panel and report it shares with the variants, and its masking, install and audit lines. */ export interface NoGstackArmCheck { required: boolean; ok: boolean; arms: string[]; problems: string[] } -export interface PreregCheck { ok: boolean; present: string[]; missing: string[]; empty: string[]; comparison: ComparisonCheck; no_gstack: NoGstackArmCheck; diagnostics: PreregDiagnostics | null } +export interface PreregCheck { ok: boolean; present: string[]; missing: string[]; empty: string[]; comparison: ComparisonCheck; no_gstack: NoGstackArmCheck; diagnostics: PreregDiagnostics | null; decisions: DecisionsCheck; scoring: ScoringCheck; frozen: string | null; grandfathered: boolean } export const NO_GSTACK_LOADOUT = 'no-gstack'; /** masking, install and audit keep the arm clean (TESTING_INTERNALS.md#no-gstack-arm): an arm that read a gstack skill file is contaminated. */ export const NO_GSTACK_KEYS = ['arms', 'inputs', 'prompt', 'panel', 'report', 'masking', 'install', 'audit'] as const; @@ -37,7 +40,10 @@ export function preregTemplate(title = 'Eval preregistration'): string { return `# ${title} ## Bars - + + +## Decisions + ## Arms @@ -48,6 +54,9 @@ export function preregTemplate(title = 'Eval preregistration'): string { ## No-gstack arm +## Scoring + + ## Decoys @@ -56,7 +65,7 @@ export function preregTemplate(title = 'Eval preregistration'): string { ## Held-out exposure - + `; } @@ -130,14 +139,19 @@ function checkNoGstackArm(text: string, stack: ComparisonCheck['stack']): NoGsta export function checkPrereg(text: string): PreregCheck { const present: string[] = []; const missing: string[] = []; const empty: string[] = []; + const exempt = grandfathered(text); for (const name of PREREG_SECTIONS) { + if (exempt && RESULT_CHECK_SECTIONS.includes(name)) continue; const body = sectionBody(text, name); if (body === null) missing.push(name); else if (body.length === 0) empty.push(name); else present.push(name); } const comparison = checkComparison(text); const no_gstack = checkNoGstackArm(text, comparison.stack); const diagnostics = parsePreregDiagnostics(text); - return { ok: missing.length === 0 && empty.length === 0 && !comparison.errors.length && no_gstack.ok && !diagnostics?.errors.length, present, missing, empty, comparison, no_gstack, diagnostics }; + const decisions = exempt ? { outcomes: [], errors: [] } : checkDecisions(sectionBody(text, 'Decisions')); + const scoring = exempt ? { judge: null, labels: null, agreement: null, errors: [] } : checkScoring(sectionBody(text, 'Scoring'), armIdentities(text)); + const ok = missing.length === 0 && empty.length === 0 && !comparison.errors.length && no_gstack.ok && !diagnostics?.errors.length && !decisions.errors.length && !scoring.errors.length; + return { ok, present, missing, empty, comparison, no_gstack, diagnostics, decisions, scoring, frozen: frozenDate(text), grandfathered: exempt }; } // --------------------------------------------------------------------------- diff --git a/lib/result-codes-eval.ts b/lib/result-codes-eval.ts index e019e3bddee..23d6143cf62 100644 --- a/lib/result-codes-eval.ts +++ b/lib/result-codes-eval.ts @@ -10,8 +10,8 @@ import type { ResultCode } from './result-codes'; export const EVAL_RESULT_CODES = { PREREG_INCOMPLETE: { anchor: 'prereg-incomplete', - summary: 'the preregistration file lacks a required section, a section is empty, or the Comparison or Diagnostics declaration is malformed', - fix: 'fill every section `gstack-eval-plan prereg --check` names (bars, arms, comparison, decoys, stop rules, held-out exposure) before any priced call', + summary: 'the preregistration file lacks a required section, a section is empty, or the Comparison, Decisions, Scoring or Diagnostics declaration is malformed', + fix: 'fill every section `gstack-eval-plan prereg --check` names (bars, decisions, arms, comparison, scoring, decoys, stop rules, held-out exposure) before any priced call: at least two decisions with different actions, and a judge from another model family checked against at least 40 labels at kappa 0.6 or better', }, // Field list 2 (2026-10-16), W8: preregistered diagnostics run before the freeze commit. PREREG_DIAGNOSTIC_UNTESTED: { @@ -30,6 +30,22 @@ export const EVAL_RESULT_CODES = { summary: 'the results file has no single table with a filled row for every arm the preregistration lists, so a no-gstack row is missing or not beside its variants', fix: 'put one row per arm identity (each #no-gstack beside its variants) in one markdown table of the results file, then rerun `gstack-eval-plan results --check`; publish no number before it says ok', }, + // The result checks (docs/TESTING_INTERNALS.md#result-checks). + EVAL_JUDGE_UNCHECKED: { + anchor: 'eval-judge-unchecked', + summary: 'the preregistration names a model judge, and its hand labels are missing, fewer than the bar, all one class, or agree with the judge below the kappa bar', + fix: 'label at least the preregistered number of outputs by hand (never held-out rows), write them as {"id", "human", "judge"} JSONL, and pass them with --labels; a judge below its bar is replaced or its numbers are not published', + }, + EVAL_REPORT_UNPLANTED_ZERO: { + anchor: 'eval-report-unplanted-zero', + summary: 'a column of a results table reports a zero, and the preregistration never showed the counter behind it finding a planted case', + fix: 'declare the counter under ## Diagnostics with a synthetic fixture that plants at least one case (expected 1 or more), run prereg --check --allow-repo-commands, and name the column after the diagnostic', + }, + EVAL_REPORT_NO_ANSWER_ONLY: { + anchor: 'eval-report-no-answer-only', + summary: 'a results table counts failures without an answer-only column beside it, so a rise in failures cannot be compared with the grader\'s own reading', + fix: 'add a column headed answer-only to the same table, counting failures by the grader\'s rule on the final answer alone, and report both readings', + }, EVAL_ARM_DUPLICATE: { anchor: 'eval-arm-duplicate', summary: 'the pilot was given the same arm identity twice, so two arms would share one set of attempts', diff --git a/test/eval-plan-no-gstack-arm.test.ts b/test/eval-plan-no-gstack-arm.test.ts index 1edef1d8803..0d4ef98537f 100644 --- a/test/eval-plan-no-gstack-arm.test.ts +++ b/test/eval-plan-no-gstack-arm.test.ts @@ -20,7 +20,8 @@ const dirs: string[] = []; const tmp = () => { const d = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-no-gstack-arm-')); dirs.push(d); return d; }; afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); -const BASE = ['Bars', 'Decoys', 'Stop rules', 'Held-out exposure'].map(s => `## ${s}\n- filled in\n`).join('\n'); +const RESULT_SECTIONS = '## Decisions\nif the variant passes more items: adopt it\nif there is no difference: keep the default\n\n## Scoring\njudge: none\npaired: yes\ninterval: 95%\nmdd: 2 of 9 items\n'; +const BASE = ['Bars', 'Decoys', 'Stop rules', 'Held-out exposure'].map(s => `## ${s}\n- filled in\n`).join('\n') + '\n' + RESULT_SECTIONS; const ARMS = (...ids: string[]) => `\n## Arms\n${ids.map(id => `- ${id} default settings, $0.01 per item`).join('\n')}\n`; const LOADED = '\n## Comparison\nstack: loaded\n'; const NO_GSTACK = (o: Partial> = {}) => { @@ -189,10 +190,10 @@ describe('gstack-eval-plan prereg --check', () => { return { code: r.status, out: r.stdout ?? '', err: r.stderr ?? '' }; }; - test('a loaded comparison without the arm: one PREREG line out of 6, PREREG_NO_GSTACK_ARM on stderr, exit 1', () => { + test('a loaded comparison without the arm: one PREREG line out of 8, PREREG_NO_GSTACK_ARM on stderr, exit 1', () => { const r = run(BASE + VARIANTS + LOADED); expect(r.code).toBe(1); - expect(r.out).toMatch(/^PREREG: incomplete present=6\/6 stack=loaded no_gstack_arm=missing file=/m); + expect(r.out).toMatch(/^PREREG: incomplete present=8\/8 stack=loaded no_gstack_arm=missing file=/m); expect(r.err).toContain('missing section'); expect(r.err).toContain('(PREREG_NO_GSTACK_ARM)'); expect(r.err).not.toContain('(PREREG_INCOMPLETE)'); @@ -216,9 +217,9 @@ describe('gstack-eval-plan prereg --check', () => { test('complete: PREREG: ok with stack=loaded no_gstack_arm=ok; an opt-out prints stack=none', () => { const ok = run(BASE + VARIANTS + LOADED + NO_GSTACK()); expect(ok.code, ok.out + ok.err).toBe(0); - expect(ok.out).toMatch(/^PREREG: ok present=6\/6 stack=loaded no_gstack_arm=ok file=/m); + expect(ok.out).toMatch(/^PREREG: ok present=8\/8 stack=loaded no_gstack_arm=ok file=/m); const none = run(BASE + ARMS('claude-opus-5-5') + '\n## Comparison\nstack: none\nwhy: scorer calibration\n'); expect(none.code, none.out + none.err).toBe(0); - expect(none.out).toMatch(/^PREREG: ok present=6\/6 stack=none file=/m); + expect(none.out).toMatch(/^PREREG: ok present=8\/8 stack=none file=/m); }); }); diff --git a/test/eval-plan-prereg-diagnostics.test.ts b/test/eval-plan-prereg-diagnostics.test.ts index 9e9e18a2038..22f94abad1f 100644 --- a/test/eval-plan-prereg-diagnostics.test.ts +++ b/test/eval-plan-prereg-diagnostics.test.ts @@ -14,7 +14,7 @@ import { checkPrereg, parsePreregDiagnostics, preregTemplate } from '../lib/eval import { capyHost, type CapyHost } from './helpers/capy-host'; const BIN = path.resolve(import.meta.dir, '..', 'bin', 'gstack-eval-plan'); -const FILLED = ['Bars', 'Arms', 'Decoys', 'Stop rules', 'Held-out exposure'].map(s => `## ${s}\n- filled in\n`).join('\n') + '\n## Comparison\nstack: none\nwhy: one arm, no skill stack\n'; +const FILLED = ['Bars', 'Arms', 'Decoys', 'Stop rules', 'Held-out exposure'].map(s => `## ${s}\n- filled in\n`).join('\n') + '\n## Comparison\nstack: none\nwhy: one arm, no skill stack\n\n## Decisions\nif the bar is met: run the full set\nif the bar is missed: fix the scorer first\n\n## Scoring\njudge: none\n'; const SUMMARIZER = [ 'touch ran.marker', 'r=$(grep -c \'"kind":"refusal"\' "$1")', @@ -54,7 +54,7 @@ describe('prereg --check: the Diagnostics section', () => { const r = check(FILLED + diagnostics([['refusals', '2'], ['truncated', '1']])); expect(r.code).toBe(3); expect(r.ran).toBe(false); - expect(r.out).toContain('PREREG: ok present=6/6 stack=none diagnostics=2 file='); + expect(r.out).toContain('PREREG: ok present=8/8 stack=none diagnostics=2 file='); expect(r.out).toContain(`PREREG_COMMAND: summarizer="sh summarize.sh {fixture}" fixture=fixtures/synthetic records.jsonl cwd=${fs.realpathSync(repo)}`); expect(r.err).toContain('(REPO_COMMANDS_NOT_ALLOWED)'); expect(r.out).not.toContain('PREREG_DIAGNOSTICS:'); @@ -104,7 +104,7 @@ describe('prereg --check: the Diagnostics section', () => { const r = check(FILLED + diagnostics([['refusals', 'two']], { summarizer: 'sh summarize.sh fixtures/x.jsonl' }), '--allow-repo-commands'); expect(r.code).toBe(1); expect(r.ran).toBe(false); - expect(r.out).toContain('PREREG: incomplete present=6/6 stack=none diagnostics=invalid'); + expect(r.out).toContain('PREREG: incomplete present=8/8 stack=none diagnostics=invalid'); expect(r.err).toContain('diagnostics: row "| refusals | two |"'); expect(r.err).toContain('diagnostics: the summarizer command never names the fixture ({fixture})'); expect(r.err).toContain('diagnostics: no | diagnostic | expected | rows'); @@ -114,7 +114,7 @@ describe('prereg --check: the Diagnostics section', () => { test('without a Diagnostics section the check is unchanged; the template mentions the section without adding a heading', () => { const r = check(FILLED); expect(r.code).toBe(0); - expect(r.out).toBe(`PREREG: ok present=6/6 stack=none file=${path.join(repo, 'evals', 'prereg.md')}\n`); + expect(r.out).toBe(`PREREG: ok present=8/8 stack=none file=${path.join(repo, 'evals', 'prereg.md')}\n`); expect(parsePreregDiagnostics(FILLED)).toBeNull(); expect(parsePreregDiagnostics(FILLED + '\n## Diagnostics\n\n')).toBeNull(); expect(preregTemplate()).toContain('## Diagnostics'); diff --git a/test/eval-plan-result-checks.test.ts b/test/eval-plan-result-checks.test.ts new file mode 100644 index 00000000000..3b24c2a5251 --- /dev/null +++ b/test/eval-plan-result-checks.test.ts @@ -0,0 +1,180 @@ +/** + * The result checks behind /eval-plan (docs/TESTING_INTERNALS.md#result-checks): + * a preregistration names the decision each result changes and its judge and + * statistics before anything is spent; a model judge's numbers count only after + * its hand labels pass; a zero comes only from a counter shown to find a planted + * case; a failures column sits beside its answer-only reading. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { checkPrereg } from '../lib/eval-plan'; +import { checkDecisions, checkJudgeLabels, checkScoring, cohensKappa, modelFamily } from '../lib/eval-plan-checks'; +import { checkResults } from '../lib/eval-plan-report'; + +const BIN = path.resolve(import.meta.dir, '..', 'bin', 'gstack-eval-plan'); +const dirs: string[] = []; +afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); + +const DECISIONS = '## Decisions\nif the skill arm passes more items: keep the skill\nif there is no difference: cut the skill\n'; +const SCORING = (judge = 'gpt-6-astra', extra = 'labels: 40\nagreement: 0.6\npaired: yes\ninterval: 95%\nmdd: 3 of 20 items\n') => `## Scoring\njudge: ${judge}\n${extra}`; +const prereg = (o: { decisions?: string; scoring?: string; frozen?: string; diagnostics?: string } = {}) => [ + o.frozen ? `frozen: ${o.frozen}\n` : '', + '## Bars\n- pass rate, higher is better\n', + o.decisions ?? DECISIONS, + '## Arms\n- claude-opus-5-5 the skill installed\n- claude-opus-5-5#plain no skill\n', + '## Comparison\nstack: none\nwhy: the scorer calibration compares prompts, not skill stacks\n', + o.scoring ?? SCORING(), + ...['Decoys', 'Stop rules', 'Held-out exposure'].map(s => `## ${s}\n- filled in\n`), + o.diagnostics ?? '', +].join('\n'); +const labels = (n: number, disagree = 0, cls = (i: number) => (i % 2 ? 'pass' : 'fail')) => + Array.from({ length: n }, (_, i) => JSON.stringify({ id: `item-${i}`, human: cls(i), judge: i < disagree ? (cls(i) === 'pass' ? 'fail' : 'pass') : cls(i) })).join('\n') + '\n'; +const table = (header: string, ...rows: string[]) => [header, header.replace(/[^|]+/g, '---'), ...rows].join('\n') + '\n'; + +describe('## Decisions', () => { + test('a passing plan names at least two results with different actions', () => { + expect(checkPrereg(prereg())).toMatchObject({ ok: true, missing: [], empty: [] }); + expect(checkDecisions(['if a: do x', 'if b: do y']).errors).toEqual([]); + }); + + test('missing, one result, an empty action, or the same action for every result fails', () => { + expect(checkPrereg(prereg({ decisions: '' })).missing).toContain('Decisions'); + expect(checkDecisions(['if it passes: ship it']).errors[0]).toContain('at least two'); + expect(checkDecisions(['if it passes: ship it', 'if it fails: tbd']).errors).toEqual(['if it fails: names no action']); + expect(checkDecisions(['if it passes: ship it', 'if it fails: Ship it']).errors[0]).toContain('changes nothing'); + expect(checkPrereg(prereg({ decisions: '## Decisions\n- we will learn a lot\n' })).ok).toBe(false); + }); +}); + +describe('## Scoring', () => { + const arms = ['claude-opus-5-5', 'claude-opus-5-5#plain']; + test('a judge from another family with 40 labels, kappa 0.6 and the paired statistics passes', () => { + expect(checkScoring(SCORING().split('\n').slice(1), arms).errors).toEqual([]); + }); + + test('a same-family judge, too few labels, a low kappa bar or missing statistics fail', () => { + expect(checkScoring(SCORING('claude-fable-5-2').split('\n').slice(1), arms).errors.join()).toContain('same model family (anthropic)'); + expect(checkScoring(SCORING('gpt-6-astra', 'labels: 39\nagreement: 0.6\npaired: yes\ninterval: 95%\nmdd: 3\n').split('\n').slice(1), arms).errors[0]).toContain('at least 40'); + expect(checkScoring(SCORING('gpt-6-astra', 'labels: 40\nagreement: 0.5\npaired: yes\ninterval: 95%\nmdd: 3\n').split('\n').slice(1), arms).errors[0]).toContain('kappa bar'); + expect(checkScoring(['judge: none'], arms).errors).toEqual(['paired: yes (every comparison is reported on paired items)', 'interval: 95% (the interval every comparison is reported with)', 'mdd: the smallest difference this run can detect, stated before the run']); + expect(checkScoring(['judge: none'], ['claude-opus-5-5']).errors).toEqual([]); + expect(checkScoring(['labels: 40'], arms).errors[0]).toContain('no judge: line'); + }); + + test('model families: labs by name, provider prefixes and loadouts dropped, else the first word', () => { + expect(['claude-opus-5-5', 'anthropic/claude-haiku-5-5', 'claude-opus-5-5#no-gstack'].map(modelFamily)).toEqual(['anthropic', 'anthropic', 'anthropic']); + expect(['gpt-6.1-sol', 'openai/gpt-6-astra', 'o3'].map(modelFamily)).toEqual(['openai', 'openai', 'openai']); + expect(['gemini-4-carbon', 'grok-4.7', 'deepseek/deepseek-v4-pro', 'particle-ai/particle-1'].map(modelFamily)).toEqual(['google', 'xai', 'deepseek', 'particle']); + }); + + test('a preregistration frozen before the result checks keeps its rules; a later freeze date does not', () => { + const old = prereg({ decisions: '', scoring: '', frozen: '2026-10-31' }); + expect(checkPrereg(old)).toMatchObject({ ok: true, grandfathered: true, frozen: '2026-10-31', missing: [] }); + expect(checkPrereg(prereg({ decisions: '', scoring: '', frozen: '2026-11-15' })).missing).toEqual(['Decisions', 'Scoring']); + }); +}); + +describe('judge labels', () => { + const scoring = { judge: 'gpt-6-astra', labels: 40, agreement: 0.6, errors: [] }; + test("Cohen's kappa: perfect, chance and undefined agreement", () => { + expect(cohensKappa([['a', 'a'], ['b', 'b']])).toBe(1); + expect(cohensKappa([['a', 'a'], ['a', 'b'], ['b', 'a'], ['b', 'b']])).toBe(0); + expect(cohensKappa([['a', 'a'], ['a', 'a']])).toBeNull(); + }); + + test('40 labels at or above the bar pass; fewer labels, a low kappa, one class or a repeated id fail', () => { + expect(checkJudgeLabels(scoring, labels(40, 4))).toMatchObject({ ok: true, n: 40, kappa: 0.8 }); + expect(checkJudgeLabels(scoring, labels(39)).problems).toEqual(['39 labelled outputs, needs 40']); + expect(checkJudgeLabels(scoring, labels(40, 10)).problems).toEqual(['kappa 0.50 is below the bar 0.6']); + expect(checkJudgeLabels(scoring, labels(40, 0, () => 'pass')).problems[0]).toContain('one class'); + expect(checkJudgeLabels(scoring, labels(40) + labels(1)).problems).toContain('id item-0 is labelled twice'); + expect(checkJudgeLabels({ ...scoring, labels: 60 }, labels(40)).problems).toEqual(['40 labelled outputs, needs 60']); + }); + + test('a row whose id, human or judge value is null, an object or empty does not count toward the bar', () => { + const bad = ['{"id": "x-1", "human": null, "judge": "pass"}', '{"id": "x-2", "human": "pass", "judge": {"v": 1}}', '{"id": {}, "human": "pass", "judge": "pass"}', '{"id": "x-4", "human": "", "judge": "pass"}']; + const r = checkJudgeLabels(scoring, labels(39) + bad.join('\n') + '\n'); + expect(r).toMatchObject({ ok: false, n: 39 }); + expect(r.problems.filter(p => p.includes('each a string, number or boolean'))).toHaveLength(4); + }); +}); + +describe('results --check: the result checks', () => { + const ROWS = table('| arm | passed | answer-only failures | failures |', '| claude-opus-5-5 | 7/9 | 2 | 3 |', '| claude-opus-5-5#plain | 5/9 | 4 | 4 |'); + test('a judged result counts only with passing labels', () => { + expect(checkResults(prereg(), ROWS).issues).toEqual([{ code: 'EVAL_JUDGE_UNCHECKED', message: 'the preregistration names judge gpt-6-astra; pass --labels ' }]); + expect(checkResults(prereg(), ROWS, labels(40, 10)).issues[0]!.code).toBe('EVAL_JUDGE_UNCHECKED'); + expect(checkResults(prereg(), ROWS, labels(40))).toMatchObject({ ok: true, issues: [] }); + expect(checkResults(prereg({ scoring: SCORING('none') }), ROWS).ok).toBe(true); + }); + + test('a zero in the arm table needs a Diagnostics counter shown to find a planted case', () => { + const zero = table('| arm | skill opens |', '| claude-opus-5-5 | 4 |', '| claude-opus-5-5#plain | 0 |'); + const diag = (n: number) => `## Diagnostics\nsummarizer: sh count.sh {fixture}\nfixture: planted.jsonl\n\n| diagnostic | expected |\n|---|---|\n| skill opens | ${n} |\n`; + expect(checkResults(prereg({ scoring: SCORING('none') }), zero).issues.map(i => i.code)).toEqual(['EVAL_REPORT_UNPLANTED_ZERO']); + expect(checkResults(prereg({ scoring: SCORING('none'), diagnostics: diag(0) }), zero).issues.map(i => i.code)).toEqual(['EVAL_REPORT_UNPLANTED_ZERO']); + expect(checkResults(prereg({ scoring: SCORING('none'), diagnostics: diag(5) }), zero).ok).toBe(true); + for (const cell of ['0%', '0/9', '0.0']) expect(checkResults(prereg({ scoring: SCORING('none') }), zero.replace('| 0 |', `| ${cell} |`)).ok, cell).toBe(false); + expect(checkResults(prereg({ scoring: SCORING('none') }), zero.replace('| 0 |', '| 0/6/3 |')).ok).toBe(true); + }); + + test('a zero in any table counts, not only the table that holds the arms', () => { + const arms = table('| arm | skill opens |', '| claude-opus-5-5 | 4 |', '| claude-opus-5-5#plain | 2 |'); + const other = table('| task | timeouts |', '| t1 | 0 |'); + expect(checkResults(prereg({ scoring: SCORING('none') }), arms + '\n' + other).issues).toEqual([{ code: 'EVAL_REPORT_UNPLANTED_ZERO', message: 'column "timeouts" reports a zero, and no Diagnostics counter by that name was shown to find a planted case' }]); + }); + + test('with stack: none, Decisions and Scoring errors still refuse the results', () => { + const r = checkResults(prereg({ scoring: SCORING('claude-fable-5-2') }), ROWS, labels(40)); + expect(r.ok).toBe(false); + expect(r.issues.filter(i => i.code === 'PREREG_INCOMPLETE').map(i => i.message)).toEqual(['## Scoring: judge claude-fable-5-2 is the same model family (anthropic) as arm claude-opus-5-5; use a judge from another family', '## Scoring: judge claude-fable-5-2 is the same model family (anthropic) as arm claude-opus-5-5#plain; use a judge from another family']); + expect(checkResults(prereg({ decisions: '## Decisions\n- we will learn a lot\n' }), ROWS, labels(40)).issues.map(i => i.code)).toContain('PREREG_INCOMPLETE'); + }); + + test('a failures column needs an answer-only column in the same table', () => { + const bare = table('| arm | failures |', '| claude-opus-5-5 | 3 |', '| claude-opus-5-5#plain | 4 |'); + expect(checkResults(prereg({ scoring: SCORING('none') }), bare).issues).toEqual([{ code: 'EVAL_REPORT_NO_ANSWER_ONLY', message: 'column "failures" counts failures with no answer-only column beside it in the same table' }]); + expect(checkResults(prereg({ scoring: SCORING('none') }), ROWS).ok).toBe(true); + }); + + test('a grandfathered preregistration skips the result checks', () => { + const bare = table('| arm | failures |', '| claude-opus-5-5 | 0 |', '| claude-opus-5-5#plain | 4 |'); + expect(checkResults(prereg({ decisions: '', scoring: '', frozen: '2026-10-31' }), bare).ok).toBe(true); + }); +}); + +describe('gstack-eval-plan judge --check and results --labels', () => { + const run = (args: string[], files: Record) => { + const d = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-result-checks-')); + dirs.push(d); + for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(d, name), text); + const r = spawnSync(BIN, args, { cwd: d, encoding: 'utf8', timeout: 60_000 }); + return { code: r.status, out: r.stdout ?? '', err: r.stderr ?? '' }; + }; + + test('judge --check prints JUDGE_AGREEMENT and exits 1 with EVAL_JUDGE_UNCHECKED below the bar', () => { + const ok = run(['judge', '--check', 'prereg.md', '--labels', 'labels.jsonl'], { 'prereg.md': prereg(), 'labels.jsonl': labels(40, 4) }); + expect(ok.code, ok.err).toBe(0); + expect(ok.out).toBe('JUDGE_AGREEMENT: ok judge=gpt-6-astra n=40/40 kappa=0.80 bar=0.6\n'); + const low = run(['judge', '--check', 'prereg.md', '--labels', 'labels.jsonl'], { 'prereg.md': prereg(), 'labels.jsonl': labels(20) }); + expect(low.code).toBe(1); + expect(low.out).toBe('JUDGE_AGREEMENT: unchecked judge=gpt-6-astra n=20/40 kappa=1.00 bar=0.6\n'); + expect(low.err).toContain('(EVAL_JUDGE_UNCHECKED)'); + expect(run(['judge', '--check', 'prereg.md', '--labels', 'labels.jsonl'], { 'prereg.md': prereg({ scoring: SCORING('none') }), 'labels.jsonl': labels(40) }).code).toBe(2); + }); + + test('results --check takes --labels before or after the results file and prints one code per kind', () => { + const files = { 'prereg.md': prereg(), 'results.md': table('| arm | failures |', '| claude-opus-5-5 | 3 |', '| claude-opus-5-5#plain | 0 |'), 'labels.jsonl': labels(40) }; + const r = run(['results', '--check', 'prereg.md', '--labels', 'labels.jsonl', 'results.md'], files); + expect(r.code).toBe(1); + expect(r.out).toBe('RESULTS: incomplete no_gstack_rows=0/0 rows=0/0 file=results.md\nJUDGE_AGREEMENT: ok judge=gpt-6-astra n=40/40 kappa=1.00 bar=0.6\n'); + expect(r.err).toContain('(EVAL_REPORT_UNPLANTED_ZERO)'); + expect(r.err).toContain('(EVAL_REPORT_NO_ANSWER_ONLY)'); + expect(r.err).not.toContain('(EVAL_REPORT_NO_GSTACK_ROW)'); + const noLabels = run(['results', '--check', 'prereg.md', 'results.md'], files); + expect(noLabels.err).toContain('(EVAL_JUDGE_UNCHECKED)'); + }); +}); diff --git a/test/eval-plan-results.test.ts b/test/eval-plan-results.test.ts index b4a2207a41c..3786453948b 100644 --- a/test/eval-plan-results.test.ts +++ b/test/eval-plan-results.test.ts @@ -14,7 +14,8 @@ const BIN = path.resolve(import.meta.dir, '..', 'bin', 'gstack-eval-plan'); const dirs: string[] = []; afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); -const BASE = ['Bars', 'Decoys', 'Stop rules', 'Held-out exposure'].map(s => `## ${s}\n- filled in\n`).join('\n'); +const RESULT_SECTIONS = '## Decisions\nif the variant passes more items: adopt it\nif there is no difference: keep the default\n\n## Scoring\njudge: none\npaired: yes\ninterval: 95%\nmdd: 2 of 9 items\n'; +const BASE = ['Bars', 'Decoys', 'Stop rules', 'Held-out exposure'].map(s => `## ${s}\n- filled in\n`).join('\n') + '\n' + RESULT_SECTIONS; const PREREG = BASE + ` ## Arms - claude-opus-5-5#review-g default settings diff --git a/test/exercised-map.test.ts b/test/exercised-map.test.ts index eec13e115d2..8704fc1df91 100644 --- a/test/exercised-map.test.ts +++ b/test/exercised-map.test.ts @@ -327,6 +327,7 @@ describe('parity with the measured prototype', () => { const REVIEWED_SUPERSET: Record = { setup: './setup, $ROOT/setup and join(..., "setup") exec edges (plan A2-2); setup is a full-gate file, so the closure stops there', 'lib/bun-isolation.ts': 'GSTA-56: every bun launcher (script-invocation, restamp, qa-deadline, the hooks) imports it, so it reaches every consumer of those launchers', + 'lib/eval-plan-checks.ts': 'lib/eval-plan.ts and bin/gstack-eval-plan import it (the result checks), so it reaches every consumer of the eval planner', 'lib/ship-receipt-docs.ts': 'bin/gstack-ship-receipt imports it (the docs audit record and doc caps), so it reaches every consumer of the receipt binary', 'lib/ship-receipt-prose.ts': 'bin/gstack-ship-receipt imports it (read --check-prose), so it reaches every consumer of the receipt binary', 'lib/default-base.ts': 'GST-511/GST-774: lib/ship-policy.ts (resolveBaseBranch), lib/gate-diff/git.ts, lib/pregate/context.ts, lib/ship-receipt-depth.ts and the review-plan, gate-diff, pregate, docs-candidate and diff-scope bins import or run it, so it reaches every consumer of those readers', diff --git a/test/fixtures/arm-benchmark/PREREG.md b/test/fixtures/arm-benchmark/PREREG.md index f484ac864f0..cc1e4987e0d 100644 --- a/test/fixtures/arm-benchmark/PREREG.md +++ b/test/fixtures/arm-benchmark/PREREG.md @@ -2,6 +2,8 @@ Frozen on 2026-10-31 before the first paid run of this design: three with/without pairs per task, a no-gstack arm on the pinned model, a spend ledger, and a paired judge that decides only after calibration. The instrument gates nothing; its assertions cover harness mechanics only. +frozen: 2026-10-31 + ## Bars - Metric order per arm: functional checks pass rate (tasks with an oracle), then paired over_engineering (wins/ties/losses and mean over both orders), then the per-diff armJudge mean (the no-loss diagnostic), then net LOC and tokens. - Decider bar, paired-judge calibration (`arm-pair`): before the paid run, `bun run scripts/judge-calibration.ts run --config arm-pair --budget 8` on the 16 paired items in test/fixtures/judge-calibration/arm-pair/corpus.json. The bar is `pairCalibrationBar` (test/helpers/arm-pair-judge.ts) on the `new` panels: all 6 crossing pairs decided in both orders for the less over-engineered diff, so 6/6 correct, 0 reversed, 0 tied, 0 incomplete. Position bias on the 4 identical-diff pairs is reported, not gated. diff --git a/test/fixtures/model-panel/PREREG.md b/test/fixtures/model-panel/PREREG.md index f5274e422f5..5d715a1c831 100644 --- a/test/fixtures/model-panel/PREREG.md +++ b/test/fixtures/model-panel/PREREG.md @@ -8,6 +8,8 @@ seen. Instrument: test/skill-e2e-model-panel.test.ts with test/helpers/model-panel-harness.ts; free selftest: test/model-panel-selftest.test.ts. +frozen: 2026-10-31 + ## Bars - Pass rate per arm: scored (non-INFRA) cells whose hidden deterministic check passes, with a Wilson 95% interval. Descriptive only: the panel gates nothing and no arm "wins". - Publication floor: an arm needs PANEL_MIN_COMPLETED = 12 scored cells before any number about it is published; below that its row says INCOMPLETE. diff --git a/test/helpers/placeholder-allowlist.ts b/test/helpers/placeholder-allowlist.ts index d9387865b47..5bee10db23a 100644 --- a/test/helpers/placeholder-allowlist.ts +++ b/test/helpers/placeholder-allowlist.ts @@ -149,6 +149,7 @@ export const IDENTIFIER_PLACEHOLDERS: Record = { '': { grammar: PATH, what: 'bound plan file path' }, '': { grammar: PATH, what: 'preregistration file path' }, '': { grammar: PATH, what: 'results table file path' }, + '': { grammar: PATH, what: 'hand-label JSONL file path' }, '': { grammar: PATH, what: 'sketch directory printed by an earlier block' }, '': { grammar: PATH, what: 'finalized HTML path' }, '': { grammar: PATH, what: 'saved page HTML path' }, diff --git a/test/pricing-eval-plan.test.ts b/test/pricing-eval-plan.test.ts index 71f78d20b83..fa721ce05fb 100644 --- a/test/pricing-eval-plan.test.ts +++ b/test/pricing-eval-plan.test.ts @@ -57,7 +57,9 @@ describe('preregistration', () => { expect(check.empty.length).toBe(PREREG_SECTIONS.length); expect(check.ok).toBe(false); expect(PREREG_SECTIONS).toContain('Comparison'); - const filled = t.replace(/^(##\s+.+)$/gm, '$1\n- filled in').replace('## Comparison\n- filled in', '## Comparison\nstack: none\nwhy: one arm, no skill stack'); + const filled = t.replace(/^(##\s+.+)$/gm, '$1\n- filled in').replace('## Comparison\n- filled in', '## Comparison\nstack: none\nwhy: one arm, no skill stack') + .replace('## Decisions\n- filled in', '## Decisions\nif the bar is met: run the full set\nif the bar is missed: stop and fix the scorer') + .replace('## Scoring\n- filled in', '## Scoring\njudge: none'); expect(checkPrereg(filled)).toMatchObject({ ok: true, missing: [], empty: [] }); expect(checkPrereg('# nothing here\n').missing).toEqual([...PREREG_SECTIONS]); }); From 28822af38c4bfc2e544668c8c7ff36f0edc61015 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 16 Nov 2026 10:57:22 +0800 Subject: [PATCH 06/62] Load the never-print-secrets rule in every skill on every host, with the commands it missed (GST-2753) (#4382) * Load the never-print-secrets rule in every skill on every host, with the commands it missed (GST-2753) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Point the shared CI-wait rule at gstack-pr-wait and name the missed secret-printing commands The Ground Rules section told every skill to wait with gh pr checks --watch, which spends the shared GitHub GraphQL quota gstack moved off; it now names gstack-pr-wait. The banned list also covers ps aux and ps -ef, set -x, git config -l and an export $(...) that expands to a bare export. Size caps raised to the measured +70 bytes. Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Say which skills carry the new rule in its release note Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- SKILL.md | 5 +++ autoplan/SKILL.md | 2 +- autoplan/sections/preamble.md | 7 ++- benchmark-models/SKILL.md | 5 +++ benchmark/SKILL.md | 5 +++ browse/SKILL.md | 5 +++ canary/SKILL.md | 2 +- canary/sections/preamble.md | 7 ++- captain/SKILL.md | 2 +- captain/sections/preamble.md | 7 ++- .../never-print-secrets-shared-rule.md | 1 + codex/SKILL.md | 2 +- codex/sections/preamble.md | 7 ++- context-restore/SKILL.md | 2 +- context-restore/sections/preamble.md | 7 ++- context-save/SKILL.md | 2 +- context-save/sections/preamble.md | 7 ++- design-consultation/SKILL.md | 2 +- design-consultation/sections/preamble.md | 7 ++- design-html/SKILL.md | 2 +- design-html/sections/preamble.md | 7 ++- design-motion/SKILL.md | 2 +- design-motion/sections/preamble.md | 7 ++- design-review/SKILL.md | 2 +- design-review/sections/preamble.md | 7 ++- design-shotgun/SKILL.md | 2 +- design-shotgun/sections/preamble.md | 7 ++- devex-review/SKILL.md | 2 +- devex-review/sections/preamble.md | 7 ++- diagram/SKILL.md | 5 +++ docs/loadouts.md | 4 +- document-generate/SKILL.md | 2 +- document-generate/sections/preamble.md | 7 ++- document-release/SKILL.md | 2 +- document-release/sections/preamble.md | 7 ++- eval-plan/SKILL.md | 2 +- eval-plan/sections/preamble.md | 7 ++- health/SKILL.md | 2 +- health/sections/preamble.md | 7 ++- ios-clean/SKILL.md | 2 +- ios-clean/sections/preamble.md | 7 ++- ios-design-review/SKILL.md | 2 +- ios-design-review/sections/preamble.md | 7 ++- ios-fix/SKILL.md | 2 +- ios-fix/sections/preamble.md | 7 ++- ios-qa/SKILL.md | 2 +- ios-qa/sections/preamble.md | 7 ++- ios-sync/SKILL.md | 2 +- ios-sync/sections/preamble.md | 7 ++- land-and-deploy/SKILL.md | 2 +- land-and-deploy/sections/preamble.md | 7 ++- landing-report/SKILL.md | 2 +- landing-report/sections/preamble.md | 7 ++- learn/SKILL.md | 2 +- learn/sections/preamble.md | 7 ++- make-pdf/SKILL.md | 5 +++ modernize/SKILL.md | 2 +- modernize/sections/preamble.md | 7 ++- modules/loadouts.json | 1 + office-hours/SKILL.md | 2 +- office-hours/sections/preamble.md | 7 ++- open-gstack-browser/SKILL.md | 5 +++ pair-agent/SKILL.md | 2 +- pair-agent/sections/preamble.md | 7 ++- plan-ceo-review/SKILL.md | 2 +- plan-ceo-review/sections/preamble.md | 7 ++- plan-design-review/SKILL.md | 2 +- plan-design-review/sections/preamble.md | 7 ++- plan-devex-review/SKILL.md | 2 +- plan-devex-review/sections/preamble.md | 7 ++- plan-eng-review/SKILL.md | 2 +- plan-eng-review/sections/preamble.md | 7 ++- plan-tune/SKILL.md | 2 +- plan-tune/sections/preamble.md | 7 ++- qa-only/SKILL.md | 2 +- qa-only/sections/preamble.md | 7 ++- qa/SKILL.md | 2 +- qa/sections/preamble.md | 7 ++- retro/SKILL.md | 2 +- retro/sections/preamble.md | 7 ++- review/SKILL.md | 2 +- review/sections/preamble.md | 7 ++- runaway-stopper/SKILL.md | 5 +++ scrape/SKILL.md | 5 +++ scripts/resolvers/preamble.ts | 2 + .../preamble/generate-ground-rules.ts | 23 ++++++++++ setup-browser-cookies/SKILL.md | 5 +++ setup-deploy/SKILL.md | 2 +- setup-deploy/sections/preamble.md | 7 ++- setup-gbrain/SKILL.md | 2 +- setup-gbrain/sections/preamble.md | 7 ++- ship/SKILL.md | 2 +- ship/sections/preamble.md | 7 ++- skillify/SKILL.md | 2 +- skillify/sections/preamble.md | 7 ++- spec/SKILL.md | 2 +- spec/sections/preamble.md | 7 ++- sync-gbrain/SKILL.md | 2 +- sync-gbrain/sections/preamble.md | 7 ++- test-audit/SKILL.md | 2 +- test-audit/sections/preamble.md | 7 ++- test/fixtures/context-budget.json | 2 +- test/fixtures/golden/agy-ship-SKILL.md | 2 +- test/fixtures/golden/claude-ship-SKILL.md | 2 +- test/fixtures/golden/codex-ship-SKILL.md | 2 +- test/fixtures/golden/factory-ship-SKILL.md | 2 +- test/ground-rules.test.ts | 43 +++++++++++++++++++ test/helpers/carve-guards.ts | 20 ++++----- .../ship/never-print-secrets-shared-rule.json | 4 ++ ubicloud/SKILL.md | 2 +- ubicloud/sections/preamble.md | 7 ++- verify/SKILL.md | 5 +++ write-skill/SKILL.md | 2 +- write-skill/sections/preamble.md | 7 ++- 114 files changed, 461 insertions(+), 107 deletions(-) create mode 100644 changelog.d/never-print-secrets-shared-rule.md create mode 100644 scripts/resolvers/preamble/generate-ground-rules.ts create mode 100644 test/ground-rules.test.ts create mode 100644 test/size-ledger/ship/never-print-secrets-shared-rule.json diff --git a/SKILL.md b/SKILL.md index 386f4b08def..300fc282e4f 100644 --- a/SKILL.md +++ b/SKILL.md @@ -94,6 +94,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/autoplan/SKILL.md b/autoplan/SKILL.md index 6fed1790541..cb0cef8e099 100644 --- a/autoplan/SKILL.md +++ b/autoplan/SKILL.md @@ -34,7 +34,7 @@ hooks: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/autoplan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/autoplan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/autoplan/sections/preamble.md b/autoplan/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/autoplan/sections/preamble.md +++ b/autoplan/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/benchmark-models/SKILL.md b/benchmark-models/SKILL.md index 0f344471861..88f3f732147 100644 --- a/benchmark-models/SKILL.md +++ b/benchmark-models/SKILL.md @@ -94,6 +94,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/benchmark/SKILL.md b/benchmark/SKILL.md index ee09bbba430..1795f5270a8 100644 --- a/benchmark/SKILL.md +++ b/benchmark/SKILL.md @@ -95,6 +95,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/browse/SKILL.md b/browse/SKILL.md index ca934a60be6..fbd8c6cc0fc 100644 --- a/browse/SKILL.md +++ b/browse/SKILL.md @@ -94,6 +94,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/canary/SKILL.md b/canary/SKILL.md index 0ef61ffd7fd..643b31b0b9c 100644 --- a/canary/SKILL.md +++ b/canary/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/canary/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/canary/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/canary/sections/preamble.md b/canary/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/canary/sections/preamble.md +++ b/canary/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/captain/SKILL.md b/captain/SKILL.md index b10edc5ab89..6ab00a2b465 100644 --- a/captain/SKILL.md +++ b/captain/SKILL.md @@ -26,7 +26,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/captain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/captain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/captain/sections/preamble.md b/captain/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/captain/sections/preamble.md +++ b/captain/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/changelog.d/never-print-secrets-shared-rule.md b/changelog.d/never-print-secrets-shared-rule.md new file mode 100644 index 00000000000..0288caa4853 --- /dev/null +++ b/changelog.d/never-print-secrets-shared-rule.md @@ -0,0 +1 @@ +- **Every skill that loads the shared preamble, on every host, now says never to print a whole environment, git config or process table.** The rule used to load only in the Capy wrapper, and its list missed `git config --list`, which can print a proxy's login header, process or container listings that show arguments or environment (`ps aux`, `ps -ef`, `ps -o args`, `docker top ... args`, `docker inspect`), where run tokens ride, and `set -x` or an `export $(...)` that expands to a bare `export`. A new Ground Rules section in the shared preamble lists these commands and the safe forms, which are to read one value by name (`git config --get `), check a variable is set without printing it, and list processes by name or pid. It also says to wait on CI with one `gstack-pr-wait` call instead of a poll loop or `gh pr checks --watch`, which spends the shared GitHub GraphQL quota. The section is pinned, so no model loadout drops it. diff --git a/codex/SKILL.md b/codex/SKILL.md index de293bd301e..45613467904 100644 --- a/codex/SKILL.md +++ b/codex/SKILL.md @@ -20,7 +20,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/codex/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/codex/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/codex/sections/preamble.md b/codex/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/codex/sections/preamble.md +++ b/codex/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/context-restore/SKILL.md b/context-restore/SKILL.md index ee68c875206..cafd34abd3a 100644 --- a/context-restore/SKILL.md +++ b/context-restore/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-restore/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-restore/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/context-restore/sections/preamble.md b/context-restore/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/context-restore/sections/preamble.md +++ b/context-restore/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/context-save/SKILL.md b/context-save/SKILL.md index 05c13659a0d..10a4e8ca6ea 100644 --- a/context-save/SKILL.md +++ b/context-save/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-save/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-save/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/context-save/sections/preamble.md b/context-save/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/context-save/sections/preamble.md +++ b/context-save/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/design-consultation/SKILL.md b/design-consultation/SKILL.md index 71ecbe7df2f..7d545778d09 100644 --- a/design-consultation/SKILL.md +++ b/design-consultation/SKILL.md @@ -45,7 +45,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-consultation/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-consultation/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-consultation/sections/preamble.md b/design-consultation/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/design-consultation/sections/preamble.md +++ b/design-consultation/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/design-html/SKILL.md b/design-html/SKILL.md index 57ee215e5ea..400cb285cf2 100644 --- a/design-html/SKILL.md +++ b/design-html/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-html/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-html/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-html/sections/preamble.md b/design-html/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/design-html/sections/preamble.md +++ b/design-html/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/design-motion/SKILL.md b/design-motion/SKILL.md index 01d2938cdd1..f9562771786 100644 --- a/design-motion/SKILL.md +++ b/design-motion/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-motion/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-motion/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-motion/sections/preamble.md b/design-motion/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/design-motion/sections/preamble.md +++ b/design-motion/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/design-review/SKILL.md b/design-review/SKILL.md index 8c6e3537a13..7713ee0f5d4 100644 --- a/design-review/SKILL.md +++ b/design-review/SKILL.md @@ -23,7 +23,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-review/sections/preamble.md b/design-review/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/design-review/sections/preamble.md +++ b/design-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/design-shotgun/SKILL.md b/design-shotgun/SKILL.md index 803fa51a662..cf888a102fd 100644 --- a/design-shotgun/SKILL.md +++ b/design-shotgun/SKILL.md @@ -39,7 +39,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-shotgun/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-shotgun/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-shotgun/sections/preamble.md b/design-shotgun/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/design-shotgun/sections/preamble.md +++ b/design-shotgun/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/devex-review/SKILL.md b/devex-review/SKILL.md index 1dc425e3c21..d353ba1bba4 100644 --- a/devex-review/SKILL.md +++ b/devex-review/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/devex-review/sections/preamble.md b/devex-review/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/devex-review/sections/preamble.md +++ b/devex-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/diagram/SKILL.md b/diagram/SKILL.md index 0a050b64761..59a7e6455ea 100644 --- a/diagram/SKILL.md +++ b/diagram/SKILL.md @@ -97,6 +97,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/docs/loadouts.md b/docs/loadouts.md index 50d4a24aa10..755a700bce4 100644 --- a/docs/loadouts.md +++ b/docs/loadouts.md @@ -9,7 +9,7 @@ One model has its own loadout: Claude Opus 5.5 gets `lite` ([below](#lite-on-cla | Term | Meaning | |---|---| | Module | One of four kinds. `skill:` is a whole skill. `section:/` is one entry of `/sections/manifest.json`. `overlay:` is one `model-overlays/.md`; excluding a base overlay also removes the base's text from every overlay that inherits it; the inheriting overlay's own text stays. `preamble:` is one piece of the shared preamble (`PREAMBLE_PIECES` in `scripts/resolvers/preamble.ts`). | -| Pinned | A module no loadout can remove where `full` renders it: the start command, plan-mode rules, the question format, completion status, the Claims Need Evidence rule, the unattended profile, /ship's review army and adversarial pass, the router and `/gstack-upgrade`. A skill's `preamble-tier` still applies, so a tier-1 skill has no question-format section in any loadout. | +| Pinned | A module no loadout can remove where `full` renders it: the start command, plan-mode rules, the question format, completion status, the Claims Need Evidence rule, the Ground Rules (never print a whole environment, git config or process table), the unattended profile, /ship's review army and adversarial pass, the router and `/gstack-upgrade`. A skill's `preamble-tier` still applies, so a tier-1 skill has no question-format section in any loadout. | | Rung | How much scaffolding a model gets: `frontier`, `strong`, `mid`, `light`, or `unknown`. Model ids are matched after lowercasing and stripping a `provider/` prefix (`anthropic/claude-haiku-5-5` is `mid`). Rungs are separate from the frontier/smart tiers in `lib/model-catalog.ts`, which choose which model runs a role. | | Loadout | `{ base, exclude, include, preamble_tier_max, note }`. `full` (include `*`) is always present. An unknown model gets `default.unknown`, which is `full`. | | Model map | `models` in `modules/loadouts.json`: an exact model id to a loadout, checked before rungs. The id also matches its dated snapshot (`-YYYYMMDD`) and `-latest`, never a point release or any other suffix (`claude-opus-5-5` matches `claude-opus-5-5-20261101`, not `claude-opus-5-50` or `claude-opus-5-5-1`). | @@ -40,7 +40,7 @@ bin/gstack-modules install --full-root "$HOME/.claude/skills" --model claude-opu ## Lite on Claude Opus 5.5 -`lite` is `full` minus ten coaching pieces of the shared preamble: voice, writing style, completeness, confusion, context health, question tuning, search before building, repo mode, brain health and context recovery. It keeps every pinned piece, including the Claims Need Evidence rule (GST-944: the honest-work design never retires it while gstack reports evidence, and it adds 804 bytes back to lite's 16,175-byte shared preamble), the upgrade check (the PROACTIVE and skill-prefix rules) and brain sync (the privacy stop-gate). Only `claude-opus-5-5` maps to it, because only Opus 5.5 has been measured: office-hours showed no loss on Opus 5.5 (GSTA-161 preamble run), and the land-and-deploy confirmation (GSTA-161, PR 1b) compared full, lite and no gstack on the same tasks. Haiku 5.5 leaned slightly against a larger cut on the same office-hours run, so small models stay on `full`. Two skills point at a preamble section lite drops: office-hours and plan-ceo-review name ETHOS.md through the "Search Before Building" section, so under lite they find ETHOS.md in the gstack checkout instead. +`lite` is `full` minus ten coaching pieces of the shared preamble: voice, writing style, completeness, confusion, context health, question tuning, search before building, repo mode, brain health and context recovery. It keeps every pinned piece, including the Ground Rules, the Claims Need Evidence rule (GST-944: the honest-work design never retires it while gstack reports evidence, and it adds 804 bytes back to lite's 16,175-byte shared preamble), the upgrade check (the PROACTIVE and skill-prefix rules) and brain sync (the privacy stop-gate). Only `claude-opus-5-5` maps to it, because only Opus 5.5 has been measured: office-hours showed no loss on Opus 5.5 (GSTA-161 preamble run), and the land-and-deploy confirmation (GSTA-161, PR 1b) compared full, lite and no gstack on the same tasks. Haiku 5.5 leaned slightly against a larger cut on the same office-hours run, so small models stay on `full`. Two skills point at a preamble section lite drops: office-hours and plan-ceo-review name ETHOS.md through the "Search Before Building" section, so under lite they find ETHOS.md in the gstack checkout instead. ### How gstack picks a loadout diff --git a/document-generate/SKILL.md b/document-generate/SKILL.md index 1c0dba74304..a1c9da8ba2e 100644 --- a/document-generate/SKILL.md +++ b/document-generate/SKILL.md @@ -25,7 +25,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-generate/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-generate/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/document-generate/sections/preamble.md b/document-generate/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/document-generate/sections/preamble.md +++ b/document-generate/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/document-release/SKILL.md b/document-release/SKILL.md index 437e8ffe59b..3d1a91dc177 100644 --- a/document-release/SKILL.md +++ b/document-release/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-release/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-release/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/document-release/sections/preamble.md b/document-release/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/document-release/sections/preamble.md +++ b/document-release/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/eval-plan/SKILL.md b/eval-plan/SKILL.md index 9f7d7ea0238..c7665440e5d 100644 --- a/eval-plan/SKILL.md +++ b/eval-plan/SKILL.md @@ -24,7 +24,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/eval-plan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/eval-plan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/eval-plan/sections/preamble.md b/eval-plan/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/eval-plan/sections/preamble.md +++ b/eval-plan/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/health/SKILL.md b/health/SKILL.md index ecde9b5f2ab..0df11a75b50 100644 --- a/health/SKILL.md +++ b/health/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/health/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/health/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/health/sections/preamble.md b/health/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/health/sections/preamble.md +++ b/health/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/ios-clean/SKILL.md b/ios-clean/SKILL.md index 099596af391..80b44691d12 100644 --- a/ios-clean/SKILL.md +++ b/ios-clean/SKILL.md @@ -20,7 +20,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-clean/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-clean/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-clean/sections/preamble.md b/ios-clean/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/ios-clean/sections/preamble.md +++ b/ios-clean/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/ios-design-review/SKILL.md b/ios-design-review/SKILL.md index 6000c79a51a..3d630daa35b 100644 --- a/ios-design-review/SKILL.md +++ b/ios-design-review/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-design-review/sections/preamble.md b/ios-design-review/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/ios-design-review/sections/preamble.md +++ b/ios-design-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/ios-fix/SKILL.md b/ios-fix/SKILL.md index f51d36ae002..af59d324473 100644 --- a/ios-fix/SKILL.md +++ b/ios-fix/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-fix/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-fix/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-fix/sections/preamble.md b/ios-fix/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/ios-fix/sections/preamble.md +++ b/ios-fix/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/ios-qa/SKILL.md b/ios-qa/SKILL.md index 2fb38d73539..f34efd2755a 100644 --- a/ios-qa/SKILL.md +++ b/ios-qa/SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-qa/sections/preamble.md b/ios-qa/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/ios-qa/sections/preamble.md +++ b/ios-qa/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/ios-sync/SKILL.md b/ios-sync/SKILL.md index 0597d91cbd5..1c49407a56d 100644 --- a/ios-sync/SKILL.md +++ b/ios-sync/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-sync/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-sync/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-sync/sections/preamble.md b/ios-sync/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/ios-sync/sections/preamble.md +++ b/ios-sync/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/land-and-deploy/SKILL.md b/land-and-deploy/SKILL.md index 0ad025054da..08a7ced13f4 100644 --- a/land-and-deploy/SKILL.md +++ b/land-and-deploy/SKILL.md @@ -20,7 +20,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/land-and-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/land-and-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/land-and-deploy/sections/preamble.md b/land-and-deploy/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/land-and-deploy/sections/preamble.md +++ b/land-and-deploy/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/landing-report/SKILL.md b/landing-report/SKILL.md index 449d24b807f..b07a98cf36d 100644 --- a/landing-report/SKILL.md +++ b/landing-report/SKILL.md @@ -20,7 +20,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/landing-report/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/landing-report/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/landing-report/sections/preamble.md b/landing-report/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/landing-report/sections/preamble.md +++ b/landing-report/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/learn/SKILL.md b/learn/SKILL.md index 12d5804da22..9c27e322b90 100644 --- a/learn/SKILL.md +++ b/learn/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/learn/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/learn/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/learn/sections/preamble.md b/learn/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/learn/sections/preamble.md +++ b/learn/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/make-pdf/SKILL.md b/make-pdf/SKILL.md index 4c164a68dd5..99c6957f07b 100644 --- a/make-pdf/SKILL.md +++ b/make-pdf/SKILL.md @@ -132,6 +132,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/modernize/SKILL.md b/modernize/SKILL.md index 7322016ed96..ed48ce690e9 100644 --- a/modernize/SKILL.md +++ b/modernize/SKILL.md @@ -23,7 +23,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/modernize/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/modernize/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/modernize/sections/preamble.md b/modernize/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/modernize/sections/preamble.md +++ b/modernize/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/modules/loadouts.json b/modules/loadouts.json index 9d3ebbc9915..74655626400 100644 --- a/modules/loadouts.json +++ b/modules/loadouts.json @@ -43,6 +43,7 @@ "preamble:ask-user-format", "preamble:completion-status", "preamble:evidence", + "preamble:ground-rules", "section:autoplan/unattended", "section:ship/review-army", "section:ship/adversarial" diff --git a/office-hours/SKILL.md b/office-hours/SKILL.md index 571f62648f4..c40b9193868 100644 --- a/office-hours/SKILL.md +++ b/office-hours/SKILL.md @@ -49,7 +49,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/office-hours/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/office-hours/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/office-hours/sections/preamble.md b/office-hours/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/office-hours/sections/preamble.md +++ b/office-hours/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/open-gstack-browser/SKILL.md b/open-gstack-browser/SKILL.md index 26fb660fd41..41371141641 100644 --- a/open-gstack-browser/SKILL.md +++ b/open-gstack-browser/SKILL.md @@ -94,6 +94,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/pair-agent/SKILL.md b/pair-agent/SKILL.md index 59f6a0113bb..45720575865 100644 --- a/pair-agent/SKILL.md +++ b/pair-agent/SKILL.md @@ -18,7 +18,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/pair-agent/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/pair-agent/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/pair-agent/sections/preamble.md b/pair-agent/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/pair-agent/sections/preamble.md +++ b/pair-agent/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/plan-ceo-review/SKILL.md b/plan-ceo-review/SKILL.md index e64c876ece9..69a4dec1efc 100644 --- a/plan-ceo-review/SKILL.md +++ b/plan-ceo-review/SKILL.md @@ -51,7 +51,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-ceo-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-ceo-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-ceo-review/sections/preamble.md b/plan-ceo-review/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/plan-ceo-review/sections/preamble.md +++ b/plan-ceo-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/plan-design-review/SKILL.md b/plan-design-review/SKILL.md index 9cdad3fa3f0..61b7a6363de 100644 --- a/plan-design-review/SKILL.md +++ b/plan-design-review/SKILL.md @@ -51,7 +51,7 @@ Recommendation: A when a branch diff exists, otherwise B. Reply with A, B, or C. ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (after scope gate) diff --git a/plan-design-review/sections/preamble.md b/plan-design-review/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/plan-design-review/sections/preamble.md +++ b/plan-design-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/plan-devex-review/SKILL.md b/plan-devex-review/SKILL.md index b9e9f11ab30..cbe3a2fe1ef 100644 --- a/plan-devex-review/SKILL.md +++ b/plan-devex-review/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-devex-review/sections/preamble.md b/plan-devex-review/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/plan-devex-review/sections/preamble.md +++ b/plan-devex-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/plan-eng-review/SKILL.md b/plan-eng-review/SKILL.md index 4061ac83ba2..745640604bc 100644 --- a/plan-eng-review/SKILL.md +++ b/plan-eng-review/SKILL.md @@ -63,7 +63,7 @@ Keep the reviewed target fixed when selecting the report destination. ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-eng-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-eng-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (after scope gate) diff --git a/plan-eng-review/sections/preamble.md b/plan-eng-review/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/plan-eng-review/sections/preamble.md +++ b/plan-eng-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/plan-tune/SKILL.md b/plan-tune/SKILL.md index d4e77e8186f..d30cacddce9 100644 --- a/plan-tune/SKILL.md +++ b/plan-tune/SKILL.md @@ -25,7 +25,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-tune/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-tune/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-tune/sections/preamble.md b/plan-tune/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/plan-tune/sections/preamble.md +++ b/plan-tune/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/qa-only/SKILL.md b/qa-only/SKILL.md index 34dfe43d6d5..4854a744afa 100644 --- a/qa-only/SKILL.md +++ b/qa-only/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa-only/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa-only/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/qa-only/sections/preamble.md b/qa-only/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/qa-only/sections/preamble.md +++ b/qa-only/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/qa/SKILL.md b/qa/SKILL.md index 5c8b6ab91da..38d95e46e62 100644 --- a/qa/SKILL.md +++ b/qa/SKILL.md @@ -22,7 +22,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/qa/sections/preamble.md b/qa/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/qa/sections/preamble.md +++ b/qa/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/retro/SKILL.md b/retro/SKILL.md index 49f2fad3871..87f44852c64 100644 --- a/retro/SKILL.md +++ b/retro/SKILL.md @@ -39,7 +39,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/retro/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/retro/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/retro/sections/preamble.md b/retro/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/retro/sections/preamble.md +++ b/retro/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/review/SKILL.md b/review/SKILL.md index 9b560bd6f83..a1809271b32 100644 --- a/review/SKILL.md +++ b/review/SKILL.md @@ -50,7 +50,7 @@ Finish only when each of these exists (contract v1): ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/review/sections/preamble.md b/review/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/review/sections/preamble.md +++ b/review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/runaway-stopper/SKILL.md b/runaway-stopper/SKILL.md index c94d9d91d00..18251352048 100644 --- a/runaway-stopper/SKILL.md +++ b/runaway-stopper/SKILL.md @@ -94,6 +94,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/scrape/SKILL.md b/scrape/SKILL.md index 50a2b158c5c..694f7f90530 100644 --- a/scrape/SKILL.md +++ b/scrape/SKILL.md @@ -95,6 +95,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/scripts/resolvers/preamble.ts b/scripts/resolvers/preamble.ts index 19575f9e62f..5194eca3780 100644 --- a/scripts/resolvers/preamble.ts +++ b/scripts/resolvers/preamble.ts @@ -49,6 +49,7 @@ import { generateCompletenessSection } from './preamble/generate-completeness-se import { generateConfusionProtocol } from './preamble/generate-confusion-protocol'; import { generateEvidenceDirective } from './preamble/generate-evidence-directive'; import { generateContextHealth } from './preamble/generate-context-health'; +import { generateGroundRules } from './preamble/generate-ground-rules'; // Tier 3+ repo mode + search import { generateRepoModeSection } from './preamble/generate-repo-mode-section'; @@ -108,6 +109,7 @@ export const PREAMBLE_PIECES: readonly PreamblePiece[] = [ { id: 'question-tuning', minTier: 2, render: generateQuestionTuning }, { id: 'repo-mode', minTier: 3, render: () => generateRepoModeSection() }, { id: 'search-before-building', minTier: 3, render: generateSearchBeforeBuildingSection }, + { id: 'ground-rules', minTier: 1, render: generateGroundRules }, { id: 'completion-status', minTier: 1, render: generateCompletionStatus }, ]; diff --git a/scripts/resolvers/preamble/generate-ground-rules.ts b/scripts/resolvers/preamble/generate-ground-rules.ts new file mode 100644 index 00000000000..0cc0270e5e5 --- /dev/null +++ b/scripts/resolvers/preamble/generate-ground-rules.ts @@ -0,0 +1,23 @@ +import type { TemplateContext } from '../types'; + +/** + * Ground Rules: the few habits every skill on every host carries, at every + * tier. Tier 1 skills inline it; tier 2+ skills read it from the shared + * sections/preamble.md. Each rule is here because agents broke it in real + * runs, so keep each bullet to one habit and the block at or under + * GROUND_RULES_MAX_BYTES; test/ground-rules.test.ts pins that budget. + */ +export const GROUND_RULES_MAX_BYTES = 850; + +export const GROUND_RULES_HEADING = '## Ground Rules'; + +export const GROUND_RULES_BULLETS = [ + 'Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid.', + 'Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`.', +] as const; + +export function generateGroundRules(_ctx?: TemplateContext): string { + return `${GROUND_RULES_HEADING} + +${GROUND_RULES_BULLETS.map(bullet => `- ${bullet}`).join('\n')}`; +} diff --git a/setup-browser-cookies/SKILL.md b/setup-browser-cookies/SKILL.md index c193d6c3fc7..aaf4ca2f16a 100644 --- a/setup-browser-cookies/SKILL.md +++ b/setup-browser-cookies/SKILL.md @@ -93,6 +93,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/setup-deploy/SKILL.md b/setup-deploy/SKILL.md index 1ad580a9fdd..c06932f5b47 100644 --- a/setup-deploy/SKILL.md +++ b/setup-deploy/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/setup-deploy/sections/preamble.md b/setup-deploy/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/setup-deploy/sections/preamble.md +++ b/setup-deploy/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.md index 97b60bed20c..7b4355c2dcb 100644 --- a/setup-gbrain/SKILL.md +++ b/setup-gbrain/SKILL.md @@ -23,7 +23,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/setup-gbrain/sections/preamble.md b/setup-gbrain/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/setup-gbrain/sections/preamble.md +++ b/setup-gbrain/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/ship/SKILL.md b/ship/SKILL.md index b439b8a3c6e..d6410127805 100644 --- a/ship/SKILL.md +++ b/ship/SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ship/sections/preamble.md b/ship/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/ship/sections/preamble.md +++ b/ship/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/skillify/SKILL.md b/skillify/SKILL.md index fbf9b99ab41..10477485e76 100644 --- a/skillify/SKILL.md +++ b/skillify/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/skillify/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/skillify/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/skillify/sections/preamble.md b/skillify/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/skillify/sections/preamble.md +++ b/skillify/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/spec/SKILL.md b/spec/SKILL.md index 722483a88de..1529f557a53 100644 --- a/spec/SKILL.md +++ b/spec/SKILL.md @@ -22,7 +22,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/spec/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/spec/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/spec/sections/preamble.md b/spec/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/spec/sections/preamble.md +++ b/spec/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/sync-gbrain/SKILL.md b/sync-gbrain/SKILL.md index b4d6ebfe46e..354f96e6f3d 100644 --- a/sync-gbrain/SKILL.md +++ b/sync-gbrain/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/sync-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/sync-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/sync-gbrain/sections/preamble.md b/sync-gbrain/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/sync-gbrain/sections/preamble.md +++ b/sync-gbrain/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/test-audit/SKILL.md b/test-audit/SKILL.md index 3072ea8cfb9..090bbb32276 100644 --- a/test-audit/SKILL.md +++ b/test-audit/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/test-audit/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/test-audit/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test-audit/sections/preamble.md b/test-audit/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/test-audit/sections/preamble.md +++ b/test-audit/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/test/fixtures/context-budget.json b/test/fixtures/context-budget.json index 5b2a295933c..b8f6d0ef303 100644 --- a/test/fixtures/context-budget.json +++ b/test/fixtures/context-budget.json @@ -56,7 +56,7 @@ "qa-only": 5726, "retro": 13484, "review": 15417, - "runaway-stopper": 3841, + "runaway-stopper": 3987, "scrape": 7312, "setup-browser-cookies": 3507, "setup-deploy": 5738, diff --git a/test/fixtures/golden/agy-ship-SKILL.md b/test/fixtures/golden/agy-ship-SKILL.md index 010b34e2e35..b84aa804577 100644 --- a/test/fixtures/golden/agy-ship-SKILL.md +++ b/test/fixtures/golden/agy-ship-SKILL.md @@ -12,7 +12,7 @@ description: | ## Shared preamble (load first) -This skill follows gstack shared preamble `6872f1ec4eb9` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `dc6688a6791f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md index b439b8a3c6e..d6410127805 100644 --- a/test/fixtures/golden/claude-ship-SKILL.md +++ b/test/fixtures/golden/claude-ship-SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.md index df8ef255ece..d535a44b4b2 100644 --- a/test/fixtures/golden/codex-ship-SKILL.md +++ b/test/fixtures/golden/codex-ship-SKILL.md @@ -12,7 +12,7 @@ description: | ## Shared preamble (load first) -This skill follows gstack shared preamble `2af24c2d75e4` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `1c66f530e65a` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.md index 83c053a6f73..31f0a060c7a 100644 --- a/test/fixtures/golden/factory-ship-SKILL.md +++ b/test/fixtures/golden/factory-ship-SKILL.md @@ -14,7 +14,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `99cd6cb5d373` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `fb2ce44dd505` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/ground-rules.test.ts b/test/ground-rules.test.ts new file mode 100644 index 00000000000..a4e1a38ee3c --- /dev/null +++ b/test/ground-rules.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from 'bun:test'; +import * as fs from 'fs'; +import * as path from 'path'; +import { + GROUND_RULES_HEADING, + GROUND_RULES_MAX_BYTES, + generateGroundRules, +} from '../scripts/resolvers/preamble/generate-ground-rules'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), 'utf-8'); + +describe('Ground Rules preamble section', () => { + const block = generateGroundRules(); + + test('stays within its byte budget', () => { + expect(Buffer.byteLength(block)).toBeLessThanOrEqual(GROUND_RULES_MAX_BYTES); + }); + + test('names every command that prints a whole environment, git config or process table, and the by-name alternative', () => { + for (const cmd of ['`env`', 'bare `printenv`', '`set` or `export`', '`export $(...)`', '`export -p`/`-n`', '`declare -p`/`-x`', '`typeset -p`', '`set -x`', '`git config --list`/`-l`', 'any `ps` with full args (`aux`, `-ef`, `-o args`)', '`docker top ... args`', '`docker inspect` Env']) { + expect(block).toContain(cmd); + } + expect(block).toContain('`git config --get `'); + expect(block).toContain('`[ -n "${NAME:-}" ] && echo set`'); + }); + + test('tells agents to wait on CI with gstack-pr-wait, not a polling loop or the GraphQL-spending gh watcher', () => { + expect(block).toContain('`gstack-pr-wait --until green`'); + expect(block).toContain('never a poll loop or `gh pr checks --watch`'); + }); + + test('renders inline in a tier 1 skill and in the shared preamble tier 2+ skills read', () => { + expect(read('browse/SKILL.md')).toContain(block); + expect(read('review/sections/preamble.md')).toContain(block); + }); + + test('is pinned, so no model loadout can drop it', () => { + const loadouts = JSON.parse(read('modules/loadouts.json')); + expect(loadouts.pinned).toContain('preamble:ground-rules'); + expect(block.startsWith(GROUND_RULES_HEADING)).toBe(true); + }); +}); diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.ts index 5971f0d454d..6539021aaac 100644 --- a/test/helpers/carve-guards.ts +++ b/test/helpers/carve-guards.ts @@ -359,7 +359,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 43_885, // GSTA-134 skill diet (2026-10-28): lowered from 80_533 to the measured skeleton after the second opinion and visual design moved to sections, 43,885. Before: GSTA-96 hoist (2026-10-26): lowered from 95_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 952 bytes; measured 79,581. Before: Office-hours + sketch outside voices include host guards and completion checks. + v1.91.19.0 wave: Q open-question prose form (#2729, approved Q3), DESIGN_READY --version probe (B4), Aside ~/.local/bin fallback (E7), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting (#3022) merged in; measured 89,684 (2026-10-03). + 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); skeleton measured 92,590 (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; skeleton measured 92,869 (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; skeleton measured 92,930 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; skeleton measured 92,756 (2026-10-07). Merged with the guard area: measured skeleton 93,099 (2026-10-07). + fix wave PR D: the Phase 4.5 builder-profile read before the session log (#2801) and the pre-telemetry design-doc check (#1049); measured skeleton 94,877 (2026-10-07). + 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). minUnionBytes: 115_800, // Phase 4 wave 4; measured union 118,175 mustContain: ['design doc', 'problem statement'], - maxSizeRatio: 1.1922, // GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the handoff menu, its default and the design-doc line name /plan-eng-review again, +42 B union; measured 156,298 / 131,110 = 1.19211, rounded up (before: 156,256 = 1.19179 on 81fb900). Before that: GSTA-134 (2026-10-28, raised from 1.1796 by GStack Minder as merge-queue owner): +1,662 B union: second-opinion question moved into the main file while CODEX_SECOND_OPINION keeps its copy; per-run load 73,248→43,885 B; measured 156,286 / 131,110 = 1.19202, rounded up. Before: + 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 149,758 / 131,110 = 1.1422 (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 150,037 / 131,110 = 1.1444 (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 150,098 / 131,110 = 1.1448 (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 150,011 / 131,110 = 1.1442 (2026-10-07). Merged with the guard area: measured 150,354 / 131,110 = 1.1468 (2026-10-07). + fix wave PR D: builder-profile read before the session log with Phase 6 using the carried values (#2801), the inline design doc before approval (#879) and the pre-telemetry design-doc check (#1049); measured 153,206 / 131,110 = 1.1685 (2026-10-07). + empty LAST_ASSIGNMENT/LAST_PROJECT guards in the welcome_back and regular greetings (backfilled profiles); measured 153,469 / 131,110 = 1.1705 (2026-10-08). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file and its own copies of shared sections; measured 160,989 / 131,110 = 1.2279 (2026-10-25). Before: 1.18. - GSTA-96 dedupe: the Q open-question form is office-hours' own appended subsection, so its copies of the shared Format and fallback subsections go; measured 154,653 / 131,110 = 1.1796 (2026-10-26), 154,624 = 1.1793 after the main merge. Before: 1.2279. + maxSizeRatio: 1.1968, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1968 (before: 1.1922). Before that: GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the handoff menu, its default and the design-doc line name /plan-eng-review again, +42 B union; measured 156,298 / 131,110 = 1.19211, rounded up (before: 156,256 = 1.19179 on 81fb900). Before that: GSTA-134 (2026-10-28, raised from 1.1796 by GStack Minder as merge-queue owner): +1,662 B union: second-opinion question moved into the main file while CODEX_SECOND_OPINION keeps its copy; per-run load 73,248→43,885 B; measured 156,286 / 131,110 = 1.19202, rounded up. Before: + 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 149,758 / 131,110 = 1.1422 (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 150,037 / 131,110 = 1.1444 (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 150,098 / 131,110 = 1.1448 (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 150,011 / 131,110 = 1.1442 (2026-10-07). Merged with the guard area: measured 150,354 / 131,110 = 1.1468 (2026-10-07). + fix wave PR D: builder-profile read before the session log with Phase 6 using the carried values (#2801), the inline design doc before approval (#879) and the pre-telemetry design-doc check (#1049); measured 153,206 / 131,110 = 1.1685 (2026-10-07). + empty LAST_ASSIGNMENT/LAST_PROJECT guards in the welcome_back and regular greetings (backfilled profiles); measured 153,469 / 131,110 = 1.1705 (2026-10-08). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file and its own copies of shared sections; measured 160,989 / 131,110 = 1.2279 (2026-10-25). Before: 1.18. - GSTA-96 dedupe: the Q open-question form is office-hours' own appended subsection, so its copies of the shared Format and fallback subsections go; measured 154,653 / 131,110 = 1.1796 (2026-10-26), 154,624 = 1.1793 after the main merge. Before: 1.2279. }, 'document-release': { skill: 'document-release', @@ -419,7 +419,7 @@ do not launch the downstream skill or open a browser.`, // eureka log, the office-hours lookup and the taste-profile read; measured // 1.0834 (2026-09-30). + named design-direction defaults to avoid in the native // subagent prompt (s02 H4a); measured 1.0911 (2026-10-02). - maxSizeRatio: 1.1623, // + v1.91.19.0 wave: design --version probe (B4), taste-profile load (F3), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting and board/approval blocks (#3022) merged in; measured 100,446 / 90,375 = 1.1114 (2026-10-03). + 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 103,384 / 90,375 = 1.1439 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 103,576 / 90,375 = 1.1461 (2026-10-07). + 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 103,522 / 90,375 = 1.1455 (2026-10-07). Both merged: measured 103,726 / 90,375 = 1.1477 (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 103,466 / 90,375 = 1.1449 (2026-10-07). Merged with the guard area: measured 103,804 / 90,375 = 1.1486 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 105,039 / 90,375 = 1.1623 (2026-10-25). Before: 1.16. + maxSizeRatio: 1.1688, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1688 (before: 1.1623). Before that: + v1.91.19.0 wave: design --version probe (B4), taste-profile load (F3), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting and board/approval blocks (#3022) merged in; measured 100,446 / 90,375 = 1.1114 (2026-10-03). + 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 103,384 / 90,375 = 1.1439 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 103,576 / 90,375 = 1.1461 (2026-10-07). + 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 103,522 / 90,375 = 1.1455 (2026-10-07). Both merged: measured 103,726 / 90,375 = 1.1477 (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 103,466 / 90,375 = 1.1449 (2026-10-07). Merged with the guard area: measured 103,804 / 90,375 = 1.1486 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 105,039 / 90,375 = 1.1623 (2026-10-25). Before: 1.16. }, cso: { skill: 'cso', @@ -493,7 +493,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 60_070, // GST-1088 lane B follow-up (raised from 60,014 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path (~/.claude/skills/gstack/bin/gstack-skill-contract) instead of a bare gstack-skill-contract that a standard install doesn't put on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 60,070. Before: GST-1088 lane B (#3909, raised from 59,774 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): CONTRACT_CHECKER_SHIPPED=true now that bin/gstack-skill-contract ships (#3912) renders the gstack-skill-contract check/waive sentence under the Done means list (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 59,073; measured 60,014. Before: GST-1088 lane B (raised from 59,073 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list rendered from it at the top of the body, plus widened triggers; F1 is a gate-rev-2 recommendation on the plan Garry approved with "do it" on gate rev 1 (2026-11-03), contingent on his gate-rev-2 answer, and lane C's diet is expected to bring /review back under 59,073; measured 59,774. Before: GSTA-96 hoist (2026-10-26): lowered from 80_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 319 bytes; measured 58,754. Before: Shared-code identity/skip/action rules + critical-severity validation; measured 74,493 (2026-09-17). + v1.91.12.0 merge of #2999 (review clarity repairs: await reads, research alongside dispatch, /review deadline and setup authority, findings sources) with #3002 (guarded state-root lines, plan-check checkpoints); each fit alone; measured 74,881 (2026-10-01). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 74,884 (2026-10-08). + gate integrity (HONEST_WORK_GATE_INTEGRITY W2): Step 3.5 Diff scans with the shared GATE_SCAN_BLOCK, the Step 4 carry, the four-option `review-gate-disposition` question in 5c, gate record fields in 5.8 and the Gate edits report line; measured 80,054 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): Step 4's enum-only paragraph becomes the sideways sweep with the forced-CRITICAL list, plus the flake-fix number sentence in the Gate Integrity paragraph; measured skeleton 80,812 (2026-10-10). minUnionBytes: 89_000, // Phase 4 wave 1; measured union 93,357 mustContain: ['confidence', 'P1', 'P2', 'Review Army', 'adversarial'], - maxSizeRatio: 1.3288, // + GST-1088 lane B follow-up (raised from 1.3283 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path instead of a bare gstack-skill-contract that isn't on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 144,203 / 108,523 = 1.328778, rounded up. Before: + GST-1088 lane B (#3909, raised from 1.3261 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): the gstack-skill-contract check/waive sentence that CONTRACT_CHECKER_SHIPPED=true renders (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 1.3180; measured 144,147 / 108,523 = 1.32826, rounded up. Before: + GST-1088 lane B (raised from 1.3180 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list, contingent on Garry's gate-rev-2 answer; lane C's diet is expected to bring /review back under 1.3180; measured 143,907 / 108,523 = 1.3261. Before: + GSTA-167 variant G part 1 (plan approved by Garry 2026-10-30, autoplan-20261030161754 "Do it", which names about +0.3k prompt tokens per voice): the native adversarial and outside-voice prompts carry the blocking floor and the Severity and Blocks lines, +537 bytes; measured 1.3180 (2026-10-30). Before: 1.3136. GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): both owner-approved raises together, measured 142,550 / 108,523 = 1.3135. Before: Shared-code feature + critical-severity validation: 128,042 union bytes / 108,523 baseline = 1.1799; preserves content floors. + v1.91.12.0 merge of #2999 (above, plus plan-completion fallback intent and specialist checklist-by-path) with #3002; measured 1.1843 (2026-10-01). + v1.91.19.0 wave: verdict-form Codex callers with sandbox preflight (INV-1/B1), P0/P1 structured gate (B1b), bound-plan discovery and data-not-instructions guard (F1/D3), visible LEARNINGS failures (B5); measured 129,941 / 108,523 = 1.1974 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 130,025 / 108,523 = 1.1981 (2026-10-04). + Oct 6 fix wave: quota_exhausted preflight branch (#3051); measured 130,359 / 108,523 = 1.2012 (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 131,314 / 108,523 = 1.2100 (2026-10-06). Combined Oct 6 wave head (A and B): measured 131,966 / 108,523 = 1.2160 (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 132,199 / 108,523 = 1.2182 (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 132,258 / 108,523 = 1.2187 (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 132,233 / 108,523 = 1.2185 (2026-10-07). Merged with the guard area: measured 132,522 / 108,523 = 1.2211 (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 133,902 / 108,523 = 1.2339 (2026-10-08). + gate integrity W2 (above); measured 1.282 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): sideways sweep and flake-fix number in Step 4; `Diff read` and `Undeclared behavior changes` in the review-mode Scope Check (plan-completion section); measured 140,497 / 108,523 = 1.2946 (2026-10-10). + harness lane E (2026-10-26): the lead-judgment stage in the finding merge and the `cause` anchor in the specialist prompts, shared with /ship through scripts/resolvers/review-army.ts; measured 141,949 / 108,523 = 1.3080. + maxSizeRatio: 1.3343, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3343 (before: 1.3288). Before that: + GST-1088 lane B follow-up (raised from 1.3283 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path instead of a bare gstack-skill-contract that isn't on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 144,203 / 108,523 = 1.328778, rounded up. Before: + GST-1088 lane B (#3909, raised from 1.3261 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): the gstack-skill-contract check/waive sentence that CONTRACT_CHECKER_SHIPPED=true renders (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 1.3180; measured 144,147 / 108,523 = 1.32826, rounded up. Before: + GST-1088 lane B (raised from 1.3180 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list, contingent on Garry's gate-rev-2 answer; lane C's diet is expected to bring /review back under 1.3180; measured 143,907 / 108,523 = 1.3261. Before: + GSTA-167 variant G part 1 (plan approved by Garry 2026-10-30, autoplan-20261030161754 "Do it", which names about +0.3k prompt tokens per voice): the native adversarial and outside-voice prompts carry the blocking floor and the Severity and Blocks lines, +537 bytes; measured 1.3180 (2026-10-30). Before: 1.3136. GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): both owner-approved raises together, measured 142,550 / 108,523 = 1.3135. Before: Shared-code feature + critical-severity validation: 128,042 union bytes / 108,523 baseline = 1.1799; preserves content floors. + v1.91.12.0 merge of #2999 (above, plus plan-completion fallback intent and specialist checklist-by-path) with #3002; measured 1.1843 (2026-10-01). + v1.91.19.0 wave: verdict-form Codex callers with sandbox preflight (INV-1/B1), P0/P1 structured gate (B1b), bound-plan discovery and data-not-instructions guard (F1/D3), visible LEARNINGS failures (B5); measured 129,941 / 108,523 = 1.1974 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 130,025 / 108,523 = 1.1981 (2026-10-04). + Oct 6 fix wave: quota_exhausted preflight branch (#3051); measured 130,359 / 108,523 = 1.2012 (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 131,314 / 108,523 = 1.2100 (2026-10-06). Combined Oct 6 wave head (A and B): measured 131,966 / 108,523 = 1.2160 (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 132,199 / 108,523 = 1.2182 (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 132,258 / 108,523 = 1.2187 (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 132,233 / 108,523 = 1.2185 (2026-10-07). Merged with the guard area: measured 132,522 / 108,523 = 1.2211 (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 133,902 / 108,523 = 1.2339 (2026-10-08). + gate integrity W2 (above); measured 1.282 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): sideways sweep and flake-fix number in Step 4; `Diff read` and `Undeclared behavior changes` in the review-mode Scope Check (plan-completion section); measured 140,497 / 108,523 = 1.2946 (2026-10-10). + harness lane E (2026-10-26): the lead-judgment stage in the finding merge and the `cause` anchor in the specialist prompts, shared with /ship through scripts/resolvers/review-army.ts; measured 141,949 / 108,523 = 1.3080. }, codex: { skill: 'codex', @@ -545,7 +545,7 @@ do not launch the downstream skill or open a browser.`, }, behavioral: 'prompt', maxSkeletonBytes: 32_216, // GSTA-161 skill diet (2026-10-30): lowered from 52_682 to the measured skeleton, 32,216; Step 7's canary script, the Aside contract, the browser fallback and Third-Party Web Actions moved to sections/canary.md. Before: GSTA-96 hoist (2026-10-26): lowered from 74_500 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 690 bytes; measured 51,992. Before: + Aside browser contract for Step 7 canary ({{ASIDE_SETUP}}); measured 73_523 - maxSizeRatio: 1.1260, // + #3318 Step 3.4 reads the ship policy and prints one VERSION_CHECK verdict (owner-approved raise, Garry 2026-10-24: "do it"); measured 1.1201 (2026-10-24). Before: 1.1120. + v1.81 Aside contract + gstack-browser fallback block; measured 1.077. + both untrusted-content marker formats in the browser fallback (W7f) + the readiness gate's project test command and live eval-store paths (s06 H6/H7); measured 1.1076 (2026-10-02). Re-measured 1.0943 (2026-10-03); cap = measured + 0.005 headroom. + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 115,226 / 104,578 = 1.1018 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,753 / 104,578 = 1.1260 (2026-10-25). Before: 1.125. + maxSizeRatio: 1.1318, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1318 (before: 1.1260). Before that: + #3318 Step 3.4 reads the ship policy and prints one VERSION_CHECK verdict (owner-approved raise, Garry 2026-10-24: "do it"); measured 1.1201 (2026-10-24). Before: 1.1120. + v1.81 Aside contract + gstack-browser fallback block; measured 1.077. + both untrusted-content marker formats in the browser fallback (W7f) + the readiness gate's project test command and live eval-store paths (s06 H6/H7); measured 1.1076 (2026-10-02). Re-measured 1.0943 (2026-10-03); cap = measured + 0.005 headroom. + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 115,226 / 104,578 = 1.1018 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,753 / 104,578 = 1.1260 (2026-10-25). Before: 1.125. minUnionBytes: 91_000, // Phase 4 wave 1; estimated union ~94.9KB mustContain: ['readiness', 'merge', 'canary', 'revert', 'staging'], }, @@ -583,7 +583,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 48_175, // GSTA-96 hoist (2026-10-26): lowered from 70_000 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 4,888 bytes; measured 43,287. Before: Phase-specific outside coverage, native fallback, and harness guard. minUnionBytes: 85_000, // measured union 86,926 mustContain: ['6 Decision Principles', 'TASTE DECISION', 'USER CHALLENGE', 'consensus', 'Restore Point'], - maxSizeRatio: 1.1723, // GST-537 /autoplan --ceo-only (GStack Minder approved A1, 2026-10-31): sections/ceo-only.md (2,168 B) plus its Section index row, read only when the invocation names --ceo-only (test/autoplan-ceo-only.test.ts pins that a normal run never reads it); measured 119,545 / 101,979 = 1.1723 (2026-10-31), +2,276 B over main's 117,269 = 1.1499. Before: 1.1511. Four validated outside invocations replace raw CLI calls; phases keep independent coverage. + 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 114,297 / 101,979 = 1.1208 (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 114,533 / 101,979 = 1.1231 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site, and phase-close publishing each report with the `true autoplan-published ` no-op before the next phase entry in a later message (CEO-1); measured 114,320 / 101,979 = 1.1210 (2026-10-07). Merged with the guard area: measured 115,149 / 101,979 = 1.1291 (2026-10-07). + Oct 8 wave (permission cards after a background reviewer): Step 1 puts RESTORE_PATH, and so every phase artifact, in the project's git-excluded `.gstack/tmp/autoplan/`, which Claude Code reads without a card after the skill turn ends; measured 115,270 / 101,979 = 1.1303 (2026-10-08). + fix wave PR D: the prerequisite offer is skipped in spawned/headless sessions (#1958); measured 115,267 / 101,979 = 1.1303 (2026-10-07). Both merged: measured 115,126 / 101,979 = 1.1289 (2026-10-08). + 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 B9/B10/B12: Phase 0 ESTIMATE and the phase-close timing record, the final gate as a gate list (`gstack-gate render/parse`, stable ids, gate_rev) and the URGENT block above the summary, offset by tightening the Phase 4 prose and the tasks-section; measured 114,980 / 101,979 = 1.1275 (2026-10-10). + Oct 10 multi-agent wave PR D1 (reality rows): the reality-rows check line in the CEO and Eng phase files, the Pre-Gate rule (unattended miss is `incomplete`, never a warning) and the two Pre-Gate cells; measured 117,042 / 101,979 = 1.1477 (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,388 / 101,979 = 1.1511 (2026-10-25). Before: 1.149. + maxSizeRatio: 1.1772, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1772 (before: 1.1723). Before that: GST-537 /autoplan --ceo-only (GStack Minder approved A1, 2026-10-31): sections/ceo-only.md (2,168 B) plus its Section index row, read only when the invocation names --ceo-only (test/autoplan-ceo-only.test.ts pins that a normal run never reads it); measured 119,545 / 101,979 = 1.1723 (2026-10-31), +2,276 B over main's 117,269 = 1.1499. Before: 1.1511. Four validated outside invocations replace raw CLI calls; phases keep independent coverage. + 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 114,297 / 101,979 = 1.1208 (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 114,533 / 101,979 = 1.1231 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site, and phase-close publishing each report with the `true autoplan-published ` no-op before the next phase entry in a later message (CEO-1); measured 114,320 / 101,979 = 1.1210 (2026-10-07). Merged with the guard area: measured 115,149 / 101,979 = 1.1291 (2026-10-07). + Oct 8 wave (permission cards after a background reviewer): Step 1 puts RESTORE_PATH, and so every phase artifact, in the project's git-excluded `.gstack/tmp/autoplan/`, which Claude Code reads without a card after the skill turn ends; measured 115,270 / 101,979 = 1.1303 (2026-10-08). + fix wave PR D: the prerequisite offer is skipped in spawned/headless sessions (#1958); measured 115,267 / 101,979 = 1.1303 (2026-10-07). Both merged: measured 115,126 / 101,979 = 1.1289 (2026-10-08). + 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 B9/B10/B12: Phase 0 ESTIMATE and the phase-close timing record, the final gate as a gate list (`gstack-gate render/parse`, stable ids, gate_rev) and the URGENT block above the summary, offset by tightening the Phase 4 prose and the tasks-section; measured 114,980 / 101,979 = 1.1275 (2026-10-10). + Oct 10 multi-agent wave PR D1 (reality rows): the reality-rows check line in the CEO and Eng phase files, the Pre-Gate rule (unattended miss is `incomplete`, never a warning) and the two Pre-Gate cells; measured 117,042 / 101,979 = 1.1477 (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,388 / 101,979 = 1.1511 (2026-10-25). Before: 1.149. }, spec: { skill: 'spec', @@ -612,7 +612,7 @@ do not launch the downstream skill or open a browser.`, behavioral: 'prompt', maxSkeletonBytes: 36_571, // GSTA-96 hoist (2026-10-26): lowered from 58_400 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 1,606 bytes; measured 34,965. Before: + v2.0 {{ASIDE_RESEARCH}} (Aside first, WebSearch fallback); measured 57_356 minUnionBytes: 64_500, // measured union 67,430 - maxSizeRatio: 1.0746, // Oct 10 multi-agent wave PR E2: the lazy gate-and-file section renders {{COORDINATOR_CONTRACT}} (the block every spawned lane inherits word for word; `gstack-autoplan contract` prints the same bytes) before the --execute spawn pipe; measured 86,614 / 81,577 = 1.0617 after the contract became a fail-closed `CONTRACT=$(…)` capture (2026-10-10). The skeleton is unchanged (57,107). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 87,656 / 81,577 = 1.0745 (2026-10-25). Before: 1.07. + maxSizeRatio: 1.0819, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.0819 (before: 1.0746). Before that: Oct 10 multi-agent wave PR E2: the lazy gate-and-file section renders {{COORDINATOR_CONTRACT}} (the block every spawned lane inherits word for word; `gstack-autoplan contract` prints the same bytes) before the --execute spawn pipe; measured 86,614 / 81,577 = 1.0617 after the contract became a fail-closed `CONTRACT=$(…)` capture (2026-10-10). The skeleton is unchanged (57,107). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 87,656 / 81,577 = 1.0745 (2026-10-25). Before: 1.07. mustContain: ['HARD GATE', 'dedupe', 'quality gate', 'acceptance criteria', 'archive'], }, 'setup-gbrain': { @@ -677,7 +677,7 @@ do not launch the downstream skill or open a browser.`, }, behavioral: 'prompt', maxSkeletonBytes: 41_669, // GSTA-96 hoist (2026-10-26): lowered from 63_500 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 12,415 bytes; measured 29,254. Before: + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} (replaces the browse setup block); measured 61_253 - maxSizeRatio: 1.1420, // + v1.81 Aside contract + gstack-browser fallback block (1.080 on v1.91.7.0) + the shared test value bar at 8a.5 ({{TEST_VALUE_BAR:qa}}); measured 1.094 + 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.101 (2026-09-30) + v1.91.12.0 merge of #2999 (await scope/method Reads, capture --after checkpoints, browser-only empty evidence list) with #3002; measured 1.1028 (2026-10-01). + both untrusted-content marker formats in the browser fallback (W7f); measured 1.1035 (2026-10-02). Re-measured 1.1038 after the W8 probe-loop renames (2026-10-03); the cap already matches. + the annotate-every-capture and superseded rule before materialize (a ship-exploratory-late-input run published evidence that omitted older-snapshot captures); measured 1.1064 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 93,282 / 84,049 = 1.1099 (2026-10-04). + reliability follow-ups C2 (judge-named gaps after trimming the added wording: feasible 180 s Browser Quick, PROBE_DIR's source line, stop goes to the §4 report, written JSON keeps full card values; lane S's {user}/timing fields); measured 93,311 / 84,049 = 1.11020 (2026-10-04). + 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 94,486 / 84,049 = 1.1242 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 94,681 / 84,049 = 1.1265 (2026-10-07). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 94,736 / 84,049 = 1.12715 (2026-10-08). + 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). + maxSizeRatio: 1.1493, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1493 (before: 1.1420). Before that: + v1.81 Aside contract + gstack-browser fallback block (1.080 on v1.91.7.0) + the shared test value bar at 8a.5 ({{TEST_VALUE_BAR:qa}}); measured 1.094 + 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.101 (2026-09-30) + v1.91.12.0 merge of #2999 (await scope/method Reads, capture --after checkpoints, browser-only empty evidence list) with #3002; measured 1.1028 (2026-10-01). + both untrusted-content marker formats in the browser fallback (W7f); measured 1.1035 (2026-10-02). Re-measured 1.1038 after the W8 probe-loop renames (2026-10-03); the cap already matches. + the annotate-every-capture and superseded rule before materialize (a ship-exploratory-late-input run published evidence that omitted older-snapshot captures); measured 1.1064 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 93,282 / 84,049 = 1.1099 (2026-10-04). + reliability follow-ups C2 (judge-named gaps after trimming the added wording: feasible 180 s Browser Quick, PROBE_DIR's source line, stop goes to the §4 report, written JSON keeps full card values; lane S's {user}/timing fields); measured 93,311 / 84,049 = 1.11020 (2026-10-04). + 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 94,486 / 84,049 = 1.1242 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 94,681 / 84,049 = 1.1265 (2026-10-07). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 94,736 / 84,049 = 1.12715 (2026-10-08). + 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). minUnionBytes: 69_500, // measured union 70,385 // 'aside repl' pins the Aside contract; '$B goto' pins the fallback block in the always-loaded skeleton. mustContain: ['bug', 'aside repl', '$B goto', 'fix', 'Health Score Rubric', 'regression'], @@ -714,7 +714,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, }, behavioral: 'prompt', - maxSkeletonBytes: 34_700, // + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} skeleton + the STOP-Read pointer; measured 29_986 + 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); skeleton measured 32,532 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort), and the cookbook's silent-failure list and signed-in-tab recipe (the rule details live here, not in every browsing skill); skeleton measured 34,047 (2026-10-07). + Oct 8 wave: the tier-1 voice directive bans "load-bearing" and adds the reply-language rule (tier 1 has no closer to tighten: +158 bytes); skeleton measured 34,209 (2026-10-08). + 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). + maxSkeletonBytes: 35_298, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 35,298 (before: 34_700). Before that: + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} skeleton + the STOP-Read pointer; measured 29_986 + 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); skeleton measured 32,532 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort), and the cookbook's silent-failure list and signed-in-tab recipe (the rule details live here, not in every browsing skill); skeleton measured 34,047 (2026-10-07). + Oct 8 wave: the tier-1 voice directive bans "load-bearing" and adds the reply-language rule (tier 1 has no closer to tighten: +158 bytes); skeleton measured 34,209 (2026-10-08). + 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). minUnionBytes: 36_000, // skeleton + command-list section (14,240); measured union ~38.5 KB // 'BEGIN/END UNTRUSTED EXTERNAL' pins the untrusted-content warning in the // command reference; 'aside repl' pins the Aside contract in the skeleton. @@ -760,7 +760,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 85_182, // /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 85,182. Before: GSTA-134 skill diet (2026-10-28): lowered from 115_947 to the measured skeleton after the outside voices and test bootstrap moved to sections, 84,869. Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the hoisted skeleton plus main's headroom of 0 bytes; measured 115,947 on the merged tree. Before: measured 137735 on the merged tree with main f27a760 (2026-10-27, #3507); 137767 (2026-10-26; 137773 on 2026-10-25 before the shorter craft-audit trigger): the Section index the external-host carve test requires, its craft-audit row, and the STOP pointer (GSTA-92; Garry 2026-10-25 'Do it' (GSTA-92)). minUnionBytes: 136_100, // GSTA-134 skill diet (2026-10-28): measured union 137,602 (lowered from 143_300); before: measured union 144802 on the merged tree with main f27a760 (2026-10-27, #3507); 145037 (2026-10-26) mustContain: ['AI Slop Detection', 'Fix Loop', 'gstack-design-lint', 'Proof beside each claim', 'holds session data'], - maxSizeRatio: 1.357, // /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 143,620 / 105,842 = 1.35693. Before: 1.3001, GSTA-134 skill diet (2026-10-28): measured 137,602 / 105,842 = 1.30007, rounded up (lowered from 1.3739). Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the union now holds sections/preamble.md (the hoist's owner-approved raise, decision A) on top of main's 1.3681; measured 145,410 / 105,842 = 1.3739 on the merged tree. Before: first parity guard for design-review: measured 144802 / 105,842 = 1.3681 on the merged tree with main f27a760 (2026-10-27, #3507: the design lint swap); before that 145082 / 105,842 = 1.3708 (2026-10-25; 145077 after the /ship review fixes, 145068 = 1.3707 after the line-13 reword, 145049 = 1.3705 after the post-merge /ship review, 145037 = 1.3704 after its second pass, 2026-10-26), the skeleton's growth since v1.64.1.0 plus the craft audit (Garry 2026-10-25 'Do it' (GSTA-92)). + maxSizeRatio: 1.3628, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3628 (before: 1.357). Before that: /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 143,620 / 105,842 = 1.35693. Before: 1.3001, GSTA-134 skill diet (2026-10-28): measured 137,602 / 105,842 = 1.30007, rounded up (lowered from 1.3739). Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the union now holds sections/preamble.md (the hoist's owner-approved raise, decision A) on top of main's 1.3681; measured 145,410 / 105,842 = 1.3739 on the merged tree. Before: first parity guard for design-review: measured 144802 / 105,842 = 1.3681 on the merged tree with main f27a760 (2026-10-27, #3507: the design lint swap); before that 145082 / 105,842 = 1.3708 (2026-10-25; 145077 after the /ship review fixes, 145068 = 1.3707 after the line-13 reword, 145049 = 1.3705 after the post-merge /ship review, 145037 = 1.3704 after its second pass, 2026-10-26), the skeleton's growth since v1.64.1.0 plus the craft audit (Garry 2026-10-25 'Do it' (GSTA-92)). }, // ── Token-reduction Phase 4 wave 4 (v1.69.x branch): design doctrine carve ── @@ -900,7 +900,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, // operational skill, no plan-mode gate }, behavioral: 'prompt', - maxSkeletonBytes: 31_300, // first carve: Section index, one STOP pointer and the vet rule on the 29.9k monolith; measured 30,781 (2026-10-26) + maxSkeletonBytes: 31_893, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 31,893 (before: 31_300). Before that: first carve: Section index, one STOP pointer and the vet rule on the 29.9k monolith; measured 30,781 (2026-10-26) minUnionBytes: 33_000, // skeleton + vet-the-number section; measured union 34,527 (2026-10-26) mustContain: ['performance.getEntries()', 'REGRESSION', 'Name the limiter', 'run-to-run variation', 'inconclusive'], // The v1.64.1.0 baseline measured the 37.2k monolith; the carved union is below it. diff --git a/test/size-ledger/ship/never-print-secrets-shared-rule.json b/test/size-ledger/ship/never-print-secrets-shared-rule.json new file mode 100644 index 00000000000..65ee7c4e515 --- /dev/null +++ b/test/size-ledger/ship/never-print-secrets-shared-rule.json @@ -0,0 +1,4 @@ +{ + "bytes": 614, + "why": "Shared Ground Rules preamble section: never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call (GST-2753)" +} diff --git a/ubicloud/SKILL.md b/ubicloud/SKILL.md index 53cf66f8682..6274dbed6a7 100644 --- a/ubicloud/SKILL.md +++ b/ubicloud/SKILL.md @@ -19,7 +19,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ubicloud/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ubicloud/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ubicloud/sections/preamble.md b/ubicloud/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/ubicloud/sections/preamble.md +++ b/ubicloud/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/verify/SKILL.md b/verify/SKILL.md index 2c13cc1ab52..ee6e6e266db 100644 --- a/verify/SKILL.md +++ b/verify/SKILL.md @@ -99,6 +99,11 @@ Reply in the language of the user's latest message unless asked otherwise. Code, The user has context you do not. Cross-model agreement is a recommendation, not a decision. The user decides. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/write-skill/SKILL.md b/write-skill/SKILL.md index 78688ecf507..85fc30a8beb 100644 --- a/write-skill/SKILL.md +++ b/write-skill/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `4e82fa4c839f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/write-skill/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/write-skill/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/write-skill/sections/preamble.md b/write-skill/sections/preamble.md index 79e0a158c80..9efe49a9da2 100644 --- a/write-skill/sections/preamble.md +++ b/write-skill/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble 227aca067dd3 ## Plan Mode Safe Operations @@ -225,6 +225,11 @@ During long-running skill sessions, when you finish a phase or change direction, If you are looping on the same diagnostic, same file, or failed fix variants, STOP and reassess. Consider escalation or /context-save. Progress summaries must NEVER mutate git state. +## Ground Rules + +- Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get `), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. +- Wait on CI with one `gstack-pr-wait --until green` call, never a poll loop or `gh pr checks --watch`. + ## Completion Status Protocol When completing a skill workflow, report status using one of: From 9e6a96c677431465de3b2d8d3c38d14f64811cd0 Mon Sep 17 00:00:00 2001 From: Mahmoud ElNeMR <83190847+ElNeMeR70@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:57:51 +0200 Subject: [PATCH 07/62] Document approval classes in the ship policy guide (#4355) --- .../docs-ship-policy-approval-classes-4320.md | 1 + docs/ship-policy.md | 56 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 changelog.d/docs-ship-policy-approval-classes-4320.md diff --git a/changelog.d/docs-ship-policy-approval-classes-4320.md b/changelog.d/docs-ship-policy-approval-classes-4320.md new file mode 100644 index 00000000000..c6e94573c79 --- /dev/null +++ b/changelog.d/docs-ship-policy-approval-classes-4320.md @@ -0,0 +1 @@ +- Document the `.gstack/approval-classes.json` schema, `gstack-approval-classes` CLI commands, and owner approval citation format in `docs/ship-policy.md#approval-classes`. diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 1e602b175fa..07dc2ac7333 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -3069,3 +3069,59 @@ PR whose check is red or missing. A PR opened before the workflow existed has no run until its title or body is edited or a commit is pushed; do one of those before landing it. The workflow reads the PR body from the event file, not an environment variable, so a very long body still reaches the checker. + +## Approval classes + +`.gstack/approval-classes.json` lists change classes that need an explicit +owner approval before `gstack-ship-receipt write` emits a ship receipt. +`gstack-approval-classes` reads `.gstack/approval-classes.json` only from +`origin/` so a branch cannot weaken or drop its own classes. + +### Configuration + +Each entry in `classes` has a `name` (`^[a-z][a-z0-9-]{0,39}$`) and one or more +matchers: + +| Key | Meaning | +|-----|---------| +| `name` | Short kebab-case identifier printed as `@` in scopes. | +| `description` | Optional summary of why the class requires owner approval. | +| `paths` | Glob patterns matched against changed file paths. | +| `patterns` | Literal substrings matched against added lines in the diff. | +| `allowed_paths` | Glob patterns excluded from this class's matches. | +| `migrations` | When `true`, matches the ship policy's `migrations` files. | + +### Commands + +```bash +gstack-approval-classes init [--force] +gstack-approval-classes validate +gstack-approval-classes check [--base ] [--head ] [--diff-base ] [--json] +``` + +- `init` writes an example `.gstack/approval-classes.json` with `$schema` set + to `https://github.com/garrytan/gstack/docs/ship-policy.md#approval-classes`. +- `validate` checks `.gstack/approval-classes.json` syntax and limits, exiting + `3` (`APPROVAL_CLASSES_INVALID`) on invalid fields. +- `check` scans the diff and prints `APPROVAL_CLASS: :` and + `APPROVAL_SCOPE: @` for each matched class, ending with + `APPROVAL_CLASSES: ok | found= | none`. It exits `0` when no classes match + (or no config exists on base), `1` when classes match (`APPROVAL_CLASS_FOUND`), + and `3` when the base config is invalid or unavailable. + +### Citations + +When `gstack-approval-classes check` finds hits, `gstack-ship-receipt write` +requires an owner citation for every matched scope (otherwise exiting with +`APPROVAL_CITATION_MISSING`). Cite the approval in the PR body or plan using: + +```text +Approved by via [for @] +``` + +The citation must be authored by a ship-policy maintainer and bound to the +current `@` token (or the class name plus every affected path), +so approvals for earlier revisions or unrelated work do not carry over. +See [troubleshooting.md](troubleshooting.md#approval-classes-invalid) for +error codes and remediation. + From 8c3c39b5220f7fb0c53af5362863a2377f756279 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 16 Nov 2026 11:26:15 +0800 Subject: [PATCH 08/62] List the new guides in the README and fix the install doc's hook count (#4403) * List the new guides in the README and fix the install doc's hook count Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Name the opt-in skill hooks in the manual uninstall steps Review-Finding: docs/install.md:29:docs-accuracy reader=core Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Mention the uninstall doc in the changelog entry Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Point the install and uninstall docs at the opt-in skill-gate hooks Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- README.md | 2 ++ changelog.d/docs-index-and-install-hooks.md | 1 + docs/install.md | 10 +++++++++- docs/uninstall.md | 6 ++++-- 4 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 changelog.d/docs-index-and-install-hooks.md diff --git a/README.md b/README.md index e7d04738bc9..11ebe35ed80 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,8 @@ On Windows without Developer Mode (MSYS2 / Git Bash), `setup` falls back to file | [Diagrams & Document Formats](docs/howto-diagrams-and-formats.md) | Mermaid/excalidraw fences in PDFs, image sizing and safety defaults, `--to html\|docx`, `/diagram` triplets | | [Preview a frontend](docs/howto-preview-a-frontend.md) | The loopback preview with canned API answers that `/design-review --build` checks, its fixtures, the state inventory, and the `gstack-design-build` receipt | | [First Production Deploy](docs/howto-bring-up-a-first-deploy.md) | What to do when `/setup-deploy` says nothing is deployed yet: hosting, env and secrets, DNS, checking it works, then back to `/setup-deploy` | +| [Land a fix in someone else's repo](docs/howto-land-a-fix-in-someone-elses-repo.md) | Read their rules, search for the same fix, run every guard their CI runs before opening, keep it small, answer each review point in a new commit | +| [Run a human playtest](docs/howto-run-human-playtests.md) | Ask about moments and where people would stop, and why a back-to-back pick between two builds measures the order, not the build | | [Builder Ethos](ETHOS.md) | Builder philosophy: Boil the Ocean, Search Before Building, three layers of knowledge | | [GBrain quick tour](docs/gbrain-quick-tour.md) | The four setup paths, MCP registration, the per-repo trust policy, memory sync, Conductor env vars | | [Using GBrain with GStack](USING_GBRAIN_WITH_GSTACK.md) | Every path, flag, bin helper, and troubleshooting step for `/setup-gbrain` | diff --git a/changelog.d/docs-index-and-install-hooks.md b/changelog.d/docs-index-and-install-hooks.md new file mode 100644 index 00000000000..94daa40d66b --- /dev/null +++ b/changelog.d/docs-index-and-install-hooks.md @@ -0,0 +1 @@ +- **The README lists the two new guides, and the install doc counts its hooks right.** The README's docs table links the guides for landing a fix in someone else's repository and for running a human playtest. `docs/install.md` no longer says setup registers "up to three hook families" before naming a fourth, and it now mentions the two hooks that stay off until you turn them on, skill routing and skill contracts. The manual uninstall steps in `docs/uninstall.md` now name those two hooks too. diff --git a/docs/install.md b/docs/install.md index 96cc1c0b95a..30ddb296029 100644 --- a/docs/install.md +++ b/docs/install.md @@ -26,7 +26,7 @@ Swap `required` for `optional` if you'd rather nudge teammates than block them. ## Hooks that `./setup` registers -`./setup` registers up to three hook families in `~/.claude/settings.json`, every one pointing at the canonical install. In team mode it registers the `SessionStart` auto-update hook (`gstack-session-update`; `./setup --no-team` skips it). It asks before registering the AskUserQuestion `PreToolUse` (preference enforcement) and `PostToolUse` (deterministic answer capture) hooks that `/plan-tune` uses at runtime; `./setup` never writes them silently. `docs/uninstall.md` lists the same families when telling you what to remove by hand. +`./setup` registers the hooks below in `~/.claude/settings.json`, every one pointing at the canonical install. In team mode it registers the `SessionStart` auto-update hook (`gstack-session-update`; `./setup --no-team` skips it). It asks before registering the AskUserQuestion `PreToolUse` (preference enforcement) and `PostToolUse` (deterministic answer capture) hooks that `/plan-tune` uses at runtime; `./setup` never writes them silently. `docs/uninstall.md` lists the same families when telling you what to remove by hand. `./setup` also registers one default-on Stop hook: `gstack-timeline-stop` (closes dangling session-timeline entries when a session @@ -39,6 +39,14 @@ explicit "no" removes a live registration. `GSTACK_TIMELINE_STOP_HOOK=no` and --source gstack-timeline-stop` removes it by hand, and `gstack-uninstall` removes it too. +Two more hooks are off by default and registered only when you turn them on: +skill routing (`./setup --skill-routing`, a `UserPromptSubmit` hook that names +the gstack skill a prompt fits) and skill contracts (`./setup --skill-contracts`, +a `Stop` hook that blocks once when a skill ends without its required outputs); +see [skill-routing-and-contracts.md](skill-routing-and-contracts.md). The +opt-in skill gates (`./setup --ceo-review-gate`, `./setup --autoplan-gate`) +register their own hooks the same way; see [skill-gates.md](skill-gates.md). + Hook registration is canonical-only: every hook command points at the stable `~/.claude/skills/gstack` install, never the tree setup ran from, so deleting a worktree or Conductor workspace can't leave dead hooks erroring in your diff --git a/docs/uninstall.md b/docs/uninstall.md index a3dea4127bb..a5a5a2ce942 100644 --- a/docs/uninstall.md +++ b/docs/uninstall.md @@ -125,8 +125,10 @@ Manual removal leaves gstack's hook entries behind in `~/.claude/settings.json` (the uninstall script removes all of them for you, including entries whose `_gstack_source` tag was stripped). Edit that file and delete every hook whose command path points into `.claude/skills/gstack/`: the SessionStart auto-update -hook, the AskUserQuestion PreToolUse/PostToolUse hooks, and the Stop hooks -(session timeline, plus verify-gate if you opted in). Left in place, they error +hook, the AskUserQuestion PreToolUse/PostToolUse hooks, the Stop hooks +(session timeline, plus verify-gate and skill contracts if you opted in), and +the skill-routing UserPromptSubmit hook if you turned it on, and the +/plan-ceo-review and /autoplan skill-gate hooks if you turned those on. Left in place, they error on every matching event once the install directory is gone. If you turned on the OpenClaw or Hermes [start hook](hosts.md#start-hook), From a15a0de7b1b2098ec59d158c90275adb75d7812b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Mu=C3=B1oz=20Rey?= <108531295+Davmunrey@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:07:44 +0100 Subject: [PATCH 09/62] docs: sixteen links reach their section again (#4394) docs/skills.md linked 12 skills to anchors with no section (13 links); those rows now open the skill's own SKILL.md, as the /captain row links crew/README.md. docs/review-policy.md's three links to #targeted-only-read-after-the-loop lost their target when the heading gained (GST-1598); an above the heading restores it. --- changelog.d/fix-docs-missing-anchors.md | 1 + docs/review-policy.md | 1 + docs/skills.md | 26 ++++++++++++------------- 3 files changed, 15 insertions(+), 13 deletions(-) create mode 100644 changelog.d/fix-docs-missing-anchors.md diff --git a/changelog.d/fix-docs-missing-anchors.md b/changelog.d/fix-docs-missing-anchors.md new file mode 100644 index 00000000000..27823e38e78 --- /dev/null +++ b/changelog.d/fix-docs-missing-anchors.md @@ -0,0 +1 @@ +Sixteen in-repo documentation links reach their section again. `docs/skills.md` linked 12 skills to `#anchors` with no section (13 links); those rows now open each skill's own `SKILL.md`. `docs/review-policy.md`'s three links to `#targeted-only-read-after-the-loop` lost their target when the heading gained `(GST-1598)`; the heading now carries that anchor. Contributed by @Davmunrey. diff --git a/docs/review-policy.md b/docs/review-policy.md index 12b8d0eab76..792067d241a 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -539,6 +539,7 @@ Over the last 100 non-release commits on main (8663c3d2..8be7f213), money hit which hit 43 of 100; those paths already get full depth, so the gate class was narrowed to the gate scan's tagged hunks. + ### Targeted-only read after the loop (GST-1598) A docs claim added after the review loop finished, such as a changelog diff --git a/docs/skills.md b/docs/skills.md index 8e2fc459fe9..ac86c53b4e3 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -5,7 +5,7 @@ Detailed guides for every gstack skill — philosophy, workflow, and examples. | Skill | Your specialist | What they do | |-------|----------------|--------------| | [`/office-hours`](#office-hours) | **YC Office Hours** | Start here. Six forcing questions that reframe your product before you write code. Pushes back on your framing, challenges premises, generates implementation alternatives. Design doc feeds into every downstream skill. | -| [`/spec`](#spec) | **Spec Author** | Turn vague intent into a precise, executable spec in five phases. Backlog-ready output that downstream skills can pick up. Optional agent spawn at the end. | +| [`/spec`](../spec/SKILL.md) | **Spec Author** | Turn vague intent into a precise, executable spec in five phases. Backlog-ready output that downstream skills can pick up. Optional agent spawn at the end. | | [`/plan-ceo-review`](#plan-ceo-review) | **CEO / Founder** | Rethink the problem. Find the 10-star product hiding inside the request. Four modes: Expansion, Selective Expansion, Hold Scope, Reduction. | | [`/plan-eng-review`](#plan-eng-review) | **Eng Manager** | Lock in architecture, data flow, diagrams, edge cases, and tests. Forces hidden assumptions into the open. | | [`/plan-design-review`](#plan-design-review) | **Senior Designer** | Interactive plan-mode design review. Rates each dimension 0-10, explains what a 10 looks like, fixes the plan. Works in plan mode. | @@ -29,33 +29,33 @@ Detailed guides for every gstack skill — philosophy, workflow, and examples. | [`/runaway-stopper`](#runaway-stopper) | **Spend Warden** | Find runaway Capy threads and subagents, stop or rotate them at a clean point, and set the defaults that keep them from coming back. | | [`/cso`](#cso) | **Chief Security Officer** | Supported security findings with explicit coverage. Static assessment remains available without catalog profiles; contained runtime/scanner execution requires matching qualified profiles. Runtime-tested bundles authenticate separate external assertions. Project-test completion remains `self_reported` because target code controls the test process; `tested` is reserved for a future target-independent completion witness. | | [`/document-release`](#document-release) | **Technical Writer** | Audit relevant docs on every ship before final verification; standalone runs can also update docs after a PR exists. Catches stale READMEs and reports unresolved gaps. | -| [`/document-generate`](#document-generate) | **Technical Writer** | Generate Diataxis docs (tutorial / how-to / reference / explanation) for a feature from code. | +| [`/document-generate`](../document-generate/SKILL.md) | **Technical Writer** | Generate Diataxis docs (tutorial / how-to / reference / explanation) for a feature from code. | | [`/retro`](#retro) | **Eng Manager** | Team-aware weekly retro. Per-person breakdowns, shipping streaks, test health trends, growth opportunities. | | [`/browse`](#browse) | **QA Engineer** | Give the agent eyes. Drives your Aside browser first — real sessions, real clicks, real screenshots — through deterministic `aside repl` scripts, and falls back to gstack's own Chromium (~100ms per command) when Aside isn't there. | | [`/setup-browser-cookies`](#setup-browser-cookies) | **Session Manager** | Copy selected cookies from Chrome, Chromium, Brave, Edge, Windows-only Opera and Opera GX, or macOS-only Comet and Arc into the fallback browser. Choose your profile and domains; check sign-in separately. Unnecessary on Aside, which already has your sessions. | | [`/autoplan`](#autoplan) | **Review Pipeline** | One command, reviewed plan. In an interactive session it runs CEO → design → DX → eng review from each skill's own method (eng always last, so the shipping gate reviews the final amended plan) with encoded decision principles, and surfaces only taste decisions for your approval. A run driven by `gstack-autoplan` (the Capy default) gives its reviewers short checklists instead of those methods: the lean run is one reviewer, `--full` one per phase ([what each run loads](#what-each-run-loads)). | -| [`/plan-devex-review`](#plan-devex-review) | **DX Reviewer** | Plan-stage DX review. TTHW (time-to-hello-world), magical moments, friction points, persona traces, and error messages scored for the agents that read them ([agent-ready errors](agent-ready-errors.md)). Three modes: Expansion, Polish, Triage. | -| [`/devex-review`](#devex-review) | **DX Reviewer (live)** | Live developer experience audit. Walks the actual onboarding flow, measures TTHW, catches the docs lies, and triggers CLI errors the way an agent meets them (no terminal, contained, redacted) through `gstack-error-capture`. | -| [`/plan-tune`](#plan-tune) | **Question Tuner** | Self-tune AskUserQuestion sensitivity per question. Mark questions as never-ask, always-ask, or only-for-one-way. | -| [`/spec`](#spec) | **Spec Author** | Turn vague intent into a precise, executable spec in five phases. Files a GitHub issue, optionally spawns a Claude Code agent in a fresh worktree, and lets `/ship` close the source issue on merge. | +| [`/plan-devex-review`](../plan-devex-review/SKILL.md) | **DX Reviewer** | Plan-stage DX review. TTHW (time-to-hello-world), magical moments, friction points, persona traces, and error messages scored for the agents that read them ([agent-ready errors](agent-ready-errors.md)). Three modes: Expansion, Polish, Triage. | +| [`/devex-review`](../devex-review/SKILL.md) | **DX Reviewer (live)** | Live developer experience audit. Walks the actual onboarding flow, measures TTHW, catches the docs lies, and triggers CLI errors the way an agent meets them (no terminal, contained, redacted) through `gstack-error-capture`. | +| [`/plan-tune`](../plan-tune/SKILL.md) | **Question Tuner** | Self-tune AskUserQuestion sensitivity per question. Mark questions as never-ask, always-ask, or only-for-one-way. | +| [`/spec`](../spec/SKILL.md) | **Spec Author** | Turn vague intent into a precise, executable spec in five phases. Files a GitHub issue, optionally spawns a Claude Code agent in a fresh worktree, and lets `/ship` close the source issue on merge. | | [`/learn`](#learn) | **Memory** | Manage what gstack learned across sessions. Review, search, prune, and export project-specific patterns and preferences. | -| [`/context-save`](#context-save) | **Save State** | Save working context (git state, decisions, remaining work) so any future session can resume. | -| [`/context-restore`](#context-restore) | **Restore State** | Resume from a saved context, even across Conductor workspace handoffs. | -| [`/health`](#health) | **Code Quality Dashboard** | Wraps type checker, linter, tests, dead code detection. Computes a weighted 0-10 score; tracks trends over time. | +| [`/context-save`](../context-save/SKILL.md) | **Save State** | Save working context (git state, decisions, remaining work) so any future session can resume. | +| [`/context-restore`](../context-restore/SKILL.md) | **Restore State** | Resume from a saved context, even across Conductor workspace handoffs. | +| [`/health`](../health/SKILL.md) | **Code Quality Dashboard** | Wraps type checker, linter, tests, dead code detection. Computes a weighted 0-10 score; tracks trends over time. | | [`/deslop-shared-libs`](#deslop-shared-libs) | **Shared Code Reviewer** | Find worthwhile shared-code extractions in recent work. Recommendations only. | | [`/write-skill`](#write-skill) | **Skill Editor** | Write or improve an agent skill without bloat: edit ladder, size per level, skill-to-bin drift check, full diets with a before/after test. | | [`/test-audit`](#test-audit) | **Test Auditor** | Sweep existing tests for low-value, implementation-coupled or duplicate tests. Report-only unless you approve a batch. | -| [`/landing-report`](#landing-report) | **Ship Queue Dashboard** | Read-only snapshot of the workspace-aware ship queue. Which version slots are claimed, which sibling workspaces have WIP. | +| [`/landing-report`](../landing-report/SKILL.md) | **Ship Queue Dashboard** | Read-only snapshot of the workspace-aware ship queue. Which version slots are claimed, which sibling workspaces have WIP. | | [`/captain`](#captain) | **Crew Controller** (Capy only: [crew/](../crew/README.md)) | Run many coding agents from one controller. Lanes build and send a READY block; the controller validates it, merges through trains (stamp on call, verify, merge with the expected head, verify again; `train land` per slot under `changelog_fragments`), keeps the digest, relays approvals in three fixed shapes and runs a daily flaky-fix pass. Also answers to `/crew`. | -| [`/benchmark-models`](#benchmark-models) | **Model Benchmark** | Side-by-side cross-model benchmark for skills (Claude vs GPT vs Gemini, plus particle-1 and DeepSeek V4.1 Flash through OpenRouter). Latency, tokens, cost, optional LLM-judged quality. | +| [`/benchmark-models`](../benchmark-models/SKILL.md) | **Model Benchmark** | Side-by-side cross-model benchmark for skills (Claude vs GPT vs Gemini, plus particle-1 and DeepSeek V4.1 Flash through OpenRouter). Latency, tokens, cost, optional LLM-judged quality. | | [`/eval-plan`](#eval-plan) | **Eval Planner** | Preregister a paid eval (bars, arms, decoys, stop rules), dry-run it for $0 with the stub model, pilot three priced items, then approve the spend from the extrapolation table. | | | | | | **Multi-AI** | | | | [`/codex`](#codex) | **Second Opinion** | OpenAI Codex review, challenge, and consultation. Available outside the Codex harness. | | [`/claude-code`](#claude-code) | **Second Opinion** | Claude Code review, challenge, and consultation. Available outside the Claude Code harness; used for automatic outside reviews in Codex. | | [`/pair-agent`](#browse) | **Remote Agent Bridge** | Pair a remote AI agent (OpenClaw, Codex, Cursor, Hermes) with gstack's own browser. Scoped tunnel, locked allowlist, session token. Fallback-browser skill; agents driving Aside open their own tabs. | -| [`/setup-gbrain`](#setup-gbrain) | **Memory Sync** | Set up gbrain for cross-machine session memory sync. One command from zero to live. | -| [`/sync-gbrain`](#sync-gbrain) | **Keep Brain Current** | Refresh gbrain against this repo's code; teach the agent when to use `gbrain search`/`code-def` over Grep. Idempotent; safe to re-run. | +| [`/setup-gbrain`](../setup-gbrain/SKILL.md) | **Memory Sync** | Set up gbrain for cross-machine session memory sync. One command from zero to live. | +| [`/sync-gbrain`](../sync-gbrain/SKILL.md) | **Keep Brain Current** | Refresh gbrain against this repo's code; teach the agent when to use `gbrain search`/`code-def` over Grep. Idempotent; safe to re-run. | | | | | | **Safety & Utility** | | | | [`/careful`](#safety--guardrails) | **Safety Guardrails** | Warns before destructive commands (rm -rf, DROP TABLE, force-push, git reset --hard). Override any MEDIUM warning; root/home recursive deletes and default-branch force-pushes are hard-denied. Common build cleanups whitelisted. | From 5dcd76b4eae6bb06f73460d3ab29cef8e33e8537 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 16 Nov 2026 22:40:56 +0800 Subject: [PATCH 10/62] Update hono to fix five security advisories (#4408) * Update hono to fix five security advisories (#4406) The weekly OSV scan flagged hono 4.13.13 with five advisories fixed in 4.13.16. hono comes in only through the dev toolchain (claude-agent-sdk, then the MCP SDK), so none was reachable. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * List hono among the dependency floors in the contributor guide The dependency security test now checks hono >= 4.13.16; the contributor guide's description of that test names it too. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CONTRIBUTING.md | 2 +- bun.lock | 4 ++-- changelog.d/update-hono-security-advisories.md | 7 +++++++ package.json | 2 +- test/dependency-security.test.ts | 2 +- 5 files changed, 12 insertions(+), 5 deletions(-) create mode 100644 changelog.d/update-hono-security-advisories.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4a189b6e91d..2c60d858f3e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -432,7 +432,7 @@ eval files, and misses the strict classifier. No API keys needed. - **Catalog budget** (`test/catalog-budget.test.ts`) — Caps the aggregate discovery surface: the sum of every skill's frontmatter `name` + `description` (what every host loads at discovery, every session) must stay under 1,452 token-equivalents, with a 260-byte per-skill cap. Counting goes through the shared census in `test/helpers/skill-census.ts` (physical files vs authored skills vs registry entries — three deliberately different counts). Adding a skill? The failure message carries the re-measure + ratchet protocol. - **Context-budget ratchet** (`test/context-budget-ratchet.test.ts`) — CI ceilings on the two token ledgers the catalog budget doesn't cover: the always-on full-frontmatter aggregate and each skill's per-invocation eager tokens (SKILL.md + forced-read references), graded against `test/fixtures/context-budget.json` via `lib/context-bill.ts`. New skills fail until they have a ceiling; ceilings for removed skills must be pruned. Legitimate growth or a landed reduction: re-run `bun test/helpers/capture-context-budget.ts` and commit the refreshed fixture in the same commit, so the change is a visible decision in the diff. - **Skill-to-bin drift ratchet** (`test/skill-bin-drift.test.ts`) — `scripts/skill-bin-drift.ts` statically reads every gstack bin call in skill templates, carved sections, references and the Claude-host renders (it never executes a bin) and fails with `DRIFT_UNKNOWN_BIN` or `DRIFT_UNKNOWN_FLAG` at file:line when a skill names a bin missing from `bin/` or a flag that bin's parser does not accept. Known misses live in `test/fixtures/skill-bin-drift-allowlist.json`, which only shrinks: a new finding fails, and so does an entry that no longer reproduces. Check one skill with `bun run scripts/skill-bin-drift.ts --skill `; bins with permissive parsers or no usage text are reported, never failed. -- **Dependency security regressions** (`test/dependency-security.test.ts`) — Run `bun test test/dependency-security.test.ts` to check the resolved `sharp`, `adm-zip`, `qs` and `@hono/node-server` version floors, load Sharp, verify ordinary ZIP extraction, and reject extraction through destination-file and destination-directory symlinks. The symlink cases skip Windows. These checks complement the OSV scan; they do not change its existing exceptions. +- **Dependency security regressions** (`test/dependency-security.test.ts`) — Run `bun test test/dependency-security.test.ts` to check the resolved `sharp`, `adm-zip`, `qs`, `@hono/node-server` and `hono` version floors, load Sharp, verify ordinary ZIP extraction, and reject extraction through destination-file and destination-directory symlinks. The symlink cases skip Windows. These checks complement the OSV scan; they do not change its existing exceptions. ### Tier 2: E2E via `claude -p` diff --git a/bun.lock b/bun.lock index ceae42b777c..bc276b4e801 100644 --- a/bun.lock +++ b/bun.lock @@ -35,7 +35,7 @@ "@modelcontextprotocol/sdk": "1.32.0", "adm-zip": "^0.6.1", "fast-uri": "3.1.9", - "hono": "4.13.13", + "hono": "4.13.16", "image-size": "2.0.4", "ip-address": "10.7.4", "proxy-addr": "2.0.8", @@ -359,7 +359,7 @@ "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], - "hono": ["hono@4.13.13", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="], + "hono": ["hono@4.13.16", "", {}, "sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A=="], "html-entities": ["html-entities@2.6.0", "", {}, "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ=="], diff --git a/changelog.d/update-hono-security-advisories.md b/changelog.d/update-hono-security-advisories.md new file mode 100644 index 00000000000..a360fb10973 --- /dev/null +++ b/changelog.d/update-hono-security-advisories.md @@ -0,0 +1,7 @@ +--- +important: security +--- +**hono is pinned to 4.13.16, which fixes five advisories the weekly OSV scan found in 4.13.13 (gstack#4406).** The 2026-11-16 scan (run 43825448246) flagged GHSA-3gg2-335m-rxc6 (CVSS 3.4, the `css` helper) and GHSA-46wx-v44x-9hh2, GHSA-4h7h-rv7c-7m2v, GHSA-4m76-xfj5-7975 and GHSA-h7mg-cq63-vhpq (CVSS 5.3 each: `csrf()`, `validator('form')`, `mount()` and RegExpRouter wildcard middleware). hono reaches gstack only through the dev and test toolchain (`@anthropic-ai/claude-agent-sdk` pulls in `@modelcontextprotocol/sdk`), gstack's own code never imports it or starts a hono server, and none of the affected helpers is used, so no advisory was reachable. Contributor checkouts get the patched version on their next `bun install`. + +- **`package.json` overrides**: `hono` moves from 4.13.13 to 4.13.16, the release that fixes all five. `bun.lock` holds the one copy. +- `test/dependency-security.test.ts`: the lockfile floor check now covers `hono >= 4.13.16`. It fails on main. diff --git a/package.json b/package.json index 9056bddea97..306cd7ddae3 100644 --- a/package.json +++ b/package.json @@ -107,7 +107,7 @@ "@modelcontextprotocol/sdk": "1.32.0", "adm-zip": "^0.6.1", "fast-uri": "3.1.9", - "hono": "4.13.13", + "hono": "4.13.16", "image-size": "2.0.4", "ip-address": "10.7.4", "proxy-addr": "2.0.8", diff --git a/test/dependency-security.test.ts b/test/dependency-security.test.ts index d6a5e16dd37..4b7a5d0f0a4 100644 --- a/test/dependency-security.test.ts +++ b/test/dependency-security.test.ts @@ -6,7 +6,7 @@ import AdmZip from "adm-zip"; import sharp from "sharp"; describe("security dependency overrides", () => { - for (const [name, minimum] of [["sharp", "0.35.4"], ["adm-zip", "0.6.1"], ["qs", "6.16.1"], ["@hono/node-server", "2.1.3"]]) { + for (const [name, minimum] of [["sharp", "0.35.4"], ["adm-zip", "0.6.1"], ["qs", "6.16.1"], ["@hono/node-server", "2.1.3"], ["hono", "4.13.16"]]) { test(`${name} resolves only versions at or above ${minimum}`, async () => { const lock = await Bun.file(join(import.meta.dir, "../bun.lock")).text(); const versions = [...lock.matchAll(new RegExp(`"${name}@([^"]+)"`, "g"))]; From 5b4fa9ea335e3ba743a36e3269da95980b77b32d Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 17 Nov 2026 14:09:13 +0800 Subject: [PATCH 11/62] Run large unit suites on Linux instead of failing with argument list too long (#4424) (#4426) * Run large unit suites on Linux instead of failing with argument list too long A lane passed every unit file in one bash -c argument; Linux caps one argument at 128 KiB, so thousands of files failed with E2BIG. Split the file list into byte-bounded chunks run in sequence and read back as one run, and classify E2BIG as its own arg-limit cause. Fixes #4424 Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: pre-landing review fixes Put the failing fixture file last after sorting so the arg-limit test really checks a failure in the final chunk. Review-Finding: p1/specialist-batched#1 reader=testing Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs: note the Windows chunk size for split lane file lists Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../lanes-large-file-lists-on-linux.md | 1 + docs/pregate.md | 7 +- lib/pregate/checks/lanes.ts | 56 +++++++++++-- lib/pregate/environment.ts | 2 + lib/pregate/types.ts | 2 +- test/pregate-lanes-arg-limit.test.ts | 82 +++++++++++++++++++ 6 files changed, 139 insertions(+), 11 deletions(-) create mode 100644 changelog.d/lanes-large-file-lists-on-linux.md create mode 100644 test/pregate-lanes-arg-limit.test.ts diff --git a/changelog.d/lanes-large-file-lists-on-linux.md b/changelog.d/lanes-large-file-lists-on-linux.md new file mode 100644 index 00000000000..68f8401de9e --- /dev/null +++ b/changelog.d/lanes-large-file-lists-on-linux.md @@ -0,0 +1 @@ +- **/ship's test step runs a large unit suite on Linux.** A lane with thousands of unit files used to stop with `PREGATE: incomplete` and `E2BIG: argument list too long` before any test ran, because every file went into one command argument and Linux caps a single argument at 128 KiB. gstack now splits a big file list into runner processes of about 96 KB each, run one after another and counted as one run, so the result is the same as before: any failing chunk fails the lane. An `E2BIG` launch failure is now reported as its own cause (`arg-limit`) instead of telling you to install a missing tool. (#4424) diff --git a/docs/pregate.md b/docs/pregate.md index 892af1ecfbb..7abffb24b3d 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -428,7 +428,11 @@ Two stages with separate clocks, both printed: `workflow.yml/job`, unless `local` names that lane. `--explain` prints each test's provenance and every uncertain mapping (a planner-computed matrix without a `selection` manifest selects conservatively). Test files matching `serial_patterns` (default - `**/*.serial.test.*`) run one process per file after the unit files. The + `**/*.serial.test.*`) run one process per file after the unit files. A unit + group whose quoted file list would pass the system's argument limits (Linux + caps one argument at 128 KiB) runs as several runner processes in sequence, + each under about 96 KB of file arguments (24 KB on Windows), read back as one run: counts add up, + any failing chunk fails the lane, and they share the group's one `--timeout`. The runner and every guard run with the verified launch Bun first on PATH: the first of `$BUN_INSTALL/bin` and `~/.bun/bin` whose Bun satisfies gstack's and the project's `engines.bun` (the row prints `runtime: bun from `), @@ -1858,6 +1862,7 @@ failure the branch caused carries `cause: "diff"` (`PREGATE_LANE_FAILED`, | Kind | Evidence | |---|---| | `missing-binary` | exit 127, `command not found`, a spawn `ENOENT`, a runner tool `not on PATH` (dart, flutter, cargo, a package manager, `python3`, or `pytest` when python3 cannot import it), Playwright's browsers not installed | +| `arg-limit` | `E2BIG`, `Argument list too long`: a command line or environment over the system's limit. gstack splits a lane's file list to stay under it, so this is a gstack bug to report | | `network` | `ENOTFOUND`, `ECONNREFUSED`, `ECONNRESET`, `ETIMEDOUT`, `EAI_AGAIN`, `Could not resolve host`, `fetch failed`, a TLS handshake or certificate failure | | `quota` | `quota`, `429 Too Many Requests`, `rate limit`, `insufficient_quota` (a vCPU quota on the remote backend) | | `disk` | `ENOSPC`, `No space left on device`, `EDQUOT` | diff --git a/lib/pregate/checks/lanes.ts b/lib/pregate/checks/lanes.ts index 219e3373565..075b1bdb220 100644 --- a/lib/pregate/checks/lanes.ts +++ b/lib/pregate/checks/lanes.ts @@ -365,18 +365,56 @@ interface LocalRun { exit: number | null; outcome: Supervised['outcome']; signal const quote = (f: string) => `'${f.replace(/'/g, `'\\''`)}'`; +/** + * Bytes of quoted file arguments one runner process may take. supervise passes the whole command as one `bash -c` + * argument: Linux caps a single execve argument at 128 KiB (MAX_ARG_STRLEN), every POSIX system caps argv plus the + * environment (ARG_MAX: 1 MiB on macOS, 2 MiB by default on Linux), and Windows caps a whole command line at 32,767 + * characters. The runner text itself and a margin come off the top. + */ +export function argBudget(runner: string, env: NodeJS.ProcessEnv, platform = process.platform): number { + const envBytes = Object.entries(env).reduce((n, [k, v]) => n + Buffer.byteLength(`${k}=${v ?? ''}`) + 9, 0); + const cap = platform === 'win32' ? 24 * 1024 : Math.min(96 * 1024, 1024 * 1024 - 64 * 1024 - envBytes); + return cap - Buffer.byteLength(runner) - 512; +} + +/** `args` split in order into chunks whose quoted, space-joined text fits `budget` bytes; an argument over it runs alone. */ +export function argChunks(args: readonly string[], budget: number): string[][] { + const chunks: string[][] = []; + let size = 0; + for (const a of args) { + const n = Buffer.byteLength(quote(a)) + 1; + if (!chunks.length || size + n > budget) { chunks.push([]); size = 0; } + chunks.at(-1)!.push(a); + size += n; + } + return chunks; +} + async function runOnce(ctx: PregateContext, env: NodeJS.ProcessEnv, g: RunGroup, files: string[], log: string, counter: Counter): Promise { // playwright test reads each file argument as a case-insensitive regex: escape it and anchor it to a path segment, so `a[1].spec.ts` runs that file, not `a1.spec.ts`. const args = /(? `(?:^|/)${f.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) : testFileArgs(g.runner, files); - const joined = args.map(quote).join(' '); - const run = g.runner.replace('{files}', () => joined); - const command = g.cwd ? `(cd ${quote(g.cwd)} && ${run})` : run; - const shown = g.cwd ? files.map(f => `${g.cwd}/${f}`) : files; - const r = await supervise({ command: run, cwd: path.join(ctx.repoRoot, g.cwd), env: { ...env, CI: env.CI ?? '1' }, log, deadline: Date.now() + ctx.timeoutMs, stallMs: ctx.stallTimeoutMs, label: `lanes (${shown.length === 1 ? shown[0] : `${shown.length} files`})`, files, adapter: adapterFor(g.runner), counter, progress: ctx.progress }); - const output = readRange(log, r.start, r.end); - const summary = parseSummary(output, g.runner); - const noBrowsers = /(? joined); + const shown = g.cwd ? part.map(f => `${g.cwd}/${f}`) : part; + const r = await supervise({ command: run, cwd: path.join(ctx.repoRoot, g.cwd), env: runEnv, log, deadline, stallMs: ctx.stallTimeoutMs, label: `lanes (${shown.length === 1 ? shown[0] : `${shown.length} files`})`, files: part, adapter: adapterFor(g.runner), counter, progress: ctx.progress }); + const output = readRange(log, r.start, r.end); + const summary = parseSummary(output, g.runner); + const noBrowsers = /(? p.exit === null) ?? parts.find(p => p.exit !== 0) ?? parts.at(-1)!; + const sum = (k: 'ran' | 'failed') => (parts.some(p => p[k] === null) ? null : parts.reduce((n, p) => n + (p[k] as number), 0)); + return { ...(parts.every(p => p.noBrowsers) ? { noBrowsers: parts[0]!.noBrowsers } : {}), exit: bad.exit, outcome: bad.outcome, signal: bad.signal, observedStart: parts.some(p => p.observedStart), ran: sum('ran'), failed: sum('failed'), tail: bad.tail, runner: g.runner, command: parts.map(p => p.command).join(' && '), files: parts.flatMap(p => p.files), lastFile: bad.lastFile, ms: parts.reduce((n, p) => n + p.ms, 0), ...(bad.error ? { error: bad.error } : {}) }; } /** diff --git a/lib/pregate/environment.ts b/lib/pregate/environment.ts index da70ab24d0c..97c2988c81f 100644 --- a/lib/pregate/environment.ts +++ b/lib/pregate/environment.ts @@ -23,6 +23,7 @@ const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g; const NOT_FOUND = /command not found|is not recognized as an internal or external command/; const RULES: Array<{ kind: EnvironmentKind; re: RegExp }> = [ { kind: 'missing-binary', re: new RegExp(`${NOT_FOUND.source}|No such file or directory: ['"]?[\\w./-]+|spawn \\S+ ENOENT|\\bENOENT\\b.*\\bspawn\\b|not on PATH`) }, + { kind: 'arg-limit', re: /\bE2BIG\b|[Aa]rgument list too long/ }, { kind: 'quota', re: /\bquota\b|\b429 Too Many Requests|status(?: code)?[:= ]+429\b|HTTP(?:\/[\d.]+)? 429\b|\brate.?limit(?:ed)?\b|insufficient_quota/i }, { kind: 'network', re: /\bE(?:NOTFOUND|CONNREFUSED|CONNRESET|TIMEDOUT|HOSTUNREACH|NETUNREACH|AI_AGAIN|PIPE)\b|getaddrinfo|Could not resolve host|Connection refused|Connection reset|Network is unreachable|fetch failed|TLS handshake|certificate verify failed|UNABLE_TO_GET_ISSUER_CERT|Temporary failure in name resolution/ }, { kind: 'disk', re: /\bENOSPC\b|No space left on device|\bEDQUOT\b|Disk quota exceeded/ }, @@ -72,6 +73,7 @@ export function classifyCommandEnvironment(command: string, output: string, exit const FIX: Record = { 'missing-binary': 'install the named tool on this machine (or put it on PATH), or run the lane remotely (--remote, or clear it with a run URL)', + 'arg-limit': 'the command line or environment passed to the runner is over the system\'s argument limit (E2BIG); gstack splits a lane\'s file list to stay under it, so report this as a gstack bug with this line, and meanwhile run the lane remotely or split the selection', network: 'check the network, proxy or registry this machine reaches, then rerun; or run the lane remotely', quota: 'wait for the quota or raise it, free the backend\'s capacity, then rerun', disk: 'free disk space (or move the state root) and rerun', diff --git a/lib/pregate/types.ts b/lib/pregate/types.ts index f0186a33e7d..8bbb5d103e8 100644 --- a/lib/pregate/types.ts +++ b/lib/pregate/types.ts @@ -105,7 +105,7 @@ export interface CheckResult extends PregateCheck { environment?: EnvironmentCause; } -export type EnvironmentKind = 'missing-binary' | 'network' | 'quota' | 'disk' | 'runtime' | 'tool'; +export type EnvironmentKind = 'missing-binary' | 'arg-limit' | 'network' | 'quota' | 'disk' | 'runtime' | 'tool'; /** How the cause was established: `launch` (the command could not start, its binary is off PATH, the runtime or a gstack tool refused), or `output` (a rule matched the command's text before any test was counted, which the diff's own output could have written). */ export type EnvironmentProof = 'launch' | 'output'; export interface EnvironmentCause { kind: EnvironmentKind; evidence: string; proof: EnvironmentProof } diff --git a/test/pregate-lanes-arg-limit.test.ts b/test/pregate-lanes-arg-limit.test.ts new file mode 100644 index 00000000000..2ffb60b547e --- /dev/null +++ b/test/pregate-lanes-arg-limit.test.ts @@ -0,0 +1,82 @@ +/** + * #4424: on Linux a local lane with thousands of unit files never started. runOnce put every file of a run group into + * one command string and supervise started it as `bash -c `; Linux caps one execve argument at MAX_ARG_STRLEN + * (128 KiB), so posix_spawn returned E2BIG, and the launch failure read as a missing binary ("install the named tool"). + * The fixture selects 700 test files with 200-character names (about 150 KB of quoted paths) and a runner that reports + * one test per file argument, so the lane's count proves every file reached a runner. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { argBudget, argChunks } from '../lib/pregate/checks/lanes'; +import { buildContext } from '../lib/pregate/context'; +import { classifyEnvironment } from '../lib/pregate/environment'; +import { runPregate } from '../lib/pregate/index'; +import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); + +const FILES = 700; +const name = (i: number, tag = 'x') => `test/big/${tag.padEnd(186, 'x')}${String(i).padStart(4, '0')}.test.js`; +const RUNNER = [ + 'const files = process.argv.slice(2);', + "const failed = files.filter(f => f.includes('fail')).length;", + "console.log(`ℹ tests ${files.length}\\nℹ pass ${files.length - failed}\\nℹ fail ${failed}`);", + 'process.exit(failed ? 1 : 0);', +].join('\n'); + +async function lanesOver(tests: string[]) { + const repo = makeFixtureRepo({ + pregate: { ...BASE_PREGATE, runner: 'node scripts/count.js {files}', dependencies: { ...BASE_PREGATE.dependencies, 'src/big/**': tests } }, + baseFiles: Object.fromEntries([...tests.map(t => [t, "require('node:test');\n"]), ['src/big/.keep', ''], ['scripts/count.js', `${RUNNER}\n`]]), + }); + repos.push(repo); + commit(repo, { 'src/big/f.js': 'exports.n = 1;\n' }, 'touch the big tree'); + const loaded = buildContext({ repoRoot: repo.work, base: 'main', policyFrom: 'base', allowRepoCommands: true, env: { ...process.env, ...repo.env }, progress: () => {}, cores: 64, testBackend: 'local' }); + if (!('ctx' in loaded)) throw new Error('fixture context refused'); + const file = await runPregate(loaded.ctx, { stage: 'tests', only: ['lanes'] }); + return file.checks.find(c => c.id === 'lanes')!; +} + +describe.skipIf(process.platform === 'win32')('a local lane whose file list is over the per-argument limit', () => { + // Value: protects=a unit group whose quoted file list is over Linux's 128 KiB per-argument cap still launches and every file + // is counted; fails_when=the whole list goes into one `bash -c` argument (E2BIG on Linux: PREGATE_ENVIRONMENT, nothing ran); + // why_new=#4424, gbrain's 5,567 unit files on gstack 1.99.5.0; seam=runPregate --only lanes on a fixture repo with a + // counting runner; no_claim=macOS has no per-argument cap, so there the old code passed too + test('every file runs and is counted, and a failure in the last chunk still fails the lane', async () => { + const tests = Array.from({ length: FILES }, (_, i) => name(i)); + expect(tests.map(t => `'${t}'`).join(' ').length).toBeGreaterThan(128 * 1024); + const green = await lanesOver(tests); + expect(green.detail).not.toContain('E2BIG'); + expect(green).toMatchObject({ status: 'pass', detail: `${FILES} tests ran in ${FILES} file(s), exit 0` }); + + const red = await lanesOver([...tests.slice(0, -1), name(FILES - 1, 'zfail')]); + expect(red).toMatchObject({ status: 'fail', code: 'PREGATE_LANE_FAILED', detail: `local lane exited 1 (1 failed of ${FILES} ran; ${FILES} files; pipefail)` }); + }, 120_000); +}); + +describe('argChunks and argBudget', () => { + // Value: protects=the split keeps order, drops nothing and keeps each chunk's quoted text under the budget, with an oversized + // argument alone in its chunk, and the budget stays under Linux's per-argument cap and shrinks with the environment; + // fails_when=a chunk passes the budget, a file is lost or reordered, or the budget ignores the cap; why_new=#4424; seam=none + test('splits in order under the byte budget, which stays under the argument limits', () => { + const args = ['a'.repeat(10), 'b'.repeat(10), "c'd".repeat(4), 'e'.repeat(40), 'f']; + const chunks = argChunks(args, 30); + expect(chunks).toEqual([[args[0], args[1]], [args[2]], [args[3]], [args[4]]]); + expect(argChunks([], 30)).toEqual([]); + expect(argChunks(args, 1_000)).toEqual([args]); + const linux = argBudget('bun test {files}', {}, 'linux'); + expect(linux).toBeLessThan(128 * 1024); + expect(argBudget('bun test {files}', { BIG: 'x'.repeat(900 * 1024) }, 'linux')).toBeLessThan(1024 * 1024 - 64 * 1024 - 900 * 1024); + expect(argBudget('bun test {files}', {}, 'win32')).toBeLessThan(32 * 1024); + }); +}); + +describe('E2BIG is its own cause', () => { + // Value: protects=an argument list over the system limit is named as such, never as a missing tool; fails_when=E2BIG + // classifies as missing-binary or as nothing (the launch path then defaulted to missing-binary); why_new=#4424's + // misleading "install the named tool"; seam=none + test('classifies E2BIG and "argument list too long" as arg-limit', () => { + expect(classifyEnvironment("E2BIG: argument list too long, posix_spawn 'bash'", null)).toEqual({ kind: 'arg-limit', evidence: "E2BIG: argument list too long, posix_spawn 'bash'", proof: 'output' }); + expect(classifyEnvironment('bash: /usr/bin/node: Argument list too long', 126)?.kind).toBe('arg-limit'); + }); +}); From 18652ccc159970db44a038e71840d7bf6f252209 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 17 Nov 2026 16:17:46 +0800 Subject: [PATCH 12/62] Stop the review coverage eval failing when zsh cuts a file-read line short (GST-2703) (#4364) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../fix-coverage-audit-zsh-separator.md | 1 + test/coverage-audit-evidence.test.ts | 72 +++++++++++++++++++ test/helpers/coverage-audit-evidence.ts | 26 ++++++- 3 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 changelog.d/fix-coverage-audit-zsh-separator.md diff --git a/changelog.d/fix-coverage-audit-zsh-separator.md b/changelog.d/fix-coverage-audit-zsh-separator.md new file mode 100644 index 00000000000..d01c3736ab5 --- /dev/null +++ b/changelog.d/fix-coverage-audit-zsh-separator.md @@ -0,0 +1 @@ +- **The /review coverage-audit eval no longer fails a run that really read the source file when zsh stops a command line at an `echo ====` separator.** zsh treats an unquoted word that starts with `=` as a command lookup, so `cat -n src/billing.ts; echo ====; cat -n test/billing.test.ts` prints the source, then `(eval):1: === not found`, and runs nothing after it. The read check now credits the files printed before that error when the error is the last line of the output and everything before it matches the usual read rules; files after the separator still count only when they are read again (gate census 43575953190). diff --git a/test/coverage-audit-evidence.test.ts b/test/coverage-audit-evidence.test.ts index 202ef0c853b..0f9e472816f 100644 --- a/test/coverage-audit-evidence.test.ts +++ b/test/coverage-audit-evidence.test.ts @@ -1327,3 +1327,75 @@ describe('coverage audit native evidence: a wc -c byte count after both reads (C expect(reads(capture.call.command.replace('cat -n test/billing.test.ts', 'cat -n test/other.test.ts'))).toMatchObject({ testsRead: false }); }); }); + +// Census 43575953190 slice 15 (main 3b650356), review-coverage-audit (claude-opus-5-5): the fifth parent Bash call +// and the Read call after it, byte-exact. zsh printed src/billing.ts, then read `echo ====` as an = command lookup +// and abandoned the line; git status is outside the closed grammar, so the recorded run got no source credit. +const zshAbortCapture = { + cwd: "/home/runner/.cache/gstack-paid-shard-KQjof8/tmp/skill-e2e-review-coverage-jdBN2G", + sessionId: "9b1ad1cd-1385-46f0-833d-651b5f04163c", + bash: { toolUseId: "toolu_0122wJEnMW6jPDckLJfkXr8m", command: "cd /home/runner/.cache/gstack-paid-shard-KQjof8/tmp/skill-e2e-review-coverage-jdBN2G; cat -n src/billing.ts; echo ====; cat -n test/billing.test.ts; git status --short; git diff HEAD --stat", + output: " 1\t\n 2\texport function processPayment(amount: number, currency: string) {\n 3\t if (amount <= 0) throw new Error('Invalid amount');\n 4\t if (currency !== 'USD' && currency !== 'EUR') throw new Error('Unsupported currency');\n 5\t return { status: 'success', amount, currency };\n 6\t}\n 7\t\n 8\texport function refundPayment(paymentId: string, reason: string) {\n 9\t if (!paymentId) throw new Error('Payment ID required');\n 10\t if (!reason) throw new Error('Reason required');\n 11\t return { status: 'refunded', paymentId, reason };\n 12\t}\n 13\t\n 14\t// coverage-read-evidence: 1767bb48-6a07-4691-a75b-42665f7db096\n(eval):1: === not found" }, + read: { toolUseId: "toolu_01DhBQc8Z19EdpFppCbGLapD", filePath: "/home/runner/.cache/gstack-paid-shard-KQjof8/tmp/skill-e2e-review-coverage-jdBN2G/test/billing.test.ts", + output: "1\t\n2\timport { describe, test, expect } from 'vitest';\n3\timport { processPayment } from '../src/billing';\n4\t\n5\tdescribe('processPayment', () => {\n6\t test('processes valid payment', () => {\n7\t const result = processPayment(100, 'USD');\n8\t expect(result.status).toBe('success');\n9\t });\n10\t // GAP: no test for invalid amount\n11\t // GAP: no test for unsupported currency\n12\t // GAP: refundPayment not tested at all\n13\t});\n14\t\n15\t// coverage-read-evidence: 3447f095-74ff-428e-9e33-5bfd0d6d44c9\n16\t" }, +}; + +describe('coverage audit native evidence: zsh abandons the line at an echo ==== separator (census 43575953190 slice 15)', () => { + const capture = zshAbortCapture, { bash } = capture; + const marked = (body: string, output: string) => body + '\n// coverage-read-evidence: ' + output.match(/coverage-read-evidence: (\S+)/)![1] + '\n'; + const files = { cwd: capture.cwd, source: { path: capture.cwd + '/src/billing.ts', content: marked(fixture.files.source, bash.output) }, + tests: { path: capture.cwd + '/test/billing.test.ts', content: marked(fixture.files.tests, capture.read.output) } }; + const both = { sourceRead: true, testsRead: true }, neither = { sourceRead: false, testsRead: false }; + type Call = { toolUseId: string; tool: string; input: Record; isError: boolean; output: string }; + const bashCall = (command = bash.command, output = bash.output, isError = false): Call => + ({ toolUseId: bash.toolUseId, tool: 'Bash', input: { command }, isError, output }); + const readCall: Call = { toolUseId: capture.read.toolUseId, tool: 'Read', input: { file_path: capture.read.filePath }, isError: false, output: capture.read.output }; + const transcript = (calls: Call[]) => [ + { type: 'system', subtype: 'init', session_id: capture.sessionId, cwd: capture.cwd }, + ...calls.flatMap(call => [ + { type: 'assistant', session_id: capture.sessionId, parent_tool_use_id: null, message: { role: 'assistant', content: [{ type: 'tool_use', id: call.toolUseId, name: call.tool, input: call.input }] } }, + { type: 'user', session_id: capture.sessionId, parent_tool_use_id: null, message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: call.toolUseId, is_error: call.isError, content: call.output }] } }, + ]), + ]; + const reads = (command?: string, output?: string, isError?: boolean) => coverageAuditReadEvidence(transcript([bashCall(command, output, isError)]), files); + const verdictOf = (calls: Call[]) => coverageAuditVerdict({ exitReason: 'success', browseErrors: [], output: diagram, transcript: transcript(calls) } as any, files); + const command = bash.command, error = '\n(eval):1: === not found'; + const nonce = files.source.content.match(/coverage-read-evidence: (\S+)/)![1]!; + + test('the source printed before the abort is credited, the unrun test display is not, and both recorded calls pass', () => { + expect(command).toBe(`cd ${capture.cwd}; cat -n src/billing.ts; echo ====; cat -n test/billing.test.ts; git status --short; git diff HEAD --stat`); + expect(bash.output.endsWith(error)).toBe(true); + expect(reads()).toEqual({ sourceRead: true, testsRead: false }); + expect(verdictOf([bashCall(), readCall])).toEqual({ ...both, diagram: true, passed: true, failures: [] }); + expect(verdictOf([bashCall()])).toMatchObject({ sourceRead: true, testsRead: false, passed: false, failures: ['missing successful test-file read'] }); + expect(reads(command.replace('cat -n src/billing.ts; ', 'cat -n src/billing.ts && '))).toEqual({ sourceRead: true, testsRead: false }); + }); + + test('output after the error, a different error, or a line that ran on still gets no credit', () => { + const shown = bash.output.slice(0, -error.length); + for (const output of [bash.output + '\n?? notes.md', bash.output.replace('=== not found', '==== not found'), + bash.output.replace('(eval):1:', 'zsh:1:'), shown, shown + '\n====\n' + files.tests.content]) { + expect(reads(command, output), output.slice(-40)).toEqual(neither); + } + expect(reads(command, bash.output, true)).toEqual(neither); + }); + + test('only an unquoted echo =word standalone after ; or && counts as the abort', () => { + for (const separator of ["echo '===='", 'echo "===="', 'echo SRC ====', 'echo ==== | cat', 'echo ==== || true', 'printf ====', + 'echo =$HOME', 'echo ==== > out.txt', 'cat -n test/billing.test.ts =x', 'echo ==== &']) { + expect(reads(command.replace('echo ====', separator)), separator).toEqual(neither); + } + expect(reads(command.replace('cat -n src/billing.ts; echo ====', 'cat -n src/billing.ts || echo ===='))).toEqual(neither); + }); + + test('the reads before the abort keep the closed grammar and exact complete bytes', () => { + for (const prefix of ['python3 -c pass; cat -n src/billing.ts', 'cat -n src/billing.ts | head -20', 'cat -n src/other.ts', + 'cat -n ../src/billing.ts', 'cat -n $(echo src/billing.ts)', 'cat -n src/billing.ts 2>/dev/null']) { + expect(reads(command.replace('cat -n src/billing.ts', prefix)), prefix).toEqual(neither); + } + expect(reads(command.replace(capture.cwd, capture.cwd + '/src'))).toEqual(neither); + expect(reads(command, bash.output.replace(nonce, nonce.slice(1) + '0'))).toEqual(neither); + expect(reads(command, bash.output.replace(/.*Unsupported currency.*\n/, ''))).toEqual(neither); + expect(reads(command, 'src/billing.ts was read' + error)).toEqual(neither); + }); +}); diff --git a/test/helpers/coverage-audit-evidence.ts b/test/helpers/coverage-audit-evidence.ts index efb3cb01a71..a813d98f0d2 100644 --- a/test/helpers/coverage-audit-evidence.ts +++ b/test/helpers/coverage-audit-evidence.ts @@ -226,8 +226,30 @@ function matchRun(run: Exclude[], out: string, offse * credit. Every later run must still appear in order. */ function shellReads(command: unknown, output: unknown, scope: ShellScope): Set { + const credited = pieceReads(commandPieces(command, scope), output, false); + const abort = credited.size ? undefined : equalsAbort(command, scope); + return abort ? pieceReads(abort, output, true) : credited; +} + +/** + * zsh expands an unquoted word that starts with = into a command path (EQUALS). + * A failed lookup prints `(eval):1: not found` and abandons the rest of + * the line (census 43575953190: `cat -n src; echo ====; cat -n test; git status` + * printed the source, then that error). For a standalone `echo =...` after ; or + * &&, the expected output is the closed prefix's pieces and that one error line, + * ending the output; nothing after the echo ran, so it needs no grammar. + */ +function equalsAbort(command: unknown, scope: ShellScope): Piece[] | undefined { + const words = shellWords(command); + const at = words?.findIndex(word => word.startsWith('=')) ?? -1; + if (!words || at < 2 || !/^=[=A-Za-z0-9_.-]+$/.test(words[at]!) || words[at - 1] !== 'echo' || + ![';', '&&'].includes(words[at - 2]!) || ![undefined, ';', '&&'].includes(words[at + 1])) return undefined; + const pieces = commandPieces(words.slice(0, at - 2).join(' '), scope); + return pieces && [...pieces, { kind: 'label', text: `(eval):1: ${words[at]!.slice(1)} not found` }]; +} + +function pieceReads(pieces: Piece[] | undefined, output: unknown, whole: boolean): Set { const credited = new Set(); - const pieces = commandPieces(command, scope); const text = outputText(output).replace(/\r\n?/g, '\n'); if (!pieces || text.length > 4 * 1024 * 1024) return credited; // Native Bash results are trimmed: leading blank lines of the first run and @@ -291,7 +313,7 @@ function shellReads(command: unknown, output: unknown, scope: ShellScope): Set credited.add(file)); cursor = matched.end; min = max = 0; pending = false; } - return credited; + return whole && (pending || !/^\n*$/.test(out.slice(cursor))) ? new Set() : credited; } function delivered(output: unknown, expected: string): boolean { From be7393888f91c2820857cdd49a43e249ca019882 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 17 Nov 2026 16:25:01 +0800 Subject: [PATCH 13/62] Nightly Windows tests fit their time limit again (GST-2827) (#4409) * Nightly Windows tests fit their time limit again (GST-2827) The Windows duration seed missed 95 of 902 files, so the planner packed them blind and one shard got about 26 minutes of work. Refresh the seed from the 2026-11-16 recording and run eight shards of about 12 minutes. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Docs say the nightly Windows run uses eight shards (GST-2827) CONTRIBUTING.md and docs/support-tiers.md still said six shards after the workflow moved to eight. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .github/workflows/windows-free-tests.yml | 7 +- CONTRIBUTING.md | 2 +- .../windows-nightly-fits-its-time-limit.md | 1 + docs/TESTING_INTERNALS.md | 2 +- docs/support-tiers.md | 2 +- scripts/free-test-durations-windows.json | 1697 +++++++++-------- test/windows-native-workflows.test.ts | 6 +- 7 files changed, 903 insertions(+), 814 deletions(-) create mode 100644 changelog.d/windows-nightly-fits-its-time-limit.md diff --git a/.github/workflows/windows-free-tests.yml b/.github/workflows/windows-free-tests.yml index d94d1d6f2cd..c71663fcbd4 100644 --- a/.github/workflows/windows-free-tests.yml +++ b/.github/workflows/windows-free-tests.yml @@ -110,8 +110,9 @@ jobs: bun-version: 1.4.2 - id: plan name: Curate and balance the Windows-safe free suite - # Six shards: ~85 s of Linux-measured work each, ~2.5 min on a - # 4-vCPU Windows runner, so the lane lands near 4 min with setup. + # Eight shards: the 2026-11-16 Windows seed sums to about 96 min of + # per-file work, about 12 min a shard, which ran at 0.6-0.9x inside a + # shard, so each job lands near 10 min, under its 15-minute limit. env: GSTACK_FREE_TEST_DURATIONS: scripts/free-test-durations-windows.json JOBS_OVERRIDE: ${{ inputs.windows_jobs }} @@ -125,7 +126,7 @@ jobs: if [ "$jobs" != "$WINDOWS_FREE_JOBS" ]; then echo "- Sub-shard experiment: $jobs sub-shards per Windows shard (default $WINDOWS_FREE_JOBS); not a PR Windows Free Tests result" >> "$GITHUB_STEP_SUMMARY" fi - matrix=$(bun run scripts/test-free-shards.ts --windows-only --ci-plan "$RUNNER_TEMP/windows-plan.json" --shards 6 --shard-jobs "$jobs") + matrix=$(bun run scripts/test-free-shards.ts --windows-only --ci-plan "$RUNNER_TEMP/windows-plan.json" --shards 8 --shard-jobs "$jobs") echo "matrix=$matrix" >> "$GITHUB_OUTPUT" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2c60d858f3e..56f9f0e4e64 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -193,7 +193,7 @@ the new defaults. | Run the full free suite from a small machine | `bun run test:ubicloud` | Free suite on a billed 16-vCPU VM, about 5 minutes | `UBICLOUD_API_KEY`, `UBI_OWNER` | | Clear pregate's test tier on a machine under 8 cores from CI, the default on gstack ([CI carry](docs/pregate.md#ci-carry)) | push, `gstack-ci-carry wait --base main`, then `gstack-pregate --allow-repo-commands` (a branch behind main first runs `gh workflow run free-tests.yml --ref `) | Free; reuses the green Free Tests run at your pushed tree | Pushed branch, `gh` | | Clear pregate's test tier on a machine under 8 cores when no CI run covers your tree ([remote gate](docs/pregate.md#remote-gate), opt-in) | `gstack-pregate --stage tests --remote --spend-cap 2 --timeout 2700 --allow-repo-commands` (same command keyed or keyless) | Keyed: one billed 16-vCPU VM, about 7 minutes and $0.06 for the whole free tier, worst case $0.38; keyless: free, local parallel shards, practical for small selections only (98 files took 103 s on 4 cores) | Keyed: `UBICLOUD_API_KEY`, `UBI_OWNER`; keyless: nothing | -| Run the curated Windows-safe subset | `bun run test:windows` (CI: six `windows-latest` jobs, nightly on main; PRs run the shorter `windows-smoke` check, and a PR that touches path, file-name or process code also runs its changed Windows-safe test files in `Windows Scoped Tests`) | Free | Windows, Git Bash | +| Run the curated Windows-safe subset | `bun run test:windows` (CI: eight `windows-latest` jobs, nightly on main; PRs run the shorter `windows-smoke` check, and a PR that touches path, file-name or process code also runs its changed Windows-safe test files in `Windows Scoped Tests`) | Free | Windows, Git Bash | | Rerun chosen Windows-safe test files on Windows CI | `gh workflow run windows-scoped-tests.yml --ref -f files=' '` (pick files from `bun run test:windows --list`) | Free CI runners | Pushed branch, `gh` with workflow rights | | Refresh the Windows duration seed | `gh workflow run windows-free-tests.yml --ref -f record_durations=true`, then commit the `free-test-durations-windows` artifact | Free CI runners | Pushed branch, `gh` with workflow rights | | Run a native Windows qualification campaign | `gh workflow run native-qualification.yml --ref -f mode=` ([modes](docs/TESTING_INTERNALS.md#windows-free-lane)) | Free CI runners | Pushed branch, `gh` with workflow rights | diff --git a/changelog.d/windows-nightly-fits-its-time-limit.md b/changelog.d/windows-nightly-fits-its-time-limit.md new file mode 100644 index 00000000000..d5409538366 --- /dev/null +++ b/changelog.d/windows-nightly-fits-its-time-limit.md @@ -0,0 +1 @@ +- **The nightly Windows test run finishes again.** Since 2026-11-06 one of its six shards ran past the 15-minute job limit almost every night, because 95 newer test files had no recorded Windows duration and the planner packed them blind, so one shard got 26 minutes of work while another got 12. The Windows durations are refreshed to a recording that covers all 902 files, and the run now uses eight shards of about 12 minutes each, so the suite fits with room to grow. No test was dropped and the time limit is unchanged. diff --git a/docs/TESTING_INTERNALS.md b/docs/TESTING_INTERNALS.md index 65042c1da5c..49f6c706966 100644 --- a/docs/TESTING_INTERNALS.md +++ b/docs/TESTING_INTERNALS.md @@ -1808,7 +1808,7 @@ install change is `package.json`'s version line. Both filters are pinned by a branch, dispatch `windows-scoped-tests.yml` with `-f files=' '`. The full curated suite below runs nightly on main and on dispatch, never on a PR. -`windows-free-tests.yml` plans on Linux (`--windows-only --ci-plan --shards 6 +`windows-free-tests.yml` plans on Linux (`--windows-only --ci-plan --shards 8 --shard-jobs $WINDOWS_FREE_JOBS`), runs one strict serial shard per `windows-latest` job (`bun run test:windows --ci-run`), and verifies every shard receipt on Linux diff --git a/docs/support-tiers.md b/docs/support-tiers.md index fc00729bcfe..fad9b308ee3 100644 --- a/docs/support-tiers.md +++ b/docs/support-tiers.md @@ -24,7 +24,7 @@ That is the whole promise. Other skills, optional parts such as `/cso`'s native ## Windows CI - `windows-smoke` is the required Windows check on pull requests. -- The six-shard Windows free suite (the `Windows Free Tests` workflow, `windows-free-tests`) runs nightly on main, or when someone starts it by hand, and never blocks a pull request. The stable release cut ignores its results too, so a red or unfinished nightly never holds a release. +- The eight-shard Windows free suite (the `Windows Free Tests` workflow, `windows-free-tests`) runs nightly on main, or when someone starts it by hand, and never blocks a pull request. The stable release cut ignores its results too, so a red or unfinished nightly never holds a release. - A red nightly run gets a fix only when it shows an install, startup or core-workflow break. - Windows checks run by path (ship-90-90 plan D, approved 2026-11-03): `Windows Scoped Tests` runs a pull request's changed Windows-safe test files on one Windows job only when it touches path, file-name or process code (a red run blocks that pull request, like any failed check), and `Windows Setup E2E` runs only when install files change (a version-only `package.json` change doesn't count). diff --git a/scripts/free-test-durations-windows.json b/scripts/free-test-durations-windows.json index ced94123978..07cb2fde996 100644 --- a/scripts/free-test-durations-windows.json +++ b/scripts/free-test-durations-windows.json @@ -1,821 +1,908 @@ { "version": 1, - "recordedAt": "2026-10-31T18:53:46.380Z", + "recordedAt": "2026-11-16T04:41:11.116Z", "durations": { - "browse/test/activity.test.ts": 160, - "browse/test/adversarial-security.test.ts": 107, - "browse/test/batch.test.ts": 7076, - "browse/test/bridge-chromium-e2e.test.ts": 4156, - "browse/test/browse-client.test.ts": 206, - "browse/test/browse-eval-wrapping.test.ts": 68, - "browse/test/browser-manager-custom-chromium.test.ts": 1339, - "browse/test/browser-skills-storage.test.ts": 146, - "browse/test/build-command-response.test.ts": 1483, - "browse/test/build.test.ts": 175, - "browse/test/bun-child-config.test.ts": 204, - "browse/test/bun-polyfill.test.ts": 2872, - "browse/test/busy-active-tab.test.ts": 14656, - "browse/test/busy-daemon-iron-rule.test.ts": 8417, - "browse/test/busy-daemon-recovery.test.ts": 735, - "browse/test/cdp-allowlist.test.ts": 96, - "browse/test/cdp-e2e.test.ts": 1235, - "browse/test/cdp-inspector-history-cap.test.ts": 67, - "browse/test/cdp-mutex.test.ts": 894, - "browse/test/cdp-session-cleanup.test.ts": 79, - "browse/test/claude-bin.test.ts": 62, - "browse/test/cli-chain-stdin.test.ts": 301, - "browse/test/cli-config-mismatch-message.test.ts": 145, - "browse/test/cli-lock.test.ts": 59, - "browse/test/cli-loopback-no-proxy.test.ts": 65, + "browse/test/activity.test.ts": 113, + "browse/test/adversarial-security.test.ts": 57, + "browse/test/batch.test.ts": 6443, + "browse/test/bridge-chromium-e2e.test.ts": 4320, + "browse/test/browse-client.test.ts": 134, + "browse/test/browse-eval-wrapping.test.ts": 79, + "browse/test/browser-manager-custom-chromium.test.ts": 762, + "browse/test/browser-skills-storage.test.ts": 148, + "browse/test/build-command-response.test.ts": 842, + "browse/test/build.test.ts": 129, + "browse/test/bun-child-config.test.ts": 90, + "browse/test/bun-polyfill.test.ts": 2163, + "browse/test/bundled-chromium-root-store.test.ts": 296, + "browse/test/busy-active-tab.test.ts": 14388, + "browse/test/busy-daemon-iron-rule.test.ts": 7839, + "browse/test/busy-daemon-recovery.test.ts": 646, + "browse/test/cdp-allowlist.test.ts": 42, + "browse/test/cdp-e2e.test.ts": 1046, + "browse/test/cdp-inspector-history-cap.test.ts": 51, + "browse/test/cdp-mutex.test.ts": 1237, + "browse/test/cdp-session-cleanup.test.ts": 89, + "browse/test/chromium-sandbox.test.ts": 833, + "browse/test/claude-bin.test.ts": 55, + "browse/test/cli-chain-stdin.test.ts": 282, + "browse/test/cli-config-mismatch-message.test.ts": 190, + "browse/test/cli-lock.test.ts": 72, + "browse/test/cli-loopback-no-proxy.test.ts": 64, "browse/test/cli-setsid-daemonize.test.ts": 56, - "browse/test/cli-start-final-healthcheck.test.ts": 82, - "browse/test/cli-supervisor.test.ts": 87, - "browse/test/command-timeout-report.test.ts": 191, - "browse/test/content-security.test.ts": 3036, - "browse/test/cookie-auth-verification.test.ts": 20125, - "browse/test/cookie-credential-deadline.test.ts": 373, - "browse/test/cookie-database.test.ts": 802, - "browse/test/cookie-fixture-delete-lease.test.ts": 1189, - "browse/test/cookie-import-browser.test.ts": 109, - "browse/test/cookie-import-native-job.test.ts": 122469, - "browse/test/cookie-import-native.test.ts": 7715, - "browse/test/cookie-import-node.test.ts": 5035, - "browse/test/cookie-import-operation.test.ts": 767, - "browse/test/cookie-import-reliability.test.ts": 1141, - "browse/test/cookie-import-transport.test.ts": 61, - "browse/test/cookie-picker-binding-browser.test.ts": 3337, - "browse/test/cookie-picker-binding.test.ts": 658, - "browse/test/cookie-picker-csrf-browser.test.ts": 1143, - "browse/test/cookie-picker-routes.test.ts": 590, - "browse/test/cookie-picker-ui.test.ts": 41255, - "browse/test/daemon-log-hygiene.test.ts": 164, - "browse/test/daemon-mismatch-refuse.test.ts": 303, - "browse/test/data-platform.test.ts": 78, - "browse/test/domain-skills-e2e.test.ts": 903, - "browse/test/domain-skills-storage.test.ts": 126, - "browse/test/dotenv-isolation.test.ts": 880, - "browse/test/dual-listener.test.ts": 1383, - "browse/test/dx-polish.test.ts": 158, - "browse/test/error-handling.test.ts": 58, - "browse/test/extension-sender-auth.test.ts": 141, - "browse/test/extension-token.test.ts": 2610, - "browse/test/file-drop.test.ts": 65, - "browse/test/file-permissions.test.ts": 565, - "browse/test/fill-change-event.test.ts": 2154, - "browse/test/find-browse.test.ts": 140, - "browse/test/from-file-path-validation.test.ts": 67, - "browse/test/handoff.test.ts": 6209, - "browse/test/headless-gpu-and-reap.test.ts": 966, - "browse/test/headless-launch-options.test.ts": 763, - "browse/test/launch-signal-flags.test.ts": 241, - "browse/test/learnings-injection.test.ts": 2070, - "browse/test/media-extract-unit.test.ts": 51, - "browse/test/memory-command.test.ts": 920, - "browse/test/memory-leak-reproducer.test.ts": 816, - "browse/test/navigation-guard.test.ts": 7147, - "browse/test/output-path-symlinks.test.ts": 44, - "browse/test/pair-agent-optin-gate.test.ts": 863, - "browse/test/path-security-realpath.test.ts": 97, - "browse/test/pdf-flags.test.ts": 51, - "browse/test/playwright-core-patch.test.ts": 57, - "browse/test/poisoned-bundle-probe.test.ts": 378, - "browse/test/process-liveness-windows.test.ts": 2658, + "browse/test/cli-start-final-healthcheck.test.ts": 62, + "browse/test/cli-supervisor.test.ts": 77, + "browse/test/command-timeout-report.test.ts": 137, + "browse/test/content-security.test.ts": 2045, + "browse/test/cookie-auth-verification.test.ts": 16202, + "browse/test/cookie-credential-deadline.test.ts": 300, + "browse/test/cookie-database.test.ts": 648, + "browse/test/cookie-fixture-delete-lease.test.ts": 1183, + "browse/test/cookie-import-browser.test.ts": 91, + "browse/test/cookie-import-native-job.test.ts": 119003, + "browse/test/cookie-import-native.test.ts": 6296, + "browse/test/cookie-import-node.test.ts": 3851, + "browse/test/cookie-import-operation.test.ts": 685, + "browse/test/cookie-import-reliability.test.ts": 1047, + "browse/test/cookie-import-transport.test.ts": 79, + "browse/test/cookie-picker-binding-browser.test.ts": 2741, + "browse/test/cookie-picker-binding.test.ts": 472, + "browse/test/cookie-picker-csrf-browser.test.ts": 781, + "browse/test/cookie-picker-routes.test.ts": 484, + "browse/test/cookie-picker-ui.test.ts": 39821, + "browse/test/daemon-log-hygiene.test.ts": 66, + "browse/test/daemon-mismatch-refuse.test.ts": 200, + "browse/test/data-platform.test.ts": 82, + "browse/test/domain-skills-e2e.test.ts": 680, + "browse/test/domain-skills-storage.test.ts": 139, + "browse/test/dotenv-isolation.test.ts": 807, + "browse/test/dual-listener.test.ts": 1224, + "browse/test/dx-polish.test.ts": 102, + "browse/test/error-handling.test.ts": 360, + "browse/test/extension-sender-auth.test.ts": 94, + "browse/test/extension-token.test.ts": 1941, + "browse/test/file-drop.test.ts": 57, + "browse/test/file-permissions.test.ts": 429, + "browse/test/fill-change-event.test.ts": 2173, + "browse/test/find-browse.test.ts": 123, + "browse/test/from-file-path-validation.test.ts": 37, + "browse/test/handoff.test.ts": 5599, + "browse/test/headless-gpu-and-reap.test.ts": 508, + "browse/test/headless-launch-options.test.ts": 592, + "browse/test/launch-signal-flags.test.ts": 40, + "browse/test/learnings-injection.test.ts": 2985, + "browse/test/media-extract-unit.test.ts": 79, + "browse/test/memory-command.test.ts": 481, + "browse/test/memory-leak-reproducer.test.ts": 513, + "browse/test/navigation-guard.test.ts": 3155, + "browse/test/output-path-symlinks.test.ts": 43, + "browse/test/pair-agent-optin-gate.test.ts": 656, + "browse/test/path-security-realpath.test.ts": 118, + "browse/test/pdf-flags.test.ts": 55, + "browse/test/playwright-core-patch.test.ts": 50, + "browse/test/poisoned-bundle-probe.test.ts": 350, + "browse/test/process-liveness-windows.test.ts": 1983, + "browse/test/project-slug.test.ts": 444, "browse/test/proxy-config.test.ts": 57, - "browse/test/proxy-direct-launch-args.test.ts": 415, - "browse/test/proxy-direct-launch-paths.test.ts": 430, - "browse/test/proxy-direct-launch.test.ts": 60, - "browse/test/proxy-env-daemon.test.ts": 107, - "browse/test/proxy-env.test.ts": 94, - "browse/test/proxy-redact.test.ts": 57, - "browse/test/pty-inject-scan.test.ts": 1434, - "browse/test/pty-session-lease.test.ts": 57, - "browse/test/rebrand-signed-bundle.test.ts": 44, - "browse/test/regression-pr1169-pdf-from-file-invalid-json.test.ts": 76, - "browse/test/restart-env.test.ts": 65, - "browse/test/runtime-root-server-bundle.test.ts": 78, - "browse/test/sanitize.test.ts": 52, - "browse/test/screenshot-size-guard.test.ts": 386, - "browse/test/security-adversarial-fixes.test.ts": 65, - "browse/test/security-adversarial.test.ts": 63, - "browse/test/security-bench.test.ts": 93, - "browse/test/security-classifier-download-cleanup.test.ts": 92, - "browse/test/security-classifier.test.ts": 61, - "browse/test/security-integration.test.ts": 71, - "browse/test/security-live-playwright.test.ts": 1160, - "browse/test/security-sidecar-client.test.ts": 122, - "browse/test/security.test.ts": 74, - "browse/test/server-auth.test.ts": 1019, - "browse/test/server-factory.test.ts": 4248, - "browse/test/server-flush-trackers.test.ts": 50, - "browse/test/server-launch-resolution.test.ts": 67, - "browse/test/server-lock-errors.test.ts": 121, - "browse/test/server-no-import-side-effects.test.ts": 807, - "browse/test/server-pty-lease-routes.test.ts": 645, - "browse/test/server-route-auth-blackbox.test.ts": 2565, - "browse/test/server-route-dispatch-ratchet.test.ts": 542, - "browse/test/server-sanitize-surrogates.test.ts": 761, - "browse/test/server-tmp-state-path.test.ts": 53, - "browse/test/session-cookie-store.test.ts": 90, - "browse/test/sidebar-tabs.test.ts": 824, - "browse/test/sidebar-ux.test.ts": 655, - "browse/test/sidepanel-patient-autoconnect.test.ts": 47, - "browse/test/sidepanel-reattach.test.ts": 47, - "browse/test/sidepanel-restart-dispose.test.ts": 52, - "browse/test/skill-token.test.ts": 76, - "browse/test/socks-bridge.test.ts": 607, - "browse/test/sse-helpers.test.ts": 220, - "browse/test/sse-session-cookie.test.ts": 67, - "browse/test/state-ttl.test.ts": 55, - "browse/test/stealth-extended.test.ts": 52, - "browse/test/stealth-layer-c.test.ts": 63, - "browse/test/stealth-webdriver.test.ts": 9871, - "browse/test/stop-ack-before-shutdown.test.ts": 181, - "browse/test/stop-dead-daemon.test.ts": 623, - "browse/test/tab-each.test.ts": 343, - "browse/test/tab-external-close-dispatch.test.ts": 2123, - "browse/test/tab-external-close.test.ts": 1467, - "browse/test/tab-guardrail.test.ts": 681, - "browse/test/tab-isolation.test.ts": 1280, - "browse/test/tab-session-frame-detach.test.ts": 69, - "browse/test/telemetry-optout.test.ts": 105, - "browse/test/telemetry.test.ts": 78, - "browse/test/temp-dirs.test.ts": 66, - "browse/test/terminal-agent-bun-exe.test.ts": 53, - "browse/test/terminal-agent-detach-reattach.test.ts": 42, + "browse/test/proxy-direct-launch-args.test.ts": 425, + "browse/test/proxy-direct-launch-paths.test.ts": 419, + "browse/test/proxy-direct-launch.test.ts": 63, + "browse/test/proxy-env-daemon.test.ts": 145, + "browse/test/proxy-env.test.ts": 97, + "browse/test/proxy-redact.test.ts": 50, + "browse/test/pty-inject-scan.test.ts": 1452, + "browse/test/pty-session-lease.test.ts": 73, + "browse/test/rebrand-signed-bundle.test.ts": 41, + "browse/test/regression-pr1169-pdf-from-file-invalid-json.test.ts": 368, + "browse/test/restart-env.test.ts": 68, + "browse/test/runtime-root-server-bundle.test.ts": 123, + "browse/test/sanitize.test.ts": 55, + "browse/test/screenshot-size-guard.test.ts": 364, + "browse/test/security-adversarial-fixes.test.ts": 63, + "browse/test/security-adversarial.test.ts": 57, + "browse/test/security-bench.test.ts": 44, + "browse/test/security-classifier-download-cleanup.test.ts": 63, + "browse/test/security-classifier.test.ts": 43, + "browse/test/security-integration.test.ts": 47, + "browse/test/security-live-playwright.test.ts": 1173, + "browse/test/security-sidecar-client.test.ts": 78, + "browse/test/security.test.ts": 49, + "browse/test/server-auth.test.ts": 833, + "browse/test/server-factory.test.ts": 3610, + "browse/test/server-flush-trackers.test.ts": 48, + "browse/test/server-launch-resolution.test.ts": 53, + "browse/test/server-lock-errors.test.ts": 114, + "browse/test/server-no-import-side-effects.test.ts": 655, + "browse/test/server-pty-lease-routes.test.ts": 581, + "browse/test/server-route-auth-blackbox.test.ts": 2239, + "browse/test/server-route-dispatch-ratchet.test.ts": 402, + "browse/test/server-sanitize-surrogates.test.ts": 536, + "browse/test/server-tmp-state-path.test.ts": 43, + "browse/test/session-cookie-store.test.ts": 74, + "browse/test/session-tabs.test.ts": 13012, + "browse/test/sidebar-tabs.test.ts": 731, + "browse/test/sidebar-ux.test.ts": 574, + "browse/test/sidepanel-patient-autoconnect.test.ts": 39, + "browse/test/sidepanel-reattach.test.ts": 40, + "browse/test/sidepanel-restart-dispose.test.ts": 41, + "browse/test/skill-token.test.ts": 46, + "browse/test/socks-bridge.test.ts": 572, + "browse/test/sse-helpers.test.ts": 219, + "browse/test/sse-session-cookie.test.ts": 44, + "browse/test/state-ttl.test.ts": 35, + "browse/test/stealth-extended.test.ts": 38, + "browse/test/stealth-layer-c.test.ts": 43, + "browse/test/stealth-webdriver.test.ts": 8727, + "browse/test/stop-ack-before-shutdown.test.ts": 603, + "browse/test/stop-dead-daemon.test.ts": 360, + "browse/test/tab-each.test.ts": 508, + "browse/test/tab-external-close-dispatch.test.ts": 1253, + "browse/test/tab-external-close.test.ts": 922, + "browse/test/tab-guardrail.test.ts": 466, + "browse/test/tab-isolation.test.ts": 510, + "browse/test/tab-session-frame-detach.test.ts": 47, + "browse/test/telemetry-optout.test.ts": 87, + "browse/test/telemetry.test.ts": 74, + "browse/test/temp-dirs.test.ts": 63, + "browse/test/terminal-agent-bun-exe.test.ts": 60, + "browse/test/terminal-agent-detach-reattach.test.ts": 45, "browse/test/terminal-agent-import.test.ts": 4455, - "browse/test/terminal-agent-keepalive.test.ts": 56, - "browse/test/terminal-agent-native-observation.test.ts": 78, - "browse/test/terminal-agent-owner-watchdog.test.ts": 828, - "browse/test/terminal-agent-pid-identity.test.ts": 140, - "browse/test/terminal-agent-port-range.test.ts": 56, - "browse/test/terminal-agent-ring-buffer-runtime.test.ts": 62, - "browse/test/terminal-agent-session-routing.test.ts": 45, - "browse/test/terminal-agent-signal-cleanup.test.ts": 61, - "browse/test/terminal-agent-watchdog.test.ts": 46, - "browse/test/terminal-agent.test.ts": 783, - "browse/test/terminal-pty-lifecycle.test.ts": 54, - "browse/test/token-registry.test.ts": 68, - "browse/test/tunnel-gate-unit.test.ts": 738, - "browse/test/watch.test.ts": 570, - "browse/test/welcome-page.test.ts": 50, - "browse/test/windows-spawn-hide.test.ts": 84, - "browse/test/xprotect-heal.test.ts": 525, - "browser-skills/hackernews-frontpage/script.test.ts": 73, - "design/test/brief.test.ts": 59, - "design/test/cli-persistence.test.ts": 7082, - "design/test/cli-version.test.ts": 85, - "design/test/feedback-roundtrip-daemon.test.ts": 309, - "design/test/feedback-roundtrip.test.ts": 3629, - "design/test/image-args.test.ts": 102, - "design/test/image-gen-pairing.test.ts": 148, - "design/test/receipted-fetch.test.ts": 66, - "ios-qa/daemon/test/allowlist.test.ts": 73, - "ios-qa/daemon/test/audit.test.ts": 112, - "ios-qa/daemon/test/auth-mint.test.ts": 77, - "ios-qa/daemon/test/daemon-integration.test.ts": 4005, - "ios-qa/daemon/test/proxy-classify.test.ts": 56, - "ios-qa/daemon/test/proxy-transport.test.ts": 1886, - "ios-qa/daemon/test/session-tokens.test.ts": 60, - "ios-qa/daemon/test/single-instance.test.ts": 54, - "ios-qa/daemon/test/tailscale-localapi.test.ts": 65, - "ios-qa/scripts/gen-accessors.test.ts": 145, - "make-pdf/test/asideClient.test.ts": 60, - "make-pdf/test/cli-args.test.ts": 50, - "make-pdf/test/cli-exit-codes.test.ts": 522, - "make-pdf/test/diagram-prepass.test.ts": 153, - "make-pdf/test/docx-image-size.test.ts": 1363, - "make-pdf/test/e2e/ci-prereqs.test.ts": 49, - "make-pdf/test/e2e/combined-gate.test.ts": 54, - "make-pdf/test/e2e/diagram-gate.test.ts": 54, - "make-pdf/test/e2e/emoji-gate.test.ts": 62, - "make-pdf/test/e2e/format-gate.test.ts": 58, - "make-pdf/test/e2e/landscape-gate.test.ts": 60, - "make-pdf/test/e2e/toc-gate.test.ts": 94, + "browse/test/terminal-agent-keepalive.test.ts": 48, + "browse/test/terminal-agent-native-observation.test.ts": 44, + "browse/test/terminal-agent-owner-watchdog.test.ts": 697, + "browse/test/terminal-agent-pid-identity.test.ts": 107, + "browse/test/terminal-agent-port-range.test.ts": 46, + "browse/test/terminal-agent-ring-buffer-runtime.test.ts": 51, + "browse/test/terminal-agent-session-routing.test.ts": 36, + "browse/test/terminal-agent-signal-cleanup.test.ts": 47, + "browse/test/terminal-agent-watchdog.test.ts": 35, + "browse/test/terminal-agent.test.ts": 560, + "browse/test/terminal-pty-lifecycle.test.ts": 47, + "browse/test/token-registry.test.ts": 57, + "browse/test/touch-commands.test.ts": 9046, + "browse/test/tunnel-gate-unit.test.ts": 542, + "browse/test/tunnel-start-state.test.ts": 3137, + "browse/test/watch.test.ts": 533, + "browse/test/welcome-page.test.ts": 52, + "browse/test/windows-spawn-hide.test.ts": 94, + "browse/test/xprotect-heal.test.ts": 422, + "browser-skills/hackernews-frontpage/script.test.ts": 53, + "crew/test/gate-cost.test.ts": 3461, + "crew/test/release-cadence.test.ts": 10373, + "crew/test/release-cut.test.ts": 84596, + "crew/test/release-gate.test.ts": 90358, + "crew/test/replay-pr-selection.test.ts": 3572, + "crew/test/review-dispatch-compare.test.ts": 378, + "crew/test/ship-queue-screen-verdict.test.ts": 245, + "crew/test/ship-queue-train-stamp.test.ts": 74332, + "crew/test/ship-recheck.test.ts": 83078, + "crew/test/train-backstop.test.ts": 26854, + "crew/test/train-gate.test.ts": 10075, + "design/test/brief.test.ts": 58, + "design/test/cli-persistence.test.ts": 7156, + "design/test/cli-version.test.ts": 81, + "design/test/feedback-roundtrip-daemon.test.ts": 268, + "design/test/feedback-roundtrip.test.ts": 3532, + "design/test/image-args.test.ts": 87, + "design/test/image-gen-pairing.test.ts": 152, + "design/test/receipted-fetch.test.ts": 63, + "ios-qa/daemon/test/allowlist.test.ts": 58, + "ios-qa/daemon/test/audit.test.ts": 60, + "ios-qa/daemon/test/auth-mint.test.ts": 65, + "ios-qa/daemon/test/daemon-integration.test.ts": 3982, + "ios-qa/daemon/test/loopback-request.test.ts": 108, + "ios-qa/daemon/test/proxy-classify.test.ts": 55, + "ios-qa/daemon/test/proxy-transport.test.ts": 1859, + "ios-qa/daemon/test/session-tokens.test.ts": 51, + "ios-qa/daemon/test/single-instance.test.ts": 51, + "ios-qa/daemon/test/tailscale-localapi.test.ts": 68, + "ios-qa/scripts/gen-accessors.test.ts": 137, + "make-pdf/test/asideClient.test.ts": 59, + "make-pdf/test/cli-args.test.ts": 48, + "make-pdf/test/cli-exit-codes.test.ts": 504, + "make-pdf/test/diagram-prepass.test.ts": 169, + "make-pdf/test/docx-image-size.test.ts": 1207, + "make-pdf/test/e2e/ci-prereqs.test.ts": 51, + "make-pdf/test/e2e/combined-gate.test.ts": 55, + "make-pdf/test/e2e/diagram-gate.test.ts": 70, + "make-pdf/test/e2e/emoji-gate.test.ts": 60, + "make-pdf/test/e2e/format-gate.test.ts": 62, + "make-pdf/test/e2e/landscape-gate.test.ts": 56, + "make-pdf/test/e2e/toc-gate.test.ts": 60, "make-pdf/test/image-policy.test.ts": 62, - "make-pdf/test/render-offline-sanitize.test.ts": 86, - "make-pdf/test/render.test.ts": 123, - "make-pdf/test/setup-smoke.test.ts": 139, - "make-pdf/test/toc-anchors.test.ts": 87, - "make-pdf/test/toc-pages.test.ts": 97, - "test/agents-digest.test.ts": 66, - "test/analytics.test.ts": 75, - "test/anthropic-preflight.test.ts": 59, - "test/archaeology-lint.test.ts": 4641, - "test/arm-benchmark-selftest.test.ts": 3993, - "test/arm-setup-smoke-workflow.test.ts": 190, - "test/auq-format-always-loaded.test.ts": 112, - "test/auq-native-capture.test.ts": 579, - "test/auq-parallel.test.ts": 37752, - "test/auq-substance-panel.test.ts": 236, - "test/autoplan-admission.test.ts": 2577, - "test/autoplan-artifact-windows-argv.test.ts": 306, - "test/autoplan-bounded-journal.test.ts": 854, - "test/autoplan-budget.test.ts": 19815, + "make-pdf/test/render-offline-sanitize.test.ts": 80, + "make-pdf/test/render.test.ts": 114, + "make-pdf/test/setup-smoke.test.ts": 156, + "make-pdf/test/toc-anchors.test.ts": 76, + "make-pdf/test/toc-pages.test.ts": 88, + "test/agent-notes.test.ts": 104, + "test/agents-digest.test.ts": 55, + "test/analytics.test.ts": 94, + "test/anthropic-preflight.test.ts": 55, + "test/archaeology-lint.test.ts": 5669, + "test/arm-setup-smoke-workflow.test.ts": 179, + "test/auq-format-always-loaded.test.ts": 128, + "test/auq-native-capture.test.ts": 473, + "test/auq-parallel.test.ts": 42441, + "test/auq-substance-panel.test.ts": 397, + "test/autoplan-admission.test.ts": 3237, + "test/autoplan-artifact-windows-argv.test.ts": 329, + "test/autoplan-bounded-journal.test.ts": 1065, + "test/autoplan-budget.test.ts": 23257, "test/autoplan-capy-e2e.test.ts": 18831, - "test/autoplan-carry.test.ts": 60768, - "test/autoplan-compaction-copies.test.ts": 374, - "test/autoplan-compaction-preserved-segment.test.ts": 1977, - "test/autoplan-guard-log.test.ts": 124, - "test/autoplan-guard-pty-fixture.test.ts": 103, + "test/autoplan-carry.test.ts": 87579, + "test/autoplan-compaction-copies.test.ts": 947, + "test/autoplan-compaction-preserved-segment.test.ts": 3156, + "test/autoplan-guard-log.test.ts": 204, + "test/autoplan-guard-pty-fixture.test.ts": 194, "test/autoplan-guard-reasons.test.ts": 61, - "test/autoplan-init.test.ts": 2169, - "test/autoplan-long-session-observer.test.ts": 156, - "test/autoplan-method-read-audit.test.ts": 603, - "test/autoplan-owned-read.test.ts": 5951, - "test/autoplan-owned-state.test.ts": 1343, - "test/autoplan-pairing.test.ts": 107, - "test/autoplan-pending-artifact.test.ts": 68, - "test/autoplan-pending-question.test.ts": 4655, - "test/autoplan-phase-handoff.test.ts": 263, - "test/autoplan-phase-observer.test.ts": 74, - "test/autoplan-phase-order.test.ts": 150, - "test/autoplan-public-narration.test.ts": 113, - "test/autoplan-publication-generation.test.ts": 205, - "test/autoplan-publication-guard.test.ts": 5629, - "test/autoplan-publication-hook.test.ts": 3584, - "test/autoplan-publication-payload.test.ts": 11796, - "test/autoplan-record.test.ts": 5156, - "test/autoplan-revise.test.ts": 18974, - "test/autoplan-schema-canary-compare.test.ts": 72, - "test/benchmark-runner.test.ts": 80, - "test/binary-version-probe.test.ts": 371, - "test/binding-template-drift.test.ts": 296, - "test/bootstrap-retention-shard.test.ts": 58, - "test/bootstrap-session-lifecycle.test.ts": 52, - "test/brain-cache-roundtrip.test.ts": 525, - "test/brain-cache-spec.test.ts": 72, - "test/brain-preflight.test.ts": 112, - "test/build-script-shell-compat.test.ts": 52, - "test/bun-config-shell-bins.test.ts": 14148, - "test/bun-isolation-launch.test.ts": 1147, - "test/bun-subprocess-fd-lifetime.test.ts": 69, - "test/cache-concurrent-refresh.test.ts": 133, - "test/captain-skill.test.ts": 76, - "test/carve-guard-completeness.test.ts": 117, - "test/carve-guards-negative.test.ts": 117, - "test/carve-plan-fixture.test.ts": 992, - "test/carve-section-ordering.test.ts": 138, - "test/carve-section-sharding.test.ts": 4590, - "test/catalog-budget.test.ts": 124, - "test/catalog-mode-full.test.ts": 2918, - "test/catalog-trim.test.ts": 158, - "test/census-red-docs.test.ts": 115, - "test/ceo-barless-submit.test.ts": 219, - "test/ceo-count-ad-v2.test.ts": 98, - "test/ceo-expansion-auq.test.ts": 230, - "test/ceo-expansion-pacing-native.test.ts": 181, - "test/ceo-hold-posture-review.test.ts": 330, - "test/ceo-mode-expansion-disposition.test.ts": 198, - "test/ceo-mode-handoff-hook.test.ts": 348, - "test/ceo-mode-labels-native.test.ts": 140, - "test/ceo-mode-option.test.ts": 915, - "test/ceo-mode-pending-submit.test.ts": 128, - "test/ceo-mode-posture-native.test.ts": 145, - "test/ceo-mode-prerequisite.test.ts": 145, - "test/ceo-mode-routing-fixture.test.ts": 8553, - "test/ceo-plan-mode-fixture.test.ts": 6883, - "test/ceo-posture-packet.test.ts": 160, - "test/ceo-section-loading-fixture.test.ts": 935, - "test/ceo-split-collection.test.ts": 981, - "test/ceo-split-question-policy.test.ts": 881, - "test/ceo-stale-fill-decision.test.ts": 209, - "test/ceo-workflow-clarity.test.ts": 84, - "test/changed-files-union.test.ts": 4655, - "test/changelog-fragments.test.ts": 26676, - "test/changelog-merge-damage.test.ts": 150, - "test/ci-image-cli-pin.test.ts": 103, - "test/ci-image-tag-binding.test.ts": 66, - "test/ci-paid-coordination.test.ts": 27721, - "test/claude-code-runner.test.ts": 5627, - "test/claude-code-windows-job.test.ts": 3271, - "test/claude-md-size.test.ts": 53, - "test/claude-overlay-models.test.ts": 126, - "test/claude-producer-stream.test.ts": 85, - "test/claude-provider-keychain.test.ts": 225, - "test/claude-usage.test.ts": 3864, - "test/codex-carve-fixture.test.ts": 4408, - "test/codex-generation-model.test.ts": 448, - "test/codex-invocation-sites.test.ts": 1091, - "test/codex-resume-flag-semantics.test.ts": 106, - "test/compare-pr-version.test.ts": 40386, - "test/conductor-env-shim.test.ts": 74, - "test/context-budget-ratchet.test.ts": 586, - "test/context-remaining-work-provenance.test.ts": 67, - "test/context-restore-fragment-verdict.test.ts": 109, - "test/copilot-windows-bash.test.ts": 63, - "test/cost-known.test.ts": 201, - "test/coverage-audit.test.ts": 9537, - "test/cso-bounded-file.test.ts": 82, - "test/cso-docker-policy.test.ts": 112, - "test/cso-docker-socket-realpath.test.ts": 104, - "test/cso-git-global-config.test.ts": 150, - "test/cso-git-hardening.test.ts": 100, - "test/cso-history.test.ts": 76, - "test/cso-image-provisioning.test.ts": 319, - "test/cso-lease-identity.test.ts": 436, - "test/cso-native-evidence.test.ts": 114, - "test/cso-node-lifecycle-integration.test.ts": 118, - "test/cso-ntfs-fixture.test.ts": 594, - "test/cso-postgresql-policy.test.ts": 92, - "test/cso-preparation-java.test.ts": 90, - "test/cso-preparation.test.ts": 299, - "test/cso-preserved.test.ts": 103, - "test/cso-public-ghcr.test.ts": 71, - "test/cso-requalification.test.ts": 180, - "test/cso-runtime-promotion.test.ts": 392, - "test/cso-scanner-docker-integration.test.ts": 104, - "test/cso-scanners.test.ts": 298, - "test/cso-snapshot-disappearance-race.test.ts": 70, - "test/cso-spec-taxonomy-alignment.test.ts": 66, - "test/cso-staging-run.test.ts": 227, - "test/cso-verifier.test.ts": 102, - "test/cso-windows-build-contract.test.ts": 73, - "test/cso-windows-docker.test.ts": 74, - "test/declared-annotation.test.ts": 70, - "test/defensive-review-framing.test.ts": 63, - "test/dependency-security.test.ts": 233, - "test/deps-smoke.test.ts": 139, - "test/design-board-reload.test.ts": 347, - "test/design-catalog.test.ts": 104, - "test/design-checklist-sync.test.ts": 2700, + "test/autoplan-init.test.ts": 2289, + "test/autoplan-long-session-observer.test.ts": 186, + "test/autoplan-method-read-audit.test.ts": 600, + "test/autoplan-owned-read.test.ts": 6298, + "test/autoplan-owned-state.test.ts": 799, + "test/autoplan-owner-words.test.ts": 102, + "test/autoplan-pending-artifact.test.ts": 54, + "test/autoplan-pending-question.test.ts": 4633, + "test/autoplan-phase-handoff.test.ts": 191, + "test/autoplan-phase-observer.test.ts": 56, + "test/autoplan-phase-order.test.ts": 153, + "test/autoplan-public-narration.test.ts": 98, + "test/autoplan-publication-generation.test.ts": 159, + "test/autoplan-publication-guard.test.ts": 6471, + "test/autoplan-publication-hook.test.ts": 3388, + "test/autoplan-publication-mid-sentence.test.ts": 193, + "test/autoplan-publication-payload.test.ts": 11935, + "test/autoplan-record.test.ts": 5392, + "test/autoplan-revise.test.ts": 16141, + "test/autoplan-schema-canary-compare.test.ts": 81, + "test/autoplan-shadow.test.ts": 7088, + "test/benchmark-runner.test.ts": 66, + "test/binary-version-probe.test.ts": 287, + "test/binding-template-drift.test.ts": 248, + "test/bootstrap-retention-shard.test.ts": 46, + "test/bootstrap-session-lifecycle.test.ts": 45, + "test/brain-cache-roundtrip.test.ts": 414, + "test/brain-cache-spec.test.ts": 65, + "test/brain-preflight.test.ts": 96, + "test/build-script-shell-compat.test.ts": 41, + "test/bun-config-shell-bins.test.ts": 14897, + "test/bun-isolation-launch.test.ts": 938, + "test/bun-subprocess-fd-lifetime.test.ts": 51, + "test/cache-concurrent-refresh.test.ts": 108, + "test/captain-skill.test.ts": 64, + "test/carve-guard-completeness.test.ts": 62, + "test/carve-guards-negative.test.ts": 74, + "test/carve-plan-fixture.test.ts": 680, + "test/carve-section-ordering.test.ts": 88, + "test/carve-section-sharding.test.ts": 3433, + "test/catalog-budget.test.ts": 164, + "test/catalog-mode-full.test.ts": 2837, + "test/catalog-trim.test.ts": 190, + "test/census-red-docs.test.ts": 120, + "test/ceo-barless-submit.test.ts": 216, + "test/ceo-count-ad-v2.test.ts": 99, + "test/ceo-expansion-auq.test.ts": 222, + "test/ceo-expansion-pacing-native.test.ts": 197, + "test/ceo-hold-posture-review.test.ts": 270, + "test/ceo-mode-expansion-disposition.test.ts": 144, + "test/ceo-mode-handoff-hook.test.ts": 260, + "test/ceo-mode-labels-native.test.ts": 116, + "test/ceo-mode-option.test.ts": 711, + "test/ceo-mode-pending-submit.test.ts": 113, + "test/ceo-mode-posture-native.test.ts": 100, + "test/ceo-mode-prerequisite.test.ts": 116, + "test/ceo-mode-routing-fixture.test.ts": 6750, + "test/ceo-plan-mode-fixture.test.ts": 5392, + "test/ceo-posture-packet.test.ts": 126, + "test/ceo-review-gate.test.ts": 40231, + "test/ceo-section-loading-fixture.test.ts": 719, + "test/ceo-split-collection.test.ts": 869, + "test/ceo-split-question-policy.test.ts": 694, + "test/ceo-stale-fill-decision.test.ts": 173, + "test/ceo-workflow-clarity.test.ts": 71, + "test/changed-files-union.test.ts": 3696, + "test/changelog-fragments.test.ts": 21734, + "test/changelog-merge-damage.test.ts": 126, + "test/ci-carry.test.ts": 110, + "test/ci-history-read.test.ts": 18827, + "test/ci-image-cli-pin.test.ts": 79, + "test/ci-image-tag-binding.test.ts": 45, + "test/ci-paid-coordination.test.ts": 23657, + "test/ci-reuse-workflow-wiring.test.ts": 889, + "test/ci-tree-reuse.test.ts": 73, + "test/claude-code-runner.test.ts": 5072, + "test/claude-code-windows-job.test.ts": 3118, + "test/claude-md-size.test.ts": 50, + "test/claude-overlay-models.test.ts": 96, + "test/claude-producer-stream.test.ts": 82, + "test/claude-provider-keychain.test.ts": 212, + "test/claude-usage.test.ts": 6237, + "test/codex-carve-fixture.test.ts": 3609, + "test/codex-generation-model.test.ts": 316, + "test/codex-invocation-sites.test.ts": 1016, + "test/codex-resume-flag-semantics.test.ts": 89, + "test/compare-pr-version.test.ts": 33728, + "test/conductor-env-shim.test.ts": 54, + "test/conflict-markers.test.ts": 4456, + "test/context-budget-ratchet.test.ts": 528, + "test/context-remaining-work-provenance.test.ts": 52, + "test/context-restore-fragment-verdict.test.ts": 76, + "test/copilot-windows-bash.test.ts": 67, + "test/cost-known.test.ts": 173, + "test/coverage-audit.test.ts": 7654, + "test/crew-move-layout.test.ts": 60, + "test/cso-bounded-file.test.ts": 66, + "test/cso-docker-policy.test.ts": 81, + "test/cso-docker-socket-realpath.test.ts": 73, + "test/cso-git-global-config.test.ts": 136, + "test/cso-git-hardening.test.ts": 67, + "test/cso-history.test.ts": 67, + "test/cso-image-provisioning.test.ts": 278, + "test/cso-lease-identity.test.ts": 350, + "test/cso-native-evidence.test.ts": 98, + "test/cso-node-lifecycle-integration.test.ts": 99, + "test/cso-ntfs-fixture.test.ts": 650, + "test/cso-postgresql-policy.test.ts": 75, + "test/cso-preparation-java.test.ts": 91, + "test/cso-preparation.test.ts": 202, + "test/cso-preserved.test.ts": 61, + "test/cso-public-ghcr.test.ts": 62, + "test/cso-requalification.test.ts": 171, + "test/cso-runtime-promotion.test.ts": 381, + "test/cso-scanner-docker-integration.test.ts": 97, + "test/cso-scanners.test.ts": 280, + "test/cso-snapshot-disappearance-race.test.ts": 72, + "test/cso-spec-taxonomy-alignment.test.ts": 58, + "test/cso-staging-run.test.ts": 201, + "test/cso-verifier.test.ts": 93, + "test/cso-windows-build-contract.test.ts": 64, + "test/cso-windows-docker.test.ts": 64, + "test/declared-annotation.test.ts": 60, + "test/defensive-review-framing.test.ts": 60, + "test/dependency-security.test.ts": 187, + "test/deps-smoke.test.ts": 157, + "test/design-board-reload.test.ts": 183, + "test/design-catalog.test.ts": 119, + "test/design-checklist-sync.test.ts": 2311, "test/design-completion-handoff-scored.test.ts": 94, - "test/design-consultation-contract.test.ts": 93, - "test/design-daemon-windows-identity.test.ts": 145, - "test/design-detect-contract.test.ts": 305, - "test/design-doc-data-guard.test.ts": 58, - "test/design-flag-utils.test.ts": 118, - "test/design-html-section-completion.test.ts": 10775, - "test/design-lint-assets.test.ts": 301, - "test/design-lint-chrome.test.ts": 471, - "test/design-lint-color.test.ts": 298, - "test/design-lint-eighth-cycle.test.ts": 22196, - "test/design-lint-fifth-cycle.test.ts": 10167, - "test/design-lint-finish.test.ts": 449, - "test/design-lint-fourth-cycle.test.ts": 10243, - "test/design-lint-motion.test.ts": 417, - "test/design-lint-recorded.test.ts": 167, - "test/design-lint-render.test.ts": 183, - "test/design-lint-settle.test.ts": 204, - "test/design-lint-structure.test.ts": 909, - "test/design-lint-tailwind.test.ts": 374, - "test/design-lint-type.test.ts": 304, - "test/design-md.test.ts": 1673, - "test/design-printed-paths.test.ts": 249, - "test/design-research-fixture.test.ts": 68, - "test/detector-corpora.test.ts": 966, - "test/detector-corpus-auto-decide-preserved.test.ts": 157, - "test/detector-corpus-plan-ceo-section-loading.test.ts": 166, - "test/detector-corpus-plan-design-review-plan-mode.test.ts": 2027, - "test/detector-corpus-plan-eng-multi-finding-batching.test.ts": 507, - "test/detector-corpus-shared-libs-plan-callers.test.ts": 93, - "test/detector-corpus-ship-docsync-late-result.test.ts": 156, - "test/detector-corpus-ship-docsync-launch-failure.test.ts": 144, - "test/devex-finding-fixture.test.ts": 3925, - "test/devex-peer-comparison-calibration.test.ts": 875, - "test/diagram-render-drift.test.ts": 190, - "test/disabled-dated-record-at.test.ts": 195, - "test/discover-section-templates.test.ts": 73, - "test/dispatch-rules.test.ts": 118, - "test/docsync-authority.test.ts": 10290, - "test/docsync-child-marker.test.ts": 80, - "test/docsync-lifecycle-interface.test.ts": 1496, - "test/doctor-components.test.ts": 122, - "test/document-skills-redaction.test.ts": 131, - "test/dom-dump-hygiene.test.ts": 731, - "test/dx-error-contract-grader.test.ts": 83, - "test/dx-error-contract.test.ts": 110, - "test/dx-selected-navigation-ap.test.ts": 213, - "test/e2e-harness-audit.test.ts": 91, - "test/e2e-tier-alignment.test.ts": 453, - "test/eng-batching-current-ledger.test.ts": 667, - "test/eng-batching-native-replay.test.ts": 198, - "test/eng-batching-saved-ledger.test.ts": 1600, - "test/eng-count-question-policy.test.ts": 159, - "test/eng-devex-s-count.test.ts": 145, - "test/eng-finding-retry-budget.test.ts": 3132, - "test/eng-first-review.test.ts": 575, - "test/eng-published-navigation.test.ts": 226, - "test/eng-resolution-block-position.test.ts": 612, - "test/eng-review-routing.test.ts": 106, - "test/eng-seeded-completion-ai.test.ts": 16846, - "test/eng-seeded-coverage.test.ts": 4582, - "test/eng-semantic-terminal.test.ts": 310, - "test/env-host-runtime-assets.test.ts": 5833, - "test/eval-budgets-policy.test.ts": 205, - "test/eval-flake-rank.test.ts": 1031, - "test/eval-history.test.ts": 3501, - "test/eval-kinds.test.ts": 118, - "test/eval-model.test.ts": 57, - "test/eval-sweep-workflow.test.ts": 61, - "test/evals-workflow-wiring.test.ts": 2006, - "test/exit-propagation.test.ts": 447, - "test/extension-pty-inject-invariant.test.ts": 65, - "test/external-host-carve.test.ts": 7604, - "test/flake-ledger.test.ts": 135, - "test/free-home-guard.test.ts": 91, - "test/free-seed-ratchet.test.ts": 612, - "crew/test/gate-cost.test.ts": 4457, - "test/gate-integrity-templates.test.ts": 133, - "test/gateway-provider.test.ts": 300, - "test/gbrain-detection-override.test.ts": 3050, - "test/gbrain-exec-invariant.test.ts": 60, - "test/gbrain-guards.test.ts": 176, - "test/gbrain-source-gitignore.test.ts": 982, - "test/gbrain-sources-parse.test.ts": 84, - "test/gbrain-spawn-windows-shell.test.ts": 222, - "test/gbrain-sync-voyage-code-3-integration.test.ts": 83, - "test/gen-skill-docs-checks.test.ts": 53939, - "test/gen-skill-docs-idempotency.test.ts": 9501, - "test/gen-skill-docs-import-purity.test.ts": 159, - "test/gen-skill-docs-prune-stale.test.ts": 1750, - "test/generated-docs-fences.test.ts": 1799, - "test/generator-eexist.test.ts": 1098, - "test/git-ref-fixture-tripwire.test.ts": 383, - "test/gitattributes-eol.test.ts": 3371, - "test/global-discover.test.ts": 7581, - "test/greptile-early.test.ts": 108, - "test/gstack-checks-go.test.ts": 14998, - "test/gstack-ci-gate.test.ts": 81, - "test/gstack-coauthor-trailers.test.ts": 5465, - "test/gstack-config-gbrain-refresh.test.ts": 2327, - "test/gstack-design-detect-plugins.test.ts": 862, - "test/gstack-doctor-check.test.ts": 186801, - "test/gstack-doctor-launch.test.ts": 162316, - "test/gstack-doctor.test.ts": 169652, - "test/gstack-home-module-scope.test.ts": 370, - "test/gstack-launch-probe.test.ts": 101, - "test/gstack-lease-git-bash.test.ts": 3733, - "test/gstack-post.test.ts": 297, - "test/gstack-regen.test.ts": 43012, - "test/gstack-render-cli.test.ts": 1110, - "test/gstack-schema-pack.test.ts": 136, - "test/gstack-ship-receipt-docs.test.ts": 47116, - "test/gstack-upgrade-migration-v1_78_0_0.test.ts": 533, - "test/gstack-wtree-windows-paths.test.ts": 1261, - "test/harness-version.test.ts": 550, - "test/helpers-unit.test.ts": 131, - "test/helpers/budget-override.test.ts": 85, - "test/helpers/capture-parity-baseline.test.ts": 669, - "test/helpers/claude-pty-runner.auq.unit.test.ts": 185, - "test/helpers/claude-pty-runner.boundaries.unit.test.ts": 187, - "test/helpers/claude-pty-runner.classify.unit.test.ts": 144, - "test/helpers/claude-pty-runner.launch.unit.test.ts": 80, - "test/helpers/claude-pty-runner.plan-native.unit.test.ts": 120, - "test/helpers/claude-pty-runner.runners.unit.test.ts": 2046, - "test/helpers/claude-pty-runner.scope-gate-floor.unit.test.ts": 128, - "test/helpers/claude-pty-runner.screen.unit.test.ts": 149, - "test/helpers/e2e-gate.unit.test.ts": 81, - "test/helpers/eval-store.test.ts": 4095, - "test/helpers/hermetic-env.test.ts": 18718, - "test/helpers/observability.test.ts": 671, - "test/helpers/providers/gemini.test.ts": 80, - "test/helpers/run-bin.test.ts": 219, - "test/heredoc-pipe-deadlock.test.ts": 811, - "test/honesty-kernel.test.ts": 140, - "test/hook-scripts.test.ts": 252101, - "test/host-renders-openai-yaml-proof.test.ts": 141, - "test/instruction-facts.test.ts": 168, - "test/ios-debug-bridge-release-guard.test.ts": 75, + "test/design-consultation-contract.test.ts": 88, + "test/design-daemon-windows-identity.test.ts": 158, + "test/design-detect-contract.test.ts": 345, + "test/design-doc-data-guard.test.ts": 55, + "test/design-flag-utils.test.ts": 106, + "test/design-html-section-completion.test.ts": 8074, + "test/design-lint-assets.test.ts": 319, + "test/design-lint-chrome.test.ts": 366, + "test/design-lint-color.test.ts": 235, + "test/design-lint-eighth-cycle.test.ts": 21442, + "test/design-lint-fifth-cycle.test.ts": 8102, + "test/design-lint-finish.test.ts": 424, + "test/design-lint-fourth-cycle.test.ts": 9050, + "test/design-lint-motion.test.ts": 370, + "test/design-lint-recorded.test.ts": 128, + "test/design-lint-render.test.ts": 105, + "test/design-lint-settle.test.ts": 171, + "test/design-lint-structure.test.ts": 724, + "test/design-lint-tailwind.test.ts": 324, + "test/design-lint-type.test.ts": 243, + "test/design-md.test.ts": 1277, + "test/design-printed-paths.test.ts": 216, + "test/design-research-fixture.test.ts": 49, + "test/detector-corpora.test.ts": 864, + "test/detector-corpus-auto-decide-preserved.test.ts": 96, + "test/detector-corpus-plan-ceo-section-loading.test.ts": 91, + "test/detector-corpus-plan-design-review-plan-mode.test.ts": 1675, + "test/detector-corpus-plan-eng-multi-finding-batching.test.ts": 438, + "test/detector-corpus-shared-libs-plan-callers.test.ts": 66, + "test/detector-corpus-ship-docsync-late-result.test.ts": 115, + "test/detector-corpus-ship-docsync-launch-failure.test.ts": 121, + "test/devex-finding-fixture.test.ts": 3597, + "test/devex-peer-comparison-calibration.test.ts": 830, + "test/diagram-render-drift.test.ts": 144, + "test/disabled-dated-record-at.test.ts": 193, + "test/discover-section-templates.test.ts": 53, + "test/dispatch-rules.test.ts": 115, + "test/docs-only-carry.test.ts": 67, + "test/docs-only-workflow.test.ts": 60, + "test/docsync-authority.test.ts": 8032, + "test/docsync-child-marker.test.ts": 64, + "test/docsync-lifecycle-interface.test.ts": 1183, + "test/doctor-components.test.ts": 144, + "test/document-skills-redaction.test.ts": 85, + "test/dom-dump-hygiene.test.ts": 403, + "test/dx-error-contract-grader.test.ts": 77, + "test/dx-error-contract.test.ts": 88, + "test/dx-selected-navigation-ap.test.ts": 161, + "test/e2e-harness-audit.test.ts": 67, + "test/e2e-tier-alignment.test.ts": 330, + "test/eng-batching-current-ledger.test.ts": 481, + "test/eng-batching-native-replay.test.ts": 169, + "test/eng-batching-saved-ledger.test.ts": 1142, + "test/eng-count-question-policy.test.ts": 109, + "test/eng-devex-s-count.test.ts": 126, + "test/eng-finding-retry-budget.test.ts": 1500, + "test/eng-first-review.test.ts": 461, + "test/eng-published-navigation.test.ts": 132, + "test/eng-resolution-block-position.test.ts": 575, + "test/eng-review-routing.test.ts": 97, + "test/eng-seeded-completion-ai.test.ts": 16163, + "test/eng-seeded-coverage.test.ts": 3846, + "test/eng-semantic-terminal.test.ts": 156, + "test/eval-budgets-policy.test.ts": 147, + "test/eval-flake-rank.test.ts": 824, + "test/eval-history.test.ts": 4338, + "test/eval-kinds.test.ts": 116, + "test/eval-model.test.ts": 165, + "test/eval-sweep-workflow.test.ts": 179, + "test/evals-workflow-wiring.test.ts": 1306, + "test/exit-propagation.test.ts": 489, + "test/extension-pty-inject-invariant.test.ts": 52, + "test/external-host-carve.test.ts": 7522, + "test/failure-routing-arm.test.ts": 2290, + "test/flake-ledger.test.ts": 127, + "test/free-home-guard.test.ts": 71, + "test/free-seed-ratchet.test.ts": 550, + "test/gate-integrity-templates.test.ts": 96, + "test/gateway-provider.test.ts": 243, + "test/gbrain-detection-override.test.ts": 2957, + "test/gbrain-exec-invariant.test.ts": 43, + "test/gbrain-guards.test.ts": 73, + "test/gbrain-source-gitignore.test.ts": 979, + "test/gbrain-sources-parse.test.ts": 54, + "test/gbrain-sync-voyage-code-3-integration.test.ts": 72, + "test/gen-skill-docs-checks.test.ts": 46425, + "test/gen-skill-docs-idempotency.test.ts": 8140, + "test/gen-skill-docs-import-purity.test.ts": 154, + "test/gen-skill-docs-prune-stale.test.ts": 1398, + "test/generated-docs-fences.test.ts": 1214, + "test/generator-eexist.test.ts": 855, + "test/gh-poll-tripwire.test.ts": 237, + "test/gh-poll.test.ts": 68, + "test/git-fixture-template.test.ts": 5524, + "test/git-ref-fixture-tripwire.test.ts": 355, + "test/gitattributes-eol.test.ts": 2988, + "test/global-discover.test.ts": 6631, + "test/greptile-early.test.ts": 97, + "test/ground-rules.test.ts": 51, + "test/gstack-checks-go.test.ts": 10095, + "test/gstack-ci-gate.test.ts": 70, + "test/gstack-coauthor-trailers.test.ts": 6276, + "test/gstack-config-gbrain-refresh.test.ts": 3634, + "test/gstack-design-detect-plugins.test.ts": 948, + "test/gstack-doctor-check.test.ts": 167976, + "test/gstack-doctor-launch.test.ts": 174850, + "test/gstack-doctor.test.ts": 212125, + "test/gstack-home-module-scope.test.ts": 473, + "test/gstack-launch-probe.test.ts": 92, + "test/gstack-lease-git-bash.test.ts": 3405, + "test/gstack-post.test.ts": 262, + "test/gstack-regen.test.ts": 35617, + "test/gstack-render-cli.test.ts": 789, + "test/gstack-schema-pack.test.ts": 65, + "test/gstack-ship-receipt-docs.test.ts": 100209, + "test/gstack-upgrade-migration-v1_78_0_0.test.ts": 438, + "test/gstack-wtree-windows-paths.test.ts": 932, + "test/harness-version.test.ts": 2612, + "test/health-detect-no-loss.test.ts": 5684, + "test/helpers-unit.test.ts": 107, + "test/helpers/budget-override.test.ts": 91, + "test/helpers/capture-parity-baseline.test.ts": 560, + "test/helpers/claude-pty-runner.auq.unit.test.ts": 143, + "test/helpers/claude-pty-runner.boundaries.unit.test.ts": 393, + "test/helpers/claude-pty-runner.classify.unit.test.ts": 121, + "test/helpers/claude-pty-runner.launch.unit.test.ts": 79, + "test/helpers/claude-pty-runner.plan-native.unit.test.ts": 94, + "test/helpers/claude-pty-runner.runners.unit.test.ts": 2355, + "test/helpers/claude-pty-runner.scope-gate-floor.unit.test.ts": 103, + "test/helpers/claude-pty-runner.screen.unit.test.ts": 95, + "test/helpers/e2e-gate.unit.test.ts": 51, + "test/helpers/eval-store.test.ts": 3118, + "test/helpers/hermetic-env.test.ts": 16603, + "test/helpers/observability.test.ts": 523, + "test/helpers/providers/gemini.test.ts": 66, + "test/helpers/run-bin.test.ts": 169, + "test/heredoc-pipe-deadlock.test.ts": 805, + "test/honesty-kernel.test.ts": 110, + "test/hook-scripts.test.ts": 213157, + "test/host-renders-openai-yaml-proof.test.ts": 108, + "test/instruction-facts.test.ts": 152, + "test/ios-debug-bridge-release-guard.test.ts": 73, "test/ios-qa-daemon-cli.test.ts": 196, - "test/ios-qa-stateserver-hardening.test.ts": 66, - "test/ios-qa-swift-build.test.ts": 82, - "test/ios-qa.test.ts": 378, - "test/is-conductor.test.ts": 66, - "test/jargon-list.test.ts": 61, - "test/judge-calibration.test.ts": 202, - "test/judge-panel-median.test.ts": 114, - "test/land-and-deploy-command-trigger.test.ts": 78, - "test/land-and-deploy-flow.test.ts": 15443, - "test/land-and-deploy-postfail.test.ts": 77, - "test/llm-judge-abort.test.ts": 111, - "test/llm-judge-frontier.test.ts": 293, + "test/ios-qa-stateserver-hardening.test.ts": 63, + "test/ios-qa-swift-build.test.ts": 73, + "test/ios-qa.test.ts": 372, + "test/is-conductor.test.ts": 52, + "test/jargon-list.test.ts": 58, + "test/jsonl-merge-encoding.test.ts": 588, + "test/judge-calibration.test.ts": 120, + "test/judge-panel-median.test.ts": 73, + "test/land-and-deploy-command-trigger.test.ts": 58, + "test/land-and-deploy-flow.test.ts": 13264, + "test/land-and-deploy-postfail.test.ts": 63, + "test/land-direct-recovery-isolation.test.ts": 71, + "test/llm-judge-abort.test.ts": 73, + "test/llm-judge-frontier.test.ts": 233, "test/llm-judge-stream.test.ts": 122, - "test/llms-txt-shape.test.ts": 112, - "test/maintenance-cli-args.test.ts": 496, - "test/memory-ingest-timeout.test.ts": 124, - "test/migration-checkpoint-ownership.test.ts": 1899, - "test/mktemp-portability.test.ts": 797, - "test/model-catalog-isolation.test.ts": 222, - "test/model-overlays.test.ts": 97, - "test/model-panel-selftest.test.ts": 5073, - "test/model-policy-freshness.test.ts": 433, - "test/model-policy.test.ts": 230, - "test/modernize-skill.test.ts": 79, - "test/module-size-ratchet.test.ts": 619, - "test/native-auto-decide-pty.test.ts": 14732, - "test/native-auto-decide.test.ts": 807, - "test/no-quoted-tilde-assignments.test.ts": 118, - "test/no-suicide-exit.test.ts": 340, - "test/office-hours-budget.test.ts": 136, - "test/office-hours-open-question-form.test.ts": 71, - "test/office-hours-phase4-caller.test.ts": 90, - "test/office-hours-review.test.ts": 2688, - "test/office-posture-recording.test.ts": 147, - "test/one-way-doors.test.ts": 62, - "test/open-gstack-browser-liveness.test.ts": 54, - "test/openclaw-native-skills.test.ts": 52, - "test/osv-config-wiring.test.ts": 49, - "test/osv-ignore-expiry.test.ts": 56, - "test/outside-review-severity.test.ts": 231, - "test/outside-review-unclosed-fence.test.ts": 139, - "test/outside-review-unparsed-severity.test.ts": 443, - "test/outside-send-boundary.test.ts": 1010, - "test/outside-voice-evidence.test.ts": 264, - "test/outside-voice-failure-policy.test.ts": 517, - "test/outside-voice-fixture.test.ts": 2398, - "test/outside-voice-native-deadline.test.ts": 157, - "test/outside-voice-routing.test.ts": 4217, - "test/overlay-lifecycle.test.ts": 659, - "test/overlay-measurement.test.ts": 941, - "test/overlay-recording-order.test.ts": 87, - "test/overlay-sdk-cancel-eof.test.ts": 256, - "test/paid-free-boundary.test.ts": 20803, - "test/paid-orphan-tripwire.test.ts": 272, - "test/paid-overlay-scheduling.test.ts": 2542, - "test/paid-pr-profile.test.ts": 9245, - "test/paid-report-census.test.ts": 586, - "test/paid-report-fail-open.test.ts": 3738, - "test/paid-run-manifest.test.ts": 9256, - "test/paid-selection-propagation.test.ts": 133, - "test/paid-shard-settlement.test.ts": 1846, - "test/paid-shards.test.ts": 16821, - "test/paid-slice-deadline.test.ts": 1673, - "test/pair-agent-token-hygiene.test.ts": 58, - "test/parity-baseline-integrity.test.ts": 128, - "test/parity-sectioned.test.ts": 65, - "test/parity-suite.test.ts": 333, - "test/path-spelling.test.ts": 1806, - "test/pending-question-completion.test.ts": 427, - "test/periodic-exclude-policy.test.ts": 411, - "test/plan-count-checkbox.test.ts": 196, - "test/plan-count-completion.test.ts": 683, - "test/plan-count-cropped-wrap.test.ts": 227, - "test/plan-count-cross-cwd-ancestry.test.ts": 616, - "test/plan-count-design-ui-recovery.test.ts": 179, - "test/plan-count-dx-handoff.test.ts": 283, - "test/plan-count-empty-review.test.ts": 180, - "test/plan-count-history.test.ts": 88, - "test/plan-count-long-edit.test.ts": 147, - "test/plan-count-native-input.test.ts": 150, - "test/plan-count-owned-permission.test.ts": 115, - "test/plan-count-pending-exit.test.ts": 262, - "test/plan-count-prerequisite.test.ts": 165, - "test/plan-count-preview-footer.test.ts": 117, - "test/plan-count-session-cwd.test.ts": 266, - "test/plan-count-timeout.test.ts": 81, - "test/plan-count-transcript.test.ts": 246, - "test/plan-count-truncated-border.test.ts": 138, - "test/plan-count-truncated-question.test.ts": 131, - "test/plan-create-combined-permission.test.ts": 398, - "test/plan-create-permission.test.ts": 249, - "test/plan-design-floor-fixture.test.ts": 1897, - "test/plan-design-sdk-fixture.test.ts": 3518, - "test/plan-design-with-ui-fixture.test.ts": 19046, - "test/plan-eng-resume.test.ts": 77, - "test/plan-floor-dx-actor.test.ts": 244, - "test/plan-floor-edit-wrap.test.ts": 186, - "test/plan-floor-review.test.ts": 162, - "test/plan-floor-target.test.ts": 15157, - "test/plan-format-approach-prompt.test.ts": 61, - "test/plan-format-kind-note.test.ts": 70, - "test/plan-mode-off-generation.test.ts": 1411, - "test/plan-mode-preamble-setup.test.ts": 195, - "test/plan-pending-question-pty.test.ts": 276, - "test/plan-review-board-feedback.test.ts": 12931, - "test/plan-review-calibration.test.ts": 3601, - "test/plan-review-decisions.test.ts": 1307, - "test/plan-scope-selection.test.ts": 4694, - "test/plan-skill-question-hook-scope.test.ts": 19669, - "test/plan-skill-read-permission.test.ts": 308, - "test/plan-skill-webfetch-permission.test.ts": 6623, - "test/platform-qualification-workflow.test.ts": 61, - "test/post-rename-doc-regen.test.ts": 79, - "test/pr-direct-cases.test.ts": 13544, - "test/pr-shared-input-selection.test.ts": 5390, - "test/pr-title-sync-workflow-safety.test.ts": 148, - "test/preamble-hoist.test.ts": 19194, - "test/pregate-always-run.test.ts": 19759, - "test/pregate-import-graph-paths.test.ts": 17850, - "test/pregate-manifest-paths.test.ts": 9330, - "test/pregate-rust.test.ts": 22406, - "test/pregate-user-policy.test.ts": 90329, - "test/pregate-wtree-refusal.test.ts": 16818, - "test/prompt-audit-manifest.test.ts": 1200, - "test/prose-voice-floor.test.ts": 738, + "test/llms-txt-shape.test.ts": 116, + "test/loadout-setup.test.ts": 147, + "test/maintenance-cli-args.test.ts": 440, + "test/memory-ingest-timeout.test.ts": 78, + "test/migration-checkpoint-ownership.test.ts": 1681, + "test/mktemp-portability.test.ts": 706, + "test/model-catalog-isolation.test.ts": 185, + "test/model-overlays.test.ts": 68, + "test/model-panel-selftest.test.ts": 10244, + "test/model-policy-freshness.test.ts": 290, + "test/model-policy.test.ts": 180, + "test/modernize-skill.test.ts": 59, + "test/module-size-ratchet.test.ts": 720, + "test/native-auto-decide-pty.test.ts": 14186, + "test/native-auto-decide.test.ts": 476, + "test/no-quoted-tilde-assignments.test.ts": 69, + "test/no-suicide-exit.test.ts": 322, + "test/office-hours-budget.test.ts": 101, + "test/office-hours-open-question-form.test.ts": 48, + "test/office-hours-phase4-caller.test.ts": 68, + "test/office-hours-review.test.ts": 2931, + "test/office-posture-recording.test.ts": 100, + "test/one-way-doors.test.ts": 214, + "test/open-gstack-browser-liveness.test.ts": 53, + "test/openclaw-native-skills.test.ts": 45, + "test/osv-config-wiring.test.ts": 46, + "test/osv-ignore-expiry.test.ts": 58, + "test/outside-review-cyber-policy.test.ts": 105, + "test/outside-review-severity.test.ts": 223, + "test/outside-review-unclosed-fence.test.ts": 136, + "test/outside-review-unparsed-severity.test.ts": 532, + "test/outside-send-boundary.test.ts": 1101, + "test/outside-voice-evidence.test.ts": 251, + "test/outside-voice-failure-policy.test.ts": 504, + "test/outside-voice-fixture.test.ts": 2144, + "test/outside-voice-native-deadline.test.ts": 140, + "test/outside-voice-routing.test.ts": 4069, + "test/overlay-lifecycle.test.ts": 473, + "test/overlay-measurement.test.ts": 780, + "test/overlay-recording-order.test.ts": 70, + "test/overlay-sdk-cancel-eof.test.ts": 185, + "test/paid-free-boundary.test.ts": 10717, + "test/paid-orphan-tripwire.test.ts": 270, + "test/paid-overlay-scheduling.test.ts": 1670, + "test/paid-pr-profile.test.ts": 5519, + "test/paid-report-census.test.ts": 601, + "test/paid-report-cost.test.ts": 158, + "test/paid-report-fail-open.test.ts": 2985, + "test/paid-run-manifest.test.ts": 4399, + "test/paid-selection-propagation.test.ts": 115, + "test/paid-shard-settlement.test.ts": 1658, + "test/paid-shards.test.ts": 13148, + "test/paid-slice-deadline.test.ts": 1604, + "test/pair-agent-token-hygiene.test.ts": 43, + "test/parity-baseline-integrity.test.ts": 55, + "test/parity-sectioned.test.ts": 49, + "test/parity-suite.test.ts": 244, + "test/path-spelling.test.ts": 1305, + "test/pending-question-completion.test.ts": 320, + "test/periodic-exclude-policy.test.ts": 239, + "test/plain-title-workflow-safety.test.ts": 138, + "test/plan-count-checkbox.test.ts": 82, + "test/plan-count-completion.test.ts": 536, + "test/plan-count-cropped-wrap.test.ts": 184, + "test/plan-count-cross-cwd-ancestry.test.ts": 351, + "test/plan-count-design-ui-recovery.test.ts": 146, + "test/plan-count-dx-handoff.test.ts": 231, + "test/plan-count-empty-review.test.ts": 103, + "test/plan-count-history.test.ts": 57, + "test/plan-count-long-edit.test.ts": 108, + "test/plan-count-native-input.test.ts": 101, + "test/plan-count-owned-permission.test.ts": 107, + "test/plan-count-pending-exit.test.ts": 186, + "test/plan-count-prerequisite.test.ts": 110, + "test/plan-count-preview-footer.test.ts": 90, + "test/plan-count-session-cwd.test.ts": 216, + "test/plan-count-timeout.test.ts": 52, + "test/plan-count-transcript.test.ts": 339, + "test/plan-count-truncated-border.test.ts": 84, + "test/plan-count-truncated-question.test.ts": 88, + "test/plan-create-combined-permission.test.ts": 340, + "test/plan-create-permission.test.ts": 201, + "test/plan-design-floor-fixture.test.ts": 1632, + "test/plan-design-sdk-fixture.test.ts": 2954, + "test/plan-design-with-ui-fixture.test.ts": 13237, + "test/plan-eng-resume.test.ts": 56, + "test/plan-floor-dx-actor.test.ts": 172, + "test/plan-floor-edit-wrap.test.ts": 157, + "test/plan-floor-review.test.ts": 86, + "test/plan-floor-target.test.ts": 14611, + "test/plan-format-approach-prompt.test.ts": 44, + "test/plan-format-kind-note.test.ts": 48, + "test/plan-mode-off-generation.test.ts": 1058, + "test/plan-mode-preamble-setup.test.ts": 113, + "test/plan-pending-question-pty.test.ts": 97, + "test/plan-review-board-feedback.test.ts": 12150, + "test/plan-review-calibration.test.ts": 681, + "test/plan-review-decisions.test.ts": 344, + "test/plan-scope-selection.test.ts": 3965, + "test/plan-skill-question-hook-scope.test.ts": 8193, + "test/plan-skill-read-permission.test.ts": 130, + "test/plan-skill-webfetch-permission.test.ts": 4190, + "test/planning-wave-prose.test.ts": 46, + "test/platform-qualification-workflow.test.ts": 49, + "test/policy-floor-stable.test.ts": 41474, + "test/post-rename-doc-regen.test.ts": 62, + "test/pr-direct-cases.test.ts": 7401, + "test/pr-title-sync-workflow-safety.test.ts": 51, + "test/preamble-hoist.test.ts": 14174, + "test/pregate-always-run.test.ts": 20978, + "test/pregate-carry-gate.test.ts": 110, + "test/pregate-clear-runs.test.ts": 115, + "test/pregate-flaky-exception.test.ts": 126, + "test/pregate-from-run.test.ts": 120, + "test/pregate-hidden-folder-paths.test.ts": 123, + "test/pregate-import-graph-paths.test.ts": 13101, + "test/pregate-lanes-large-selection.test.ts": 103, + "test/pregate-manifest-paths.test.ts": 6838, + "test/pregate-partial-record.test.ts": 108, + "test/pregate-remote-gate-runs.test.ts": 128, + "test/pregate-rust.test.ts": 15073, + "test/pregate-user-policy.test.ts": 80716, + "test/pregate-wtree-refusal.test.ts": 13846, + "test/prompt-audit-manifest.test.ts": 934, + "test/prose-voice-floor.test.ts": 111, "test/prosons-neutral-posture.test.ts": 54, - "test/provider-model-defaults.test.ts": 232, - "test/pstack-sections.test.ts": 98, - "test/pty-askuserquestion-single-line.test.ts": 122, - "test/pty-numbered-option-indent-native.test.ts": 164, - "test/pty-option-selection.test.ts": 80, - "test/pty-output-wake.test.ts": 3335, - "test/pty-screen-session.test.ts": 70, - "test/pty-screen-supervision.test.ts": 11228, - "test/pty-screen-unicode-ap.test.ts": 219, - "test/pty-screen.test.ts": 236, - "test/pty-skill-seeding-wiring.test.ts": 1200, - "test/pty-trust-dialog.test.ts": 625, - "test/published-text.test.ts": 95, - "test/qa-browser-preservation.test.ts": 16041, - "test/qa-bugs-fixture.test.ts": 91, - "test/qa-caller-authority.test.ts": 335, - "test/qa-caller-freshness-order.test.ts": 182, - "test/qa-caller-report-observer.test.ts": 109, - "test/qa-checkpoint-evidence.test.ts": 358, - "test/qa-deadline-publication-observer.test.ts": 89, - "test/qa-deadline-selection.test.ts": 112, - "test/qa-deadline.test.ts": 30097, - "test/qa-evidence-selection.test.ts": 177, - "test/qa-evidence.test.ts": 18281, - "test/qa-fix-loop-fixture.test.ts": 8900, - "test/qa-health-rubric.test.ts": 384, - "test/qa-only-browser-probe.test.ts": 2442, - "test/qa-probe-gates.test.ts": 228, - "test/qa-report-fields.test.ts": 63, - "test/qa-supervision-selection.test.ts": 110, - "test/question-tuning-registry-path.test.ts": 65, - "test/readme-skill-lists.test.ts": 72, - "test/redact-constant-and-at-filename.test.ts": 92, - "test/redact-context-exemptions.test.ts": 187, - "test/redact-doc-resolver.test.ts": 132, - "test/redact-dotenv-filename-false-positive.test.ts": 79, - "test/redact-engine-autoredact.test.ts": 66, - "test/redact-parcel-id-false-positive.test.ts": 79, - "test/redact-pattern-lint.test.ts": 107, - "test/redact-prepush-emails.test.ts": 52521, - "test/redact-prepush-target.test.ts": 61351, - "test/redact-span-binding.test.ts": 131, - "test/redact-unicode-offsets.test.ts": 234, - "test/regression-1539-review-self-verify.test.ts": 73, - "test/regression-1834-retro-recommendations.test.ts": 61, - "test/regression-issue2091-bsd-mktemp.test.ts": 755, - "test/regression-pr1169-mktemp-fallbacks.test.ts": 180, - "test/regression-transcript-frontmatter-fence.test.ts": 133, - "crew/test/release-cut.test.ts": 138015, - "test/remote-identity-vectors.test.ts": 286, - "crew/test/replay-pr-selection.test.ts": 4793, - "test/resolvers-gbrain-put-rewrite.test.ts": 107, - "test/resolvers-gbrain-save-results.test.ts": 72, - "test/restamp-base-merge.test.ts": 14319, - "test/restamp-four-part-manifest.test.ts": 22166, - "test/restamp-mentions.test.ts": 48900, - "test/retired-commands.test.ts": 129, - "test/review-army-budget.test.ts": 5686, - "test/review-base-refresh.test.ts": 2106, - "test/review-collect.test.ts": 18677, - "test/review-consensus-lifecycle.test.ts": 114, - "test/review-count-markdown.test.ts": 267, - "crew/test/review-dispatch-compare.test.ts": 234, - "test/review-dispatch-counters.test.ts": 86, - "test/review-entry-and-design-clarity-au.test.ts": 174, - "test/review-enum-lifecycle.test.ts": 91, - "test/review-finalization-budget.test.ts": 7436, - "test/review-loop-budget-wording.test.ts": 74, - "test/review-n-plus-one-contract.test.ts": 6694, - "test/review-quality-provenance.test.ts": 126, - "test/review-scope-followups.test.ts": 96, - "test/router-disabled-skills.test.ts": 2292, - "test/run-shard-child.test.ts": 1389, - "test/runtime-pins.test.ts": 245, - "test/safety-rule-registry.test.ts": 106, - "test/salience-allowlist.test.ts": 103, - "test/schema-version-migration.test.ts": 412, - "test/section-manifest-consistency.test.ts": 98, - "test/session-runner-browse-errors.test.ts": 5462, - "test/session-runner-stream-lifecycle.test.ts": 411, - "test/session-runner-timeout.test.ts": 83, - "test/session-runner-tools.test.ts": 265, - "test/setup-alias-name-uniqueness.test.ts": 24711, - "test/setup-browser-hint.test.ts": 613, - "test/setup-bun-cmd-and-pipe-bugs.test.ts": 360, - "test/setup-cleanup-orphans.test.ts": 80, - "test/setup-codex-design-pdf-runtime.test.ts": 78, - "test/setup-codex-model.test.ts": 69, - "test/setup-codex-scope-review-boundaries.test.ts": 161, - "test/setup-cso-windows-probe.test.ts": 80, - "test/setup-cursor-legacy-skills.test.ts": 170, - "test/setup-deploy-key-presence.test.ts": 144, - "test/setup-deploy-not-deployed.test.ts": 83, - "test/setup-deploy-vercel-trigger.test.ts": 65, - "test/setup-gbrain-bin-invocation-paths.test.ts": 69, - "test/setup-gbrain-path4-caller.test.ts": 15185, - "test/setup-gbrain-path4-structure.test.ts": 66, - "test/setup-gbrain-remote-caller.test.ts": 20976, - "test/setup-help.test.ts": 373, - "test/setup-hook-syntax-gate.test.ts": 111941, - "test/setup-playwright-platform.test.ts": 7517, - "test/setup-prune-stale-generated.test.ts": 2303, - "test/setup-sections-linking.test.ts": 79, - "test/setup-skill-copies.test.ts": 88, - "test/setup-staged-copy.test.ts": 551, - "test/setup-windows-fallback.test.ts": 106, - "test/setup-windows-rerun-refresh.test.ts": 1717, - "test/shard-cli-parity.test.ts": 330, - "test/shared-libs-cancellation.test.ts": 334, - "test/shared-libs-evidence.test.ts": 95, - "test/shared-libs-plan-actor.test.ts": 187, - "test/shared-libs-rendering.test.ts": 4524, - "test/shared-libs-source-reads.test.ts": 19941, - "test/ship-apple-gate.test.ts": 115, - "test/ship-budget-batch.test.ts": 10536, - "test/ship-budget-calibration.test.ts": 113, - "test/ship-budget-chain.test.ts": 118227, - "test/ship-budget-meter-contract.test.ts": 20311, - "test/ship-budget-projection.test.ts": 107262, - "test/ship-budget-reader-drift.test.ts": 53273, - "test/ship-budget-review-log.test.ts": 131834, - "test/ship-budget-section.test.ts": 109, - "test/ship-budget-small-run.test.ts": 7146, - "test/ship-budget-step-prior.test.ts": 2101, - "test/ship-control-flow.test.ts": 3877, - "test/ship-coverage-audit-af.test.ts": 173, - "test/ship-frozen-scope-actor.test.ts": 578, - "test/ship-greptile-early.test.ts": 71, - "test/ship-greptile-pr-check.test.ts": 1153, - "test/ship-handoff-brief.test.ts": 20871, - "test/ship-hook-windows-paths.test.ts": 2319, - "test/ship-measure-bar.test.ts": 179, - "test/ship-measure-loop-skill.test.ts": 68, - "test/ship-pr-liveness-policy.test.ts": 66, - "test/ship-publication-gates.test.ts": 7889, - "crew/test/ship-queue-train-stamp.test.ts": 78565, - "test/ship-receipt-carry-rewrite.test.ts": 75723, - "test/ship-receipt-carry-squash.test.ts": 76600, - "test/ship-receipt-depth.test.ts": 68005, - "test/ship-reentry-gates.test.ts": 84, - "test/ship-review-loop.test.ts": 84, - "test/ship-section-fixture.test.ts": 1966, - "test/ship-skip-requeue.test.ts": 141, - "test/ship-template-redaction.test.ts": 85, - "test/ship-test-detection-markers.test.ts": 3459, - "test/ship-triage-labels.test.ts": 73, - "test/ship-workflow-clarity.test.ts": 159, - "test/shortcut-debt-ledger.test.ts": 72, - "test/sideways-review.test.ts": 67, - "test/size-ledger.test.ts": 6713, - "test/skill-browse-state-extraction.test.ts": 240, - "test/skill-budget-regression.test.ts": 374, - "test/skill-check-driver.test.ts": 376, - "test/skill-collision-sentinel.test.ts": 95, - "test/skill-coverage-floor.test.ts": 151, - "test/skill-cross-model-recommendation-emit.test.ts": 92, - "test/skill-eval-tasks.test.ts": 329, - "test/skill-md-size-guard.test.ts": 4449, - "test/skill-parser.test.ts": 102, - "test/skill-positional-literals.test.ts": 6446, - "test/skill-preflight-budget.test.ts": 71, - "test/skill-triggers.test.ts": 75, - "test/skillify-host-paths.test.ts": 4396, - "test/spawnsync-timeout-tripwire.test.ts": 644, - "test/spec-template-invariants.test.ts": 83, - "test/spend-ledger.test.ts": 345, - "test/state-root-parity.test.ts": 2114, - "test/strict-output-capture.test.ts": 213, - "test/strict-output-formats.test.ts": 2732, - "test/strict-output-settlement.test.ts": 4260, - "test/strict-output.test.ts": 56, - "test/sync-gbrain-readiness-fixture.test.ts": 606, - "test/takes-fence-fallback.test.ts": 60, - "test/tasks-section-jq.test.ts": 228, - "test/team-init-hook-shell-neutral.test.ts": 1385, - "test/template-context-parity.test.ts": 65, - "test/terse-build.test.ts": 67, - "test/test-free-shards-files-from.test.ts": 338, - "test/test-free-shards-git-maintenance.test.ts": 947, - "test/test-free-shards-sandbox-knobs.test.ts": 443, + "test/provider-model-defaults.test.ts": 82, + "test/pstack-sections.test.ts": 61, + "test/pty-askuserquestion-single-line.test.ts": 94, + "test/pty-numbered-option-indent-native.test.ts": 103, + "test/pty-option-selection.test.ts": 49, + "test/pty-output-wake.test.ts": 3305, + "test/pty-screen-session.test.ts": 58, + "test/pty-screen-supervision.test.ts": 10300, + "test/pty-screen-unicode-ap.test.ts": 174, + "test/pty-screen.test.ts": 171, + "test/pty-skill-seeding-wiring.test.ts": 526, + "test/pty-trust-dialog.test.ts": 61, + "test/published-text.test.ts": 78, + "test/qa-browser-preservation.test.ts": 12699, + "test/qa-bugs-fixture.test.ts": 84, + "test/qa-caller-authority.test.ts": 298, + "test/qa-caller-freshness-order.test.ts": 159, + "test/qa-caller-report-observer.test.ts": 71, + "test/qa-checkpoint-evidence.test.ts": 276, + "test/qa-deadline-publication-observer.test.ts": 67, + "test/qa-deadline-selection.test.ts": 84, + "test/qa-deadline.test.ts": 27543, + "test/qa-evidence-selection.test.ts": 171, + "test/qa-evidence.test.ts": 15934, + "test/qa-fix-loop-fixture.test.ts": 6716, + "test/qa-health-rubric.test.ts": 304, + "test/qa-only-browser-probe.test.ts": 1814, + "test/qa-probe-gates.test.ts": 150, + "test/qa-report-dir.test.ts": 2154, + "test/qa-report-fields.test.ts": 52, + "test/qa-supervision-selection.test.ts": 86, + "test/qid-marker.test.ts": 62, + "test/qm-edition.test.ts": 70, + "test/question-tuning-registry-path.test.ts": 57, + "test/readme-skill-lists.test.ts": 66, + "test/redact-constant-and-at-filename.test.ts": 87, + "test/redact-context-exemptions.test.ts": 217, + "test/redact-doc-resolver.test.ts": 100, + "test/redact-dotenv-filename-false-positive.test.ts": 68, + "test/redact-engine-autoredact.test.ts": 69, + "test/redact-env-kv-attribute-reference.test.ts": 67, + "test/redact-hostname-property-read.test.ts": 164, + "test/redact-parcel-id-false-positive.test.ts": 70, + "test/redact-pattern-lint.test.ts": 86, + "test/redact-prepush-emails.test.ts": 45802, + "test/redact-prepush-target.test.ts": 54278, + "test/redact-span-binding.test.ts": 152, + "test/redact-unicode-offsets.test.ts": 244, + "test/regression-1539-review-self-verify.test.ts": 89, + "test/regression-1834-retro-recommendations.test.ts": 66, + "test/regression-3749-retro-history-worktree.test.ts": 20925, + "test/regression-issue2091-bsd-mktemp.test.ts": 700, + "test/regression-pr1169-mktemp-fallbacks.test.ts": 161, + "test/regression-transcript-frontmatter-fence.test.ts": 107, + "test/release-stamp.test.ts": 129937, + "test/remote-identity-vectors.test.ts": 244, + "test/resolvers-gbrain-put-rewrite.test.ts": 98, + "test/resolvers-gbrain-save-results.test.ts": 62, + "test/restamp-base-merge.test.ts": 13188, + "test/restamp-foreign-version.test.ts": 24541, + "test/restamp-four-part-manifest.test.ts": 20923, + "test/restamp-mentions.test.ts": 362459, + "test/retired-commands.test.ts": 101, + "test/retro-friction.test.ts": 60, + "test/review-army-budget.test.ts": 4746, + "test/review-base-refresh.test.ts": 1772, + "test/review-bots.test.ts": 97, + "test/review-closing-summary.test.ts": 130, + "test/review-consensus-lifecycle.test.ts": 87, + "test/review-count-markdown.test.ts": 230, + "test/review-dispatch-counters.test.ts": 122, + "test/review-entry-and-design-clarity-au.test.ts": 131, + "test/review-enum-lifecycle.test.ts": 79, + "test/review-exclude-secret-value.test.ts": 13765, + "test/review-finalization-budget.test.ts": 6408, + "test/review-gst1031.test.ts": 186, + "test/review-ledger-invariant.test.ts": 1077, + "test/review-ledger-verdict-line.test.ts": 122, + "test/review-loop-binding.test.ts": 97, + "test/review-loop-budget-wording.test.ts": 61, + "test/review-n-plus-one-contract.test.ts": 5350, + "test/review-native-finding-heading.test.ts": 115, + "test/review-native-nested-list.test.ts": 107, + "test/review-negated-severity.test.ts": 125, + "test/review-plan-post-review-stamps.test.ts": 155895, + "test/review-prose-severity.test.ts": 128, + "test/review-quality-provenance.test.ts": 110, + "test/review-reader-selection.test.ts": 129194, + "test/review-risk-linear.test.ts": 1592, + "test/review-risk-redos.test.ts": 679, + "test/review-risk-token-paths.test.ts": 1249, + "test/review-scope-followups.test.ts": 82, + "test/review-scope-windows-launch.test.ts": 2847, + "test/review-secret-excerpt.test.ts": 58509, + "test/review-targeted-stamp-carry.test.ts": 161293, + "test/review-verdict.test.ts": 473, + "test/router-disabled-skills.test.ts": 2025, + "test/run-evidence.test.ts": 307, + "test/run-shard-child.test.ts": 1366, + "test/runtime-pins.test.ts": 221, + "test/safety-none-arm.test.ts": 117, + "test/safety-rule-registry.test.ts": 93, + "test/salience-allowlist.test.ts": 82, + "test/schema-version-migration.test.ts": 344, + "test/sdk-system-prompt-tripwire.test.ts": 564, + "test/sealed-stream.test.ts": 12908, + "test/section-manifest-consistency.test.ts": 89, + "test/session-runner-browse-errors.test.ts": 4309, + "test/session-runner-stream-lifecycle.test.ts": 350, + "test/session-runner-timeout.test.ts": 76, + "test/session-runner-tools.test.ts": 199, + "test/setup-alias-name-uniqueness.test.ts": 10525, + "test/setup-browser-hint.test.ts": 506, + "test/setup-bun-cmd-and-pipe-bugs.test.ts": 279, + "test/setup-cleanup-orphans.test.ts": 59, + "test/setup-codex-design-pdf-runtime.test.ts": 75, + "test/setup-codex-model.test.ts": 58, + "test/setup-codex-scope-review-boundaries.test.ts": 143, + "test/setup-cso-windows-probe.test.ts": 58, + "test/setup-cursor-legacy-skills.test.ts": 146, + "test/setup-deploy-key-presence.test.ts": 108, + "test/setup-deploy-not-deployed.test.ts": 48, + "test/setup-deploy-vercel-trigger.test.ts": 55, + "test/setup-gbrain-bin-invocation-paths.test.ts": 61, + "test/setup-gbrain-db-url-argv.test.ts": 56, + "test/setup-gbrain-path4-caller.test.ts": 10997, + "test/setup-gbrain-path4-structure.test.ts": 53, + "test/setup-gbrain-remote-caller.test.ts": 18641, + "test/setup-help.test.ts": 283, + "test/setup-hook-syntax-gate.test.ts": 146276, + "test/setup-playwright-platform.test.ts": 4492, + "test/setup-prune-stale-generated.test.ts": 2343, + "test/setup-sections-linking.test.ts": 53, + "test/setup-skill-copies.test.ts": 59, + "test/setup-staged-copy.test.ts": 404, + "test/setup-windows-fallback.test.ts": 57, + "test/setup-windows-rerun-refresh.test.ts": 1210, + "test/shard-cli-parity.test.ts": 256, + "test/shard-jobs.test.ts": 2883, + "test/shared-libs-cancellation.test.ts": 301, + "test/shared-libs-evidence.test.ts": 86, + "test/shared-libs-plan-actor.test.ts": 160, + "test/shared-libs-rendering.test.ts": 4425, + "test/shared-libs-source-reads.test.ts": 16538, + "test/ship-apple-gate.test.ts": 91, + "test/ship-budget-batch.test.ts": 16316, + "test/ship-budget-calibration.test.ts": 102, + "test/ship-budget-chain.test.ts": 142563, + "test/ship-budget-meter-contract.test.ts": 22298, + "test/ship-budget-meter-scope.test.ts": 67764, + "test/ship-budget-projection.test.ts": 141214, + "test/ship-budget-reader-drift.test.ts": 75817, + "test/ship-budget-review-log.test.ts": 182883, + "test/ship-budget-section.test.ts": 110, + "test/ship-budget-small-run.test.ts": 12378, + "test/ship-budget-step-prior.test.ts": 3487, + "test/ship-budget-successor.test.ts": 38787, + "test/ship-control-flow.test.ts": 3508, + "test/ship-coverage-audit-af.test.ts": 149, + "test/ship-frozen-scope-actor.test.ts": 473, + "test/ship-greptile-early.test.ts": 73, + "test/ship-greptile-pr-check.test.ts": 1003, + "test/ship-handoff-brief.test.ts": 28705, + "test/ship-hook-windows-paths.test.ts": 2058, + "test/ship-measure-bar.test.ts": 152, + "test/ship-measure-loop-skill.test.ts": 62, + "test/ship-pr-liveness-policy.test.ts": 55, + "test/ship-publication-gates.test.ts": 5089, + "test/ship-receipt-carry-fragment-conversion.test.ts": 82102, + "test/ship-receipt-carry-large-diff.test.ts": 210104, + "test/ship-receipt-carry-ported-pin.test.ts": 34703, + "test/ship-receipt-carry-rewrite.test.ts": 93961, + "test/ship-receipt-carry-squash.test.ts": 172600, + "test/ship-receipt-result-head.test.ts": 825, + "test/ship-receipt-runs.test.ts": 110, + "test/ship-receipt-session-kind.test.ts": 6352, + "test/ship-reentry-gates.test.ts": 73, + "test/ship-review-loop.test.ts": 64, + "test/ship-section-fixture.test.ts": 1915, + "test/ship-skip-requeue.test.ts": 135, + "test/ship-template-redaction.test.ts": 69, + "test/ship-test-detection-markers.test.ts": 2966, + "test/ship-triage-labels.test.ts": 55, + "test/ship-workflow-clarity.test.ts": 134, + "test/shortcut-debt-ledger.test.ts": 75, + "test/sideways-review.test.ts": 55, + "test/size-ledger.test.ts": 5750, + "test/skill-browse-state-extraction.test.ts": 245, + "test/skill-budget-regression.test.ts": 284, + "test/skill-check-driver.test.ts": 1724, + "test/skill-collision-sentinel.test.ts": 67, + "test/skill-coverage-floor.test.ts": 136, + "test/skill-cross-model-recommendation-emit.test.ts": 91, + "test/skill-eval-tasks.test.ts": 259, + "test/skill-gates-advisory-bytes.test.ts": 1498, + "test/skill-md-size-guard.test.ts": 4344, + "test/skill-parser.test.ts": 523, + "test/skill-positional-literals.test.ts": 5207, + "test/skill-preflight-budget.test.ts": 59, + "test/skill-triggers.test.ts": 56, + "test/skillify-host-paths.test.ts": 4091, + "test/spawnsync-timeout-tripwire.test.ts": 639, + "test/spec-template-invariants.test.ts": 70, + "test/spend-ledger.test.ts": 309, + "test/state-root-parity.test.ts": 2092, + "test/strict-output-capture.test.ts": 198, + "test/strict-output-formats.test.ts": 2305, + "test/strict-output-settlement.test.ts": 6094, + "test/strict-output.test.ts": 47, + "test/sync-gbrain-readiness-fixture.test.ts": 532, + "test/takes-fence-fallback.test.ts": 50, + "test/tasks-section-jq.test.ts": 212, + "test/team-init-hook-shell-neutral.test.ts": 1452, + "test/template-context-parity.test.ts": 48, + "test/terse-build.test.ts": 62, + "test/test-fixture-root.test.ts": 942, + "test/test-free-shards-files-from.test.ts": 257, + "test/test-free-shards-git-maintenance.test.ts": 863, + "test/test-free-shards-sandbox-knobs.test.ts": 467, "test/test-free-shards-settlement-lifecycle.test.ts": 73, - "test/test-free-shards-settlement-ownership.test.ts": 74, - "test/test-health-report.test.ts": 1544, - "test/test-health-workflow.test.ts": 87, - "test/test-of-test-ratchet.test.ts": 693, - "test/test-pr-profile.test.ts": 4087, - "test/test-value-bar.test.ts": 748, - "test/third-party-actions-recording.test.ts": 693, - "test/third-party-actions.test.ts": 409, - "test/timeline-stop-hook-slug.test.ts": 5032, - "test/touchfiles-facade.test.ts": 99, - "test/touchfiles-map-diff.test.ts": 2147, - "test/tracker-guard-wiring.test.ts": 164, - "crew/test/train-backstop.test.ts": 52410, - "crew/test/train-gate.test.ts": 12718, - "test/trial-cause.test.ts": 1190, - "test/typecheck-test-ratchet.test.ts": 126, - "test/unattended-grant.test.ts": 68, - "test/uninstall-windows-copies.test.ts": 10151, - "test/v0-dormancy.test.ts": 113, - "test/version-gate-fragments.test.ts": 16278, - "test/version-source.test.ts": 64, - "test/voice-directive.test.ts": 152, - "test/weekly-release-workflow.test.ts": 88, - "test/windows-free-selection-autoplan-guard.test.ts": 82, - "test/windows-native-workflows.test.ts": 696, - "test/workflow-action-pins.test.ts": 84, - "test/workflow-concurrency.test.ts": 72, - "test/workflow-excerpt.test.ts": 328, - "test/workflow-gh-token.test.ts": 73, - "test/workflow-required-steps.test.ts": 101, - "test/workflow-shell-lint.test.ts": 107, - "test/worktree-isolated-shapes.test.ts": 116, - "test/worktree.test.ts": 6314 + "test/test-free-shards-settlement-ownership.test.ts": 75, + "test/test-health-report.test.ts": 1390, + "test/test-health-workflow.test.ts": 62, + "test/test-of-test-ratchet.test.ts": 625, + "test/test-pr-profile.test.ts": 5461, + "test/test-value-bar.test.ts": 900, + "test/third-party-actions-recording.test.ts": 623, + "test/third-party-actions.test.ts": 369, + "test/timeline-stop-hook-slug.test.ts": 4937, + "test/timeline-stop-hook-stdin.test.ts": 649, + "test/touchfiles-facade.test.ts": 67, + "test/touchfiles-map-diff.test.ts": 1236, + "test/tracker-guard-wiring.test.ts": 182, + "test/tree-receipt-release-tool.test.ts": 19247, + "test/trial-cause.test.ts": 1142, + "test/trunk-dynamic-ci-observers.test.ts": 63, + "test/typecheck-test-ratchet.test.ts": 92, + "test/unattended-grant.test.ts": 57, + "test/uninstall-windows-copies.test.ts": 8417, + "test/v0-dormancy.test.ts": 70, + "test/version-gate-fragments.test.ts": 13578, + "test/version-source.test.ts": 58, + "test/voice-directive.test.ts": 136, + "test/weekly-release-workflow.test.ts": 64, + "test/windows-free-selection-autoplan-guard.test.ts": 78, + "test/workflow-action-pins.test.ts": 75, + "test/workflow-concurrency.test.ts": 56, + "test/workflow-excerpt.test.ts": 254, + "test/workflow-gh-token.test.ts": 68, + "test/workflow-judge-input.test.ts": 97, + "test/workflow-required-steps.test.ts": 77, + "test/workflow-shell-lint.test.ts": 93, + "test/worktree-isolated-shapes.test.ts": 94, + "test/worktree.test.ts": 5468 } } diff --git a/test/windows-native-workflows.test.ts b/test/windows-native-workflows.test.ts index c027d769e2d..fa89d2d7b8f 100644 --- a/test/windows-native-workflows.test.ts +++ b/test/windows-native-workflows.test.ts @@ -34,7 +34,7 @@ test('the Windows lane runs nightly and by hand, plans, runs one strict shard pe const plan = windows.jobs['windows-plan']; expect(plan['runs-on']).toBe('ubuntu-24.04'); const planStep = plan.steps.find((step: any) => step.id === 'plan'); - expect(planStep.run).toContain('--windows-only --ci-plan "$RUNNER_TEMP/windows-plan.json" --shards 6'); + expect(planStep.run).toContain('--windows-only --ci-plan "$RUNNER_TEMP/windows-plan.json" --shards 8'); expect(planStep.env.GSTACK_FREE_TEST_DURATIONS).toBe('scripts/free-test-durations-windows.json'); const shard = windows.jobs['windows-free-shard']; expect(shard['runs-on']).toBe('windows-latest'); @@ -72,8 +72,8 @@ test.skipIf(!Bun.which('bash'))('windows-plan passes the one sub-shard constant, return { status: result.status, args: existsSync(path.join(directory, 'bun-args')) ? readFileSync(path.join(directory, 'bun-args'), 'utf8') : '' }; }; try { - expect(resolve('')).toEqual({ status: 0, args: expect.stringContaining(`--shards 6 --shard-jobs ${windows.env.WINDOWS_FREE_JOBS}`) }); - expect(resolve('2')).toEqual({ status: 0, args: expect.stringContaining('--shards 6 --shard-jobs 2') }); + expect(resolve('')).toEqual({ status: 0, args: expect.stringContaining(`--shards 8 --shard-jobs ${windows.env.WINDOWS_FREE_JOBS}`) }); + expect(resolve('2')).toEqual({ status: 0, args: expect.stringContaining('--shards 8 --shard-jobs 2') }); for (const bad of ['0', '5', '2; true', 'x']) { const refused = resolve(bad); expect(refused.status, bad).not.toBe(0); From e9f38d6fe14a4ec5138238a5e6c52de204e163bf Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 17 Nov 2026 16:39:43 +0800 Subject: [PATCH 14/62] Review a pull request's final head in full and count review rounds per PR (GST-2673) (#4360) * Count review rounds per pull request across /ship runs (GST-2673) /ship's two-round review cap was counted inside each run, so a pull request shipped many times was reviewed again at every head. Step 1 now reads the rounds the PR body's receipt history records, passes them to the review plan, and sends later heads to the scoped re-check, with a lane or Captain round grant for an extra round. Adds the no-loss replay preregistration. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Cap full review rounds per pull request and keep fix-checks to each run The plan counts a PR's earlier full rounds (--prior-full) against the cap of two, as the approved plan says, and prints every earlier round as pr_rounds=. Renames the troubleshooting anchor to pr-round-cap, lists as a reviewed placeholder, and leaves ship/DRIVER.md at its size cap. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Point the ship driver's review pass at Step 9's plan flags, which carry the PR round count Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Give a pull request's final head a full review and make the diff-only re-check advice only (GST-2673) A scoped re-check that reads only what changed since the last reviewed head caught 22 of 24 planted faults but none of 8 real faults that full rounds had caught, so it no longer carries a /ship receipt. A later head whose own lines changed now gets a fresh full review, the PR's last before merge; a PR already at two full rounds gets one read-only full review with no fix round, whose blocker goes to the lane's Captain. carry prints RECHECK: advisory and refuses --recheck. The drift threshold, the re-check blocker count and the design-change grant kind are removed with the route they fed. Repins lib/review-depth.ts and ship/sections/review-army.md under replay GST-2673 (docs/evals/pr-round-count-results.md; deterministic grid against main: 196,608 of 196,608 plans identical with no prior rounds). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep a review round grant usable through its fix round and after a read-only review A grant now holds after the fix round's commits move HEAD past it, counts only the rounds earlier heads spent, and a receipt written without a run keeps other runs' stubs. Review-Finding: p1/specialist-batched#1 reader=state-machines Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/red-team#3 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Count every review round at a granted head again, so a grant can't reset the count Reverts the history change that skipped rounds recorded at a round grant's head: the run that hit the cap is recorded at that same head, so skipping it wiped the count. A grant recorded after a read-only review still doesn't buy a fix round (fails closed). Review-Finding: p2/adversarial-native#1 reader=adversarial-native Review-Finding: p2/outside-voice#1 reader=outside-voice Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-approvals | 28 ++++- bin/gstack-no-stop | 2 +- bin/gstack-review-plan | 29 ++++- bin/gstack-ship-receipt | 110 ++++++++++++++--- changelog.d/count-review-rounds-per-pr.md | 1 + crew/docs/captain.md | 3 + crew/lib/ship-recheck.ts | 41 ++----- crew/test/ship-recheck.test.ts | 59 +++------ docs/evals/pr-round-count-prereg.md | 75 +++++++++++ docs/evals/pr-round-count-results.md | 50 ++++++++ docs/inventory/evidence.json | 3 +- docs/review-policy.md | 64 +++++++++- docs/ship-policy.md | 15 ++- docs/troubleshooting.md | 60 +++++---- lib/factory-scorecard.ts | 11 +- lib/headless-artifacts.ts | 7 +- lib/plan-record.ts | 2 +- lib/pr-review-history.ts | 108 ++++++++++++++++ lib/redact-patterns.ts | 5 +- lib/review-depth.ts | 35 +++++- lib/review-round-grant.ts | 43 +++++++ lib/review-scope.ts | 4 + lib/ship-preflight.ts | 10 +- lib/ship-receipt.ts | 23 ++-- ship/DRIVER.md | 2 +- ship/DRIVER.md.tmpl | 2 +- ship/sections/pr-body.md | 2 +- ship/sections/pr-body.md.tmpl | 2 +- ship/sections/review-army.md | 7 +- ship/sections/review-army.md.tmpl | 7 +- test/factory-scorecard.test.ts | 10 +- .../files/lib/review-depth.ts.json | 2 +- .../files/ship/sections/review-army.md.json | 2 +- .../review-pins/replays/GST-2673.json | 1 + test/helpers/placeholder-allowlist.ts | 1 + test/pr-review-history.test.ts | 116 ++++++++++++++++++ test/pr-round-cli.test.ts | 109 ++++++++++++++++ test/review-plan-pr-rounds.test.ts | 78 ++++++++++++ test/review-round-grant.test.ts | 32 +++++ test/ship-preflight.test.ts | 15 +++ test/ship-receipt-carry-mixed.test.ts | 21 ++-- .../ship/count-review-rounds-per-pr.json | 4 + 42 files changed, 1025 insertions(+), 176 deletions(-) create mode 100644 changelog.d/count-review-rounds-per-pr.md create mode 100644 docs/evals/pr-round-count-prereg.md create mode 100644 docs/evals/pr-round-count-results.md create mode 100644 lib/pr-review-history.ts create mode 100644 lib/review-round-grant.ts create mode 100644 test/fixtures/review-pins/replays/GST-2673.json create mode 100644 test/pr-review-history.test.ts create mode 100644 test/pr-round-cli.test.ts create mode 100644 test/review-plan-pr-rounds.test.ts create mode 100644 test/review-round-grant.test.ts create mode 100644 test/size-ledger/ship/count-review-rounds-per-pr.json diff --git a/bin/gstack-approvals b/bin/gstack-approvals index 2cf9ff7320c..d76c0a4a395 100755 --- a/bin/gstack-approvals +++ b/bin/gstack-approvals @@ -13,6 +13,7 @@ * gstack-approvals gate --finding --gate-id --head --reason --words --by [--json] * gstack-approvals dispositions [--branch ] * gstack-approvals lane-exception --head --files --reason --words --by [--json] + * gstack-approvals round-grant --pr --head --kind extra-round --reason --by [--words ] [--json] * gstack-approvals list [--json] [--branch ] * gstack-approvals sync [--branch ] * gstack-approvals path [--branch ] @@ -32,6 +33,7 @@ import { GSTACK_ACTOR, openShipRun, RULED_NOTE_SCOPE, ruledNoteRow, ruledNotes, import { resultLine } from '../lib/result-codes'; import { parsePlanLine, publicPlanLine, resolvePlan } from '../lib/plan-record'; import { TEST_LANE_EXCEPTION_SCOPE, testLaneExceptionRow } from '../lib/test-lane-exception'; +import { REVIEW_ROUND_GRANT_SCOPE, reviewRoundGrantRow, ROUND_GRANT_KINDS, type RoundGrantKind } from '../lib/review-round-grant'; import { GATE_DISPOSITION_SCOPE, GATE_SOURCE, gateDispositionRow, gateDispositions, gateDispositionText, ONE_LINE, recordGateDisposition, validGateId } from '../lib/gate-dispositions'; const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gstack/captain.md) @@ -54,6 +56,12 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs finish prints it, and the receipt, PR body and READY carry it; refused while any worktree holds an open /ship run on the branch; the lander accepts each one with gstack-ship-queue land|verify --accept-gate-disposition dispositions the "Gate disposition: …" lines the Pre-Landing Review and the PR body carry + round-grant --pr --head --kind extra-round --reason + --by [--words ] + a review round the PR's R51 count would not plan (docs/review-policy.md#rounds-per-pull-request): extra-round is + one round with its fix round past the cap of 2, instead of the read-only final review; it binds + that head of that PR only and is spent by the round; the lane or its Captain records it, never the owner, and + --by is recorded, not enforced; refused inside this checkout's open /ship run, so a run never grants itself lane-exception --head --files --reason --words --by the owner's grant that a CI-carried lane counts although exactly those files are in no run's tree.json @@ -80,7 +88,7 @@ Example: ${exitTableHelp()}`; -const VALUE_FLAGS = new Set(['--ask', '--words', '--by', '--scope', '--pending', '--outcome', '--date', '--source', '--branch', '--autoplan', '--stack', '--finding', '--reason', '--head', '--files', '--plan', '--gate-id']); +const VALUE_FLAGS = new Set(['--ask', '--words', '--by', '--scope', '--pending', '--outcome', '--date', '--source', '--branch', '--autoplan', '--stack', '--finding', '--reason', '--head', '--files', '--plan', '--gate-id', '--pr', '--kind']); function parse(args: string[]): { flags: Record; bools: Set; error?: string } { const flags: Record = {}; @@ -157,9 +165,22 @@ function main(argv: string[]): number { const json = bools.has('--json'); const recorded = (where: StoreLocation) => `${where.file}${where.mirror ? ` mirror=${where.mirror}` : ''}`; - if (cmd === 'add' || cmd === 'import' || cmd === 'rule' || cmd === 'lane-exception' || cmd === 'gate') { + if (cmd === 'add' || cmd === 'import' || cmd === 'rule' || cmd === 'lane-exception' || cmd === 'gate' || cmd === 'round-grant') { let rows; - if (cmd === 'lane-exception') { + if (cmd === 'round-grant') { + const invalid = (message: string) => fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message }); + const pr = (flags['--pr'] ?? '').trim(), kind = (flags['--kind'] ?? '').trim() as RoundGrantKind, reason = (flags['--reason'] ?? '').trim(), by = (flags['--by'] ?? '').trim(); + if (!/^[1-9]\d*$/.test(pr) || !ROUND_GRANT_KINDS.includes(kind)) return invalid(`round-grant needs --pr and --kind ${ROUND_GRANT_KINDS.join('|')}`); + if (!reason || /[\x00-\x1f\x7f]/.test(reason)) return invalid('round-grant needs --reason '); + const head = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${flags['--head'] ?? ''}^{commit}`], { encoding: 'utf8', timeout: 10_000 }); + if (!flags['--head'] || head.status !== 0) return invalid('round-grant needs --head '); + if (!by || GSTACK_ACTOR.test(by)) return invalid('round-grant needs --by : gstack never grants itself a round'); + const open = openShipRun(process.cwd()); + if (open) return invalid(`/ship run ${open} is open on this checkout: a round grant is the lane's or its Captain's, never the run's own; record it from the lane after the run stops`); + const built = buildRow({ ...reviewRoundGrantRow(head.stdout.trim(), Number(pr), kind, reason), words: flags['--words'] ?? reason, by, date: flags['--date'] }, loc.branch); + if ('code' in built) return fail(cmd, built); + rows = [built]; + } else if (cmd === 'lane-exception') { const invalid = (message: string) => fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message }); const files = [...new Set((flags['--files'] ?? '').split(',').map(f => f.trim().replace(/^(\.\/)+/, '')).filter(Boolean))].sort(); const reason = (flags['--reason'] ?? '').trim(); @@ -205,6 +226,7 @@ function main(argv: string[]): number { if (RULED_NOTE_SCOPE.test(flags['--scope'] ?? '')) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a ruled_note scope is recorded with gstack-approvals rule' }); if (GATE_DISPOSITION_SCOPE.test(flags['--scope'] ?? '') || (flags['--source'] ?? '').trim() === GATE_SOURCE) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a gate_disposition scope is recorded with gstack-approvals gate' }); if (TEST_LANE_EXCEPTION_SCOPE.test(flags['--scope'] ?? '')) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a test_lane_exception scope is recorded with gstack-approvals lane-exception' }); + if (REVIEW_ROUND_GRANT_SCOPE.test(flags['--scope'] ?? '')) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a review_round_grant scope is recorded with gstack-approvals round-grant' }); const built = buildRow({ ask: flags['--ask'] ?? '', words: flags['--words'] ?? '', by: flags['--by'] ?? '', scope: flags['--scope'] ?? '', pending: flags['--pending'], outcome: flags['--outcome'], date: flags['--date'], source: flags['--source'] }, loc.branch); if ('code' in built) return fail(cmd, built); rows = [built]; diff --git a/bin/gstack-no-stop b/bin/gstack-no-stop index 9477de83925..9ab8e2d22b1 100755 --- a/bin/gstack-no-stop +++ b/bin/gstack-no-stop @@ -29,7 +29,7 @@ const HELP = `gstack-no-stop — record one of the five no-stop defaults (docs/r finding takes the printed GATE_DISPOSITION: kept reason instead of open pregate-flake-rerun one rerun of a failed pregate case at the same tree (rule 16): green is flaky, red is real stamp-only-carry carry refused a head whose change is a version stamp (--range-base the receipt head, - --base origin/): take the carry's RECHECK: route instead of Steps 2-16 + --base origin/): go on to Steps 2-16 without waiting; the plan reviews HEAD in full autoplan-regate gstack-autoplan records it; import --from /no-stop.json adds it here Step 19's receipt write adds --no-stop @ when list shows records. --range-base: the commit the fix or change is measured from (round 2's PASS_HEAD for scoped-fix-check, which must be diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan index f50c342af39..e5bee01226b 100755 --- a/bin/gstack-review-plan +++ b/bin/gstack-review-plan @@ -25,6 +25,7 @@ import * as path from 'node:path'; import { spawnSync } from 'node:child_process'; import { baseContainsHead } from '../lib/default-base'; import { locate, readRecord } from '../lib/approval-record'; +import { reviewRoundGrants } from '../lib/review-round-grant'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { resultLine } from '../lib/result-codes'; import { runScriptSync } from '../lib/script-invocation'; @@ -96,7 +97,16 @@ const HELP = `gstack-review-plan — the review depth of the next /ship step (do line-exact) and docs (docsChangeSince, the receipt's classifier), with no executable, symlink or gitlink mode and no gate-scan tag in the range, are no gate-class edit: done, or targeted when a docs claim needs the targeted read on a targeted-class diff (GST-1702) - --pr the PR whose platform review counts under review.platform on (default: this branch's PR) + --pr the PR whose platform review counts under review.platform on (default: this branch's PR); with + --round-grant, the PR the grant must name + --prior-rounds R51 rounds earlier /ship runs on this PR already spent, fix-checks included (printed as pr_rounds=) + --prior-full the full rounds among them: with this run's full passes they count against the cap of 2, so pass 1 + of a PR with 2 is one read-only full review (no fix round; a blocker is NEXT: stop (PR_ROUND_CAP) + for the lane's Captain to decide, never the owner). + Both come from the PR_REVIEW_FLAGS: line gstack-ship-preflight prints (gstack-ship-receipt history) + (docs/review-policy.md#rounds-per-pull-request; GST-2673) + --round-grant a review round grant at HEAD, recorded with gstack-approvals round-grant by the lane or its Captain: + one more round for the PR at this head; any other row is refused (exit 3) --declare-risk risk classes the lane declares for the diff (comma list of ${RISK_CLASSES.join(', ')}): they join the detected classes and only raise the depth; RISK_DECLARED: prints both (GST-1129) --fix-check-prompt print the fix-check reviewer's prompt from --fix-list, --hunks, --tests and --callers files @@ -171,6 +181,18 @@ function main(): number { if (logged && logged.status !== 0) { process.stderr.write(`gstack-review-plan: --grant ${grant}: gstack-review-read exited ${logged.status}, so whether a fix-check already spent this grant is unknown; no plan is safer than a fix-check the grant may not buy\n`); return EXIT.fail; } if (logged && row && (logged.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').some(l => { try { const v = JSON.parse(l); return v?.skill === 'review-fix-check' && Date.parse(v.timestamp) > Date.parse(row.recorded_at); } catch { return false; } })) { process.stderr.write(`gstack-review-plan: --grant ${grant}: a fix-check was logged after this grant was recorded, so the grant already bought a link of the fix-check chain; the stop at --range-base ${rangeBase} needs a new grant recorded after the last fix-check (gstack-approvals add --ask '... (review_loop_grant ${passHead!.slice(0, 12)})')\n`); return EXIT.refused; } } + const priorRounds = Number(flag('--prior-rounds') ?? '0'); + const priorFull = Number(flag('--prior-full') ?? '0'); + if (![priorRounds, priorFull].every(n => Number.isInteger(n) && n >= 0)) { process.stderr.write('gstack-review-plan: --prior-rounds and --prior-full need integers >= 0 (PR_REVIEW_FLAGS: from gstack-ship-preflight)\n'); return EXIT.usage; } + const roundGrant = flag('--round-grant'); + if (has('--round-grant')) { + const at = git(['rev-parse', 'HEAD'])?.trim(); + const loc = locate({ cwd: root, env: process.env }); + const g = reviewRoundGrants('file' in loc ? readRecord(loc).rows : []).find(x => x.approval === roundGrant); + const pr = flag('--pr'); + const atOrBefore = !!g && !!at && (g.head === at || git(['merge-base', '--is-ancestor', g.head, at]) !== null); + if (!roundGrant || !g || !atOrBefore || (pr !== undefined && String(g.pr) !== pr)) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant ?? ''}: no approved review_round_grant row ${roundGrant ?? ''} naming HEAD ${(at ?? 'unknown').slice(0, 12)} or a commit before it${pr ? ` and PR #${pr}` : ''} in this branch's approval record; record one with gstack-approvals round-grant (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; } + } const collected = collectLive(root, base); if (collected.errors.length) { for (const e of collected.errors) process.stderr.write(`gstack-review-plan: git could not list the diff (${e.input}: ${e.detail}); fix: ${e.repair}; no plan is safer than a plan for an empty diff\n`); @@ -254,8 +276,9 @@ function main(): number { const plan = planReview({ ...collected, ...exclusionInput, ...riskPaths, declared: declared as RiskClass[], shape: { panel: review.panel, readerModel: review.reader_model, platform: review.platform, head, platformReview: platform?.ok ? platform.review : null }, scope, gateTagged, targeted: { classes: targeted.classes, ran }, numbers: scanNumbers(kept(added)), force, gated: list('--gated'), floor, tiers: auditEffort !== 'host', criticalFound: has('--critical-found'), adversarialRan: has('--adversarial-ran'), reviewedNumbers: flag('--reviewed-numbers'), - history: { fullPasses: pass, last, fixedBlocking: has('--fixed-blocking'), fixedBelow: (has('--fixed-below') || (postReview && pass > 0)) && last !== 'fix-check', blockingOpen: has('--blocking-open'), touchedGate: has('--touched-gate') || (!carried && (!!fixRange?.touched_gate || (postReview && pass > 0))), pass1Depth, rangeRuntimeLines: fixRange?.runtime_lines, granted: grant, fixChecks: has('--fix-checks') ? fixChecks : undefined, postReview, chained: inLoopLink }, + history: { priorRounds, priorFull, ...(roundGrant ? { roundGrant } : {}), fullPasses: pass, last, fixedBlocking: has('--fixed-blocking'), fixedBelow: (has('--fixed-below') || (postReview && pass > 0)) && last !== 'fix-check', blockingOpen: has('--blocking-open'), touchedGate: has('--touched-gate') || (!carried && (!!fixRange?.touched_gate || (postReview && pass > 0))), pass1Depth, rangeRuntimeLines: fixRange?.runtime_lines, granted: grant, fixChecks: has('--fix-checks') ? fixChecks : undefined, postReview, chained: inLoopLink }, }); + if (plan.next.reason.startsWith('PR_ROUND_CAP')) plan.next.reason += `: gstack-approvals round-grant --pr ${flag('--pr') ?? ''} --head ${head} --kind extra-round --reason "" --by , then rerun gstack-ship-preflight and pass the --round-grant id its PR_REVIEW_FLAGS: line prints; the grant buys one round at ${head.slice(0, 12)} and is then spent (docs/troubleshooting.md#pr-round-cap)`; if (carried) plan.next.reason = `the edits after the last fix-check ${fixCheckAt!.slice(0, 12)} are ${carried.paths.length ? `${carried.verdict === 'plain' ? 'plain docs' : `docs (${carried.paths.join(', ')})`}${carried.stamps.length ? ' and release stamps' : ''}` : 'release stamps'} (docsChangeSince), no gate-class edit (GST-1702): ${plan.next.reason}`; else if (postReview && pass > 0) plan.next.reason = `edits after the review bound (Step 16 stage 2.1) plan as a fix to a gate-class path, never a note: ${plan.next.reason}`; const ranArg = flag('--targeted-ran'); @@ -285,7 +308,7 @@ function main(): number { if (platform) out.push(platform.ok ? `PLATFORM_REVIEW: ${platform.review.id} reviewer=${platform.review.reviewer} head=${platform.review.head}` : `PLATFORM_REVIEW: none (${platform.reason})`); if (fixRange) out.push(`FIX_RANGE: ${fixRange.runtime_lines === null ? `unread (${fixRange.error})` : `runtime_lines=${fixRange.runtime_lines}`} base=${fixRange.base}`); if (targetedDeltaOut) out.push(`TARGETED_DELTA: range_base=${targetedDeltaOut.range_base} paths=${targetedDeltaOut.paths.join(',')} classes=${classList(targetedDeltaOut.classes)}`); - out.push(reviewPlanLine(plan, pass + (plan.next.step === 'full' || plan.next.step === 'scoped' ? 1 : 0)), `NEXT: ${plan.next.step} (${plan.next.reason})`); + out.push(reviewPlanLine(plan, pass + (plan.next.step === 'full' || plan.next.step === 'scoped' ? 1 : 0), priorRounds), `NEXT: ${plan.next.step} (${plan.next.reason})`); for (const e of plan.errors) out.push(`DEPTH_ERROR: ${e.code} input=${e.input} detail=${e.detail}; fix: ${e.repair}${e.result ? ` (${e.result})` : ''}`); for (const d of plan.dispatches) { const key = d.name.split(' ')[0]; diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 5709d718e39..6977267aa0d 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -15,6 +15,8 @@ * gstack-ship-receipt census --repo --since [--cohort ] [--limit ] [--json] * gstack-ship-receipt carry (--pr [--repo ] | --body ) [--base ] [--head ] [--pregate ] [--dry-run] [--out ] [--json] * gstack-ship-receipt docs-caps [--base ] [--policy ] [--json] + * gstack-ship-receipt history (--pr [--repo ] | --body ) [--head ] [--json] + * gstack-ship-receipt stub (--pr [--repo ] | --body ) --run [--head ] [--review-loop ] [--void] * * `write` validates against `gstack-artifact schema ship-receipt`, prints the * fenced block (and SHIP_RECEIPT: on stderr), writes it to --out, @@ -51,7 +53,7 @@ import { } from '../lib/ship-receipt'; import { checkDocsCaps, docsCapLine, docsExceptionLine, parseReceiptDocs } from '../lib/ship-receipt-docs'; import { comparePath, contextPacket, PACKET_SECTION_CAP, readScopedReview, touchedPaths } from '../lib/ship-patch'; -import { planRecheck, readRecheck, recheckPacket, recheckRecordTemplate } from '../crew/lib/ship-recheck'; +import { planRecheck, recheckPacket } from '../crew/lib/ship-recheck'; import { carryExcludeBinds, deeper, depthBelow, exceptionHead, exceptionLoopProblem, exceptionProblems, parseReviewLoopException, parseReviewTargeted, plainDocsSince, platformReceiptDepth, receiptExclude, receiptReviewAtHead, receiptTargetedAtHead, reviewLoopExceptionLine, targetedClassesSince, writeExcludeBinds } from '../lib/ship-receipt-depth'; import { RISK_CLASSES, type RiskClass } from '../lib/review-risk'; import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose'; @@ -60,6 +62,8 @@ import { readPause, receiptBaseRed } from '../lib/base-red'; import { readRuledNotes, ruledNoteText } from '../lib/ruled-notes'; import { appliedGateDispositions, gateDispositionText } from '../lib/gate-dispositions'; import { laneExceptionBodyLines } from '../lib/test-lane-exception'; +import { historyLine, placeRunEntry, prReviewHistory, reviewRoute, runStub } from '../lib/pr-review-history'; +import { grantAt, readReviewRoundGrants } from '../lib/review-round-grant'; import { readMechanicalLines } from '../lib/ship-mechanical'; import { isRegistryUnavailable, loadRegistryFromBase } from '../lib/regen'; @@ -86,8 +90,19 @@ const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block RECEIPT_CARRY_TREE_MISMATCH / RECEIPT_CARRY_REFUSED leave the body unchanged (exit 3); a receipt that records a pregate needs --pregate current for HEAD (RECEIPT_CARRY_PREGATE_STALE); a product change on linear history whose range-diff is within the re-check cap prints - RECHECK: eligible … packet=: one reader reads it, then --recheck (J1); + RECHECK: advisory … packet=: one reader may read it for advice; it never carries + the receipt, so the head that merges runs /ship (J1, GST-2673); needs git >= 2.39 (RECEIPT_GIT_TOO_OLD) + history --pr [--repo ] | --body [--head ] + R51 per pull request (docs/review-policy.md#rounds-per-pull-request): sums the review rounds + the receipt and its runs block record across every head and /ship run, and prints + PR_REVIEW_HISTORY:, PR_REVIEW_FLAGS: (what Step 9 passes to every gstack-review-plan call) and + PR_REVIEW_ROUTE: first|final|read-only (why); a PR body gh cannot read prints source=unavailable + with its cause and fix on stderr (exit 1), and the plan then counts as it did before + stub --pr | --body --run [--head ] [--review-loop ] [--void] + Step 9: record this /ship run's rounds so far in the runs block before its receipt exists, so a + run that stops still counts; the run's receipt write (same --run) replaces it; --void marks an + infrastructure failure that counts nothing docs-caps [--base ] /ship Step 14.5: one DOCS_CAP: / ok|over line per docs.caps entry of the reviewed policy (origin/'s .gstack/ship-policy.json; --policy reads that file instead); any over (or absent) file exits 1 (DOCS_AUDIT_BLOCKED) @@ -338,7 +353,7 @@ function cmdWrite(rest: string[], json: boolean): number { policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'), ...pregate, issues: issuesFile ? receiptIssuesFrom(issuesFile) : undefined, approval: approval.kind === 'ok' ? approval.approval : undefined, review_loop: reviewLoop, ...(docs?.ok ? { docs: docs.docs } : {}), ...product, - gstack_version: installedGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, ruled_notes: ruledNotes.length ? ruledNotes : undefined, gate_dispositions: gateDispositions, mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined, + gstack_version: installedGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, review_round_grants: roundGrantsFor(repoRoot, flag(rest, '--pr')), ruled_notes: ruledNotes.length ? ruledNotes : undefined, gate_dispositions: gateDispositions, mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined, design: review.frontend ? { mode: 'static', reason: 'no preview declared' } : undefined, base_red: pause ? receiptBaseRed(pause) : undefined, review_exclude: receiptExclude(review.exclude), @@ -657,6 +672,7 @@ function cmdCarry(rest: string[], json: boolean): number { if ((pr === undefined) === (bodyFile === undefined)) { process.stderr.write(`gstack-ship-receipt carry: pass --pr or --body , not both\n${HELP}\n`); return EXIT.usage; } const repoRoot = git(['rev-parse', '--show-toplevel']); if (!repoRoot) { process.stderr.write('gstack-ship-receipt carry: run it inside the git checkout whose head carries the receipt\n'); return EXIT.usage; } + if (rest.includes('--recheck')) { process.stderr.write('gstack-ship-receipt carry: --recheck is gone: a scoped re-check is advice only and never carries a receipt (GST-2673); run /ship on HEAD for the merge head\'s full review (docs/review-policy.md#rounds-per-pull-request)\n'); return EXIT.refused; } const head = (flag(rest, '--head') ?? git(['rev-parse', 'HEAD'], repoRoot))?.toLowerCase(); if (!head || !/^[0-9a-f]{40,64}$/.test(head)) { process.stderr.write('gstack-ship-receipt carry: cannot resolve HEAD\n'); return EXIT.usage; } const refused = (code: 'QUEUE_RECEIPT_MISSING' | 'QUEUE_RECEIPT_CONDITIONAL' | 'RECEIPT_CARRY_REFUSED' | 'RECEIPT_CARRY_PRODUCT_CHANGED' | 'RECEIPT_CARRY_SCOPED_REVIEW' | 'RECEIPT_CARRY_TREE_MISMATCH' | 'RECEIPT_GIT_TOO_OLD' | 'RECEIPT_CARRY_PREGATE_STALE', message: string) => { @@ -724,7 +740,6 @@ function cmdCarry(rest: string[], json: boolean): number { const retarget = reviewedBase !== base.replace(/^origin\//, ''); let plan: ReturnType; let scopedDryRun: string | undefined; - let recheck: string | undefined; if (!ancestor) { // Rewritten history: the receipt follows only onto a tree it already covers, with the product diff it recorded. const recorded = receipt.product_patch_id !== undefined ? (receipt.product_patch_id === 'none' ? '' : receipt.product_patch_id) : fromKnown ? productPatchAgainstBase(repoRoot, rules, baseRef, from) : { error: 'the receipt records no product patch-id and its head is not in this clone' }; @@ -852,7 +867,7 @@ function cmdCarry(rest: string[], json: boolean): number { // Evidence for the record, never the decision: a slow range-diff is reported unavailable rather than waited for. const rangeRaw = spawnSync('git', ['range-diff', '--no-color', `${rangeBase}..${from}`, `${headBase}..${head}`], { cwd: repoRoot, encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024 * 1024 }); const rangeDiff = rangeRaw.status === 0 ? (rangeRaw.stdout.trim().split('\n').slice(0, 20).join('\n') || '(empty: identical ranges)') : `unavailable: ${(rangeRaw.stderr ?? '').trim().split('\n')[0] || (rangeRaw.signal ? `range-diff killed by ${rangeRaw.signal} after 15 s` : 'range-diff failed')}`; - // J1: a bounded product change since the reviewed head gets one reader on the range-diff instead of a full /ship (crew/lib/ship-recheck.ts). + // J1: a bounded product change since the reviewed head gets an advisory packet for one reader; it never carries (crew/lib/ship-recheck.ts, GST-2673). if (changedProduct.length) { const named = changedProduct.filter(p => !p.startsWith('(') && !p.includes(' (')); const inter = named.length ? spawnSync('git', ['diff', '--no-color', '--no-ext-diff', from, head, '--', ...named.map(p => `:(literal)${p}`)], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024 }) : null; @@ -863,23 +878,18 @@ function cmdCarry(rest: string[], json: boolean): number { const context = contextPaths.length ? contextPacket(repoRoot, { reviewedBase: rangeBase, reviewed: from, currentBase: headBase, current: head }, contextPaths) : undefined; const bound = context ? { rangeBase, context: context.text } : {}; const r = planRecheck({ code: 'RECEIPT_CARRY_PRODUCT_CHANGED', ancestor, retarget, rangeDiff: fullRange, unnamedPaths: named.length !== changedProduct.length, legacy: !receipt.review_depth, walkCut, contextPaths: contextPaths.length, context, binary }); - const record = flag(rest, '--recheck'); if (!r.ok) process.stderr.write(`RECHECK: not eligible (${r.reason}); run /ship on ${head.slice(0, 12)}\n`); - else if (record) { - const read = readRecheck(record, { from, head, sha256: r.sha256, ...bound }); - if (!read.ok) return refused('RECEIPT_CARRY_REFUSED', `--recheck: ${read.message}`); - recheck = `scoped re-check by ${read.record.reader} (range-diff ${r.lines} lines${context ? `; base context moved in ${contextPaths.join(', ')}; range_base ${rangeBase.slice(0, 12)}` : ''})`; - } else { + else { let where = 'not written (dry run)'; if (!rest.includes('--dry-run')) { const packet = path.resolve(repoRoot, git(['rev-parse', '--git-path', `gstack/recheck-${head.slice(0, 12)}.md`], repoRoot) ?? `.git/gstack/recheck-${head.slice(0, 12)}.md`); try { fs.mkdirSync(path.dirname(packet), { recursive: true }); fs.writeFileSync(packet, recheckPacket({ from, head, plan: r, rangeDiff: fullRange!, ...bound })); where = packet; } catch (e) { where = `unwritable: ${(e as Error).message.split('\n')[0]}`; } } - process.stderr.write(`RECHECK: eligible range_diff_lines=${r.lines} range_diff_sha256=${r.sha256} packet=${where}; one reader reads it, then carry --recheck (${recheckRecordTemplate({ from, head, sha256: r.sha256, ...bound })}); a blocking finding means /ship on ${head.slice(0, 12)}\n`); + process.stderr.write(`RECHECK: advisory range_diff_lines=${r.lines} range_diff_sha256=${r.sha256} packet=${where}; one reader may read it for advice, but it never carries the receipt (GST-2673): run /ship on ${head.slice(0, 12)} for the merge head's full review (docs/review-policy.md#rounds-per-pull-request)\n`); } } - plan = planCarry({ from, head, changed, productPatchId: { from: reviewed as string, head: current as string }, testPatchId: { from: testFrom, head: testHead }, changedProduct, mergeCommits: Number(mergeCommits) || 0, rangeDiff, ...(retarget ? { retargetedFrom: reviewedBase } : {}), ...(stackParent ? { stackParent } : {}), ...(scopedReview ? { scopedReview } : {}), ...(stampedRows.length ? { stampedRows } : {}), ...(recheck ? { recheck } : {}) }); + plan = planCarry({ from, head, changed, productPatchId: { from: reviewed as string, head: current as string }, testPatchId: { from: testFrom, head: testHead }, changedProduct, mergeCommits: Number(mergeCommits) || 0, rangeDiff, ...(retarget ? { retargetedFrom: reviewedBase } : {}), ...(stackParent ? { stackParent } : {}), ...(scopedReview ? { scopedReview } : {}), ...(stampedRows.length ? { stampedRows } : {}) }); } if (!plan.ok) return refused(plan.code, plan.message); // Eligibility is not publication: a receipt that recorded a pregate is rebound only with a pregate current for HEAD, @@ -908,8 +918,6 @@ function cmdCarry(rest: string[], json: boolean): number { if (review.exclude.state === 'refused') return refused('RECEIPT_CARRY_REFUSED', `${review.exclude.lines.join('; ')}; run /ship on ${head.slice(0, 12)} once the base policy reads`); const digest = review.exclude.state === 'active' ? review.exclude.record.digest : 'none'; if (!carryExcludeBinds(review.exclude, receipt)) return refused('RECEIPT_CARRY_REFUSED', `review_exclude changed: recorded=${receipt.review_exclude?.digest ?? 'none'} now=${digest} source=${review.exclude.state === 'active' ? review.exclude.record.source : `${base} (no review_exclude_paths)`}; the receipt's digest is the --review-exclude argument write was given, and it names another selection than HEAD ${head.slice(0, 12)} has under the base policy and the two give the PR's files different selections (carry compares those, not the review ledger), so carry does not apply; run /ship on ${head.slice(0, 12)}`); - const riskOf = (d: { class: string; risk?: readonly string[] }) => `${d.class}:${[...(d.risk ?? [])].sort().join(',')}`; - if (recheck && riskOf(now) !== riskOf(receipt.review_depth)) return refused('RECEIPT_CARRY_REFUSED', `HEAD ${head.slice(0, 12)} is risk class ${riskOf(now)}, not the reviewed ${riskOf(receipt.review_depth)}, so a scoped re-check cannot stand in for review; run /ship on ${head.slice(0, 12)}`); if (depthBelow(receipt.review_depth.depth, now.depth)) return refused('RECEIPT_CARRY_REFUSED', `HEAD ${head.slice(0, 12)} needs ${now.depth} review depth (${now.reasons.join(', ')}), above the receipt's ${receipt.review_depth.depth}; run /ship on ${head.slice(0, 12)}`); depthField = { review_depth: { ...now, depth: deeper(receipt.review_depth.depth, now.depth) }, review_exclude: receiptExclude(review.exclude) }; } @@ -1008,6 +1016,76 @@ function cmdDocsCaps(rest: string[], json: boolean): number { return EXIT.fail; } +/** The round grants the branch's approval record holds for this PR (the receipt's review_round_grants). */ +function roundGrantsFor(repoRoot: string | undefined, pr: string | undefined): ShipReceipt['review_round_grants'] { + if (!repoRoot || !pr) return undefined; + const grants = readReviewRoundGrants(repoRoot).filter(g => String(g.pr) === pr); + return grants.length ? grants : undefined; +} + +/** The PR body from --body or gh, or why it cannot be read. */ +function readBody(rest: string[]): { ok: true; body: string; pr?: string } | { ok: false; why: string; fix: string } { + const bodyFile = flag(rest, '--body'); + if (bodyFile) { + try { return { ok: true, body: fs.readFileSync(bodyFile, 'utf8') }; } catch (e) { return { ok: false, why: `${bodyFile} is unreadable (${(e as Error).message.split('\n')[0]})`, fix: 'pass a readable --body file' }; } + } + const pr = flag(rest, '--pr'); + if (!pr || !/^[1-9]\d*$/.test(pr)) return { ok: false, why: '--pr or --body is required', fix: 'pass the open PR number' }; + const repo = flag(rest, '--repo'); + const r = gh(['pr', 'view', pr, ...(repo ? ['--repo', repo] : []), '--json', 'body']); + if (!r.ok) return { ok: false, why: `gh pr view ${pr} failed: ${r.err.split('\n')[0]}`, fix: 'check gh auth status and the PR number, then rerun' }; + try { return { ok: true, body: JSON.parse(r.out).body ?? '', pr }; } catch { return { ok: false, why: 'gh returned no JSON body', fix: 'rerun; check gh auth status' }; } +} + +function postBody(rest: string[], pr: string | undefined, body: string): string | null { + const bodyFile = flag(rest, '--body'); + if (bodyFile) { fs.writeFileSync(bodyFile, body); return null; } + const repo = flag(rest, '--repo'); + const tmp = path.join(fs.mkdtempSync(path.join(process.env.TMPDIR ?? '/tmp', 'gstack-runs-')), 'body.md'); + fs.writeFileSync(tmp, body, { mode: 0o600 }); + const edit = gh(['pr', 'edit', pr!, ...(repo ? ['--repo', repo] : []), '--body-file', tmp]); + fs.rmSync(path.dirname(tmp), { recursive: true, force: true }); + return edit.ok ? null : `gh pr edit failed: ${edit.err}`; +} + +/** R51 per pull request: the rounds the PR body records, and what the next head gets (GST-2673). */ +function cmdHistory(rest: string[], json: boolean): number { + const pr = flag(rest, '--pr') ?? '?'; + const read = readBody(rest); + if (!read.ok) { + process.stderr.write(`gstack-ship-receipt history: ${read.why}; fix: ${read.fix}; until then the review plan counts this run's rounds only\n`); + process.stdout.write(json ? JSON.stringify({ pr, source: 'unavailable', why: read.why }) + '\n' : `PR_REVIEW_HISTORY: pr=#${pr} source=unavailable\n`); + return EXIT.fail; + } + const repoRoot = git(['rev-parse', '--show-toplevel']); + const head = (flag(rest, '--head') ?? (repoRoot ? git(['rev-parse', 'HEAD'], repoRoot) : undefined))?.toLowerCase(); + const h = prReviewHistory(read.body); + const grant = repoRoot && head && /^\d+$/.test(pr) ? grantAt(readReviewRoundGrants(repoRoot), Number(pr), head) : undefined; + const route = reviewRoute(h, { grant: grant?.approval }); + const flagsLine = `PR_REVIEW_FLAGS: --prior-rounds ${h.rounds} --prior-full ${h.full}${grant ? ` --round-grant ${grant.approval}` : ''}`; + if (json) { process.stdout.write(JSON.stringify({ pr, ...h, grant: grant ?? null, route }) + '\n'); return EXIT.ok; } + process.stdout.write(`${historyLine(pr, h)}\n${flagsLine}\nPR_REVIEW_ROUTE: ${route.route} (${route.reason})\n`); + return EXIT.ok; +} + +/** Step 9: this run's rounds so far, recorded before its receipt exists (a started stub), or voided. */ +function cmdStub(rest: string[]): number { + const run = flag(rest, '--run'); + if (!run || !/^[\w.:-]{1,120}$/.test(run)) { process.stderr.write('gstack-ship-receipt stub: --run is required\n'); return EXIT.usage; } + const read = readBody(rest); + if (!read.ok) { process.stderr.write(`gstack-ship-receipt stub: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; } + let loop: ReturnType; + try { loop = flag(rest, '--review-loop') !== undefined ? parseReviewLoop(jsonArg(flag(rest, '--review-loop'))) : { passes: 1, blocking_found: 0, deferred: 0, rounds: 1 }; } catch (e) { process.stderr.write(`gstack-ship-receipt stub: --review-loop: ${(e as Error).message}\n`); return EXIT.usage; } + if (!loop) { process.stderr.write('gstack-ship-receipt stub: --review-loop needs {passes, blocking_found, deferred[, fix_checks, rounds, scoped]}\n'); return EXIT.usage; } + const head = (flag(rest, '--head') ?? git(['rev-parse', 'HEAD']))?.toLowerCase(); + if (!head || !/^[0-9a-f]{40,64}$/.test(head)) { process.stderr.write('gstack-ship-receipt stub: cannot resolve HEAD\n'); return EXIT.usage; } + const status = rest.includes('--void') ? 'voided' : 'started'; + const err = postBody(rest, read.pr, placeRunEntry(read.body, runStub({ head, run, status, loop }))); + if (err) { process.stderr.write(`gstack-ship-receipt stub: ${err}; the run is not recorded\n`); return EXIT.fail; } + process.stdout.write(`RUN_STUB: run=${run} status=${status} rounds=${loop.rounds ?? loop.passes + (loop.fix_checks ?? 0)} head=${head.slice(0, 12)}\n`); + return EXIT.ok; +} + function main(argv: string[]): number { const [cmd, ...rest] = argv; const json = rest.includes('--json'); @@ -1018,6 +1096,8 @@ function main(argv: string[]): number { if (cmd === 'census') return cmdCensus(rest, json); if (cmd === 'carry') return cmdCarry(rest, json); if (cmd === 'docs-caps') return cmdDocsCaps(rest, json); + if (cmd === 'history') return cmdHistory(rest, json); + if (cmd === 'stub') return cmdStub(rest); process.stderr.write(`gstack-ship-receipt: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; } diff --git a/changelog.d/count-review-rounds-per-pr.md b/changelog.d/count-review-rounds-per-pr.md new file mode 100644 index 00000000000..5fb3fa1c847 --- /dev/null +++ b/changelog.d/count-review-rounds-per-pr.md @@ -0,0 +1 @@ +- **`/ship` now counts review rounds per pull request, and the head that merges always gets a full review.** gstack's two-round review cap (R51) was counted inside each `/ship` run, so a PR shipped five times could be reviewed ten times. `/ship` Step 1 now reads the PR body's receipt history (`gstack-ship-receipt history`), prints `PR_REVIEW_HISTORY:` and `PR_REVIEW_ROUTE:`, and passes the earlier rounds to `gstack-review-plan` (`--prior-rounds`, and `--prior-full` for the full rounds the cap counts). A new head whose own lines changed gets a fresh full review, the PR's last before merge; a PR already at two full rounds gets one read-only full review with no fix round, whose blocker goes to the lane's Captain. A scoped re-check of only what changed is now advice only: `carry` prints `RECHECK: advisory` and refuses `--recheck`, because in the replay a diff-only re-check caught none of 8 real faults that full rounds had caught (docs/evals/pr-round-count-results.md). A run that stops before its receipt still counts (`gstack-ship-receipt stub`), and the lane or Captain can buy one more round with `gstack-approvals round-grant --kind extra-round`; gstack cannot grant itself one. See docs/review-policy.md#rounds-per-pull-request. diff --git a/crew/docs/captain.md b/crew/docs/captain.md index 64ff032b308..83d81079d1e 100644 --- a/crew/docs/captain.md +++ b/crew/docs/captain.md @@ -668,6 +668,9 @@ case-kind change, closing a contribution without landing it, and anything destru Standing spend is the commonest standing approval: `SPEND` in CREW.md names what the owner pre-approved (train gates, screens, bisects, the backstop, focused paid cases) with the owner's date and words and the cap per rerun; anything over the cap is a fresh ask. +A review round past a PR's two (`PR_ROUND_CAP`) is the lane's or the controller's call, recorded +with `gstack-approvals round-grant`, never an owner ask +([rounds per pull request](../../docs/review-policy.md#rounds-per-pull-request)). **B. The plan ask** ([template](../../captain/templates/plan-ask.md)): before → after, why it matters, what caused this work, the big decisions, and what we need from you in the ask diff --git a/crew/lib/ship-recheck.ts b/crew/lib/ship-recheck.ts index 37a14814e75..6e088d9a221 100644 --- a/crew/lib/ship-recheck.ts +++ b/crew/lib/ship-recheck.ts @@ -1,9 +1,9 @@ /** * J1 (GSTA-258 plan H, relabeled J1): a scoped re-check after a refused receipt carry. When `gstack-ship-receipt carry` refuses - * because the product patch changed since the reviewed head, and the change is bounded, one reader reads `git range-diff` of - * the reviewed range against the current one instead of a full second /ship (gbrain-evals #246/#247: about 100k credits per - * full rerun; #300's scoped reader: about 300). A clean verdict bound to that exact range-diff rebinds the receipt; the carry's - * later checks still refuse a deeper review depth or a changed risk class, which need the full /ship. + * because the product patch changed since the reviewed head, and the change is bounded, carry writes a packet of `git + * range-diff` of the reviewed range against the current one, which one reader may read for advice. Since GST-2673 the read + * never rebinds the receipt: a packet-only reader caught 0 of 8 real faults that full rounds had caught (22 of 24 seeded ones; + * docs/evals/pr-round-count-prereg.md), so the head that merges gets /ship's full review. * * Qualifies: RECEIPT_CARRY_PRODUCT_CHANGED on linear history (the receipt's head is an ancestor of HEAD) against the same base. * Does not qualify: RECEIPT_CARRY_TREE_MISMATCH (rewritten history: the reviewed commits are gone, so there is no range to @@ -14,11 +14,9 @@ * their inputs repaired, not a review). * * Moved base context composes (GST-1561, founderstar#563): the context paths' scoped-review sections (lib/ship-patch.ts contextPacket) - * join the range-diff in the one packet, the caps count both, the verdict binds both, and the record also names range_base, the - * commit the reviewed range starts from. + * join the range-diff in the one packet, and the caps count both. */ import { createHash } from 'node:crypto'; -import * as fs from 'node:fs'; export const RECHECK_RANGE_DIFF_CAP = 400; /** The packet's byte cap: 400 lines of unbounded width (a minified bundle) would not bound the one reader's input. */ @@ -62,36 +60,17 @@ export function planRecheck(i: RecheckInput): RecheckPlan { return { ok: true, lines, sha256: sha(text) }; } -/** What range_diff_sha256 binds: the range-diff, then any moved base context's scoped-review sections. */ +/** What the RECHECK line's range_diff_sha256 names: the range-diff, then any moved base context's scoped-review sections. */ const packetMaterial = (rangeDiff: string, context?: string) => (context ? `${rangeDiff.trim()}\n\n${context.trim()}` : rangeDiff.trim()); -/** The clean record a reader writes; range_base only when base context composes into the packet. */ -export const recheckRecordTemplate = (o: { from: string; head: string; sha256: string; rangeBase?: string }) => - JSON.stringify({ from: o.from, head: o.head, ...(o.rangeBase ? { range_base: o.rangeBase } : {}), range_diff_sha256: o.sha256, reader: '', verdict: 'clean' }); - -/** The packet the one reader reads: what to judge, the record to write, then the range-diff verbatim and any moved base context. */ +/** The packet an advisory reader reads: what to judge, that it carries nothing, then the range-diff verbatim and any moved base context. */ export function recheckPacket(o: { from: string; head: string; plan: Extract; rangeDiff: string; context?: string; rangeBase?: string }): string { return [ - `# Scoped re-check: the product patch changed since the reviewed head\n`, + `# Scoped re-check (advice only): the product patch changed since the reviewed head\n`, `reviewed ${o.from}${o.context ? ` (range_base ${o.rangeBase})` : ''}; current ${o.head}. Below is \`git range-diff\` of the reviewed range against the current one, then the diff of the changed product paths between the two heads${o.context ? ', then the hunks where base context moved next to the reviewed ones' : ''} (${o.plan.lines} lines).`, 'Review only what changed between the two ranges, against the blocking floor: would fail a test, break production, or lose data or secrets.', - `Reply NO FINDINGS, or one finding per line with path:line, Severity and Blocks. A clean reply is recorded as ${recheckRecordTemplate({ ...o, sha256: o.plan.sha256 })}.`, - 'A blocking finding means the full /ship on the current head.\n', + 'Reply NO FINDINGS, or one finding per line with path:line, Severity and Blocks.', + 'This read is advice for the lane only. It never carries the receipt: the head that merges still gets a full review from /ship (GST-2673; docs/review-policy.md#rounds-per-pull-request).\n', '```diff', o.rangeDiff.trim(), '```', '', ...(o.context ? [o.context.trim(), ''] : []), ].join('\n'); } - -export interface RecheckRecord { from: string; head: string; range_base?: string; range_diff_sha256: string; reader: string; verdict: 'clean' } - -/** A clean re-check record bound to this carry's from, head and range-diff, or why it does not stand. */ -export function readRecheck(file: string, bind: { from: string; head: string; sha256: string; rangeBase?: string }): { ok: true; record: RecheckRecord } | { ok: false; message: string } { - let v: Record; - try { v = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { return { ok: false, message: `${file} is not readable JSON (${(e as Error).message.split('\n')[0]})` }; } - if (!v || typeof v !== 'object') return { ok: false, message: `${file} is not a JSON object` }; - if (v.verdict !== 'clean') return { ok: false, message: `the re-check is ${JSON.stringify(v.verdict)}, not clean: run /ship on ${bind.head.slice(0, 12)}` }; - if (typeof v.reader !== 'string' || !v.reader.trim()) return { ok: false, message: 'the re-check names no reader' }; - for (const [k, want] of [['from', bind.from], ['head', bind.head], ['range_diff_sha256', bind.sha256], ...(bind.rangeBase ? [['range_base', bind.rangeBase] as const] : [])] as const) { - if (v[k] !== want) return { ok: false, message: `the re-check is for ${k} ${String(v[k] ?? 'none').slice(0, 12)}, not ${want.slice(0, 12)}` }; - } - return { ok: true, record: v as unknown as RecheckRecord }; -} diff --git a/crew/test/ship-recheck.test.ts b/crew/test/ship-recheck.test.ts index 8106281bf0e..fe1565a6a80 100644 --- a/crew/test/ship-recheck.test.ts +++ b/crew/test/ship-recheck.test.ts @@ -1,9 +1,9 @@ /** - * J1 (GSTA-258 L4): a scoped re-check after a refused receipt carry. Each refusal reason that does or does not qualify, - * the record binding, and the carry end to end: a bounded product change prints RECHECK: eligible and writes the packet, - * a clean record bound to that packet carries the receipt with the reader named, and a changed risk class, a legacy - * receipt and more paths than the walk names never take the re-check (the /ship p1 red-team and security findings). - * Moved base context joins the packet instead (GST-1561; test/ship-receipt-carry-mixed.test.ts). + * J1 (GSTA-258 L4), advice only since GST-2673: a scoped re-check packet after a refused receipt carry. Each refusal + * reason that does or does not qualify, and the carry end to end: a bounded product change prints RECHECK: advisory and + * writes the packet, and no re-check record carries the receipt, because a diff-only re-check caught 0 of 8 real faults + * full rounds had caught; a legacy receipt and more paths than the walk names get no packet. Moved base context joins + * the packet (GST-1561; test/ship-receipt-carry-mixed.test.ts). */ import { afterEach, describe, expect, test } from 'bun:test'; import * as fs from 'node:fs'; @@ -11,7 +11,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { EXIT } from '../../lib/headless-artifacts'; import { extractReceipt, placeReceipt } from '../../lib/ship-receipt'; -import { planRecheck, readRecheck, RECHECK_PACKET_BYTES, RECHECK_RANGE_DIFF_CAP } from '../lib/ship-recheck'; +import { planRecheck, RECHECK_PACKET_BYTES, RECHECK_RANGE_DIFF_CAP } from '../lib/ship-recheck'; import { cleanup, makeFixtureRepo, runBin, type FixtureRepo } from '../../test/helpers/restamp-fixture'; const repos: FixtureRepo[] = []; @@ -46,20 +46,6 @@ describe('planRecheck: which refusals qualify', () => { }); }); -describe('readRecheck binds to from, head and the range-diff', () => { - test('only a clean record for this exact range-diff stands', () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'recheck-')); - const bind = { from: 'a'.repeat(40), head: 'b'.repeat(40), sha256: 'c'.repeat(64) }; - const write = (o: object) => { const f = path.join(dir, `${Math.random()}.json`); fs.writeFileSync(f, JSON.stringify(o)); return f; }; - const good = { from: bind.from, head: bind.head, range_diff_sha256: bind.sha256, reader: 'anthropic/claude-opus-5-5', verdict: 'clean' }; - expect(readRecheck(write(good), bind).ok).toBe(true); - expect(readRecheck(write({ ...good, verdict: 'blocking' }), bind)).toMatchObject({ ok: false, message: expect.stringContaining('not clean') }); - expect(readRecheck(write({ ...good, range_diff_sha256: 'd'.repeat(64) }), bind)).toMatchObject({ ok: false, message: expect.stringContaining('range_diff_sha256') }); - expect(readRecheck(write({ ...good, reader: '' }), bind)).toMatchObject({ ok: false, message: 'the re-check names no reader' }); - fs.rmSync(dir, { recursive: true, force: true }); - }); -}); - /** A branch reviewed at one commit, with a receipt written by gstack-ship-receipt write (so it records review_depth). */ function reviewed(files: Record = { 'src/app.ts': 'export const a = 2;\n' }) { const repo = makeFixtureRepo({ prefix: 'ship-recheck-' }); repos.push(repo); @@ -83,10 +69,10 @@ function reviewed(files: Record = { 'src/app.ts': 'export const }; return { repo, from, body, env, commit }; } -const eligible = (err: string) => /^RECHECK: eligible range_diff_lines=(\d+) range_diff_sha256=([0-9a-f]{64}) packet=(\S+);/m.exec(err); +const eligible = (err: string) => /^RECHECK: advisory range_diff_lines=(\d+) range_diff_sha256=([0-9a-f]{64}) packet=(\S+);/m.exec(err); describe('carry with a scoped re-check (CLI)', () => { - test('a bounded product change prints RECHECK: eligible, keeps the refusal, and a clean record carries with the reader named', () => { + test('a bounded product change prints RECHECK: advisory and keeps the refusal; a clean record bound to the packet carries nothing', () => { const { repo, from, body, env, commit } = reviewed(); const head = commit({ 'src/app.ts': 'export const a = 3;\n' }, 'fix: a=3'); const refused = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body], env); @@ -94,33 +80,16 @@ describe('carry with a scoped re-check (CLI)', () => { expect(refused.out.trim().split('\n')[0]).toBe('CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)'); const m = eligible(refused.err); expect(m).not.toBeNull(); + expect(refused.err).toContain('it never carries the receipt (GST-2673)'); expect(fs.readFileSync(m![3]!, 'utf8')).toContain('export const a = 3;'); + expect(fs.readFileSync(m![3]!, 'utf8')).toContain('advice only'); + const before = fs.readFileSync(body, 'utf8'); const record = path.join(repo.root, 'recheck.json'); fs.writeFileSync(record, JSON.stringify({ from, head, range_diff_sha256: m![2], reader: 'anthropic/claude-opus-5-5', verdict: 'clean' })); const carried = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--recheck', record, '--out', path.join(repo.root, 'run')], env); - expect([carried.status, carried.err.slice(0, 400)]).toEqual([EXIT.ok, expect.any(String)]); - expect(carried.out.trim().split('\n')[0]).toBe(`CARRY: carried from ${from.slice(0, 12)} to ${head.slice(0, 12)} (scoped re-check by anthropic/claude-opus-5-5 (range-diff ${m![1]} lines))`); - expect(extractReceipt(fs.readFileSync(body, 'utf8')).receipt).toMatchObject({ head, carry: { from } }); - const stale = path.join(repo.root, 'stale.json'); - fs.writeFileSync(stale, JSON.stringify({ from: head, head, range_diff_sha256: 'f'.repeat(64), reader: 'x', verdict: 'clean' })); - commit({ 'src/app.ts': 'export const a = 4;\n' }, 'fix: a=4'); - const bad = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--recheck', stale], env); - expect([bad.status, bad.out.trim().split('\n')[0]]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_REFUSED)']); - }, 60_000); - - test('a clean re-check cannot carry across a changed risk class', () => { - const { repo, from, body, env, commit } = reviewed(); - const before = extractReceipt(fs.readFileSync(body, 'utf8')).receipt!.review_depth!; - const head = commit({ 'src/app.ts': 'export const a = 3;\n', 'src/billing.ts': 'export function charge(cents: number) { return stripe.charges.create({ amount: cents }); }\n' }, 'feat: billing'); - const refused = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body], env); - const m = eligible(refused.err); - expect(m).not.toBeNull(); - const record = path.join(repo.root, 'recheck.json'); - fs.writeFileSync(record, JSON.stringify({ from, head, range_diff_sha256: m![2], reader: 'x', verdict: 'clean' })); - const r = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--recheck', record], env); - expect(r.status).toBe(EXIT.refused); - expect(r.err).toMatch(/risk class|review depth/); - expect(before.risk ?? []).not.toContain('money'); + expect(carried.status).toBe(EXIT.refused); + expect(carried.err).toContain('--recheck is gone'); + expect(fs.readFileSync(body, 'utf8')).toBe(before); }, 60_000); test('a legacy receipt, more changed paths than the walk names, and moved base context print RECHECK: not eligible', () => { diff --git a/docs/evals/pr-round-count-prereg.md b/docs/evals/pr-round-count-prereg.md new file mode 100644 index 00000000000..16bb4002881 --- /dev/null +++ b/docs/evals/pr-round-count-prereg.md @@ -0,0 +1,75 @@ +# Prereg: does a scoped re-check reader lose blockers that a full round would catch? (GST-2673) + +Status: locked 2026-11-13, before any paid call. Owner: GStack Minder (GSTA-36). Runs once, on the branch that adds +the per-PR round count ([review-policy.md](../review-policy.md#rounds-per-pull-request)), before that branch merges. + +## Question +Once a pull request has had a full review round, design A sends each new head to one scoped re-check reader that +sees only what changed since the last reviewed head (the [carry re-check](../troubleshooting.md#receipt-carry-recheck) +packet), instead of a fresh full round. Does that reader still find the blocking faults that review fixes create +after round 1, and stay quiet on heads that had none? + +Where the evidence comes from: one crew working on an internal product had three heavily reviewed PRs whose later +rounds raised dozens of findings. A small share led to a real code fix, and most of those repaired a fault created +after round 2 inside the diff since the previous head, which is the scoped reader's range. One more fault, a race a +round-1 fix created, sat outside that range. That crew, its product and its repository are not named here; its +packets and labels stay private, and this repository reports only aggregates. + +## The decision this changes (R97) +If the scoped reader keeps the blockers (Part 2's bars met), later heads go to the scoped re-check by default and +this branch merges as built. If it loses them, the branch does not merge as built: later heads keep a full round +(the count and stop rule stay, the re-check route is narrowed or widened first) and the loss is reported. Part 1 +decides the drift threshold the router ships with. + +## Part 1: free deterministic replay (no model calls) +Over every PR body with receipts in gstack and in the source crew's repository (read only), run the new counter +and router (`lib/pr-review-history.ts`, `reviewRoute`) head by head and record: +1. Route labels for every later head: re-check eligible, re-check refused (with carry's reason), re-check found a + blocker then a full /ship ran, a run stopped with no receipt, or the lane ignored the route. +2. Rounds: on PRs with three or more /ship runs, at most two full rounds planned; on one-run PRs, no plan change. +3. Drift: how often `PR_DRIFT_LINES` (400) fires and at which head. If a value between 200 and 800 would send the + known out-of-range fault to a full round without firing on more than a quarter of the multi-head PRs, that value + replaces 400 before Part 2 runs, and the change is recorded in the results. +4. Coverage, scored on each labelled fault's cause line: whether that line sits inside the packet design A builds. + +## Part 2: paid scoped-reader replay (no-loss) +**Cases.** 48 packets, each the packet `gstack-ship-receipt carry` writes (`crew/lib/ship-recheck.ts` +`recheckPacket`, the text on this branch) for one later head: +- 32 positives: every in-range fix-made fault from the source sample (fewer than ten), plus faults seeded into fix + ranges of gstack's own public PRs to make 32. A seeded fault is one edit in a later head's own range, of a class + a test would catch or production would feel (an inverted condition, an off-by-one, a dropped error path, a wrong + variable, a missing await, a lost write). A separate subagent seeds them; each label (path, line, cause, and + two to four cause words) is written and committed to the private label file before any reader runs. +- 16 controls: later heads whose round found only notes, from the source sample and from gstack's PRs. +- The out-of-range race is a known miss: listed in the results, not scored. + +**Reader.** The lane model, Claude Opus 5.5, through the Messages API with the packet as the whole prompt and no +tool or repository access, plus one fixed output line: "List each blocking finding on its own line as BLOCKING: +: , then the record." This reads less than a real reader, which can open files, so a loss here +is an upper bound on the real one. A model refusal is a result, never a swap (R95). + +**Kind and trials.** `behavior`: 3 independent trials per packet. A positive passes when at least 2 of 3 trials +list a BLOCKING line within 3 lines of the labelled line in the labelled path, carrying at least one of its cause +words. A control fails when at least 2 of 3 trials list any BLOCKING line. Matching is a script, not a judge. + +**Bars, fixed now.** +1. Recall on the 32 positives at least 0.85, reported with its 95% Wilson interval. The smallest difference this size + can tell apart from the bar is about 0.15. +2. At most 2 of 16 controls fail, with the 95% interval of the control failure rate. +3. Paired, on the real faults: each fault's scoped-reader result beside the later full round that found it (a full + round found every one, by construction), with the paired difference and its 95% interval. No bar: too few faults. + +**Verdict.** Both bars met: KEEP the scoped re-check as the default for later heads. Recall below the bar or more +than 2 controls failing: FIX-METHOD (widen the packet or send those heads to a full round), after one "Why null?" +cycle (did the reader read the range, do the faults fit it, is n enough, does a full round see what it missed). + +**Reruns.** None, except the one AGENTS.md allows: a red case may be rerun once at the same packet as a new panel +of 3; a pass is green with a flaky note and a red is real. Harness and infrastructure failures never rerun. + +**Budget.** 144 dispatches at about $1 each, capped at $160 including any rerun. A cap stop ends the run +incomplete with every finished case reported. + +## After merge (separate brief) +A free 7-day before-and-after on full rounds per PR, re-checks per PR and /ship runs per PR (with each window's daily +spread), and a paid escape audit on merged PRs whose later code only re-checks read, under its own prereg. The +ledger row is `ship-review-panel` in `docs/inventory/evidence.json`; measure by 2026-12-08. diff --git a/docs/evals/pr-round-count-results.md b/docs/evals/pr-round-count-results.md new file mode 100644 index 00000000000..575a194987f --- /dev/null +++ b/docs/evals/pr-round-count-results.md @@ -0,0 +1,50 @@ +# Per-PR review rounds replay: results (GST-2673) + +We learned that a reviewer shown only the diff since the last reviewed head catches planted one-line bugs but missed +every real fault that later full review rounds had caught. You should give a pull request's final head a full review +before it merges, and treat a diff-only re-check as advice: that is what gstack's /ship now does. + +Preregistration: [pr-round-count-prereg.md](pr-round-count-prereg.md), locked 2026-11-13 before any paid call. All +figures below are counts with 95% Wilson intervals. + +## What worked + +- **Counting rounds per pull request works.** The counter reads the receipt history the PR body already keeps. Over + 306 gstack PRs with receipts it changed no plan (none had three or more /ship runs, 295 had one). In the other + crew's sample of 88 PRs, 2 had three or more runs and both had gone past two rounds, which is the case the stop rule + is for. +- **The re-check reader finds planted bugs and stays quiet on clean heads.** On gstack's own PRs it found 22 of 24 + seeded faults (0.92, 0.74 to 0.98) and flagged no blocker on 12 clean heads (0 of 12, 0 to 0.24). + +## What didn't + +- **It missed all 8 real faults.** Another crew's internal product supplied 8 faults that review fixes had created + after round 1 and a later full round had caught. The re-check reader found 0 of 8 (0 to 0.32). Paired against the + full round that found each one (8 of 8 by construction), the difference is -1.00 (-1.00 to -0.68). It wrote no + finding on 34 of 36 reads, so the scorer is not the cause. The other 2 reads, both on one fault, named the right + file and fault 14 lines from the labelled line, outside the preregistered 3-line window; read leniently that is 1 of + 8 (0.02 to 0.47). It flagged none of 3 clean heads from that sample. +- **Bar 1 failed.** Recall over all 32 positives was 22 of 32 (0.69, 0.51 to 0.82), under the 0.85 bar. Bar 2 held: + 0 of 15 controls failed (0 to 0.20). The preregistered verdict is FIX-METHOD. +- **Why null?** The reader did read the range. The real faults sit in it, but each is wrong only against code, data + or deployment order outside the diff (a migration that sorts before the backfill it depends on, a sign-in id + compared against the wrong field), while every seeded fault is visible on its changed line. The 8 faults come from + 3 PRs, so they are not independent draws; even counting each PR as one draw, missing all of them at a true recall of + 0.85 has odds of about 1 in 300. The reader had no repository access, as preregistered, so a reader that can open + files may do better; that is not measured. + +## What changed + +The count and the stop at two full rounds stay. A head whose own added and removed lines are byte-identical to the +reviewed head's keeps its receipt, as before. Any other head gets a fresh full review, the PR's last before merge; a +PR already at two full rounds gets one read-only full review with no fix round. The scoped re-check still writes its +packet, but it never carries a receipt, and that also changes the carry re-check that was already on main +([rounds per pull request](../review-policy.md#rounds-per-pull-request)). The drift threshold Part 1 was to tune is +gone with the re-check route: it never fired on either sample. + +## Departures from the preregistration + +- 15 controls ran, not 16: the other crew's sample had 3 clean later heads, not 4. +- The private leg ran twice. The first run's scorer dropped findings written in bold, and its raw output was deleted + before that was noticed, so it could not be rescored. The prereg forbids rerunning a harness failure; the rerun, + with the repaired scorer, is the one reported above. diff --git a/docs/inventory/evidence.json b/docs/inventory/evidence.json index cc04c39ce69..45c1a315ac6 100644 --- a/docs/inventory/evidence.json +++ b/docs/inventory/evidence.json @@ -590,7 +590,8 @@ "seed": "GEVA-2, 2026-11-02: ship: review panel (specialist, adversarial, targeted, outside voice, red team): untested (unfair test: none arm on the SDK stub; arms from different harnesses and gstack versions; cohort mined from gstack's own catches)", "aliases": [ "ship: review panel (specialist, adversarial, targeted, outside voice, red team)" - ] + ], + "note": "GST-2673 adds the per-PR round count to Step 9 (docs/review-policy.md#rounds-per-pull-request); its replay (docs/evals/pr-round-count-prereg.md) found a diff-only re-check caught 0 of 8 real faults, so re-checks are advice only and the merge head gets a full review. Owner GStack Minder (GSTA-36); measure by 2026-12-08" }, "ship-docs-audit": { "status": "untested", diff --git a/docs/review-policy.md b/docs/review-policy.md index 792067d241a..4d760c5632a 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -110,6 +110,9 @@ incomplete coverage, which blocks until the reviewer is rerun. including a grant for a stop head before `--range-base` (an earlier /ship). A fix-check never earns another, so the grant cannot repeat, and a stop after the granted fix-check still goes to the owner. The cap approves nothing. + This cap counts rounds inside one run. Across heads and runs the PR's own + count applies ([rounds per pull request](#rounds-per-pull-request)), and an + extra round there is the lane's or Captain's grant, never an owner ask. Edits that /ship Step 16 later finds after the review bound are a new stop: a new grant at a stop head after the last fix-check's commit, passed as `gstack-review-plan --post-review --last fix-check --range-base @@ -128,6 +131,65 @@ incomplete coverage, which blocks until the reviewer is rerun. symlink or gitlink file in that range, or a commit the gate scan tags there (a `[skip ci]` message), still stops. + +### Rounds per pull request (R51, GST-2673) + +The two-round cap is per pull request, counted across every head, every `/ship` +run and every reader. Each run used to start its own count, so a PR pushed five +times could be reviewed ten times. The count now lives where every host can read +it: the PR body, which already keeps each run's `review_loop` in the receipt and +the `gstack-receipt-runs` block. + +The PR's last review before merge is a full review of its final head. A scoped +re-check that reads only what changed since the last reviewed head is advice +only: it never carries a receipt and is not one of the two rounds. In the replay +behind this rule ([prereg](evals/pr-round-count-prereg.md)), a diff-only re-check +caught 22 of 24 planted faults but none of 8 real faults that full rounds had +caught on another crew's PRs. + +1. **Count.** `gstack-ship-receipt history --pr ` adds up the rounds the body + records (full passes, scoped passes and fix-checks; a run listed twice counts + once) and prints `PR_REVIEW_HISTORY:`, the flag line `PR_REVIEW_FLAGS: + --prior-rounds --prior-full ` and `PR_REVIEW_ROUTE:`. + `/ship` Step 1 prints all three. A re-check that carried a receipt before + this rule adds no round. +2. **Runs that stop count too.** After each Step 9 pass, `gstack-ship-receipt + stub --pr --run --review-loop ` writes a `status: started` + entry, so a run that stops before its receipt still counts. The run's receipt + write (same `--run`) replaces its stub; `--void` marks a stub that reviewed + nothing. +3. **Route.** A head whose own added and removed lines match the reviewed head's + byte for byte (a base merge, tests, release metadata) keeps its receipt through + carry, as before. Any other new head runs `/ship` Steps 2-16, and + `PR_REVIEW_ROUTE:` names the review it gets: `first` on a PR with no full + round, `final` after one (a fresh full review of this head, the PR's last + before merge), and `read-only` after two. Carry may still print `RECHECK: + advisory … packet=`: one reader may read that packet for advice, but + its verdict never rebinds the receipt, and `carry --recheck` is refused + ([scoped re-check](troubleshooting.md#receipt-carry-recheck)). +4. **Stop rule.** `gstack-review-plan --prior-full ` adds the PR's earlier + full rounds to this run's full passes; fix-checks stay the in-run table's + call, and `--prior-rounds` is printed as `pr_rounds=`. A full pass past two + stops with `PR_ROUND_CAP` and prints the exact `gstack-approvals + round-grant` command; a below-floor fix at the cap finishes with its notes + listed. The stop is the lane's or Captain's call, never an owner ask + ([troubleshooting](troubleshooting.md#pr-round-cap)). +5. **Read-only final review.** A PR that already had two full rounds and whose + own code changed since still gets one full review of its final head. It has + no fix round: below-floor findings ship as notes, and a blocker (open or + fixed) or a gate-class edit stops with `PR_ROUND_CAP` for the lane's Captain + to decide: ship with the note, record a round grant, or park. The count does + not reopen. +6. **Round grant.** `gstack-approvals round-grant --pr --head --kind + extra-round --reason --by ` records one grant for one + head: one round past the cap, with its fix round, instead of the read-only + review. Step 1's `PR_REVIEW_FLAGS:` then adds `--round-grant `, which + raises that run's cap by one round, and the plan refuses a grant for another + head or PR. The plan keeps the grant after the fix round's commits move HEAD + past it. gstack never grants itself a round: `--by gstack` and a grant + from inside an open `/ship` run are refused, and `add` refuses the scope. + The receipt lists grants under `review_round_grants`. + ### Transitions @@ -205,7 +267,7 @@ stop goes to the owner as before. Every other stop still stops. | `scoped-fix-check` | Round 2 stops for a fix whose range since round 2's `PASS_HEAD` is docs class only, or only raises timeout values. `--range-base` must be the commit the newest review-log pass row read. One per branch: the ledger keeps every record, so a later /ship on the branch stops for the owner. | It records the standing grant in the approval record (`by: gstack no-stop default (K1)`) and prints `GRANT:`. `gstack-review-plan --grant` plans the one scoped fix-check. A blocking finding there goes to the owner. | | `test-timeout-fix` | Every changed line is in a test file and only raises a timeout value: the value of a timeout key (`timeout: 5_000`, `setDefaultTimeout(5_000)`, `--timeout=5000`) or bun's and jest's trailing per-test argument, only on the line that opens the test call itself (`test('…', () => {…}, 30_000);`, likewise `it(` and `describe(`). A multi-line test's closing `}, 30_000);` does not qualify and stops for the owner. A line with `expect`, `assert` or a comparison never qualifies. | The gate scan's relaxation finding takes the printed `GATE_DISPOSITION: kept` reason instead of `open`. | | `pregate-flake-rerun` | One rerun of a failed pregate case at the same tree (CREW rule 16). One per branch. | Green counts as flaky. Red again is a real failure. | -| `stamp-only-carry` | A refused carry, where the receipt head merged into the base (base side on conflict) differs from HEAD only in a version stamp: `VERSION`, the `"version"` line of `package.json`, `CHANGELOG.md`, the agents digest or `changelog.d/` fragments. | Take the carry's `RECHECK:` route instead of running Steps 2–16 again. | +| `stamp-only-carry` | A refused carry, where the receipt head merged into the base (base side on conflict) differs from HEAD only in a version stamp: `VERSION`, the `"version"` line of `package.json`, `CHANGELOG.md`, the agents digest or `changelog.d/` fragments. | Go on to Steps 2–16 without waiting for a Captain: the plan reviews HEAD in full, since a re-check no longer carries a receipt ([rounds per pull request](#rounds-per-pull-request)). | | `autoplan-regate` | An edit to the plan file made after the owner's answer, or after the revise that took their changes, while the reviewed plan itself is unchanged. The edit only adds lines, all inside the plan's `## ELI5` section (an added `## ELI5` heading opens one), and no added line holds a number or a word for spend, cost, budget, price, cap, credits, limit, max, arm, model, judge, verdict, threshold, bar, trial, sample, stop rule, paid or eval. A removed or reworded line, or a line added anywhere else, goes to the owner. The carry exports the reviewed plan, so the added explanation is never built. | `gstack-autoplan` carries the owner's words (`reason=no-stop autoplan-regate: …`) and writes `/no-stop.json`. `gstack-no-stop import` adds it to the branch's ledger. | The ledger is one JSON array per branch under the checkout's git directory diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 07dc2ac7333..2291a418ce4 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -2262,20 +2262,19 @@ changes is [`RECEIPT_CARRY_REFUSED`](troubleshooting.md#receipt-carry-refused). A `RECEIPT_CARRY_PRODUCT_CHANGED` on linear history against the reviewed base whose range-diff, plus the diff of the changed product paths, is at most 400 lines and 64 KB, with no binary path and a receipt that -records its review depth, also prints `RECHECK: eligible … packet=`: one reader on that -packet and `carry --recheck ` rebind the receipt instead of a -full second /ship, unless HEAD needs a deeper review depth or another risk -class ([scoped re-check](troubleshooting.md#receipt-carry-recheck), J1). +records its review depth, also prints `RECHECK: advisory … packet=`: one reader may read +that packet for advice, but it never rebinds the receipt, so the head runs /ship and its plan +reviews HEAD in full ([scoped re-check](troubleshooting.md#receipt-carry-recheck), J1; advice +only since GST-2673, [rounds per pull request](review-policy.md#rounds-per-pull-request)). **Changed and context paths together (GST-1561).** When the base also moved context next to reviewed hunks in other paths, the scoped review and J1 compose -into one bounded re-check instead of refusing each other (founderstar#563 hit +into one bounded advisory packet instead of refusing each other (founderstar#563 hit this on every rules-number PR). The one packet holds the range-diff and the changed paths' diff, then the scoped-review sections of the context paths. The 400-line and 64 KB caps count the whole packet, and `range_diff_sha256` binds -all of it. The record also names `range_base`, the commit the reviewed range -starts from (the fork point, or a landed stack parent), and the carry reason -logs the context paths and that `range_base`. A context section with over 200 +all of it. The packet also names `range_base`, the commit the reviewed range +starts from (the fork point, or a landed stack parent). A context section with over 200 of the branch's own +/- lines, or a packet over the caps, prints `RECHECK: not eligible ()` and stays `RECEIPT_CARRY_PRODUCT_CHANGED`. A changed path alone, or context paths alone, keep the routes above, and their output is unchanged. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 50c43ef6a8a..84064e69a8d 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -7127,34 +7127,52 @@ In /ship Step 1, `gstack-ship-preflight` prints the route as `NEXT: carry route (Step 1.4)`. -### Scoped re-check after `RECEIPT_CARRY_PRODUCT_CHANGED` (J1) +### Scoped re-check after `RECEIPT_CARRY_PRODUCT_CHANGED` (J1, advice only) **Meaning.** The product diff changed since the receipt's head, so the receipt -can't carry as it is. When the history is linear, the base is the one the -receipt was reviewed against, and `git range-diff` of the reviewed range -against the current one is at most 400 lines (`RECHECK_RANGE_DIFF_CAP` in -`crew/lib/ship-recheck.ts`), carry also prints `RECHECK: eligible -range_diff_lines=N range_diff_sha256= packet=`: one reader on that -range-diff can clear it instead of a full second /ship. A rebased branch +can't carry. When the history is linear, the base is the one the receipt was +reviewed against, and `git range-diff` of the reviewed range against the +current one is at most 400 lines (`RECHECK_RANGE_DIFF_CAP` in +`crew/lib/ship-recheck.ts`), carry also prints `RECHECK: advisory +range_diff_lines=N range_diff_sha256= packet=`: one reader may read +that range-diff for advice, but it never carries the receipt. A rebased branch (`RECEIPT_CARRY_TREE_MISMATCH`), a retargeted stack, a receipt with no `review_depth`, more than 20 changed product paths, a binary path, a moved base context section with over 200 of the branch's own +/- lines, an empty or unreadable range-diff and a packet over 400 lines or 64 KB print `RECHECK: not eligible ()` instead. When base context also moved next to reviewed hunks in other paths, their -scoped-review sections join the same packet (GST-1561): the caps count the -whole packet, `range_diff_sha256` binds all of it, and the RECHECK line's record -adds `"range_base"`. - -**Fix.** Dispatch one reader on the packet (`.git/gstack/recheck-.md`; -`--dry-run` writes none). When it comes back clean, write -`{"from":"","head":"","range_diff_sha256":"","reader":"","verdict":"clean"}` -(plus `"range_base"` when the line's record names one; a record without it then -refuses) and rerun `gstack-ship-receipt carry ... --recheck `. The carry -reason records the reader and the range-diff size, and with moved context the -context paths and `range_base`. Carry still refuses when -HEAD needs a deeper review depth or a different risk class than the receipt -recorded; that, or a blocking finding, means /ship on the new head. In /ship -Step 1, `gstack-ship-preflight` prints this as `NEXT: carry route (Step 1.4, J1)`. +scoped-review sections join the same packet (GST-1561), the caps count the +whole packet, and the packet names its `range_base`. + +**Fix.** Run /ship on HEAD: its review plan gives the PR's final head a full +review ([rounds per pull request](review-policy.md#rounds-per-pull-request)). +The packet (`.git/gstack/recheck-.md`; `--dry-run` writes none) is +advice for that run, never a substitute: in the replay behind this rule a +diff-only re-check caught none of 8 real faults that full rounds had caught +(GST-2673). `carry --recheck` is refused. In /ship Step 1, +`gstack-ship-preflight` sends this head to Steps 2-16. + + +### `PR_ROUND_CAP` + +**Meaning.** `gstack-review-plan --prior-full ` found that this pull +request already had its two full review rounds (R51), counted across every head and +`/ship` run from the PR body's receipt history, so it planned no new round with a fix +round. A PR at the cap whose own code changed gets one read-only full review of its +final head; this stop then means that review found a blocker or a gate-class edit. +`/ship` Step 1 prints the count as `PR_REVIEW_HISTORY:` and passes it on from +`PR_REVIEW_FLAGS:`. A fix below the blocking floor finishes with its notes +listed instead of stopping. + +**Fix.** The lane's Captain decides. Ship with the open notes listed, or, when a finding above the floor is +open in this PR's own change or the design changed, have the lane or Captain +record one round with the command the `NEXT:` line prints, +`gstack-approvals round-grant --pr --head --kind extra-round --reason + --by `, then rerun `gstack-ship-preflight`: its +`PR_REVIEW_FLAGS:` line adds `--round-grant ` for the plan. +The grant names one head; a new push needs a new grant. This is not an owner +ask, and gstack cannot grant itself one (`--by gstack` is refused) +([review-policy.md](review-policy.md#rounds-per-pull-request)). ### `RECEIPT_PROSE_MISMATCH` diff --git a/lib/factory-scorecard.ts b/lib/factory-scorecard.ts index 80514f52302..689e6087062 100644 --- a/lib/factory-scorecard.ts +++ b/lib/factory-scorecard.ts @@ -36,6 +36,8 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; +import { prReviewHistory } from './pr-review-history'; +import { extractReceipt } from './ship-receipt'; import { GH_CLIENT, createdFilter, downloadRunArtifacts, filesUnder, historyFetcher, listWorkflowRuns, readFlakeLedgerDir, reuseChecker, unavailableReason, type GhClient, @@ -181,7 +183,7 @@ export function readMergedPrs(source: ScorecardSource, o: ScorecardOptions, w: S const author = String(pr.user?.login ?? ''); const association = String(pr.author_association ?? 'NONE'); const comments = readComments(source, o.repo, Number(pr.number), { readyMarker: o.readyMarker, passMarker: o.passMarker, mergedAt }); - const bodyPasses = passCount(String(pr.body ?? ''), o.passMarker); + const bodyPasses = receiptRounds(String(pr.body ?? '')) ?? passCount(String(pr.body ?? ''), o.passMarker); out.push({ number: Number(pr.number), author, association, title: String(pr.title ?? ''), crew: crewLogins ? crewLogins.has(author.toLowerCase()) : CREW_ASSOCIATIONS.has(association), createdAt: String(pr.created_at), mergedAt, readyAt: comments.readyAt, commentCostUsd: comments.costUsd, @@ -193,6 +195,13 @@ export function readMergedPrs(source: ScorecardSource, o: ScorecardOptions, w: S return out.sort((a, b) => a.mergedAt.localeCompare(b.mergedAt)); } +/** R51 rounds summed across a PR body's receipt and its runs block (GST-2673), null when no receipt records a review run. */ +export function receiptRounds(body: string): number | null { + if (!extractReceipt(body).found) return null; + const h = prReviewHistory(body); + return h.runs + h.stubs > 0 ? h.rounds : null; +} + /** The largest pass count the marker captures in a text, null when it never matches. */ export function passCount(text: string, marker: RegExp): number | null { let max: number | null = null; diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 8436de1106f..e9fab098271 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -117,7 +117,7 @@ export interface ShipReceipt { // Related open PRs by other authors (Lane D): `supersedes` / `credit` only on the owner's confirmation. issues?: { fixes: number[]; refs: number[]; flakes: Array<{ issue: number; run: string }>; related?: Array<{ pr: number; repo?: string; author: string; closes: number[]; supersedes?: boolean; credit?: boolean }> }; /** Harness lane E: the review loop's counters (gstack-review-scope summary) and the carry record when the receipt followed a head whose product diff was unchanged (gstack-ship-receipt carry). */ - review_loop?: { passes: number; blocking_found: number; deferred: number; noted?: number; fixed?: number; scope?: string; fix_checks?: number; rounds?: number; dispatches?: Record; est_input_tokens?: number; unrecorded?: number; ledgers_read?: number; unbound?: number }; + review_loop?: { passes: number; blocking_found: number; deferred: number; noted?: number; fixed?: number; scope?: string; fix_checks?: number; rounds?: number; scoped?: number; dispatches?: Record; est_input_tokens?: number; unrecorded?: number; ledgers_read?: number; unbound?: number }; carry?: { from: string; reason: string; product_patch_id: string; changed_paths: string[]; merge_commits: number; range_diff: string; covers: string[]; reruns: string[]; trees?: string[]; ancestry?: 'linear' | 'rewritten' }; /** The reviewed head's tree and its product patch-id against the base (gstack-ship-receipt write; carry rebinds both): what a carry across rewritten history compares. */ head_tree?: string; product_patch_id?: string; @@ -126,6 +126,8 @@ export interface ShipReceipt { review_depth?: { depth: 'platform' | 'light' | 'standard' | 'full'; class: 'docs' | 'tests' | 'code' | 'gate'; runtime_lines: number; rules: string; base: string; registry: string | null; gate_scan: { tagged: number | null; head: string }; reasons: string[]; risk?: string[]; mode?: 'lean' | 'panel' | 'platform'; platform_review?: { id: string; head: string; reviewer: string }; declared?: string[]; detected?: string[] }; /** The owner's acceptance of a stop after a fix-check edit under frozen scope (#3559); the PR body repeats it word for word. */ review_loop_exception?: { accepted_by: string; date: string; via: string; reason: string; fix_check?: { head: string; findings: number; files?: string[] }; second_pass?: { head: string; deferred: string[] } }; + /** Review round grants the lane or its Captain recorded for this PR (gstack-approvals round-grant, lib/review-round-grant.ts; GST-2673): never the owner's, so never in review_loop_exception. */ + review_round_grants?: Array<{ kind: 'extra-round'; head: string; pr: number; by: string; reason: string; at: string; approval: string }>; /** The owner's rulings that a finding ships as a disclosed note (gstack-approvals rule, lib/ruled-notes.ts); the PR body lists each one word for word (GST-1537). */ ruled_notes?: Array<{ finding: string; head: string; by: string; reason: string; at: string; approval: string }>; /** The owner's dispositions of gate findings (gstack-approvals gate, lib/gate-dispositions.ts); the PR body lists each one word for word (GST-2491). */ @@ -269,7 +271,7 @@ export const ARTIFACT_SCHEMAS = { thread: str, tree: { enum: ['same-modulo-stamps', 'changed', 'not-compared'] }, gate_reuse: str, policy: str, queue_mode: str, preregistration: str, history: str, pregate: { ...str, description: 'pass|warn|requires-remote cleared … @ from pregate.json, current for this head' }, requires_remote: strList, approval: { type: 'object', description: 'approval classes: { source, status: checked|unavailable, classes: [{ class, scope, effects, citation: verified|unverified, approved_by, date, via, binding, evidence }], report_only }' }, - review_loop: { type: 'object', required: ['passes', 'blocking_found', 'deferred'], properties: { passes: { type: 'integer', minimum: 0 }, blocking_found: { type: 'integer', minimum: 0 }, deferred: { type: 'integer', minimum: 0 }, noted: { type: 'integer', minimum: 0 }, fixed: { type: 'integer', minimum: 0 }, scope: str, fix_checks: { type: 'integer', minimum: 0 }, rounds: { type: 'integer', minimum: 0 }, dispatches: { type: 'object', description: 'reviewer dispatches by role' }, est_input_tokens: { type: 'integer', minimum: 0 }, unrecorded: { type: 'integer', minimum: 0 }, ledgers_read: { type: 'integer', minimum: 0 }, unbound: { type: 'integer', minimum: 0, description: 'rows, ledger ids or fix trailers gstack-review-scope summary could not bind (GST-1168)' } } }, + review_loop: { type: 'object', required: ['passes', 'blocking_found', 'deferred'], properties: { passes: { type: 'integer', minimum: 0 }, blocking_found: { type: 'integer', minimum: 0 }, deferred: { type: 'integer', minimum: 0 }, noted: { type: 'integer', minimum: 0 }, fixed: { type: 'integer', minimum: 0 }, scope: str, fix_checks: { type: 'integer', minimum: 0 }, rounds: { type: 'integer', minimum: 0 }, scoped: { type: 'integer', minimum: 0, description: 'passes that were scoped repeats (GST-2673): a round, not a full round' }, dispatches: { type: 'object', description: 'reviewer dispatches by role' }, est_input_tokens: { type: 'integer', minimum: 0 }, unrecorded: { type: 'integer', minimum: 0 }, ledgers_read: { type: 'integer', minimum: 0 }, unbound: { type: 'integer', minimum: 0, description: 'rows, ledger ids or fix trailers gstack-review-scope summary could not bind (GST-1168)' } } }, carry: { type: 'object', required: ['from', 'reason', 'product_patch_id'], properties: { from: str, reason: str, product_patch_id: str, changed_paths: strList, merge_commits: { type: 'integer', minimum: 0 }, range_diff: str, covers: strList, reruns: strList, trees: strList, ancestry: { enum: ['linear', 'rewritten'] } } }, head_tree: str, product_patch_id: str, gstack_version: str, base_red: { type: 'object', required: ['cases', 'files', 'base', 'lane', 'expires_at'], properties: { cases: strList, files: strList, base: str, lane: str, expires_at: str } }, @@ -278,6 +280,7 @@ export const ARTIFACT_SCHEMAS = { review_targeted: { type: 'object', required: ['classes', 'rules', 'brief_sha', 'product_patch_id', 'status', 'findings', 'raised_by'], properties: { classes: { type: 'array', items: { enum: ['money', 'gate', 'auth', 'secret'] } }, rules: str, brief_sha: str, product_patch_id: str, status: { enum: ['done', 'failed', 'not-run'] }, findings: { type: 'integer', minimum: 0 }, raised_by: str } }, review_exclude: { type: 'object', required: ['source', 'patterns', 'applied', 'excluded', 'excluded_bytes', 'kept', 'gate_tagged', 'patterns_sha256', 'list_sha256', 'digest'], properties: { source: str, patterns: strList, applied: strList, excluded: { type: 'integer', minimum: 0 }, excluded_bytes: { type: 'integer', minimum: 0 }, kept: { type: 'integer', minimum: 0 }, gate_tagged: strList, patterns_sha256: str, list_sha256: str, digest: str } }, review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } } } }, + review_round_grants: { type: 'array', items: { type: 'object', required: ['kind', 'head', 'pr', 'by', 'reason', 'at', 'approval'], properties: { kind: { enum: ['extra-round'] }, head: str, pr: { type: 'integer', minimum: 1 }, by: str, reason: str, at: str, approval: str } } }, ruled_notes: { type: 'array', items: { type: 'object', required: ['finding', 'head', 'by', 'reason', 'at', 'approval'], properties: { finding: str, head: str, by: str, reason: str, at: str, approval: str } } }, gate_dispositions: { type: 'array', items: { type: 'object', required: ['finding', 'gate_id', 'head', 'by', 'reason', 'words', 'at', 'approval'], properties: { finding: str, gate_id: str, head: str, by: str, reason: str, words: str, at: str, approval: str } } }, mechanical: strList, diff --git a/lib/plan-record.ts b/lib/plan-record.ts index 279dc9865bb..db95a710791 100644 --- a/lib/plan-record.ts +++ b/lib/plan-record.ts @@ -42,7 +42,7 @@ export interface PlanRecord { line: string; state: 'approved' | 'exempt'; ref?: export interface PlanFailure { code: ResultCodeName; message: string; fix: string } export type PlanResolution = { ok: true; record: PlanRecord; summary: string } | { ok: false; failure: PlanFailure }; -const NOT_PLAN_ROW = /\b(ruled_note|gate_disposition|review_loop_grant|review_loop_exception|test_lane_exception)\b/; +const NOT_PLAN_ROW = /\b(ruled_note|gate_disposition|review_loop_grant|review_loop_exception|review_round_grant|test_lane_exception)\b/; const ROW_ID = /^a-[0-9a-f]{12}$/; const RECORD_ID = /^r-[0-9a-f]{12}$/; const LOCAL_SOURCE = 'state-root config'; diff --git a/lib/pr-review-history.ts b/lib/pr-review-history.ts new file mode 100644 index 00000000000..9fc080992a1 --- /dev/null +++ b/lib/pr-review-history.ts @@ -0,0 +1,108 @@ +/** + * pr-review-history — R51 per pull request (GST-2673, docs/review-policy.md#rounds-per-pull-request). gstack caps a + * PR at two review rounds across every head, /ship run and reader, but each /ship run starts its own count, so a PR + * pushed N times could get 2N rounds. The PR body already keeps every run's review loop (the receipt plus the + * gstack-receipt-runs block, lib/ship-receipt.ts), on GitHub, where every host reads it the same way: this module adds + * it up, records runs that stop before their receipt (a started stub), and says what review the next head gets. The + * PR's last review before merge is a full review of its final head: a diff-only re-check caught 0 of 8 real faults + * that full rounds had caught (GST-2673), so a re-check is advice only and never carries a receipt. + */ +import type { ShipReceipt } from './headless-artifacts'; +import { withAgentNotes, splitAgentNotes } from './agent-notes'; +import { extractReceipt, receiptRun, receiptRuns, RECEIPT_RUNS_KEPT, RUNS_FENCE, RUNS_RE, type ReceiptRun } from './ship-receipt'; +import { FULL_PASS_CAP } from './review-depth'; + +export interface PrReviewHistory { + /** /ship runs that reviewed (stubs and carries excluded). */ + runs: number; + /** R51 rounds: full and scoped passes plus fix-checks, every run and started stub. */ + rounds: number; + full: number; + scoped: number; + fix_checks: number; + /** Scoped re-checks that carried the receipt to a new head before GST-2673 made them advice only. */ + rechecks: number; + /** Runs that started and wrote no receipt yet. */ + stubs: number; + heads: number; + first_full: string | null; + last_full: string | null; + source: 'pr-body'; +} + +const roundsOf = (l: ReceiptRun['review_loop']) => (l ? (l.rounds ?? (l.passes ?? 0) + (l.fix_checks ?? 0)) : 0); + +/** Every entry the body records, oldest first: the runs block, then the current receipt. */ +function entries(body: string): ReceiptRun[] { + const current = extractReceipt(body).receipt; + return [...receiptRuns(body), ...(current && typeof current.head === 'string' ? [receiptRun(current)] : [])]; +} + +export function prReviewHistory(body: string): PrReviewHistory { + const all = entries(body); + const reviewed = new Map(); + const ordered: Array = []; + all.forEach((e, i) => { + if (e.status || e.carry_kind || e.carried_from) { ordered.push(e); return; } + const key = e.run ? `run:${e.run}` : `#${i}`; + if (!reviewed.has(key)) ordered.push(key); + reviewed.set(key, e); + }); + const h: PrReviewHistory = { runs: 0, rounds: 0, full: 0, scoped: 0, fix_checks: 0, rechecks: 0, stubs: 0, heads: new Set(all.map(e => e.head)).size, first_full: null, last_full: null, source: 'pr-body' }; + for (const item of ordered) { + const e = typeof item === 'string' ? reviewed.get(item)! : item; + if (e.status === 'voided') continue; + if (e.carry_kind === 'recheck') { h.rechecks++; continue; } + if (e.carry_kind || e.carried_from) continue; + const l = e.review_loop; + const scoped = l?.scoped ?? 0, full = Math.max(0, (l?.passes ?? 0) - scoped); + h.rounds += roundsOf(l); h.scoped += scoped; h.full += full; h.fix_checks += l?.fix_checks ?? 0; + if (e.status === 'started') h.stubs++; else h.runs++; + if (full > 0) { h.first_full ??= e.head; h.last_full = e.head; } + } + return h; +} + +/** + * Put one entry in the runs block: a stub replaces the same run's earlier stub, and any other entry is appended. + * The receipt, when there is one, is unchanged; a body without one gets the block in its Agent notes section. + */ +export function placeRunEntry(body: string, entry: ReceiptRun): string { + const runs = receiptRuns(body).filter(r => !(entry.status && r.status && r.run === entry.run)); + const kept = [...runs, JSON.parse(JSON.stringify(entry)) as ReceiptRun].slice(-RECEIPT_RUNS_KEPT); + const block = '```' + RUNS_FENCE + '\n' + kept.map(r => JSON.stringify(r)).join('\n') + '\n```\n'; + if (RUNS_RE.test(body)) return body.replace(RUNS_RE, () => block); + if (extractReceipt(body).found) { + const end = /```gstack-ship-receipt[ \t]*\r?\n[\s\S]*?\r?\n```[ \t]*(?:\r?\n|$)/.exec(body)!; + const at = end.index + end[0].length; + return body.slice(0, at) + '\n' + block + body.slice(at); + } + const notes = (splitAgentNotes(body).notes ?? '').trim(); + return withAgentNotes(body.replace(/^\s+/, ''), (notes ? notes + '\n\n' : '') + block); +} + +/** A started (or voided) stub for a /ship run that has not written its receipt yet. */ +export const runStub = (o: { head: string; run: string; status: 'started' | 'voided'; loop: NonNullable }): ReceiptRun => + ({ head: o.head, run: o.run, status: o.status, review_loop: o.loop }); + +export type Route = { route: 'first' | 'final' | 'read-only'; reason: string }; + +/** + * What review a head of the PR gets when carry can't keep its receipt (the PR's own lines changed; a head that only + * merges in the base keeps it). Before any full round: the first review, as today. Below the cap: a fresh full review + * of this head, the PR's last before merge. At the cap: one read-only full review of the final head, with no fix round, + * whose blocker goes to the lane's Captain as a decision; an extra-round grant at this head buys a fix round instead. + * A scoped re-check is advice only and never stands in (GST-2673). + */ +export function reviewRoute(h: Pick, o: { grant?: string } = {}): Route { + if (!h.full) return { route: 'first', reason: 'no full review round on this PR yet' }; + if (h.full < FULL_PASS_CAP) return { route: 'final', reason: `the PR had ${h.full} full review round${h.full === 1 ? '' : 's'}; this head gets a fresh full review, the PR's round ${h.full + 1} of ${FULL_PASS_CAP} and its last before merge (R51)` }; + if (o.grant && h.full === FULL_PASS_CAP) return { route: 'final', reason: `the PR had ${h.full} full review rounds; round grant ${o.grant} buys one more at this head, with its fix round` }; + return { route: 'read-only', reason: `the PR had ${h.full} full review rounds; this head gets one read-only full review: no fix round, a blocker goes to the lane's Captain as a decision, and the count does not reopen (R51)` }; +} + +const s12 = (s: string | null) => (s ? s.slice(0, 12) : 'none'); + +export function historyLine(pr: string, h: PrReviewHistory): string { + return `PR_REVIEW_HISTORY: pr=#${pr} rounds=${h.rounds} cap=${FULL_PASS_CAP} full=${h.full} scoped=${h.scoped} fix_checks=${h.fix_checks} rechecks=${h.rechecks} runs=${h.runs} stubs=${h.stubs} heads_reviewed=${h.heads} first_full=${s12(h.first_full)} last_full=${s12(h.last_full)} source=${h.source}`; +} diff --git a/lib/redact-patterns.ts b/lib/redact-patterns.ts index 10536ed74d7..e951c24bf8c 100644 --- a/lib/redact-patterns.ts +++ b/lib/redact-patterns.ts @@ -420,13 +420,14 @@ export function isCiRunIdentifier(span: string, match: RegExpExecArray): boolean /** * The owner's grant of one scoped fix-check is recorded as `review_loop_grant `, and an accepted stop as - * `review_loop_exception ` (docs/review-policy.md). About one 12-character sha in 300 is all digits + * `review_loop_exception ` (docs/review-policy.md), and a lane's review round grant as `review_round_grant ` + * or `review_round_grant at ` (GST-2673). About one 12-character sha in 300 is all digits * (`367120488513`), and pii.phone.e164 read it as a phone number, so gstack-approvals refused the owner's grant * (APPROVAL_RECORD_SECRET; Free Tests 41667825418, 41766865679). Only the position decides: a digits-only span right * after one of those two tokens and a space, `=` or `:`. The same digits anywhere else, or a number with a `+`, * spaces or dashes after the token, still report. */ -const REVIEW_LOOP_SHA_BEFORE = /\breview_loop_(?:grant|exception)(?:[ \t]+|[ \t]*[:=][ \t]*)$/; +const REVIEW_LOOP_SHA_BEFORE = /\breview_(?:loop_(?:grant|exception)|round_grant(?:[ \t]+extra-round[ \t]+at)?)(?:[ \t]+|[ \t]*[:=][ \t]*)$/; function isReviewLoopSha(span: string, match: RegExpExecArray): boolean { if (!/^\d+$/.test(span)) return false; const input = match.input ?? ""; diff --git a/lib/review-depth.ts b/lib/review-depth.ts index 352beca11e6..dd2c2ca2999 100644 --- a/lib/review-depth.ts +++ b/lib/review-depth.ts @@ -388,6 +388,12 @@ export interface History { postReview?: boolean; /** In the loop, the CLI bound `granted` to the last fix-check's own stop head, its commit (--range-base): a new grant, never the previous link's. */ chained?: boolean; + /** R51 rounds earlier /ship runs on this PR already spent, fix-checks and scoped passes included (--prior-rounds; GST-2673): printed as pr_rounds=. */ + priorRounds?: number; + /** The full review rounds among them (--prior-full): the PR cap compares these plus this run's full passes with FULL_PASS_CAP, so a run's own fix rounds stay as the in-run table plans them. */ + priorFull?: number; + /** The lane's or Captain's recorded round grant at this head (--round-grant): one more round for the PR, never the owner's. */ + roundGrant?: string; } export interface NextStep { step: Step; reason: string } @@ -407,7 +413,7 @@ export interface NextStep { step: Step; reason: string } * loop, a grant the CLI bound to the last fix-check's own stop head (`chained`) adds one more the same way (GST-1681). */ export function nextStep(h: History, depth?: Depth): NextStep { - const n = h.lean ? leanStep(h, depth) : loopStep(h, depth); + const n = prCapped(h, h.lean ? leanStep(h, depth) : loopStep(h, depth)); if (n.step !== 'stop') return n; if (h.gate && !h.adversarialRan) return { step: 'voices', reason: `gate class: Step 11's ${h.lean ? 'one reader' : 'voices (adversarial, outside, targeted)'} run${h.lean ? 's' : ''} before the owner's exit, then ask again with --adversarial-ran (${n.reason})` }; const afterFixCheck = h.last === 'fix-check' && h.fullPasses === FULL_PASS_CAP - 1 && h.fixChecks === 1; @@ -417,6 +423,29 @@ export function nextStep(h: History, depth?: Depth): NextStep { return n; } +/** + * R51 per pull request (GST-2673, docs/review-policy.md#rounds-per-pull-request): the rounds earlier /ship runs on this + * PR spent count against FULL_PASS_CAP with this run's, and a recorded round grant at this head adds one. At the cap a + * below-floor fix ships as notes and anything else stops with PR_ROUND_CAP for the lane or its Captain, never the owner. + * A PR already at the cap gets one read-only full review of this head: no fix round, the count does not reopen, and a + * blocker stops with PR_ROUND_CAP as the lane's Captain's decision. + */ +function prCapped(h: History, n: NextStep): NextStep { + const prior = h.priorFull ?? 0; + const cap = FULL_PASS_CAP + (h.roundGrant ? 1 : 0); + if (prior >= cap) { + if (h.last === 'none') return n.step === 'full' || n.step === 'scoped' ? { step: 'full', reason: `read-only final review (R51): this PR already had ${prior} full review rounds on earlier heads, so this head gets one full review with no fix round; a blocker goes to the lane's Captain as a decision and the count does not reopen` } : n; + if (n.step === 'done') return n; + if (!h.fixedBlocking && !h.blockingOpen && !h.touchedGate && n.step !== 'stop') return { step: 'done', reason: `read-only final review done (R51): its below-floor findings ship as notes in the PR body and receipt, with no fix round` }; + return { step: 'stop', reason: `PR_ROUND_CAP: the read-only final review of a PR that already had ${prior} full review rounds found a blocker; the lane's Captain decides (ship with the note, a round grant, or park), not an owner ask` }; + } + if (!prior || (n.step !== 'full' && n.step !== 'scoped')) return n; + const used = prior + h.fullPasses; + if (used < cap) return { ...n, reason: `${n.reason}; this PR already had ${prior} full review round${prior === 1 ? '' : 's'} on earlier heads, so this is its full round ${used + 1} of ${cap}${used + 1 === cap ? ', the last' : ''}` }; + if (h.last !== 'none' && !h.fixedBlocking && !h.blockingOpen && !h.touchedGate) return { step: 'done', reason: `PR round cap ${cap} reached (${prior} on earlier heads): the below-floor fixes ship as notes in the PR body and receipt` }; + return { step: 'stop', reason: `PR_ROUND_CAP: this PR already had ${used} full review round${used === 1 ? '' : 's'} across its heads and /ship runs${h.roundGrant ? ` (round grant ${h.roundGrant} included)` : ''}; another needs a reason the lane or its Captain records with gstack-approvals round-grant, not an owner ask` }; +} + /** * R65's lean table (GSTA-258): pass 1 is the one reviewer; any fix on a risk-class diff, and a fixed blocker or a gate-class * edit on any diff, earns one scoped fix-check (round 2, the cap); below-floor fixes on a light diff ship as notes. After the @@ -713,8 +742,8 @@ function leanPlan(i: PlanInput, c: ClassResult, depth: DepthResult, next: NextSt return plan(next, 'lean'); } -export function reviewPlanLine(p: ReviewPlan, pass: number): string { - return `REVIEW_PLAN: class=${p.class} pass=${pass} next=${p.next.step} dispatches=${p.dispatches.length} numbers=${p.numbers.publishes ? `yes(${p.numbers.claims})` : 'no'} fingerprint=${p.numbers.fingerprint} reason=${JSON.stringify(p.next.reason)}`; +export function reviewPlanLine(p: ReviewPlan, pass: number, priorRounds = 0): string { + return `REVIEW_PLAN: class=${p.class} pass=${pass}${priorRounds ? ` pr_rounds=${priorRounds}` : ''} next=${p.next.step} dispatches=${p.dispatches.length} numbers=${p.numbers.publishes ? `yes(${p.numbers.claims})` : 'no'} fingerprint=${p.numbers.fingerprint} reason=${JSON.stringify(p.next.reason)}`; } export function reviewDepthLine(p: ReviewPlan): string { diff --git a/lib/review-round-grant.ts b/lib/review-round-grant.ts new file mode 100644 index 00000000000..12f36710e78 --- /dev/null +++ b/lib/review-round-grant.ts @@ -0,0 +1,43 @@ +/** + * Review round grants (GST-2673, docs/review-policy.md#rounds-per-pull-request): a reason the lane or its Captain + * records when a PR needs a review round its R51 count would not plan. kind=extra-round: one round, with its fix + * round, past the PR's cap of two. It binds one head of one PR and is spent by the round it buys. It is recorded with gstack-approvals round-grant, + * is never an owner ask and never a plan approval (lib/plan-record.ts NOT_PLAN_ROW). --by is recorded, not enforced. + */ +import { locate, readRecord, type ApprovalRow, type Env } from './approval-record'; +import { GSTACK_ACTOR } from './ruled-notes'; + +export const ROUND_GRANT_KINDS = ['extra-round'] as const; +export type RoundGrantKind = (typeof ROUND_GRANT_KINDS)[number]; +export interface ReviewRoundGrant { kind: RoundGrantKind; head: string; pr: number; by: string; reason: string; at: string; approval: string } + +const SCOPE = /^review_round_grant ([0-9a-f]{40}) pr=([1-9]\d*) kind=(extra-round)$/; +const ASK = /^review_round_grant (extra-round) at ([0-9a-f]{40}) for pr ([1-9]\d*): (\S(?:.*\S)?)$/; +export const REVIEW_ROUND_GRANT_SCOPE = /^\s*review_round_grant\b/; + +export const reviewRoundGrantRow = (head: string, pr: number, kind: RoundGrantKind, reason: string) => + ({ scope: `review_round_grant ${head} pr=${pr} kind=${kind}`, ask: `review_round_grant ${kind} at ${head} for pr ${pr}: ${reason}` }); + +export function reviewRoundGrants(rows: readonly ApprovalRow[]): ReviewRoundGrant[] { + const out: ReviewRoundGrant[] = []; + for (const r of rows) { + const s = SCOPE.exec(r.scope), a = ASK.exec(r.ask); + if (r.outcome !== 'approved' || !s || !a || GSTACK_ACTOR.test(r.by)) continue; + if (a[1] !== s[3] || a[2] !== s[1] || a[3] !== s[2]) continue; + out.push({ kind: s[3] as RoundGrantKind, head: s[1]!, pr: Number(s[2]), by: r.by, reason: a[4]!, at: r.recorded_at, approval: r.id }); + } + return out; +} + +export function readReviewRoundGrants(cwd: string, env: Env = process.env): ReviewRoundGrant[] { + const loc = locate({ cwd, env }); + return 'code' in loc ? [] : reviewRoundGrants(readRecord(loc).rows); +} + +/** The newest grant for this PR at exactly this head. */ +export const grantAt = (grants: readonly ReviewRoundGrant[], pr: number, head: string) => + [...grants].reverse().find(g => g.pr === pr && g.head === head.toLowerCase()); + +/** The text after "Review round grant: " in the PR body. */ +export const reviewRoundGrantText = (g: ReviewRoundGrant) => + `${g.kind} at ${g.head.slice(0, 12)} for PR #${g.pr} recorded by ${g.by} at ${g.at}: ${g.reason} (approval ${g.approval})`; diff --git a/lib/review-scope.ts b/lib/review-scope.ts index 45182e86e41..9fa10e476a8 100644 --- a/lib/review-scope.ts +++ b/lib/review-scope.ts @@ -281,6 +281,8 @@ export interface ReviewLoopSummary { passes: number; blocking_found: number; deferred: number; noted: number; fixed: number; scope: ReviewScopePolicy | 'unknown'; /** One-reviewer re-checks of a fix (docs/review-policy.md#transitions); never passes. */ fix_checks?: number; + /** Passes that were scoped repeats (`"scope":"scoped"` rows): rounds, not full rounds (GST-2673). */ + scoped?: number; /** Review rounds (R51): passes plus fix-checks; the loop caps them at 2. */ rounds?: number; /** Reviewer dispatches of this invocation by role (specialist, red-team, adversarial-native, outside-voice, fix-check, targeted). */ @@ -488,6 +490,8 @@ export function summarizeReviewLoop(rows: readonly Record[], since: const fixChecks = Math.max(rowFixChecks, fixCheckStarts.length); if (fixChecks) out.fix_checks = fixChecks; out.rounds = passes.length + fixChecks; + const scopedPasses = passes.filter(r => r.scope === 'scoped').length; + if (scopedPasses) out.scoped = scopedPasses; const byRole: Record = {}; let bytes = 0; let measured = false; for (const row of rows.filter(r => inRun(r) && DISPATCH_SKILLS.includes(r.skill))) { diff --git a/lib/ship-preflight.ts b/lib/ship-preflight.ts index 5f99780ff6b..d026664779b 100644 --- a/lib/ship-preflight.ts +++ b/lib/ship-preflight.ts @@ -96,14 +96,16 @@ function integrate(cwd: string, base: string, run: string | undefined, r: Report const carry = bin(cwd, 'gstack-ship-receipt', ['carry', '--pr', n, '--base', base, '--dry-run'], 120_000); const line = (carry.stdout.match(/^CARRY: .*$/m) ?? [`CARRY: check failed (${firstLine(carry.stderr)})`])[0]; r.add(`PR: #${n}`).add(line); + // R51 per pull request (GST-2673): the rounds earlier heads spent, which Step 9 passes to every plan, and the review this + // head gets: a product change runs Steps 2-16, whose plan is the merge head's full review; a re-check never carries. + const hist = bin(cwd, 'gstack-ship-receipt', ['history', '--pr', n], 120_000); + const histLines = hist.stdout.split('\n').filter(l => /^PR_REVIEW_(HISTORY|FLAGS|ROUTE): /.test(l)); + histLines.forEach(l => r.add(l)); + if (hist.status !== 0 || !histLines.some(l => l.startsWith('PR_REVIEW_FLAGS: '))) r.add('PR_REVIEW_FLAGS: --prior-rounds 0').add(`PR_REVIEW_ROUTE: first (history unavailable: ${firstLine(hist.stderr) || `gstack-ship-receipt history exit ${hist.status}`}; the plan counts this run's rounds only)`); if (line.startsWith('CARRY: would carry')) { r.next(`carry route (Step 1.4): fix what the base merge broke (CHANGELOG, size caps), commit, gstack-ship-release push --branch ${branch} --early, gstack-ci-carry wait --base ${base} (CI_CARRY: none is not a stop), gstack-pregate --allow-repo-commands, then gstack-ship-receipt carry --pr ${n} --base ${base} --pregate .gstack/tmp/pregate.json`); return false; } - if (line === 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)' && /^RECHECK: eligible /m.test(carry.stderr ?? '')) { - r.next(`carry route (Step 1.4, J1): the product changed since the receipt within the scoped re-check cap: gstack-ship-receipt carry --pr ${n} --base ${base} writes the re-check packet; one reader reads it; gstack-pregate --allow-repo-commands, then carry again with --recheck --pregate .gstack/tmp/pregate.json; a blocking finding runs Steps 2-16`); - return false; - } if (line === 'CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)') { r.next(`carry route (Step 1.4): the base edited context next to reviewed hunks: fix what the base merge broke (CHANGELOG, size caps), commit and push; then gstack-ship-receipt carry --pr ${n} --base ${base} writes the packet for that head; one fix-check reviewer reads it; gstack-pregate --allow-repo-commands, then carry again with --scoped-review --pregate .gstack/tmp/pregate.json; a blocking finding runs Steps 2-16`); return false; diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index 67339df3804..34cdfe13d49 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -24,7 +24,7 @@ const KEY_ORDER: Array = [ 'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history', 'head_tree', 'product_patch_id', 'gstack_version', 'review_depth', 'pregate', 'requires_remote', 'issues', 'approval', 'docs', 'review_loop', - 'review_loop_exception', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'carry', 'base_red', 'flaky_exception', 'no_stop', + 'review_loop_exception', 'review_round_grants', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'carry', 'base_red', 'flaky_exception', 'no_stop', ]; /** Keys in the fixed order so identifiers lead; undefined values are dropped. */ @@ -125,15 +125,22 @@ export function bindReceipt(body: string, pr: string | undefined, accepted: read */ export const RUNS_FENCE = 'gstack-receipt-runs'; export const RECEIPT_RUNS_KEPT = 30; -const RUNS_RE = /```gstack-receipt-runs[ \t]*\r?\n([\s\S]*?)\r?\n```[ \t]*(?:\r?\n|$)/; -export type ReceiptRun = Pick & { depth?: string; carried_from?: string }; +export const RUNS_RE = /```gstack-receipt-runs[ \t]*\r?\n([\s\S]*?)\r?\n```[ \t]*(?:\r?\n|$)/; +/** + * carry_kind (GST-2673): `recheck` when the latest carry hop was a scoped re-check (old receipts only: a re-check no longer + * carries), `carry` for any other hop. status: a /ship run that + * started and wrote no receipt yet (`started`, its counters so far) or ended on an infrastructure failure (`voided`). + */ +export type ReceiptRun = Pick & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided' }; export function receiptRuns(body: string): ReceiptRun[] { const m = RUNS_RE.exec(receiptSource(body)); return m ? m[1]!.split('\n').flatMap(l => { try { const o = JSON.parse(l); return o && typeof o.head === 'string' ? [o as ReceiptRun] : []; } catch { return []; } }) : []; } export function receiptRun(r: ShipReceipt): ReceiptRun { const { head, version, gstack_version, run, review_loop, review_loop_exception } = r; - return JSON.parse(JSON.stringify({ head, version, gstack_version, run, review_loop, review_loop_exception, depth: r.review_depth?.depth, carried_from: r.carry?.from })); + const hop = r.carry ? r.carry.reason.split(' + ').pop()! : undefined; + const carry_kind = hop === undefined ? undefined : hop.includes('scoped re-check by ') ? 'recheck' : 'carry'; + return JSON.parse(JSON.stringify({ head, version, gstack_version, run, review_loop, review_loop_exception, depth: r.review_depth?.depth, carried_from: r.carry?.from, carry_kind })); } /** Every receipt and runs block with the blank lines after it. */ @@ -151,7 +158,7 @@ const STRIP_RE = /```gstack-(?:ship-receipt|receipt-runs)[ \t]*\r?\n[\s\S]*?\r?\ export function placeReceipt(body: string, receipt: ShipReceipt): string { const ex = extractReceipt(body); const prior = ex.receipt; - const runs = receiptRuns(body); + const runs = receiptRuns(body).filter(r => !r.status || !!receipt.carry || receipt.run === undefined || r.run !== receipt.run); if (prior && typeof prior.head === 'string' && JSON.stringify(prior) !== JSON.stringify(receipt)) runs.push(receiptRun(prior)); const kept = runs.slice(-RECEIPT_RUNS_KEPT); const block = renderReceiptBlock(receipt) + (kept.length ? '\n```' + RUNS_FENCE + '\n' + kept.map(r => JSON.stringify(r)).join('\n') + '\n```\n' : ''); @@ -272,8 +279,6 @@ export interface CarryPlanInput { scopedReview?: string; /** Stamp files the branch changed as product whose only change since the reviewed head is a stamp on the branch's own rows, the base untouched, and without which the two product patches match (GST-980). */ stampedRows?: string[]; - /** A clean scoped re-check of the range-diff since the reviewed head (crew/lib/ship-recheck.ts, J1): the carry reason it adds. */ - recheck?: string; } export interface CarryRecord { from: string; reason: string; product_patch_id: string; changed_paths: string[]; merge_commits: number; range_diff: string; covers: string[]; reruns: string[]; trees?: string[]; ancestry?: 'linear' | 'rewritten' } export type CarryPlan = { ok: true; carry: CarryRecord } | { ok: false; code: 'RECEIPT_CARRY_PRODUCT_CHANGED' | 'RECEIPT_CARRY_REFUSED' | 'RECEIPT_CARRY_TREE_MISMATCH'; message: string }; @@ -342,14 +347,13 @@ export function classifyCarryPath(rel: string, extra: { metadata?: readonly stri * branch's own rows in a stamp file the branch also changed as product (`stampedRows`, GST-980). */ export function planCarry(input: CarryPlanInput): CarryPlan { - if (input.productPatchId.from !== input.productPatchId.head && !input.recheck && (input.changedProduct.length || (!input.scopedReview && !input.stampedRows?.length))) { + if (input.productPatchId.from !== input.productPatchId.head && (input.changedProduct.length || (!input.scopedReview && !input.stampedRows?.length))) { const named = input.changedProduct.slice(0, CARRY_NAMED_PATHS); return { ok: false, code: 'RECEIPT_CARRY_PRODUCT_CHANGED', message: `product diff changed between ${input.from.slice(0, 12)} and ${input.head.slice(0, 12)}: ${named.join(', ') || 'patch-id differs'}${input.changedProduct.length > named.length ? ` (+${input.changedProduct.length - named.length} more)` : ''}` }; } const parent = input.retargetedFrom ?? input.stackParent?.slice(0, 12); const reasons: string[] = parent ? [`stack parent ${parent} landed`] : []; if (input.mergeCommits > 0) reasons.push(input.mergeCommits === 1 ? 'base merge' : `${input.mergeCommits} base merges`); - if (input.recheck && input.productPatchId.from !== input.productPatchId.head) reasons.push(input.recheck); if (input.scopedReview && input.productPatchId.from !== input.productPatchId.head) reasons.push(input.scopedReview); if (input.stampedRows?.length && input.productPatchId.from !== input.productPatchId.head) reasons.push(`a stamp on the branch's own rows (${input.stampedRows.join(', ')})`); if (input.testPatchId.from !== input.testPatchId.head) reasons.push('test-only change'); @@ -488,6 +492,7 @@ export function parseReviewLoop(value: unknown): ReviewLoopReceipt | undefined { if (typeof v.scope === 'string') out.scope = v.scope.slice(0, 20); if (n('fix_checks') !== undefined) out.fix_checks = n('fix_checks'); if (n('rounds') !== undefined) out.rounds = n('rounds'); + if (n('scoped')) out.scoped = n('scoped'); if (n('est_input_tokens') !== undefined) out.est_input_tokens = n('est_input_tokens'); if (n('unrecorded')) out.unrecorded = n('unrecorded'); if (n('ledgers_read')) out.ledgers_read = n('ledgers_read'); diff --git a/ship/DRIVER.md b/ship/DRIVER.md index effbebd92fe..e50f772b885 100644 --- a/ship/DRIVER.md +++ b/ship/DRIVER.md @@ -45,7 +45,7 @@ end with `gstack-ship-parts next --run --phase --room <32000 - i **One program per pass.** Each review pass, Step 11 and the Step 14.5 audit is one program, and the parent makes no other call while it runs: (1) `gstack-review-dispatch pass`: `gstack-review-plan --base ` -with the pass's flags, then its staged manifest (Step 14.5: one reader, `docs`); (2) `gstack-review-log --start +with Step 9's plan flags, then its staged manifest (Step 14.5: one reader, `docs`); (2) `gstack-review-log --start ` once per row the step logs; (3) `BEFORE`; (4) `sent` (`BRIEF_MISMATCH` voids it), then one subagent per reader on its rendered file; (5) a poll until every reader settles (status `done` or `failed`, or a final summary; a fresh `idle` diff --git a/ship/DRIVER.md.tmpl b/ship/DRIVER.md.tmpl index f14197dd3c8..72a39e0c7ee 100644 --- a/ship/DRIVER.md.tmpl +++ b/ship/DRIVER.md.tmpl @@ -43,7 +43,7 @@ end with `gstack-ship-parts next --run --phase --room <32000 - i **One program per pass.** Each review pass, Step 11 and the Step 14.5 audit is one program, and the parent makes no other call while it runs: (1) `gstack-review-dispatch pass`: `gstack-review-plan --base ` -with the pass's flags, then its staged manifest (Step 14.5: one reader, `docs`); (2) `gstack-review-log --start +with Step 9's plan flags, then its staged manifest (Step 14.5: one reader, `docs`); (2) `gstack-review-log --start ` once per row the step logs; (3) `BEFORE`; (4) `sent` (`BRIEF_MISMATCH` voids it), then one subagent per reader on its rendered file; (5) a poll until every reader settles (status `done` or `failed`, or a final summary; a fresh `idle` diff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.md index 39d72452fb2..18d7e926c7c 100644 --- a/ship/sections/pr-body.md +++ b/ship/sections/pr-body.md @@ -247,7 +247,7 @@ per-lane counts (`{"":{"pass":N,"fail":N,"skip":N}}`) to rm -f .gstack/tmp/review-loop.json NS=$(~/.claude/skills/gstack/bin/gstack-no-stop list | sed -n 's/^NO_STOP_FILE: //p'); [ -s "$NS" ] || NS= ~/.claude/skills/gstack/bin/gstack-review-scope summary --since "$REVIEW_SINCE" --no-ledger --out .gstack/tmp/review-loop.json && -~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr --base --gate @.gstack/tmp/ship-gate.json --pregate .gstack/tmp/pregate.json --issues @.gstack/tmp/issues.json --review-loop @.gstack/tmp/review-loop.json --docs @.gstack/tmp/docs-audit.json $([ -s .gstack/tmp/targeted.json ] && echo --review-targeted @.gstack/tmp/targeted.json) ${NS:+--no-stop "@$NS"} --body "$PR_BODY_FILE" +~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr --run --base --gate @.gstack/tmp/ship-gate.json --pregate .gstack/tmp/pregate.json --issues @.gstack/tmp/issues.json --review-loop @.gstack/tmp/review-loop.json --docs @.gstack/tmp/docs-audit.json $([ -s .gstack/tmp/targeted.json ] && echo --review-targeted @.gstack/tmp/targeted.json) ${NS:+--no-stop "@$NS"} --body "$PR_BODY_FILE" ``` If write refuses `review_targeted` for a docs claim added after the read, or after a granted fix round (add its `--grant`), rerun Step 9's plan with `--range-base diff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmpl index 4fe6e0d5d70..af7ed820eef 100644 --- a/ship/sections/pr-body.md.tmpl +++ b/ship/sections/pr-body.md.tmpl @@ -230,7 +230,7 @@ per-lane counts (`{"":{"pass":N,"fail":N,"skip":N}}`) to rm -f .gstack/tmp/review-loop.json NS=$(~/.claude/skills/gstack/bin/gstack-no-stop list | sed -n 's/^NO_STOP_FILE: //p'); [ -s "$NS" ] || NS= ~/.claude/skills/gstack/bin/gstack-review-scope summary --since "$REVIEW_SINCE" --no-ledger --out .gstack/tmp/review-loop.json && -~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr --base --gate @.gstack/tmp/ship-gate.json --pregate .gstack/tmp/pregate.json --issues @.gstack/tmp/issues.json --review-loop @.gstack/tmp/review-loop.json --docs @.gstack/tmp/docs-audit.json $([ -s .gstack/tmp/targeted.json ] && echo --review-targeted @.gstack/tmp/targeted.json) ${NS:+--no-stop "@$NS"} --body "$PR_BODY_FILE" +~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr --run --base --gate @.gstack/tmp/ship-gate.json --pregate .gstack/tmp/pregate.json --issues @.gstack/tmp/issues.json --review-loop @.gstack/tmp/review-loop.json --docs @.gstack/tmp/docs-audit.json $([ -s .gstack/tmp/targeted.json ] && echo --review-targeted @.gstack/tmp/targeted.json) ${NS:+--no-stop "@$NS"} --body "$PR_BODY_FILE" ``` If write refuses `review_targeted` for a docs claim added after the read, or after a granted fix round (add its `--grant`), rerun Step 9's plan with `--range-base diff --git a/ship/sections/review-army.md b/ship/sections/review-army.md index 5c06bf26420..add34ef9f38 100644 --- a/ship/sections/review-army.md +++ b/ship/sections/review-army.md @@ -17,7 +17,8 @@ Finish the complete review and QA before applying any fix in Step 9.4. **Review plan.** Pass 1 runs `~/.claude/skills/gstack/bin/gstack-review-plan --base `, plus `--depth-floor ` on every plan run when the /ship prompt -gave `--depth-floor ` (it only raises); add `--declare-risk ` when the diff touches a risk +gave `--depth-floor ` (it only raises), and Step 1's `PR_REVIEW_FLAGS:` on every plan run (the PR's +earlier rounds and a round grant; past two the plan is one read-only full review, and `PR_ROUND_CAP` stops for the lane, never the owner); add `--declare-risk ` when the diff touches a risk class the plan's `REVIEW_DEPTH:` misses (spend it reserves or binds: `money`), and give Step 16's receipt write the same flag; a repeat uses the plan run that picked it. A `scoped` repeat is a full pass on the range: its `fix-check` is decision 3.5's @@ -821,7 +822,9 @@ finding makes that PR a draft. ### Decide whether to repeat Step 9 -After persistence, record missing output, CYCLES and fixes in the invocation record. +After persistence, record missing output, CYCLES and fixes in the invocation record. With a PR open, run +`gstack-review-scope summary --since "$REVIEW_SINCE" --no-ledger --out .gstack/tmp/review-loop.json && gstack-ship-receipt stub --pr --run --review-loop @.gstack/tmp/review-loop.json` +so a run that stops still counts its rounds (Step 19's write, same `--run`, replaces it). Decision 1 always applies first. Then, under `frozen`, run `gstack-review-plan --base --pass $PASS --last full` with each flag that holds (`--fixed-blocking`, `--fixed-below`, `--blocking-open`, `--touched-gate` for a fix to an item 2.5 path, `--critical-found` when this pass diff --git a/ship/sections/review-army.md.tmpl b/ship/sections/review-army.md.tmpl index d7e7f6ec6a0..24800f01a0e 100644 --- a/ship/sections/review-army.md.tmpl +++ b/ship/sections/review-army.md.tmpl @@ -15,7 +15,8 @@ Finish the complete review and QA before applying any fix in Step 9.4. **Review plan.** Pass 1 runs `~/.claude/skills/gstack/bin/gstack-review-plan --base `, plus `--depth-floor ` on every plan run when the /ship prompt -gave `--depth-floor ` (it only raises); add `--declare-risk ` when the diff touches a risk +gave `--depth-floor ` (it only raises), and Step 1's `PR_REVIEW_FLAGS:` on every plan run (the PR's +earlier rounds and a round grant; past two the plan is one read-only full review, and `PR_ROUND_CAP` stops for the lane, never the owner); add `--declare-risk ` when the diff touches a risk class the plan's `REVIEW_DEPTH:` misses (spend it reserves or binds: `money`), and give Step 16's receipt write the same flag; a repeat uses the plan run that picked it. A `scoped` repeat is a full pass on the range: its `fix-check` is decision 3.5's @@ -231,7 +232,9 @@ finding makes that PR a draft. ### Decide whether to repeat Step 9 -After persistence, record missing output, CYCLES and fixes in the invocation record. +After persistence, record missing output, CYCLES and fixes in the invocation record. With a PR open, run +`gstack-review-scope summary --since "$REVIEW_SINCE" --no-ledger --out .gstack/tmp/review-loop.json && gstack-ship-receipt stub --pr --run --review-loop @.gstack/tmp/review-loop.json` +so a run that stops still counts its rounds (Step 19's write, same `--run`, replaces it). Decision 1 always applies first. Then, under `frozen`, run `gstack-review-plan --base --pass $PASS --last full` with each flag that holds (`--fixed-blocking`, `--fixed-below`, `--blocking-open`, `--touched-gate` for a fix to an item 2.5 path, `--critical-found` when this pass diff --git a/test/factory-scorecard.test.ts b/test/factory-scorecard.test.ts index bb26faac364..6cbb33d9f3f 100644 --- a/test/factory-scorecard.test.ts +++ b/test/factory-scorecard.test.ts @@ -11,7 +11,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { - BENCHMARKS, DEFAULTS, classifyGate, collectScorecard, fixtureSource, flakeRecords, fmtHours, gateOutcome, inWindow, passCount, percentile, readComments, renderCsv, + BENCHMARKS, DEFAULTS, classifyGate, collectScorecard, fixtureSource, flakeRecords, fmtHours, gateOutcome, inWindow, passCount, percentile, readComments, receiptRounds, renderCsv, renderMarkdown, scorecardRows, searchRange, verdictCost, type FixtureFile, type ScorecardOptions, } from '../lib/factory-scorecard'; @@ -346,6 +346,14 @@ describe('factory-scorecard: pieces', () => { expect(passCount('no count here', new RegExp(DEFAULTS.passMarker, 'm'))).toBeNull(); }); + // Value: protects=a PR shipped three times at two rounds each reports 6 rounds, not the largest run's 2 (GST-2673); fails_when=the scorecard takes the max again; why_new=R51 counts per PR; seam=none; no_claim=bodies without a receipt, which keep the marker's max + test('receiptRounds sums R51 rounds across the receipt and its runs', () => { + const run = (c: string, id: string) => JSON.stringify({ head: c.repeat(40), run: id, review_loop: { passes: 1, blocking_found: 0, deferred: 0, fix_checks: 1, rounds: 2 } }); + const body = '```gstack-ship-receipt\n' + JSON.stringify({ schema_version: 1, ...JSON.parse(run('c', 'r3')) }) + '\n```\n\n```gstack-receipt-runs\n' + run('a', 'r1') + '\n' + run('b', 'r2') + '\n```\n'; + expect(receiptRounds(body)).toBe(6); + expect(receiptRounds('passes=2')).toBeNull(); + }); + test('verdict cost reads collector-outcomes.json and ignores an unreadable one; flake records skip torn lines and unknown rerun cost', () => { const dir = scratch(); fs.mkdirSync(path.join(dir, 'a', 'paid-report'), { recursive: true }); diff --git a/test/fixtures/review-pins/files/lib/review-depth.ts.json b/test/fixtures/review-pins/files/lib/review-depth.ts.json index 9a556d9b5ba..08524f6d605 100644 --- a/test/fixtures/review-pins/files/lib/review-depth.ts.json +++ b/test/fixtures/review-pins/files/lib/review-depth.ts.json @@ -1 +1 @@ -{"sha":"057c5f84b5227d6ad8c6010447875ac9f031e35a4e6ef1aaaf17726cdd797ae6","replay":"GST-2547"} +{"sha":"554bb5187acbe3eee749d765fd6abf3ee6122a542530bfedc3450504f7a0cd49","replay":"GST-2673"} diff --git a/test/fixtures/review-pins/files/ship/sections/review-army.md.json b/test/fixtures/review-pins/files/ship/sections/review-army.md.json index 99d8f1ea2b1..205237247aa 100644 --- a/test/fixtures/review-pins/files/ship/sections/review-army.md.json +++ b/test/fixtures/review-pins/files/ship/sections/review-army.md.json @@ -1 +1 @@ -{"sha":"346dfea9dcc2e28cd0c9dbfb9f1207798a93a3cecbd913d12e16557a32b0f3fc","replay":"GST-2073"} +{"sha":"41631ea2501711a8a32b3d266540afa52b142a10b37af88980b3186e92340517","replay":"GST-2673"} diff --git a/test/fixtures/review-pins/replays/GST-2673.json b/test/fixtures/review-pins/replays/GST-2673.json new file mode 100644 index 00000000000..ce566c27c93 --- /dev/null +++ b/test/fixtures/review-pins/replays/GST-2673.json @@ -0,0 +1 @@ +{"replay":"GST-2673","justification":"GST-2673 (R51 per pull request). Paid no-loss replay (docs/evals/pr-round-count-prereg.md, results in docs/evals/pr-round-count-results.md): a diff-only scoped re-check found 22 of 24 seeded faults but 0 of 8 real ones, so bar 1 failed (FIX-METHOD) and the re-check no longer stands in for a review; these bytes give the merge head a full review instead. Deterministic no-loss replay, no paid run, old lib/review-depth.ts from origin/main 3c15b7210 against the new one: nextStep over 196,608 History cases with no prior rounds, 196,608 identical. With --prior-full 1 to 3, with and without a round grant (122,880 cases): pass 1 is a full pass in every case, and the 14,528 lighter steps are each a review step past the PR's two full rounds (three with a grant), which R51 caps, ending done with notes or PR_ROUND_CAP for the lane. ship/sections/review-army.md adds Step 1's PR_REVIEW_FLAGS to every plan run and the run stub; no reviewer brief, checklist or finding rule changes."} diff --git a/test/helpers/placeholder-allowlist.ts b/test/helpers/placeholder-allowlist.ts index 5bee10db23a..974049129eb 100644 --- a/test/helpers/placeholder-allowlist.ts +++ b/test/helpers/placeholder-allowlist.ts @@ -66,6 +66,7 @@ export const IDENTIFIER_PLACEHOLDERS: Record = { '': { grammar: NUM, what: 'GitHub Actions run id' }, '': { grammar: NUM, what: 'process id printed by an earlier block' }, '': { grammar: ID, what: 'run id printed by Setup' }, + '': { grammar: ID, what: "the /ship run id Step 1's gstack-ship-preflight --run took" }, '': { grammar: ID, what: 'run id printed by Setup' }, '': { grammar: oneOf('ceo', 'design', 'dx', 'eng'), what: 'autoplan phase' }, '': { grammar: /^[A-Z]$/, what: 'variant letter' }, diff --git a/test/pr-review-history.test.ts b/test/pr-review-history.test.ts new file mode 100644 index 00000000000..102c63ab03c --- /dev/null +++ b/test/pr-review-history.test.ts @@ -0,0 +1,116 @@ +/** + * GST-2673: /ship counts review rounds per pull request, across every head and /ship run, from the receipt and the + * receipt-runs history the PR body already keeps (docs/review-policy.md#rounds-per-pull-request). + */ +import { describe, expect, test } from 'bun:test'; +import { historyLine, placeRunEntry, prReviewHistory, reviewRoute } from '../lib/pr-review-history'; +import { orderReceipt, placeReceipt, receiptRun, receiptRuns } from '../lib/ship-receipt'; +import type { ShipReceipt } from '../lib/headless-artifacts'; + +const sha = (c: string) => c.repeat(40); +const loop = (l: Partial>) => ({ passes: 1, blocking_found: 0, deferred: 0, ...l }); +const receipt = (head: string, l: Partial> = {}, extra: Partial = {}): ShipReceipt => + orderReceipt({ schema_version: 1, head, base: 'main', version: '1.0.0.0', review_loop: loop(l), ...extra }); +const carried = (r: ShipReceipt, head: string, reason: string): ShipReceipt => + orderReceipt({ ...r, head, carry: { from: r.carry?.from ?? r.head, reason, product_patch_id: 'x', changed_paths: [], merge_commits: 0, range_diff: '', covers: [], reruns: [] } }); + +describe('prReviewHistory', () => { + test('a body with no receipt has no history', () => { + expect(prReviewHistory('## Summary\nprose\n')).toMatchObject({ rounds: 0, full: 0, runs: 0, first_full: null, source: 'pr-body' }); + }); + + test('rounds follow R51 (passes plus fix-checks) summed across /ship runs, not the largest run', () => { + let body = placeReceipt('', receipt(sha('a'), { passes: 1, fix_checks: 1, rounds: 2 }, { run: 'r1' })); + body = placeReceipt(body, receipt(sha('b'), { passes: 1, fix_checks: 1, rounds: 2 }, { run: 'r2' })); + const h = prReviewHistory(body); + expect(h).toMatchObject({ runs: 2, rounds: 4, full: 2, fix_checks: 2, first_full: sha('a'), last_full: sha('b') }); + }); + + test('a scoped pass 2 is a round but not a full round', () => { + const h = prReviewHistory(placeReceipt('', receipt(sha('a'), { passes: 2, scoped: 1, rounds: 2 }))); + expect(h).toMatchObject({ rounds: 2, full: 1, scoped: 1 }); + }); + + test('a carried receipt repeats its run\'s loop and adds no round; a re-check carry counts as a re-check', () => { + const r1 = receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' }); + let body = placeReceipt('', r1); + const c1 = carried(r1, sha('b'), 'scoped re-check by anthropic/claude-opus-5-5 (range-diff 40 lines)'); + body = placeReceipt(body, c1); + body = placeReceipt(body, carried(c1, sha('c'), 'test-only change')); + expect(receiptRuns(body).map(r => r.carry_kind ?? 'run')).toEqual(['run', 'recheck']); + expect(prReviewHistory(body)).toMatchObject({ rounds: 1, full: 1, rechecks: 1, runs: 1, heads: 3 }); + }); + + test('the same run written twice counts once', () => { + let body = placeReceipt('', receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' })); + body = placeReceipt(body, receipt(sha('b'), { passes: 1, rounds: 1 }, { run: 'r1' })); + expect(prReviewHistory(body)).toMatchObject({ rounds: 1, runs: 1 }); + }); + + test('a started stub counts its rounds so far until its run writes a receipt, which replaces it', () => { + let body = placeReceipt('', receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' })); + body = placeRunEntry(body, { head: sha('b'), run: 'r2', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); + expect(prReviewHistory(body)).toMatchObject({ rounds: 2, stubs: 1 }); + body = placeRunEntry(body, { head: sha('b'), run: 'r2', status: 'started', review_loop: loop({ passes: 1, fix_checks: 1, rounds: 2 }) }); + expect(receiptRuns(body).filter(r => r.status === 'started').length).toBe(1); + expect(prReviewHistory(body).rounds).toBe(3); + body = placeReceipt(body, receipt(sha('c'), { passes: 1, fix_checks: 1, rounds: 2 }, { run: 'r2' })); + expect(receiptRuns(body).some(r => r.status === 'started')).toBe(false); + expect(prReviewHistory(body)).toMatchObject({ rounds: 3, stubs: 0, runs: 2 }); + }); + + test('a voided stub (an infrastructure failure) counts nothing', () => { + let body = placeReceipt('', receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' })); + body = placeRunEntry(body, { head: sha('b'), run: 'r2', status: 'voided', review_loop: loop({ passes: 1, rounds: 1 }) }); + expect(prReviewHistory(body).rounds).toBe(1); + }); + + test('a receipt written without a run keeps the stubs of other runs', () => { + let body = placeReceipt('', receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' })); + body = placeRunEntry(body, { head: sha('b'), run: 'r2', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); + body = placeReceipt(body, receipt(sha('c'), { passes: 1, rounds: 1 })); + expect(prReviewHistory(body)).toMatchObject({ stubs: 1, full: 3 }); + }); + + test('a stub lands in a body with no receipt yet, inside the Agent notes section', () => { + const body = placeRunEntry('## Summary\nprose\n', { head: sha('a'), run: 'r1', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); + expect(body.startsWith('## Summary\nprose\n')).toBe(true); + expect(prReviewHistory(body)).toMatchObject({ rounds: 1, stubs: 1 }); + }); + + test('receiptRun records the carry kind of the latest hop only', () => { + const r1 = receipt(sha('a')); + expect(receiptRun(carried(r1, sha('b'), 'test-only change + scoped re-check by x (range-diff 3 lines)')).carry_kind).toBe('recheck'); + expect(receiptRun(carried(r1, sha('b'), 'scoped re-check by x (range-diff 3 lines) + base merge')).carry_kind).toBe('carry'); + expect(receiptRun(r1).carry_kind).toBeUndefined(); + }); +}); + +describe('route (F1: the merge head gets a full review; a re-check is advice only)', () => { + test('no prior full round: the first full round, as today', () => { + expect(reviewRoute({ full: 0 })).toMatchObject({ route: 'first' }); + }); + + test('after one full round a new head gets a fresh full review, its last before merge, never the re-check', () => { + expect(reviewRoute({ full: 1 })).toMatchObject({ route: 'final', reason: expect.stringContaining('round 2 of 2') }); + }); + + test('at the cap a new head gets one read-only full review; an extra-round grant buys a round with its fix round', () => { + expect(reviewRoute({ full: 2 })).toMatchObject({ route: 'read-only', reason: expect.stringContaining('no fix round') }); + expect(reviewRoute({ full: 3 }).route).toBe('read-only'); + expect(reviewRoute({ full: 2 }, { grant: 'a-1' })).toMatchObject({ route: 'final', reason: expect.stringContaining('a-1') }); + expect(reviewRoute({ full: 3 }, { grant: 'a-1' }).route).toBe('read-only'); + }); + + test('a re-check carry from an old receipt adds no full round, so it never moves the route', () => { + const r1 = receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' }); + const body = placeReceipt(placeReceipt('', r1), carried(r1, sha('b'), 'scoped re-check by x (range-diff 3 lines)')); + expect(reviewRoute(prReviewHistory(body)).route).toBe('final'); + }); + + test('the history line carries no drift or re-check-blocker fields', () => { + const line = historyLine('7', prReviewHistory(placeReceipt('', receipt(sha('a'), { passes: 1, rounds: 1 })))); + expect(line).toStartWith('PR_REVIEW_HISTORY: pr=#7 rounds=1 cap=2 full=1 '); + expect(line).not.toMatch(/drift|recheck_blocked/); + }); +}); diff --git a/test/pr-round-cli.test.ts b/test/pr-round-cli.test.ts new file mode 100644 index 00000000000..e54622cc1f9 --- /dev/null +++ b/test/pr-round-cli.test.ts @@ -0,0 +1,109 @@ +/** + * GST-2673 CLI seams: gstack-review-plan --prior-rounds / --round-grant, gstack-approvals round-grant, and + * gstack-ship-receipt history / stub over a PR body file. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +const BIN = (n: string) => path.join(import.meta.dir, '..', 'bin', n); +const dirs: string[] = []; +afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); +const tmp = (p: string) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), p)); dirs.push(d); return d; }; + +function repo() { + const dir = tmp('pr-rounds-'), state = tmp('pr-rounds-state-'); + const git = (...a: string[]) => spawnSync('git', a, { cwd: dir, encoding: 'utf8', timeout: 10_000 }); + git('init', '-q', '-b', 'main'); git('config', 'user.email', 't@t'); git('config', 'user.name', 't'); git('config', 'commit.gpgsign', 'false'); + fs.writeFileSync(path.join(dir, 'README.md'), '# x\n'); git('add', '.'); git('commit', '-qm', 'base'); + git('checkout', '-qb', 'feat'); + fs.mkdirSync(path.join(dir, 'src')); fs.writeFileSync(path.join(dir, 'src', 'a.ts'), 'export const a = 1;\n'); git('add', '.'); git('commit', '-qm', 'feat'); + const env = { ...process.env, GSTACK_STATE_ROOT: state, GSTACK_APPROVALS_MIRROR: '0', GSTACK_CAPY: '' }; + const run = (bin: string, args: string[]) => spawnSync(BIN(bin), args, { cwd: dir, encoding: 'utf8', timeout: 60_000, env }); + return { dir, head: git('rev-parse', 'HEAD').stdout.trim(), run }; +} + +describe('gstack-review-plan with the PR round count', () => { + test('two prior full rounds plan one read-only full review of HEAD; a grant at HEAD plans a round with its fix round', () => { + const r = repo(); + const ro = r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '2', '--prior-full', '2', '--pr', '5']); + expect(ro.status).toBe(0); + expect(ro.stdout).toMatch(/REVIEW_PLAN: class=\S+ pass=1 pr_rounds=2 next=full /); + expect(ro.stdout).toContain('read-only final review (R51)'); + expect(ro.stdout).not.toContain('for the owner'); + const granted = r.run('gstack-approvals', ['round-grant', '--pr', '5', '--head', r.head, '--kind', 'extra-round', '--reason', 'the design changed after round 2', '--by', 'captain:test']); + expect(granted.status).toBe(0); + const id = /APPROVAL_RECORDED: (a-[0-9a-f]{12})/.exec(granted.stdout)?.[1]; + expect(id).toBeDefined(); + const full = r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '2', '--prior-full', '2', '--pr', '5', '--round-grant', id!]); + expect(full.stdout).toContain('next=full'); + expect(full.stdout).toContain('round 3 of 3'); + expect(r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '2', '--prior-full', '2', '--pr', '6', '--round-grant', id!]).status).toBe(3); + expect(r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-full', 'x']).status).toBe(2); + }); + + test('a grant still plans after the fix round commits on top of its head, and never for a head off the branch', () => { + const r = repo(); + const id = /APPROVAL_RECORDED: (a-[0-9a-f]{12})/.exec(r.run('gstack-approvals', ['round-grant', '--pr', '5', '--head', r.head, '--kind', 'extra-round', '--reason', 'the design changed after round 2', '--by', 'captain:test']).stdout)?.[1]; + expect(id).toBeDefined(); + const git = (...a: string[]) => spawnSync('git', a, { cwd: r.dir, encoding: 'utf8', timeout: 10_000 }); + fs.writeFileSync(path.join(r.dir, 'src', 'a.ts'), 'export const a = 2;\n'); git('commit', '-qam', 'fix'); + const decide = r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '2', '--prior-full', '2', '--pr', '5', '--round-grant', id!, '--pass', '2', '--last', 'full', '--fixed-below', '--range-base', r.head]); + expect(decide.status).toBe(0); + git('checkout', '-q', 'main'); git('checkout', '-qb', 'other'); fs.writeFileSync(path.join(r.dir, 'b.ts'), 'export const b = 1;\n'); git('add', '.'); git('commit', '-qm', 'other'); + expect(r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '2', '--prior-full', '2', '--pr', '5', '--round-grant', id!]).status).toBe(3); + }); +}); + +describe('gstack-approvals round-grant', () => { + test('gstack cannot grant itself a round, and add refuses the scope', () => { + const r = repo(); + expect(r.run('gstack-approvals', ['round-grant', '--pr', '5', '--head', r.head, '--kind', 'extra-round', '--reason', 'x', '--by', 'gstack']).status).toBe(2); + expect(r.run('gstack-approvals', ['round-grant', '--pr', '5', '--head', r.head, '--kind', 'more', '--reason', 'x', '--by', 'lane']).status).toBe(2); + expect(r.run('gstack-approvals', ['add', '--ask', 'a', '--words', 'w', '--by', 'b', '--scope', `review_round_grant ${r.head} pr=5 kind=extra-round`]).status).toBe(2); + }); +}); + +describe('gstack-ship-receipt history and stub', () => { + test('history prints the rounds, the flags Step 9 passes and the route; a stub counts until the run writes its receipt', () => { + const r = repo(); + const loop = { passes: 1, blocking_found: 0, deferred: 0, rounds: 1 }; + const body = path.join(r.dir, 'body.md'); + fs.writeFileSync(body, '## Summary\nprose\n\n```gstack-ship-receipt\n' + JSON.stringify({ schema_version: 1, head: 'a'.repeat(40), run: 'r1', review_loop: loop }) + '\n```\n'); + const h = r.run('gstack-ship-receipt', ['history', '--body', body, '--pr', '5']); + expect(h.status).toBe(0); + expect(h.stdout).toMatch(/^PR_REVIEW_HISTORY: pr=#5 rounds=1 cap=2 full=1 /m); + expect(h.stdout).toContain('PR_REVIEW_FLAGS: --prior-rounds 1 --prior-full 1\n'); + expect(h.stdout).toMatch(/^PR_REVIEW_ROUTE: final \(the PR had 1 full review round; this head gets a fresh full review/m); + expect(h.stdout).not.toMatch(/drift|recheck_blocked/); + const s = r.run('gstack-ship-receipt', ['stub', '--body', body, '--run', 'r2', '--review-loop', JSON.stringify({ ...loop, fix_checks: 1, rounds: 2 })]); + expect(s.stdout).toContain('RUN_STUB: run=r2 status=started rounds=2'); + const after = r.run('gstack-ship-receipt', ['history', '--body', body, '--pr', '5']).stdout; + expect(after).toContain('PR_REVIEW_FLAGS: --prior-rounds 3 --prior-full 2\n'); + expect(after).toMatch(/^PR_REVIEW_ROUTE: read-only \(.*no fix round/m); + expect(fs.readFileSync(body, 'utf8').startsWith('## Summary\nprose\n')).toBe(true); + expect(r.run('gstack-ship-receipt', ['stub', '--body', body]).status).toBe(2); + }); + + test('an unreadable PR body prints source=unavailable and its fix', () => { + const r = repo(); + const h = r.run('gstack-ship-receipt', ['history', '--body', path.join(r.dir, 'missing.md')]); + expect(h.status).toBe(1); + expect(h.stdout).toContain('source=unavailable'); + expect(h.stderr).toContain('fix:'); + }); +}); + +describe('a scoped re-check is advice only (G1)', () => { + test('carry refuses --recheck: no re-check record carries a receipt', () => { + const r = repo(); + const body = path.join(r.dir, 'body.md'); + fs.writeFileSync(body, '## Summary\n'); + const c = r.run('gstack-ship-receipt', ['carry', '--body', body, '--recheck', path.join(r.dir, 'r.json')]); + expect(c.status).toBe(3); + expect(c.stderr).toContain('--recheck is gone: a scoped re-check is advice only and never carries a receipt'); + expect(fs.readFileSync(body, 'utf8')).toBe('## Summary\n'); + }); +}); diff --git a/test/review-plan-pr-rounds.test.ts b/test/review-plan-pr-rounds.test.ts new file mode 100644 index 00000000000..66355c3d998 --- /dev/null +++ b/test/review-plan-pr-rounds.test.ts @@ -0,0 +1,78 @@ +/** + * GST-2673: the review plan caps full review rounds per pull request (R51) with the full rounds earlier /ship runs on the + * PR already spent (--prior-full from PR_REVIEW_FLAGS), prints every earlier round as pr_rounds= (--prior-rounds), and + * a recorded round grant buys one more full round at its head. + */ +import { describe, expect, test } from 'bun:test'; +import { FULL_PASS_CAP, nextStep, type History } from '../lib/review-depth'; + +const h = (x: Partial): History => ({ fullPasses: 0, last: 'none', ...x }); + +describe('PR round cap', () => { + test('no prior rounds leaves the plan as today', () => { + expect(nextStep(h({})).step).toBe('full'); + expect(nextStep(h({ lean: true })).step).toBe('full'); + expect(nextStep(h({ priorRounds: 0, priorFull: 0, fullPasses: 1, last: 'full', fixedBlocking: true }), 'standard').reason).not.toContain('PR_ROUND_CAP'); + }); + + // Value: protects=the plan's d3a case: a run of a full pass plus a scoped pass 2 leaves the next head one full round; + // fails_when=the cap counts scoped passes or fix-checks as full rounds; seam=nextStep; no_claim=preflight's re-check route + test('one prior full round (two rounds with a scoped pass 2): pass 1 is the PR\'s second and last full round, in both tables', () => { + for (const lean of [false, true]) { + const n = nextStep(h({ priorRounds: 2, priorFull: 1, lean })); + expect(n.step).toBe('full'); + expect(n.reason).toContain('full round 2 of 2, the last'); + } + }); + + test('one prior full round: after pass 1, a below-floor fix keeps its in-run fix-check and a fixed blocker stops for the lane, not the owner', () => { + expect(nextStep(h({ priorFull: 1, fullPasses: 1, last: 'full', fixedBelow: true }), 'standard').step).toBe('fix-check'); + const stop = nextStep(h({ priorFull: 1, fullPasses: 1, last: 'full', fixedBlocking: true }), 'standard'); + expect(stop.step).toBe('stop'); + expect(stop.reason).toStartWith('PR_ROUND_CAP'); + expect(stop.reason).not.toContain('for the owner'); + }); + + test('a fix-check stays the in-run table\'s call: lean\'s one fix-check after a fixed blocker still runs', () => { + expect(nextStep(h({ priorFull: 1, fullPasses: 1, last: 'full', fixedBlocking: true, lean: true }), 'standard').step).toBe('fix-check'); + }); + + // Value: protects=F1's past-cap case: a PR with two full rounds whose own code changed gets one read-only full review of + // the merge head; fails_when=a third /ship run gets a fix round without a grant, or the merge head goes unreviewed; + // seam=nextStep; no_claim=the CLI's pr_rounds= print (pr-round-cli) + test('two prior full rounds: pass 1 is one read-only full review with no fix round, in both tables', () => { + for (const lean of [false, true]) { + const n = nextStep(h({ priorRounds: 4, priorFull: FULL_PASS_CAP, lean })); + expect(n.step).toBe('full'); + expect(n.reason).toStartWith('read-only final review (R51): this PR already had 2 full review rounds'); + } + }); + + test('after the read-only review: below-floor findings ship as notes, a blocker stops for the lane\'s Captain', () => { + for (const lean of [false, true]) { + expect(nextStep(h({ priorFull: 2, fullPasses: 1, last: 'full', lean })).step).toBe('done'); + expect(nextStep(h({ priorFull: 2, fullPasses: 1, last: 'full', fixedBelow: true, lean }), 'standard')).toMatchObject({ step: 'done', reason: expect.stringContaining('no fix round') }); + for (const x of [{ blockingOpen: true }, { fixedBlocking: true }, { touchedGate: true, fixedBelow: true }]) { + const stop = nextStep(h({ priorFull: 3, fullPasses: 1, last: 'full', lean, ...x }), 'standard'); + expect(stop.step).toBe('stop'); + expect(stop.reason).toStartWith('PR_ROUND_CAP: the read-only final review'); + expect(stop.reason).toContain("lane's Captain"); + } + } + }); + + test('a round grant buys one more full round at its head, never two', () => { + expect(nextStep(h({ priorFull: 2, roundGrant: 'a-1' })).step).toBe('full'); + expect(nextStep(h({ priorFull: 3, roundGrant: 'a-1' }))).toMatchObject({ step: 'full', reason: expect.stringContaining('read-only final review') }); + expect(nextStep(h({ priorFull: 2, roundGrant: 'a-1', fullPasses: 1, last: 'full', fixedBlocking: true }), 'standard').reason).toStartWith('PR_ROUND_CAP'); + }); + + test('gate class still runs Step 11\'s voices before the PR cap stop', () => { + expect(nextStep(h({ priorFull: 2, fullPasses: 1, last: 'full', blockingOpen: true, gate: true, adversarialRan: false }), 'standard').step).toBe('voices'); + }); + + test('a blocking finding still open keeps today\'s stop', () => { + const n = nextStep(h({ priorFull: 1, fullPasses: 1, last: 'full', blockingOpen: true }), 'standard'); + expect(n.step).toBe('stop'); + }); +}); diff --git a/test/review-round-grant.test.ts b/test/review-round-grant.test.ts new file mode 100644 index 00000000000..913318f70fd --- /dev/null +++ b/test/review-round-grant.test.ts @@ -0,0 +1,32 @@ +/** + * GST-2673: a review round grant is a reason the lane or its Captain records in the approvals path; it is never an + * owner ask, never a plan approval, and it binds one head of one PR. + */ +import { describe, expect, test } from 'bun:test'; +import { grantAt, reviewRoundGrantRow, reviewRoundGrants, reviewRoundGrantText, REVIEW_ROUND_GRANT_SCOPE } from '../lib/review-round-grant'; +import type { ApprovalRow } from '../lib/approval-record'; + +const head = '1'.repeat(40); +const row = (o: Partial): ApprovalRow => ({ id: 'a-000000000001', date: '2026-11-14', recorded_at: '2026-11-14T00:00:00Z', words: 'w', by: 'captain:GStack Minder', pending: 'none', outcome: 'approved', source: 'manual', branch: 'b', ...reviewRoundGrantRow(head, 12, 'extra-round', 'the design changed after round 2'), ...o } as ApprovalRow); + +describe('review round grants', () => { + test('the row round-trips with kind, head, PR and reason', () => { + const [g] = reviewRoundGrants([row({})]); + expect(g).toMatchObject({ kind: 'extra-round', head, pr: 12, reason: 'the design changed after round 2', approval: 'a-000000000001' }); + expect(REVIEW_ROUND_GRANT_SCOPE.test(row({}).scope)).toBe(true); + expect(reviewRoundGrantText(g!)).toContain('extra-round at 111111111111 for PR #12'); + }); + + test('only an approved row that gstack did not write counts, and it binds only its head and PR', () => { + expect(reviewRoundGrants([row({ outcome: 'pending' as any })])).toEqual([]); + expect(reviewRoundGrants([row({ by: 'gstack' })])).toEqual([]); + const gs = reviewRoundGrants([row({})]); + expect(grantAt(gs, 12, head)).toBeDefined(); + expect(grantAt(gs, 13, head)).toBeUndefined(); + expect(grantAt(gs, 12, '2'.repeat(40))).toBeUndefined(); + }); + + test('a mismatched ask and scope is no grant', () => { + expect(reviewRoundGrants([row({ ask: 'review_round_grant extra-round at ' + '2'.repeat(40) + ' for pr 12: x' })])).toEqual([]); + }); +}); diff --git a/test/ship-preflight.test.ts b/test/ship-preflight.test.ts index 8957772e853..6c7741dca5d 100644 --- a/test/ship-preflight.test.ts +++ b/test/ship-preflight.test.ts @@ -253,6 +253,21 @@ describe('gstack-ship-preflight', () => { expect(r.stdout).toContain('NEXT: Step 4'); }); + // Value: protects=preflight prints the PR's review rounds from its body and the flags Step 9 passes to every plan (GST-2673); fails_when=a second /ship run on a PR starts its round count at zero; + // why_new=R51 counted per run, so a PR pushed N times got 2N rounds; seam=gh, gstack-ship-receipt history; no_claim=carry's own refusal of --recheck (pr-round-cli, ship-recheck) + test('an open PR prints PR_REVIEW_HISTORY and the --prior-rounds flags from its body', () => { + const f = fx(); + const run = (head: string, id: string) => ({ head, run: id, review_loop: { passes: 1, blocking_found: 0, deferred: 0, fix_checks: 1, rounds: 2 } }); + const body = '## Summary\n\n```gstack-ship-receipt\n' + JSON.stringify({ schema_version: 1, ...run('b'.repeat(40), 'r2') }) + '\n```\n\n```gstack-receipt-runs\n' + JSON.stringify(run('a'.repeat(40), 'r1')) + '\n```\n'; + fs.writeFileSync(path.join(f.root, 'body.json'), JSON.stringify({ body })); + f.gh(`case "$*" in *"pr view"*) cat '${path.join(f.root, 'body.json')}';; *) echo 7;; esac`); + const r = f.run(PREFLIGHT, ['--base', 'main']); + expect(lineOf(r.stdout, 'PR_REVIEW_HISTORY')).toMatch(/^PR_REVIEW_HISTORY: pr=#7 rounds=4 cap=2 full=2 /); + expect(lineOf(r.stdout, 'PR_REVIEW_FLAGS')).toBe('PR_REVIEW_FLAGS: --prior-rounds 4 --prior-full 2'); + expect(lineOf(r.stdout, 'PR_REVIEW_ROUTE')).toMatch(/^PR_REVIEW_ROUTE: read-only \(the PR had 2 full review rounds; this head gets one read-only full review/); + expect(r.stdout).not.toMatch(/--recheck|drift_lines|recheck_blocked/); + }); + // Value: protects=the branch name reaches gh as one argv item, never through a shell; fails_when=a branch named with $(...) runs a command on the shipper's machine; // why_new=GSTA-167 /ship review of #3633 (security, CRITICAL); seam=gh; no_claim=gh's own handling of the name test('a branch name with shell syntax is never executed', () => { diff --git a/test/ship-receipt-carry-mixed.test.ts b/test/ship-receipt-carry-mixed.test.ts index c0cfa8485be..07409bec384 100644 --- a/test/ship-receipt-carry-mixed.test.ts +++ b/test/ship-receipt-carry-mixed.test.ts @@ -66,7 +66,7 @@ function founderstar(resolvedSave = 84, baseBlock = 0) { } const scopedPacket = (err: string) => /one fix-check reviewer reads (\S+), then rerun carry/.exec(err)?.[1]; -const eligible = (err: string) => /^RECHECK: eligible range_diff_lines=(\d+) range_diff_sha256=([0-9a-f]{64}) packet=(\S+);/m.exec(err); +const eligible = (err: string) => /^RECHECK: advisory range_diff_lines=(\d+) range_diff_sha256=([0-9a-f]{64}) packet=(\S+);/m.exec(err); const recordAt = (f: ShipFx, name: string, v: object) => { const file = path.join(f.root, name); fs.writeFileSync(file, JSON.stringify(v)); return file; }; describe('a base-side removed line next to byte-identical added lines (GST-1561 ask 2)', () => { @@ -136,26 +136,19 @@ describe('carry: a changed path plus context paths compose into one bounded re-c return { ...x, head: x.f.git('rev-parse', 'HEAD').stdout.trim() }; }; - test('one packet holds the range-diff and the context hunks, bound to range_base; a clean record carries', () => { + test('one advisory packet holds the range-diff and the context hunks, bound to range_base; no record carries (GST-2673)', () => { const { f, from, head, reviewedBase, carry, body } = composed(); const ask = carry(); expect([ask.status, ask.stdout.trim().split('\n')[0]], ask.stderr).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)']); const m = eligible(ask.stderr); expect(m, ask.stderr).not.toBeNull(); - const rangeBase = /"range_base":"([0-9a-f]{40,64})"/.exec(ask.stderr)?.[1]; - expect(rangeBase).toBe(reviewedBase); const text = fs.readFileSync(m![3]!, 'utf8'); for (const s of ['var score0 := 2', 'was_vesting_clear', 'moved by the base', 'const SAVE_VERSION := 83', `range_base ${reviewedBase}`]) expect(text).toContain(s); - const record = { from, head, range_base: rangeBase, range_diff_sha256: m![2], reader: READER, verdict: 'clean' }; - const noBase = carry(['--recheck', recordAt(f, 'nobase.json', { ...record, range_base: undefined })]); - expect([noBase.status, noBase.stdout.includes('RECEIPT_CARRY_REFUSED'), noBase.stderr.includes('range_base')]).toEqual([EXIT.refused, true, true]); - const ok = carry(['--recheck', recordAt(f, 'recheck.json', record)]); - expect([ok.status, ok.stderr.slice(0, 600)]).toEqual([EXIT.ok, expect.any(String)]); - expect(ok.stdout).toContain(`scoped re-check by ${READER}`); - const reason = extractReceipt(fs.readFileSync(body, 'utf8')).receipt!.carry!.reason; - expect(reason).toContain(`scoped re-check by ${READER}`); - expect(reason).toContain(VESTING); - expect(reason).toContain(`range_base ${reviewedBase.slice(0, 12)}`); + const before = fs.readFileSync(body, 'utf8'); + const record = { from, head, range_base: reviewedBase, range_diff_sha256: m![2], reader: READER, verdict: 'clean' }; + const r = carry(['--recheck', recordAt(f, 'recheck.json', record)]); + expect([r.status, r.stderr.includes('--recheck is gone')]).toEqual([EXIT.refused, true]); + expect(fs.readFileSync(body, 'utf8')).toBe(before); }); test('past the size cap it refuses as before: RECEIPT_CARRY_PRODUCT_CHANGED, re-check not eligible', () => { diff --git a/test/size-ledger/ship/count-review-rounds-per-pr.json b/test/size-ledger/ship/count-review-rounds-per-pr.json new file mode 100644 index 00000000000..312721105f3 --- /dev/null +++ b/test/size-ledger/ship/count-review-rounds-per-pr.json @@ -0,0 +1,4 @@ +{ + "bytes": 529, + "why": "GST-2673 F1+G1: a PR past two full rounds gets one read-only full review (review-army plan sentence)" +} From 76fad3edd9e8a1e68c84ba1fa34ccb3078baf8e6 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 17 Nov 2026 17:00:55 +0800 Subject: [PATCH 15/62] Make gstack agents lead every report with what failed, what's unverified and what else changed (GST-1455) (#4273) * Make gstack agents lead every report with what failed, what's unverified and what else changed (GST-1455) The shared closer asks a status report to stay under 250 words and open with Failed or skipped:, Unverified: and Also changed: lines, each naming every item or none; lists past 10 give the top 10 and a count. Capy's factory.md point 10, the lane report Outcome and READY's lane lines carry the same lines, and point 10 points findings write-ups at ETHOS.md section 8. The wording is GEVA-2's round-3 candidate f83eba4, ported without the retired /investigate rows. factory.md is 4,396 B, so its budget rises from 4,200 to 4,400. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Update the ship skill golden files for the new shared preamble id (GST-1455) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- autoplan/SKILL.md | 2 +- autoplan/sections/preamble.md | 7 +++---- canary/SKILL.md | 2 +- canary/sections/preamble.md | 7 +++---- captain/SKILL.md | 2 +- captain/sections/preamble.md | 7 +++---- captain/templates/READY.md | 2 ++ captain/templates/report.md | 2 +- capy/skill/gstack/factory.md | 2 +- changelog.d/gstack-reports-lead-with-failures.md | 1 + codex/SKILL.md | 2 +- codex/sections/preamble.md | 7 +++---- context-restore/SKILL.md | 2 +- context-restore/sections/preamble.md | 7 +++---- context-save/SKILL.md | 2 +- context-save/sections/preamble.md | 7 +++---- design-consultation/SKILL.md | 2 +- design-consultation/sections/preamble.md | 7 +++---- design-html/SKILL.md | 2 +- design-html/sections/preamble.md | 7 +++---- design-motion/SKILL.md | 2 +- design-motion/sections/preamble.md | 7 +++---- design-review/SKILL.md | 2 +- design-review/sections/preamble.md | 7 +++---- design-shotgun/SKILL.md | 2 +- design-shotgun/sections/preamble.md | 7 +++---- devex-review/SKILL.md | 2 +- devex-review/sections/preamble.md | 7 +++---- document-generate/SKILL.md | 2 +- document-generate/sections/preamble.md | 7 +++---- document-release/SKILL.md | 2 +- document-release/sections/preamble.md | 7 +++---- eval-plan/SKILL.md | 2 +- eval-plan/sections/preamble.md | 7 +++---- health/SKILL.md | 2 +- health/sections/preamble.md | 7 +++---- ios-clean/SKILL.md | 2 +- ios-clean/sections/preamble.md | 7 +++---- ios-design-review/SKILL.md | 2 +- ios-design-review/sections/preamble.md | 7 +++---- ios-fix/SKILL.md | 2 +- ios-fix/sections/preamble.md | 7 +++---- ios-qa/SKILL.md | 2 +- ios-qa/sections/preamble.md | 7 +++---- ios-sync/SKILL.md | 2 +- ios-sync/sections/preamble.md | 7 +++---- land-and-deploy/SKILL.md | 2 +- land-and-deploy/sections/preamble.md | 7 +++---- landing-report/SKILL.md | 2 +- landing-report/sections/preamble.md | 7 +++---- learn/SKILL.md | 2 +- learn/sections/preamble.md | 7 +++---- modernize/SKILL.md | 2 +- modernize/sections/preamble.md | 7 +++---- office-hours/SKILL.md | 2 +- office-hours/sections/preamble.md | 7 +++---- pair-agent/SKILL.md | 2 +- pair-agent/sections/preamble.md | 7 +++---- plan-ceo-review/SKILL.md | 2 +- plan-ceo-review/sections/preamble.md | 7 +++---- plan-design-review/SKILL.md | 2 +- plan-design-review/sections/preamble.md | 7 +++---- plan-devex-review/SKILL.md | 2 +- plan-devex-review/sections/preamble.md | 7 +++---- plan-eng-review/SKILL.md | 2 +- plan-eng-review/sections/preamble.md | 7 +++---- plan-tune/SKILL.md | 2 +- plan-tune/sections/preamble.md | 7 +++---- qa-only/SKILL.md | 2 +- qa-only/sections/preamble.md | 7 +++---- qa/SKILL.md | 2 +- qa/sections/preamble.md | 7 +++---- retro/SKILL.md | 2 +- retro/sections/preamble.md | 7 +++---- review/SKILL.md | 2 +- review/sections/preamble.md | 7 +++---- scripts/resolvers/preamble/generate-voice-directive.ts | 5 ++--- setup-deploy/SKILL.md | 2 +- setup-deploy/sections/preamble.md | 7 +++---- setup-gbrain/SKILL.md | 2 +- setup-gbrain/sections/preamble.md | 7 +++---- ship/SKILL.md | 2 +- ship/sections/preamble.md | 7 +++---- skillify/SKILL.md | 2 +- skillify/sections/preamble.md | 7 +++---- spec/SKILL.md | 2 +- spec/sections/preamble.md | 7 +++---- sync-gbrain/SKILL.md | 2 +- sync-gbrain/sections/preamble.md | 7 +++---- test-audit/SKILL.md | 2 +- test-audit/sections/preamble.md | 7 +++---- test/capy-skill-wrapper.test.ts | 6 ++++-- test/fixtures/golden/agy-ship-SKILL.md | 2 +- test/fixtures/golden/claude-ship-SKILL.md | 2 +- test/fixtures/golden/codex-ship-SKILL.md | 2 +- test/fixtures/golden/factory-ship-SKILL.md | 2 +- .../ship/gstack-reports-lead-with-failures.json | 4 ++++ ubicloud/SKILL.md | 2 +- ubicloud/sections/preamble.md | 7 +++---- write-skill/SKILL.md | 2 +- write-skill/sections/preamble.md | 7 +++---- 101 files changed, 199 insertions(+), 236 deletions(-) create mode 100644 changelog.d/gstack-reports-lead-with-failures.md create mode 100644 test/size-ledger/ship/gstack-reports-lead-with-failures.json diff --git a/autoplan/SKILL.md b/autoplan/SKILL.md index cb0cef8e099..1eda17e558c 100644 --- a/autoplan/SKILL.md +++ b/autoplan/SKILL.md @@ -34,7 +34,7 @@ hooks: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/autoplan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/autoplan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/autoplan/sections/preamble.md b/autoplan/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/autoplan/sections/preamble.md +++ b/autoplan/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/canary/SKILL.md b/canary/SKILL.md index 643b31b0b9c..68d2b514fa2 100644 --- a/canary/SKILL.md +++ b/canary/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/canary/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/canary/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/canary/sections/preamble.md b/canary/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/canary/sections/preamble.md +++ b/canary/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/captain/SKILL.md b/captain/SKILL.md index 6ab00a2b465..14d68cedb45 100644 --- a/captain/SKILL.md +++ b/captain/SKILL.md @@ -26,7 +26,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/captain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/captain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/captain/sections/preamble.md b/captain/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/captain/sections/preamble.md +++ b/captain/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/captain/templates/READY.md b/captain/templates/READY.md index d31cda187e6..acbd4b84a3c 100644 --- a/captain/templates/READY.md +++ b/captain/templates/READY.md @@ -37,6 +37,8 @@ The lane's own lines, after the block: ```text pin: # the full head SHA, restated +Failed or skipped: +Also changed: screen choice: <--no-screen: cases ran focused and passed | --screen: > flaky: > review passes: (deferred: ) diff --git a/captain/templates/report.md b/captain/templates/report.md index bac7b35c868..39292b894ca 100644 --- a/captain/templates/report.md +++ b/captain/templates/report.md @@ -4,7 +4,7 @@ Written by the lane when it finishes. The controller reads this before chat. ## Outcome - + Unverified: diff --git a/capy/skill/gstack/factory.md b/capy/skill/gstack/factory.md index fa10da5d101..c6134b3a008 100644 --- a/capy/skill/gstack/factory.md +++ b/capy/skill/gstack/factory.md @@ -11,7 +11,7 @@ Your crew's CREW.md and recorded approvals decide who may merge, update a base, 7. **Measure before you act.** Run the real system on the merged tree you ship; a real run outranks a reviewed plan. Each number names its run, commit or uncapped query; say what you did not verify. 8. **Evals decide, and losses get reported.** Preregister bars, cap and stop rule before paying [/eval-plan]. Cheap proof (a keyless fake, a smoke) first. Controls: no-skill and placebo arms, clean decoys. Report use and pass apart; quote spend from the meter. A new part needs proof it helps or a dated test plan [ETHOS.md: 9. Earn Its Place]. 9. **Flakes: one rerun, a ledger, a daily fix.** Only the policy's rerun, never for a harness or infra red; a second red is real; never loosen a test. [crew/docs/captain.md: The daily flaky pass] -10. **Quiet.** Messages wake the Captain cold: send READY, a blocker, done or a Captain or owner call, else end_turn; no acks or progress notes. Broadcasts go in its notes. +10. **Quiet.** Messages wake the Captain cold: send READY, a blocker, done or a Captain or owner call, else end_turn; no acks or progress notes. Reports and replies open with `Failed or skipped:`, `Unverified:` and `Also changed:` lines (each item, or none), under 250 words; top 10 of long lists. Findings write-ups follow [ETHOS.md: 8. Explain the Number]. Broadcasts go in its notes. 11. **Ask once, plainly.** One ask per decision, explained like the owner is five: your Captain's name, then a lettered line each: "A: hit problem p, which happens when h. We could do 1) x, 2) y or 3) z. Recommendation x because why. A1 to take recommendation." "do it" takes every recommendation; "A2" takes option 2. Owner tasks: the exact link (in Capy: path and field), numbered steps, the reply word. Never re-ask a standing rule; check what you can yourself. [crew/docs/captain.md: The ask format] 12. **Fresh threads, closed out.** One thread per unit of work. A thread keeps its PR until it merges or closes and hands off only then, never mid-PR on a token count; past 1B own tokens it checks in with its Captain once and carries on. Standing threads that wake on every event (merge lanes, watchers) rotate at 500M tokens or 3 days [/runaway-stopper]. Crew threads never create threads: ask your Captain (Captain to Captain across projects), or report one you made by code for crew.add. Its Captain archives only its crew's threads, never one holding an open PR, successor or not (R91), or an open issue; a PR closes only as landed, superseded or dropped. Threads outside every crew are the owner's, even its automation's. Size reviews to the diff. [docs/ship-budget.md; crew/docs/captain.md: New threads join the crew] 13. **The owner's model preference.** `gstack-models resolve --role agent` picks agent models, except cross-family voices and eval subjects. [docs/model-policy.md: Your model preference] diff --git a/changelog.d/gstack-reports-lead-with-failures.md b/changelog.d/gstack-reports-lead-with-failures.md new file mode 100644 index 00000000000..dd0dda6ec2f --- /dev/null +++ b/changelog.d/gstack-reports-lead-with-failures.md @@ -0,0 +1 @@ +- **gstack agents now open every status report with what failed, what they didn't verify and what else they changed.** The shared closing rule used to ask for "a few short lines". Now a report stays under 250 words and opens with three lines, `Failed or skipped:`, `Unverified:` and `Also changed:`, each naming every item or saying none. Lists longer than 10 get the top 10 and a count of the rest. Capy crews follow the same shape (factory.md point 10, the lane report and READY templates). On a 40-task dev split with Claude Opus 5.5, this wording raised the share of key facts disclosed in a report's first 250 words from 0.442 to 0.520 against the old closer, and in Capy lane reports from 0.552 to 0.604. Those are dev numbers, and the sealed held-out read is still to come (GST-1455). diff --git a/codex/SKILL.md b/codex/SKILL.md index 45613467904..b19d6ef5aef 100644 --- a/codex/SKILL.md +++ b/codex/SKILL.md @@ -20,7 +20,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/codex/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/codex/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/codex/sections/preamble.md b/codex/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/codex/sections/preamble.md +++ b/codex/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/context-restore/SKILL.md b/context-restore/SKILL.md index cafd34abd3a..68efd7af70a 100644 --- a/context-restore/SKILL.md +++ b/context-restore/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-restore/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-restore/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/context-restore/sections/preamble.md b/context-restore/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/context-restore/sections/preamble.md +++ b/context-restore/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/context-save/SKILL.md b/context-save/SKILL.md index 10a4e8ca6ea..28a4f9b6466 100644 --- a/context-save/SKILL.md +++ b/context-save/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-save/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-save/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/context-save/sections/preamble.md b/context-save/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/context-save/sections/preamble.md +++ b/context-save/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/design-consultation/SKILL.md b/design-consultation/SKILL.md index 7d545778d09..adaa68b430d 100644 --- a/design-consultation/SKILL.md +++ b/design-consultation/SKILL.md @@ -45,7 +45,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-consultation/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-consultation/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-consultation/sections/preamble.md b/design-consultation/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/design-consultation/sections/preamble.md +++ b/design-consultation/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/design-html/SKILL.md b/design-html/SKILL.md index 400cb285cf2..dee5afe1ab0 100644 --- a/design-html/SKILL.md +++ b/design-html/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-html/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-html/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-html/sections/preamble.md b/design-html/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/design-html/sections/preamble.md +++ b/design-html/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/design-motion/SKILL.md b/design-motion/SKILL.md index f9562771786..9d6601577d2 100644 --- a/design-motion/SKILL.md +++ b/design-motion/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-motion/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-motion/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-motion/sections/preamble.md b/design-motion/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/design-motion/sections/preamble.md +++ b/design-motion/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/design-review/SKILL.md b/design-review/SKILL.md index 7713ee0f5d4..97749121776 100644 --- a/design-review/SKILL.md +++ b/design-review/SKILL.md @@ -23,7 +23,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-review/sections/preamble.md b/design-review/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/design-review/sections/preamble.md +++ b/design-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/design-shotgun/SKILL.md b/design-shotgun/SKILL.md index cf888a102fd..a5fa30b71f3 100644 --- a/design-shotgun/SKILL.md +++ b/design-shotgun/SKILL.md @@ -39,7 +39,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-shotgun/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-shotgun/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-shotgun/sections/preamble.md b/design-shotgun/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/design-shotgun/sections/preamble.md +++ b/design-shotgun/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/devex-review/SKILL.md b/devex-review/SKILL.md index d353ba1bba4..d2b158dc82e 100644 --- a/devex-review/SKILL.md +++ b/devex-review/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/devex-review/sections/preamble.md b/devex-review/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/devex-review/sections/preamble.md +++ b/devex-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/document-generate/SKILL.md b/document-generate/SKILL.md index a1c9da8ba2e..c8d9cdbcb57 100644 --- a/document-generate/SKILL.md +++ b/document-generate/SKILL.md @@ -25,7 +25,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-generate/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-generate/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/document-generate/sections/preamble.md b/document-generate/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/document-generate/sections/preamble.md +++ b/document-generate/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/document-release/SKILL.md b/document-release/SKILL.md index 3d1a91dc177..8047fc11e31 100644 --- a/document-release/SKILL.md +++ b/document-release/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-release/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-release/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/document-release/sections/preamble.md b/document-release/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/document-release/sections/preamble.md +++ b/document-release/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/eval-plan/SKILL.md b/eval-plan/SKILL.md index c7665440e5d..e5a34067e45 100644 --- a/eval-plan/SKILL.md +++ b/eval-plan/SKILL.md @@ -24,7 +24,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/eval-plan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/eval-plan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/eval-plan/sections/preamble.md b/eval-plan/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/eval-plan/sections/preamble.md +++ b/eval-plan/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/health/SKILL.md b/health/SKILL.md index 0df11a75b50..2a9e6b7f70e 100644 --- a/health/SKILL.md +++ b/health/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/health/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/health/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/health/sections/preamble.md b/health/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/health/sections/preamble.md +++ b/health/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/ios-clean/SKILL.md b/ios-clean/SKILL.md index 80b44691d12..d76f480b167 100644 --- a/ios-clean/SKILL.md +++ b/ios-clean/SKILL.md @@ -20,7 +20,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-clean/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-clean/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-clean/sections/preamble.md b/ios-clean/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/ios-clean/sections/preamble.md +++ b/ios-clean/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/ios-design-review/SKILL.md b/ios-design-review/SKILL.md index 3d630daa35b..1d47b721903 100644 --- a/ios-design-review/SKILL.md +++ b/ios-design-review/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-design-review/sections/preamble.md b/ios-design-review/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/ios-design-review/sections/preamble.md +++ b/ios-design-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/ios-fix/SKILL.md b/ios-fix/SKILL.md index af59d324473..8771cf89ce6 100644 --- a/ios-fix/SKILL.md +++ b/ios-fix/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-fix/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-fix/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-fix/sections/preamble.md b/ios-fix/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/ios-fix/sections/preamble.md +++ b/ios-fix/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/ios-qa/SKILL.md b/ios-qa/SKILL.md index f34efd2755a..712a3616611 100644 --- a/ios-qa/SKILL.md +++ b/ios-qa/SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-qa/sections/preamble.md b/ios-qa/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/ios-qa/sections/preamble.md +++ b/ios-qa/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/ios-sync/SKILL.md b/ios-sync/SKILL.md index 1c49407a56d..8a75aebfc38 100644 --- a/ios-sync/SKILL.md +++ b/ios-sync/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-sync/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-sync/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-sync/sections/preamble.md b/ios-sync/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/ios-sync/sections/preamble.md +++ b/ios-sync/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/land-and-deploy/SKILL.md b/land-and-deploy/SKILL.md index 08a7ced13f4..7a12e351bef 100644 --- a/land-and-deploy/SKILL.md +++ b/land-and-deploy/SKILL.md @@ -20,7 +20,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/land-and-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/land-and-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/land-and-deploy/sections/preamble.md b/land-and-deploy/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/land-and-deploy/sections/preamble.md +++ b/land-and-deploy/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/landing-report/SKILL.md b/landing-report/SKILL.md index b07a98cf36d..616a9eb4c0c 100644 --- a/landing-report/SKILL.md +++ b/landing-report/SKILL.md @@ -20,7 +20,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/landing-report/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/landing-report/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/landing-report/sections/preamble.md b/landing-report/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/landing-report/sections/preamble.md +++ b/landing-report/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/learn/SKILL.md b/learn/SKILL.md index 9c27e322b90..52b620d8a60 100644 --- a/learn/SKILL.md +++ b/learn/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/learn/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/learn/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/learn/sections/preamble.md b/learn/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/learn/sections/preamble.md +++ b/learn/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/modernize/SKILL.md b/modernize/SKILL.md index ed48ce690e9..e73b7b965c5 100644 --- a/modernize/SKILL.md +++ b/modernize/SKILL.md @@ -23,7 +23,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/modernize/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/modernize/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/modernize/sections/preamble.md b/modernize/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/modernize/sections/preamble.md +++ b/modernize/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/office-hours/SKILL.md b/office-hours/SKILL.md index c40b9193868..374b09e8a78 100644 --- a/office-hours/SKILL.md +++ b/office-hours/SKILL.md @@ -49,7 +49,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/office-hours/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/office-hours/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/office-hours/sections/preamble.md b/office-hours/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/office-hours/sections/preamble.md +++ b/office-hours/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/pair-agent/SKILL.md b/pair-agent/SKILL.md index 45720575865..cb3d8c48e04 100644 --- a/pair-agent/SKILL.md +++ b/pair-agent/SKILL.md @@ -18,7 +18,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/pair-agent/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/pair-agent/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/pair-agent/sections/preamble.md b/pair-agent/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/pair-agent/sections/preamble.md +++ b/pair-agent/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/plan-ceo-review/SKILL.md b/plan-ceo-review/SKILL.md index 69a4dec1efc..f34a1f22325 100644 --- a/plan-ceo-review/SKILL.md +++ b/plan-ceo-review/SKILL.md @@ -51,7 +51,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-ceo-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-ceo-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-ceo-review/sections/preamble.md b/plan-ceo-review/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/plan-ceo-review/sections/preamble.md +++ b/plan-ceo-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/plan-design-review/SKILL.md b/plan-design-review/SKILL.md index 61b7a6363de..fe6c303e8fc 100644 --- a/plan-design-review/SKILL.md +++ b/plan-design-review/SKILL.md @@ -51,7 +51,7 @@ Recommendation: A when a branch diff exists, otherwise B. Reply with A, B, or C. ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (after scope gate) diff --git a/plan-design-review/sections/preamble.md b/plan-design-review/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/plan-design-review/sections/preamble.md +++ b/plan-design-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/plan-devex-review/SKILL.md b/plan-devex-review/SKILL.md index cbe3a2fe1ef..d815672a511 100644 --- a/plan-devex-review/SKILL.md +++ b/plan-devex-review/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-devex-review/sections/preamble.md b/plan-devex-review/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/plan-devex-review/sections/preamble.md +++ b/plan-devex-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/plan-eng-review/SKILL.md b/plan-eng-review/SKILL.md index 745640604bc..79714f317b4 100644 --- a/plan-eng-review/SKILL.md +++ b/plan-eng-review/SKILL.md @@ -63,7 +63,7 @@ Keep the reviewed target fixed when selecting the report destination. ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-eng-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-eng-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (after scope gate) diff --git a/plan-eng-review/sections/preamble.md b/plan-eng-review/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/plan-eng-review/sections/preamble.md +++ b/plan-eng-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/plan-tune/SKILL.md b/plan-tune/SKILL.md index d30cacddce9..d0a41297182 100644 --- a/plan-tune/SKILL.md +++ b/plan-tune/SKILL.md @@ -25,7 +25,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-tune/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-tune/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-tune/sections/preamble.md b/plan-tune/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/plan-tune/sections/preamble.md +++ b/plan-tune/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/qa-only/SKILL.md b/qa-only/SKILL.md index 4854a744afa..23f911322c2 100644 --- a/qa-only/SKILL.md +++ b/qa-only/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa-only/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa-only/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/qa-only/sections/preamble.md b/qa-only/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/qa-only/sections/preamble.md +++ b/qa-only/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/qa/SKILL.md b/qa/SKILL.md index 38d95e46e62..c1fb54fed28 100644 --- a/qa/SKILL.md +++ b/qa/SKILL.md @@ -22,7 +22,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/qa/sections/preamble.md b/qa/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/qa/sections/preamble.md +++ b/qa/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/retro/SKILL.md b/retro/SKILL.md index 87f44852c64..c4f0c624013 100644 --- a/retro/SKILL.md +++ b/retro/SKILL.md @@ -39,7 +39,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/retro/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/retro/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/retro/sections/preamble.md b/retro/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/retro/sections/preamble.md +++ b/retro/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/review/SKILL.md b/review/SKILL.md index a1809271b32..eb7b4cabee5 100644 --- a/review/SKILL.md +++ b/review/SKILL.md @@ -50,7 +50,7 @@ Finish only when each of these exists (contract v1): ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/review/sections/preamble.md b/review/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/review/sections/preamble.md +++ b/review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/scripts/resolvers/preamble/generate-voice-directive.ts b/scripts/resolvers/preamble/generate-voice-directive.ts index 07b3e0279ab..ccb72a3aef2 100644 --- a/scripts/resolvers/preamble/generate-voice-directive.ts +++ b/scripts/resolvers/preamble/generate-voice-directive.ts @@ -31,8 +31,7 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: \`Failed or skipped:\` (anything that failed, even if fixed, was skipped or never ran), \`Unverified:\` (claims no output confirmed), \`Also changed:\` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned.`; +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none."`; } diff --git a/setup-deploy/SKILL.md b/setup-deploy/SKILL.md index c06932f5b47..184cf047cf1 100644 --- a/setup-deploy/SKILL.md +++ b/setup-deploy/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/setup-deploy/sections/preamble.md b/setup-deploy/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/setup-deploy/sections/preamble.md +++ b/setup-deploy/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.md index 7b4355c2dcb..1d3c9563d1c 100644 --- a/setup-gbrain/SKILL.md +++ b/setup-gbrain/SKILL.md @@ -23,7 +23,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/setup-gbrain/sections/preamble.md b/setup-gbrain/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/setup-gbrain/sections/preamble.md +++ b/setup-gbrain/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/ship/SKILL.md b/ship/SKILL.md index d6410127805..6f0453a16ca 100644 --- a/ship/SKILL.md +++ b/ship/SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ship/sections/preamble.md b/ship/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/ship/sections/preamble.md +++ b/ship/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/skillify/SKILL.md b/skillify/SKILL.md index 10477485e76..cb169962f3e 100644 --- a/skillify/SKILL.md +++ b/skillify/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/skillify/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/skillify/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/skillify/sections/preamble.md b/skillify/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/skillify/sections/preamble.md +++ b/skillify/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/spec/SKILL.md b/spec/SKILL.md index 1529f557a53..016aa36205a 100644 --- a/spec/SKILL.md +++ b/spec/SKILL.md @@ -22,7 +22,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/spec/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/spec/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/spec/sections/preamble.md b/spec/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/spec/sections/preamble.md +++ b/spec/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/sync-gbrain/SKILL.md b/sync-gbrain/SKILL.md index 354f96e6f3d..63e4054b757 100644 --- a/sync-gbrain/SKILL.md +++ b/sync-gbrain/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/sync-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/sync-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/sync-gbrain/sections/preamble.md b/sync-gbrain/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/sync-gbrain/sections/preamble.md +++ b/sync-gbrain/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/test-audit/SKILL.md b/test-audit/SKILL.md index 090bbb32276..48f3f457805 100644 --- a/test-audit/SKILL.md +++ b/test-audit/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/test-audit/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/test-audit/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test-audit/sections/preamble.md b/test-audit/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/test-audit/sections/preamble.md +++ b/test-audit/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/test/capy-skill-wrapper.test.ts b/test/capy-skill-wrapper.test.ts index 9ae7afb500a..2f4e310311b 100644 --- a/test/capy-skill-wrapper.test.ts +++ b/test/capy-skill-wrapper.test.ts @@ -680,14 +680,16 @@ describe('capy skill: factory.md, the auto-loaded "how we work" page', () => { return [...new Set(problems)]; } - test('it fits the 4,200-byte budget, and every citation, heading and skill it names resolves', () => { + test('it fits the 4,400-byte budget, and every citation, heading and skill it names resolves', () => { const text = fs.readFileSync(FACTORY, 'utf8'); // 3,300 since #3634; raised to 3,450 (the page's new size, rounded up to the next 25 bytes) for point 12's // R68 clause (Garry, 2026-11-03: crew threads ask their Captain for new threads). Raise it only by what a rule needs. // 3,475 for the crew/ prefix on its four Captain-manual citations (GST-1833 moved docs/captain.md to crew/docs/; no rule text changed). // 3,650 for point 2's one-open-PR-per-lane rule and point 12's no-orphan and close-reason rule (GST-2077, Garry's "do it" 2026-11-09: lessons from gbrain's merge queue). // 4,200 for point 12's keep-the-PR-to-the-end and standing-thread rotation clause and point 14's cap of 10 finished PRs before a new fix thread (Garry's "do it" 2026-11-09, relayed by FOUN-32). - expect(Buffer.byteLength(text)).toBeLessThanOrEqual(4200); + // 4,400 for point 10's report shape, Failed or skipped / Unverified / Also changed lines first, and its pointer to ETHOS.md section 8 for + // findings write-ups (GST-1455, Garry's "do it" 2026-11-05 on R73; the clause is the wording GEVA-2's dev climb measured, so it is not trimmed). + expect(Buffer.byteLength(text)).toBeLessThanOrEqual(4400); expect(text).toMatch(/^# How we work/); expect(citationProblems(text)).toEqual([]); }); diff --git a/test/fixtures/golden/agy-ship-SKILL.md b/test/fixtures/golden/agy-ship-SKILL.md index b84aa804577..d38fbc2b65d 100644 --- a/test/fixtures/golden/agy-ship-SKILL.md +++ b/test/fixtures/golden/agy-ship-SKILL.md @@ -12,7 +12,7 @@ description: | ## Shared preamble (load first) -This skill follows gstack shared preamble `dc6688a6791f` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `673baf289542` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md index d6410127805..6f0453a16ca 100644 --- a/test/fixtures/golden/claude-ship-SKILL.md +++ b/test/fixtures/golden/claude-ship-SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.md index d535a44b4b2..002db2ba459 100644 --- a/test/fixtures/golden/codex-ship-SKILL.md +++ b/test/fixtures/golden/codex-ship-SKILL.md @@ -12,7 +12,7 @@ description: | ## Shared preamble (load first) -This skill follows gstack shared preamble `1c66f530e65a` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `0876a471d87b` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.md index 31f0a060c7a..1a11689c3b2 100644 --- a/test/fixtures/golden/factory-ship-SKILL.md +++ b/test/fixtures/golden/factory-ship-SKILL.md @@ -14,7 +14,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `fb2ce44dd505` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `b517469fdbdb` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/size-ledger/ship/gstack-reports-lead-with-failures.json b/test/size-ledger/ship/gstack-reports-lead-with-failures.json new file mode 100644 index 00000000000..8f317672fa7 --- /dev/null +++ b/test/size-ledger/ship/gstack-reports-lead-with-failures.json @@ -0,0 +1,4 @@ +{ + "bytes": -4, + "why": "GST-1455: the shared closer opens status reports with failed-or-skipped, unverified and also-changed lines (-4 B)" +} diff --git a/ubicloud/SKILL.md b/ubicloud/SKILL.md index 6274dbed6a7..c86b42b5c1e 100644 --- a/ubicloud/SKILL.md +++ b/ubicloud/SKILL.md @@ -19,7 +19,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ubicloud/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ubicloud/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ubicloud/sections/preamble.md b/ubicloud/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/ubicloud/sections/preamble.md +++ b/ubicloud/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery diff --git a/write-skill/SKILL.md b/write-skill/SKILL.md index 85fc30a8beb..7d4986e2a46 100644 --- a/write-skill/SKILL.md +++ b/write-skill/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `227aca067dd3` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/write-skill/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/write-skill/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/write-skill/sections/preamble.md b/write-skill/sections/preamble.md index 9efe49a9da2..a7fb731da7f 100644 --- a/write-skill/sections/preamble.md +++ b/write-skill/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 227aca067dd3 +# gstack shared preamble d56c99c92144 ## Plan Mode Safe Operations @@ -171,10 +171,9 @@ GStack voice: Garry-shaped product and engineering judgment. Good: "auth.ts:47 returns undefined when the session cookie expires. Users hit a white screen. Fix: add a null check and redirect to /login. Two lines." Bad: "I've identified a potential issue in the authentication flow that may cause problems under certain conditions." -**Bounded closer.** After completing work, report in at most a few short lines: what changed, what was skipped, what to watch. No feature tours or unrequested design notes. Exempt: decision briefs, completion-status blocks, requested explanations, and a skill's mandated report (/qa-only, /plan-*-review, /retro, /document-generate). The rule limits prose around the deliverable, never the deliverable. +**Bounded closer.** A status report (after work or when asked) stays under 250 words and opens with three lines, each item named, or none: `Failed or skipped:` (anything that failed, even if fixed, was skipped or never ran), `Unverified:` (claims no output confirmed), `Also changed:` (config, CI, files outside the ask). Then what changed and ran; claim nothing more. Over 10 items: top 10, the rest counted, an offer to list. Exempt: decision briefs, requested explanations, mandated reports (/qa-only, /plan-*-review, /retro, /document-generate). -Good closer: "Renamed the flag in 3 files, regenerated docs, tests green. Skipped the CLI alias (unused since v1.2); watch the Windows job." -Bad closer: a tour of every edit, a restatement of the plan, and three paragraphs justifying choices nobody questioned. +Good: "Failed or skipped: lint (fixed), 2 e2e tests (no key). Unverified: Windows alias. Also changed: none." ## Context Recovery From bcece3fbcdf0e84e029caac5d04524af3ff6ba41 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 17 Nov 2026 17:05:25 +0800 Subject: [PATCH 16/62] Make gstack's shell locks hold when mkdir reports a race it lost (GST-2247) (#4262) * Make gstack's shell locks hold when mkdir reports a race it lost (GST-2247) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Fix lock tests and fixtures for gstack_lock_take; trim setup-gbrain lock prose Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Ship the lock helper with every copied runtime and fixture that runs a lock The Claude Code wrapper's copied runtime now includes bin/gstack-lock.sh, and bin/gstack-render-claude.sh sources it beside itself, so gstack-config set works in a copied runtime and the render lock is taken by every caller. Test fixtures that copy single bin scripts now copy the helper too, and the mkdir lock guard is registered as a repo-wide docs reader. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Release a lock whose owner file could not be fully written gstack_lock_take created the owner file with a noclobber redirect and, when that redirect failed, treated an existing file as a competing holder. If the file was created but the write then failed (disk full, quota, ulimit -f), the helper found its own empty file, returned 1 and left a lock nobody held; freeze's state lock has no stale recovery, so it stayed busy until removed by hand. The helper now tells "opened but write failed" from "already held", removes its own file and directory, and returns 3. The inline copy in gstack-ff-update is updated byte for byte, and a new test under ulimit -f 0 fails on the old helper. Review-Finding: s11/outside-voice#1 reader=outside-voice Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Describe the lease lock as gstack_lock_take's O_EXCL owner file Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- USING_GBRAIN_WITH_GSTACK.md | 2 +- bin/gstack-brain-lock.sh | 15 +- bin/gstack-browser-ensure | 4 +- bin/gstack-capy-session | 2 +- bin/gstack-codex-probe | 20 +- bin/gstack-config | 14 +- bin/gstack-developer-profile | 22 ++- bin/gstack-ff-update | 28 ++- bin/gstack-install-registry.sh | 13 +- bin/gstack-lease | 27 +-- bin/gstack-lock.sh | 48 +++++ bin/gstack-memorable | 12 +- bin/gstack-render-claude.sh | 13 +- bin/gstack-session-update | 27 +-- bin/gstack-settings-hook | 16 +- bin/gstack-upgrade | 6 +- ...ell-locks-hold-when-mkdir-lies-gst-2247.md | 5 + docs/capy-install.md | 8 +- docs/troubleshooting.md | 30 +++ freeze/bin/freeze-state.sh | 5 +- lib/claude-code-migration.ts | 2 +- lib/docs-only.ts | 2 +- setup | 25 +-- setup-gbrain/SKILL.md | 11 +- setup-gbrain/SKILL.md.tmpl | 11 +- test/capy-skill-wrapper.test.ts | 2 +- test/codex-probe-cache.test.ts | 9 +- test/freeze-owned-lifecycle.test.ts | 2 +- test/gen-skill-docs.test.ts | 2 +- test/gstack-browser-ensure.test.ts | 1 + test/gstack-ff-update.test.ts | 7 + test/gstack-lease.test.ts | 3 +- test/gstack-lock-race.test.ts | 186 ++++++++++++++++++ test/gstack-settings-hook-symlink.test.ts | 9 +- test/gstack-upgrade-bin.test.ts | 2 +- test/helpers/ship-measure-seeded-fixture.ts | 8 +- test/mkdir-lock-guard.test.ts | 131 ++++++++++++ test/plan-mode-preamble-render.test.ts | 2 +- test/relink-disabled-router.test.ts | 2 +- test/relink.test.ts | 1 + test/session-update-autostash.test.ts | 2 +- test/session-update-hook-hold.test.ts | 2 +- test/setup-claude-code-migration.test.ts | 2 +- test/setup-gbrain-fixture.test.ts | 6 +- test/setup-playwright-best-effort.test.ts | 2 + test/setup-production-deps.test.ts | 4 +- test/setup-skill-hooks-gate.test.ts | 2 +- test/team-mode.test.ts | 2 +- test/uninstall.test.ts | 14 +- test/update-channel.test.ts | 4 +- 50 files changed, 621 insertions(+), 154 deletions(-) create mode 100644 bin/gstack-lock.sh create mode 100644 changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md create mode 100644 test/gstack-lock-race.test.ts create mode 100644 test/mkdir-lock-guard.test.ts diff --git a/USING_GBRAIN_WITH_GSTACK.md b/USING_GBRAIN_WITH_GSTACK.md index d4a59d370e6..457bdeea3ed 100644 --- a/USING_GBRAIN_WITH_GSTACK.md +++ b/USING_GBRAIN_WITH_GSTACK.md @@ -243,7 +243,7 @@ Gbrain itself ships with these that gstack wraps: |---|---| | `~/.gbrain/config.json` | Engine (pglite/postgres), database URL or path, API keys. Mode 0600. Written by `gbrain init`. When `GBRAIN_HOME` is set, gbrain and gstack's helpers read `$GBRAIN_HOME/.gbrain/config.json` instead. | | `~/.gstack/gbrain-repo-policy.json` | Per-remote trust triad. Schema v2. Mode 0600. | -| `~/.gstack/.setup-gbrain.lock.d` | Concurrent-run lock (atomic mkdir). Released on normal exit + SIGINT. | +| `~/.gstack/.setup-gbrain.lock.d` | Concurrent-run lock: a directory whose `pid` file is created with O_EXCL (`gstack_lock_take`, `bin/gstack-lock.sh`), so it holds even where `mkdir` misreports a race. Released on normal exit + SIGINT. | | `~/.gstack/.brain-queue.d/` | Pending sync records for gstack memory sync — maildir-style spool, one file per record. A legacy `.brain-queue.jsonl` from older releases migrates automatically on the next drain. | | `~/.gstack/.brain-last-push` | Timestamp of last sync push (for `/health` scoring) | | `~/.gstack-artifacts-remote.txt` | URL of your gstack memory sync remote (safe to copy between machines; legacy name `~/.gstack-brain-remote.txt` still read) | diff --git a/bin/gstack-brain-lock.sh b/bin/gstack-brain-lock.sh index 2f60ac942cc..110caebb0db 100644 --- a/bin/gstack-brain-lock.sh +++ b/bin/gstack-brain-lock.sh @@ -23,10 +23,14 @@ # gstack_brain_lock_release # Removes the lock only when this process took it and still owns it. # -# The lock is a directory (mkdir is atomic on every POSIX filesystem; flock(1) -# is not on macOS) holding `pid` and `owner`. A lock whose pid is dead is -# stale and is cleared. A lock directory with no pid file is a holder killed -# between mkdir and the pid write once it is older than 10 minutes. +# The lock is a directory holding `pid` and `owner`, taken with +# gstack_lock_take (bin/gstack-lock.sh), which creates `pid` with O_EXCL: +# mkdir's exit status is not a lock on Ubuntu 26.04's uutils mkdir, and +# flock(1) is not on macOS. A lock whose pid is dead is stale and is cleared. +# A lock directory with no pid file is a holder killed between mkdir and the +# pid write once it is older than 10 minutes. + +. "$(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { echo "gstack: $(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh is missing; reinstall with ./setup" >&2; return 2; } _GSTACK_BRAIN_LOCK_DIR="" _GSTACK_BRAIN_LOCK_MINE=0 @@ -34,10 +38,9 @@ _GSTACK_BRAIN_LOCK_HOLDER="" _gstack_brain_lock_try_once() { local dir="$1" pid - if mkdir "$dir" 2>/dev/null; then + if gstack_lock_take "$dir" pid "$$"; then GSTACK_BRAIN_LOCK_TOKEN="$$-${RANDOM:-0}-$(date +%s 2>/dev/null || echo 0)" export GSTACK_BRAIN_LOCK_TOKEN - printf '%s\n' "$$" > "$dir/pid" 2>/dev/null || true printf '%s\n' "$GSTACK_BRAIN_LOCK_TOKEN" > "$dir/owner" 2>/dev/null || true _GSTACK_BRAIN_LOCK_MINE=1 return 0 diff --git a/bin/gstack-browser-ensure b/bin/gstack-browser-ensure index 0f87e327469..95e1d1824b5 100755 --- a/bin/gstack-browser-ensure +++ b/bin/gstack-browser-ensure @@ -101,8 +101,9 @@ BUN=$(command -v bun 2>/dev/null) || fail "Chromium is not installed and bun is # Same lock ./setup takes (#2136), so two installs never race on the cache. LOCK="${TMPDIR:-/tmp}/gstack-playwright-install.lock" +. "$ROOT/bin/gstack-lock.sh" 2>/dev/null || fail "$ROOT/bin/gstack-lock.sh is missing" "reinstall with cd $ROOT && ./setup" tries=0 -while ! mkdir "$LOCK" 2>/dev/null; do +while ! gstack_lock_take "$LOCK" pid "$$"; do holder=$(cat "$LOCK/pid" 2>/dev/null || true) case "$holder" in ''|*[!0-9]*) holder=0 ;; esac if [ "$holder" -eq 0 ] || ! kill -0 "$holder" 2>/dev/null; then rm -rf "$LOCK" 2>/dev/null; continue; fi @@ -110,7 +111,6 @@ while ! mkdir "$LOCK" 2>/dev/null; do [ "$tries" -ge "$TIMEOUT" ] && fail "another gstack install holds the Chromium lock ($LOCK, pid $holder)" "wait for it, or remove a stale lock: rm -rf \"$LOCK\"" sleep 1 done -echo "$$" > "$LOCK/pid" 2>/dev/null || true trap 'rm -rf "$LOCK" 2>/dev/null' EXIT INT TERM OVERRIDE="" diff --git a/bin/gstack-capy-session b/bin/gstack-capy-session index 314390708dd..64b83926f13 100755 --- a/bin/gstack-capy-session +++ b/bin/gstack-capy-session @@ -283,7 +283,7 @@ EOF_OWN report_behind "$RERUN" export GSTACK_CAPY_BEHIND_BLOCKED="$REASON" elif [ -n "$SWITCH" ] && ! { SETUP_LOCK="$("$ROOT/bin/gstack-paths" --get GSTACK_STATE_ROOT 2>/dev/null)/.setup-lock"; [ "$SETUP_LOCK" != /.setup-lock ] \ - && mkdir -p "$(dirname "$SETUP_LOCK")" 2>/dev/null && mkdir "$SETUP_LOCK" 2>/dev/null && echo "$$" > "$SETUP_LOCK/pid"; }; then + && mkdir -p "$(dirname "$SETUP_LOCK")" 2>/dev/null && . "$ROOT/bin/gstack-lock.sh" && gstack_lock_take "$SETUP_LOCK" pid "$$"; }; then # The switch and the fast-forward happen under gstack-upgrade's setup lock, # taken here and handed over in GSTACK_SETUP_LOCK_OWNER, so a concurrent # updater never sees the checkout between the two. diff --git a/bin/gstack-codex-probe b/bin/gstack-codex-probe index 9f0a4f11512..afbcadab064 100755 --- a/bin/gstack-codex-probe +++ b/bin/gstack-codex-probe @@ -103,6 +103,7 @@ fi # === end gstack self-locate === _GSTACK_CODEX_BIN="$_gstack_helper_dir" unset _gstack_helper _gstack_helper_dir _gstack_helper_shell +. "$_GSTACK_CODEX_BIN/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { return 2; } # --- Auth probe ------------------------------------------------------------- @@ -631,19 +632,16 @@ _gstack_codex_probe_cache_store() { _gstack_codex_lock_acquire() { # $1 lock directory, $2 seconds to wait, $3 seconds after which even a live - # owner is abandoned. mkdir is atomic on every platform bash runs on. A dead - # owner on this host is recovered at once; a missing owner file is the + # owner is abandoned. gstack_lock_take (bin/gstack-lock.sh) creates the owner + # file with O_EXCL, since mkdir's exit status is not a lock on Ubuntu 26.04's + # uutils mkdir. A dead owner on this host is recovered at once; a missing owner file is the # creation window and becomes stale after 5 seconds. 0 = held, 1 = timed # out, 2 = the lock or its owner record cannot be created. local _dir="$1" _tries=$(( ${2:-45} * 10 )) _stale="${3:-90}" _host _owner _pid _ohost _ts _now _i=0 _dead _host=$(uname -n 2>/dev/null || echo unknown) while :; do - if mkdir "$_dir" 2>/dev/null; then - printf '%s %s %s\n' "$$" "$_host" "$(date +%s 2>/dev/null || echo 0)" > "$_dir/owner" 2>/dev/null && return 0 - rm -f "$_dir/owner" 2>/dev/null - rmdir "$_dir" 2>/dev/null - return 2 - fi + gstack_lock_take "$_dir" owner "$$ $_host $(date +%s 2>/dev/null || echo 0)" + case $? in 0) return 0 ;; 3) return 2 ;; esac if [ ! -d "$_dir" ]; then { [ -e "$_dir" ] || [ -L "$_dir" ]; } && return 2 { [ -d "${_dir%/*}" ] && [ -w "${_dir%/*}" ] && [ -x "${_dir%/*}" ]; } || return 2 @@ -677,15 +675,15 @@ _gstack_codex_lock_break() { # Breakers serialize on $1.break and remove the lock only if it still has the # owner they judged abandoned, so a lock re-taken meanwhile survives. local _dir="$1" _seen="$2" _bt _now - if mkdir "$_dir.break" 2>/dev/null; then + if gstack_lock_take "$_dir.break" pid "$$"; then [ "$(cat "$_dir/owner" 2>/dev/null)" = "$_seen" ] && rm -rf "$_dir" 2>/dev/null - rmdir "$_dir.break" 2>/dev/null + rm -rf "$_dir.break" 2>/dev/null return 0 fi _now=$(date +%s 2>/dev/null || echo 0) _bt=$(stat -c %Y "$_dir.break" 2>/dev/null || stat -f %m "$_dir.break" 2>/dev/null || echo "$_now") case "$_bt" in ''|*[!0-9]*) _bt="$_now" ;; esac - [ $((_now - _bt)) -ge 10 ] && rmdir "$_dir.break" 2>/dev/null + [ $((_now - _bt)) -ge 10 ] && rm -rf "$_dir.break" 2>/dev/null return 0 } diff --git a/bin/gstack-config b/bin/gstack-config index 8eb26cf7289..89c4a815023 100755 --- a/bin/gstack-config +++ b/bin/gstack-config @@ -552,18 +552,21 @@ read_config_value() { # ── Config writes: one lock, one read-modify-write rename ────────────────── # Every mutation of config.yaml (set, unset, the transcript_repos pair, the -# user-slug writer) holds an atomic mkdir lock and replaces the file with one +# user-slug writer) holds one lock directory and replaces the file with one # rename, so concurrent writers never lose each other's keys and an -# interrupted write leaves the old file. The pid file holds " "; -# a lock whose holder is dead or older than 10 s is taken over. No flock(1): -# stock macOS does not ship it. +# interrupted write leaves the old file. The lock is taken with +# gstack_lock_take (bin/gstack-lock.sh), which creates the pid file with +# O_EXCL because mkdir's exit status is not a lock on Ubuntu 26.04's uutils +# mkdir. The pid file holds " "; a lock whose holder is dead or +# older than 10 s is taken over. No flock(1): stock macOS does not ship it. CONFIG_LOCK="$STATE_DIR/.config-yaml.lock" _config_locked="" config_lock() { mkdir -p "$STATE_DIR" + . "$(dirname "$0")/gstack-lock.sh" 2>/dev/null || { echo "Error: $(dirname "$0")/gstack-lock.sh is missing. Existing value left unchanged. fix: reinstall with ./setup or /gstack-upgrade" >&2; exit 1; } local waited=0 held pid ts stale - while ! mkdir "$CONFIG_LOCK" 2>/dev/null; do + while ! gstack_lock_take "$CONFIG_LOCK" pid "$$ $(date +%s)"; do if [ ! -w "$STATE_DIR" ]; then echo "Error: cannot write to $STATE_DIR (its config lock could not be created). Existing value left unchanged." >&2 exit 1 @@ -589,7 +592,6 @@ config_lock() { fi sleep 0.05 done - printf '%s %s\n' "$$" "$(date +%s)" > "$CONFIG_LOCK/pid" _config_locked=1 trap 'config_unlock' EXIT } diff --git a/bin/gstack-developer-profile b/bin/gstack-developer-profile index 624dc723cdb..2db44df2e3a 100755 --- a/bin/gstack-developer-profile +++ b/bin/gstack-developer-profile @@ -66,16 +66,18 @@ shift || true # changes and renames the whole file, and gstack-question-log starts a # background --derive after every append, so writers overlap: a shared temp # name made renames fail and an unlocked rewrite dropped a concurrent -# --log-session. Writers hold a mkdir lock (.lock/, whose owner file +# --log-session. Writers hold a lock directory (.lock/, whose owner file # names the holder's pid and a random token; release is ownership-checked) # from before their read until after their rename, and write a unique temp # file. A lock whose holder process is gone is taken over at once; one older # than 5 minutes is taken over even when its pid is alive, since no writer -# runs that long and the pid may have been reused. Takeovers are serialized by a second mkdir lock +# runs that long and the pid may have been reused. Takeovers are serialized by a second lock # (.lock.takeover/) and re-read the owner under it, so two waiters # cannot both take over or remove a lock a third writer just took. A lock or # takeover directory older than 30 s with no owner belongs to a writer that -# died before writing one; cleanup removes a takeover lock this writer holds. A writer that cannot get the lock within the +# died before writing one; cleanup removes a takeover lock this writer holds. Both locks +# are taken with gstack_lock_take (bin/gstack-lock.sh): mkdir's exit status is not +# a lock on Ubuntu 26.04's uutils mkdir, so the owner file is created with O_EXCL. A writer that cannot get the lock within the # give-up window writes nothing and exits 5. Writers outside this binary # (gstack-distill-apply, /plan-tune's declared edits) do not take it yet. # ----------------------------------------------------------------------- @@ -87,7 +89,7 @@ PROFILE_TMP="" cleanup() { if [ -n "$PROFILE_TMP" ]; then rm -f "$PROFILE_TMP"; fi - if [ -n "$HOLDS_TAKEOVER" ]; then rmdir "$TAKEOVER_DIR" 2>/dev/null || true; fi + if [ -n "$HOLDS_TAKEOVER" ]; then rm -rf "$TAKEOVER_DIR" 2>/dev/null || true; fi if [ -n "$LOCK_TOKEN" ] && [ "$(cat "$LOCK_DIR/owner" 2>/dev/null || true)" = "$LOCK_TOKEN" ]; then rm -rf "$LOCK_DIR" fi @@ -117,8 +119,9 @@ acquire_lock() { # GSTACK_PROFILE_LOCK_TIMEOUT_MS: test-only override for the give-up. local give_up_ms="${GSTACK_PROFILE_LOCK_TIMEOUT_MS:-10000}" waited_ms=0 started=$SECONDS vanished=0 owner local token="$$-$RANDOM$RANDOM" - until mkdir "$LOCK_DIR" 2>/dev/null; do - # mkdir failed with no lock to wait for: retry once in case a holder just + . "$SCRIPT_DIR/gstack-lock.sh" 2>/dev/null || { echo "gstack-developer-profile: $SCRIPT_DIR/gstack-lock.sh is missing, so nothing was written (exit 5). fix: reinstall with ./setup or /gstack-upgrade" >&2; exit 5; } + until gstack_lock_take "$LOCK_DIR" owner "$token"; do + # The take failed with no lock to wait for: retry once in case a holder just # released it, then report the directory instead of waiting out the window. if [ ! -e "$LOCK_DIR" ]; then if [ "$vanished" -eq 0 ]; then vanished=1; continue; fi @@ -128,13 +131,13 @@ acquire_lock() { vanished=0 owner=$(cat "$LOCK_DIR/owner" 2>/dev/null || true) if [ -d "$LOCK_DIR" ] && lock_abandoned "$owner"; then - if [ -d "$TAKEOVER_DIR" ] && [ "$(dir_age_s "$TAKEOVER_DIR")" -gt 30 ]; then rmdir "$TAKEOVER_DIR" 2>/dev/null || true; fi - if mkdir "$TAKEOVER_DIR" 2>/dev/null; then + if [ -d "$TAKEOVER_DIR" ] && [ "$(dir_age_s "$TAKEOVER_DIR")" -gt 30 ]; then rm -rf "$TAKEOVER_DIR" 2>/dev/null || true; fi + if gstack_lock_take "$TAKEOVER_DIR" pid "$$"; then HOLDS_TAKEOVER=1 if [ "$(cat "$LOCK_DIR/owner" 2>/dev/null || true)" = "$owner" ] && lock_abandoned "$owner"; then rm -rf "$LOCK_DIR" 2>/dev/null || true fi - rmdir "$TAKEOVER_DIR" 2>/dev/null || true + rm -rf "$TAKEOVER_DIR" 2>/dev/null || true HOLDS_TAKEOVER="" if [ ! -e "$LOCK_DIR" ]; then continue; fi fi @@ -146,7 +149,6 @@ acquire_lock() { sleep 0.05 waited_ms=$(( waited_ms + 50 )) done - printf '%s\n' "$token" > "$LOCK_DIR/owner" LOCK_TOKEN="$token" } diff --git a/bin/gstack-ff-update b/bin/gstack-ff-update index 8ee22267af6..a385fe80e74 100755 --- a/bin/gstack-ff-update +++ b/bin/gstack-ff-update @@ -9,7 +9,8 @@ # the new revision (git show FETCH_HEAD:bin/gstack-ff-update) and run it in a # private temp directory, so it sources nothing. The lock and the # flatten-and-strip sanitizer are inlined; test/gstack-ff-update.test.ts pins -# them to their twins in bin/gstack-session-update. +# them to their twins in bin/gstack-session-update, and gstack_lock_take to +# bin/gstack-lock.sh. # # Inside an install-scoped lock (/gstack-ff.lock): # 1. The working tree is captured as-is through a private index (tracked @@ -115,18 +116,38 @@ LOCK_DIR="$COMMON/gstack-ff.lock" LOCK_TTL_MINUTES=30 MYPID=$$ OWN_INDEX_LOCK="" TMP="" HB_PID="" +# Twin of bin/gstack-lock.sh (test-pinned): mkdir's exit status is not a lock +# on Ubuntu 26.04's uutils mkdir, so the pid file is created with O_EXCL. +gstack_lock_take() { + local _gl_dir="$1" _gl_file="${2:-pid}" _gl_content="${3:-$$}" + if [ -e "$_gl_dir" ] || [ -L "$_gl_dir" ]; then return 1; fi + mkdir "$_gl_dir" 2>/dev/null || : + if [ ! -d "$_gl_dir" ] || [ -L "$_gl_dir" ]; then + if [ -e "$_gl_dir" ] || [ -L "$_gl_dir" ]; then return 1; fi + return 2 + fi + local _gl_opened + _gl_opened=$(set -o noclobber; { echo o; printf '%s\n' "$_gl_content" >&3; } 2>/dev/null 3> "$_gl_dir/$_gl_file") && return 0 + if [ "$_gl_opened" = o ]; then + rm -f "$_gl_dir/$_gl_file"; rmdir "$_gl_dir" 2>/dev/null || : + return 3 + fi + if [ -e "$_gl_dir/$_gl_file" ] || [ -L "$_gl_dir/$_gl_file" ] || [ ! -d "$_gl_dir" ]; then return 1; fi + rmdir "$_gl_dir" 2>/dev/null || : + return 3 +} lock_is_expired() { _hb="$LOCK_DIR/pid" [ -f "$_hb" ] || _hb="$LOCK_DIR" [ -n "$(find "$_hb" -maxdepth 0 -mmin +$LOCK_TTL_MINUTES 2>/dev/null)" ] } lock_try() { - mkdir "$LOCK_DIR" 2>/dev/null && return 0 + gstack_lock_take "$LOCK_DIR" pid "$MYPID" && return 0 _lp=$(cat "$LOCK_DIR/pid" 2>/dev/null) if lock_is_expired || { [ "${_lp:-0}" -gt 0 ] 2>/dev/null && ! kill -0 "$_lp" 2>/dev/null; }; then mv "$LOCK_DIR" "$LOCK_DIR.reap.$$" 2>/dev/null || return 1 rm -rf "$LOCK_DIR.reap.$$" 2>/dev/null - mkdir "$LOCK_DIR" 2>/dev/null && return 0 + gstack_lock_take "$LOCK_DIR" pid "$MYPID" && return 0 fi return 1 } @@ -145,7 +166,6 @@ until lock_try; do [ "$_wait" -gt 0 ] || refuse 75 ff-busy "another gstack update is moving $DIR (lock $LOCK_DIR held by pid $(cat "$LOCK_DIR/pid" 2>/dev/null || echo unknown)); nothing was changed, retry in a minute" sleep 1; _wait=$((_wait - 1)) done -echo "$MYPID" > "$LOCK_DIR/pid" 2>/dev/null trap cleanup_ff_update EXIT trap 'exit 129' HUP trap 'exit 130' INT diff --git a/bin/gstack-install-registry.sh b/bin/gstack-install-registry.sh index a56caf18040..7f53f9330b4 100644 --- a/bin/gstack-install-registry.sh +++ b/bin/gstack-install-registry.sh @@ -23,10 +23,12 @@ # render render directory, or 'committed' # # Callers must set GSTACK_STATE_ROOT first (bin/gstack-state-root.sh). Bash 3.2 -# clean; no flock (macOS lacks it), so the lock is an atomic mkdir. +# clean; no flock (macOS lacks it), so the lock is gstack_lock_take +# (bin/gstack-lock.sh). # Same-path and containment checks (bin/gstack-path-spelling.sh). . "$(dirname "${BASH_SOURCE[0]}")/gstack-path-spelling.sh" 2>/dev/null || true +. "$(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { echo "gstack: $(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh is missing; reinstall with ./setup" >&2; return 2; } # gstack_install_move_hint SRC HOST — when HOST's runtime root ROOT is SRC (the # checkout) or contains it, `./setup --host HOST` would replace the checkout @@ -53,15 +55,17 @@ gstack_install_registry_file() { printf '%s/installs.tsv\n' "${GSTACK_STATE_ROOT:?gstack-install-registry: GSTACK_STATE_ROOT is not set}" } -# _gstack_registry_lock — take the registry lock (mkdir is atomic). A lock whose -# owner pid is gone is stale and is broken. Gives up after ~10 s. +# _gstack_registry_lock — take the registry lock (gstack_lock_take, which +# creates the pid file with O_EXCL; mkdir's exit status is not a lock on Ubuntu +# 26.04's uutils mkdir). A lock whose owner pid is gone is stale and is broken. +# Gives up after ~10 s. _gstack_registry_lock() { local file lock tries owner file="$(gstack_install_registry_file)" || return 1 lock="$file.lock" mkdir -p "$(dirname "$file")" || return 1 tries=0 - while ! mkdir "$lock" 2>/dev/null; do + while ! gstack_lock_take "$lock" pid "$$"; do owner="$(cat "$lock/pid" 2>/dev/null || true)" if [ -n "$owner" ] && ! kill -0 "$owner" 2>/dev/null; then rm -rf "$lock" @@ -74,7 +78,6 @@ _gstack_registry_lock() { fi sleep 0.1 done - echo "$$" > "$lock/pid" } _gstack_registry_unlock() { diff --git a/bin/gstack-lease b/bin/gstack-lease index 25b50870020..ea6b05f4202 100755 --- a/bin/gstack-lease +++ b/bin/gstack-lease @@ -55,6 +55,8 @@ BIN="$(cd "$(dirname "$0")" && pwd -P)" gstack_harness_pid() { printf '%s\n' "$1"; } gstack_shared_harness() { [ "$(ps -o comm= -p "$1" 2>/dev/null | head -1 | sed 's|.*/||; s/^-//')" = capy-server ]; } } +# shellcheck source=bin/gstack-lock.sh +. "$BIN/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { echo "gstack-lease: $BIN/gstack-lock.sh is missing; reinstall with ./setup" >&2; return 2; } VERB="${1:-}"; [ $# -gt 0 ] && shift ROOT="" PID="" EXCLUDE="" FROM="" SHARED=0 RUN="" @@ -119,21 +121,22 @@ state() { # The lease directory's lock: touch's publish and prune, and reclaim's # reread-and-delete, run under it, so a reclaim never deletes a renewal and a # lease never disappears while it is live. The lock is a directory, .lock, -# whose owner file names its holder (` `); mkdir is -# atomic everywhere gstack runs, Git Bash on Windows included, where ln -s to a -# target that does not exist always fails (#3330). A taker publishes its token -# as a claim (.lock.claim.) before its mkdir and renames the claim into -# the lock as its owner after, so a lock without an owner is either being +# whose owner file names its holder (` `). It is taken +# with gstack_lock_take (bin/gstack-lock.sh), which creates the owner file +# with O_EXCL: mkdir's exit status is not a lock on Ubuntu 26.04's uutils +# mkdir, and ln -s to a target that does not exist always fails on Git Bash +# (#3330). A taker publishes its token as a claim (.lock.claim.) before +# its mkdir and creates the owner file after, so a lock without an owner is either being # taken by a live claimant or orphaned by a dead one. A lock is broken only # when its holder is dead or its pid now belongs to another process, never by # age, and unlock removes only the caller's own lock. An ownerless lock is # broken once no claimant lives and it is at least 2 s old (and unchanged -# while it was checked), so a taker between its mkdir and its owner rename is +# while it was checked), so a taker between its mkdir and its owner create is # never taken for a crash, even when its claim landed after the claims were # read. A claim is honored while its claimant lives; one that records no # start identity (so a reused pid cannot be told apart) is abandoned after 2 # minutes, since a live taker holds one for milliseconds. Known limit: on such -# a host a taker stalled over 2 minutes between its mkdir and its owner rename +# a host a taker stalled over 2 minutes between its mkdir and its owner create # can be broken and then publish into its successor's lock. An owner whose # pid is 0, zero-padded or not a number counts as a dead holder, and a lock # whose owner file exists but cannot be read is never treated as ownerless. A symlink .lock left by an older @@ -148,10 +151,7 @@ LOCK="$DIR/.lock" TOKEN="" take() { if [ -e "$1" ] || [ -L "$1" ]; then return 1; fi { printf '%s\n' "$TOKEN" > "$1.claim.$$"; } 2>/dev/null || { rm -f "$1.claim.$$"; return 1; } - if mkdir "$1" 2>/dev/null; then - [ ! -e "$1/owner" ] && mv -f "$1.claim.$$" "$1/owner" && return 0 - [ -e "$1/owner" ] || rm -rf "$1" - fi + if gstack_lock_take "$1" owner "$TOKEN"; then rm -f "$1.claim.$$"; return 0; fi rm -f "$1.claim.$$" return 1 } @@ -162,8 +162,9 @@ mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null; } # missing or readable and empty, has no live claimant, is at least 2 s old and kept # its mtime throughout. The clock is read before the first mtime, so a pause # only makes the lock look younger, and a lock made since (a new generation) -# has a newer mtime. Claims are read before the owner, so a taker that renames -# its claim in between is seen as the owner. An empty claim is a taker that +# has a newer mtime. Claims are read before the owner, and a taker removes its +# claim only after its owner file is written, so a taker that finishes in +# between is seen as the owner. An empty claim is a taker that # has not reached its mkdir, so it never made this lock. An mtime a minute or # more in the future (clock skew) counts as old. orphaned() { diff --git a/bin/gstack-lock.sh b/bin/gstack-lock.sh new file mode 100644 index 00000000000..fee3e71ad79 --- /dev/null +++ b/bin/gstack-lock.sh @@ -0,0 +1,48 @@ +# shellcheck shell=bash +# gstack-lock.sh — the one way gstack shell code takes a lock directory. +# +# Source it, then call: +# +# gstack_lock_take DIR [FILE] [CONTENT] +# Take the lock DIR by creating DIR/FILE (default `pid`) holding CONTENT +# (default $$). Returns 0 when this shell took the lock, 1 when it is held +# (DIR already existed, or another process created FILE first), 2 when DIR +# could not be created (missing or unwritable parent, read-only filesystem) +# and 3 when DIR was made but FILE could not be created or fully written +# in it (disk full, quota, a file-size limit; FILE and DIR are removed +# again, so a failed write never leaves a lock nobody holds). Neither 2 +# nor 3 is evidence of a competing holder. +# +# Why not `mkdir DIR && ...`: mkdir's exit status is not a lock. Rust +# coreutils (uutils) 0.8.0, the mkdir on Ubuntu 26.04 and on GitHub's +# ubuntu-latest from 2026-11-09, reports success when another process created +# the directory first, so two racing callers could both think they held it. +# Here mkdir only makes the directory and its status is ignored. The arbiter is +# the shell's noclobber redirect, which bash, zsh and dash open with +# O_CREAT|O_EXCL themselves (no external binary), so the kernel lets exactly one +# caller create FILE. flock(1) is not used: stock macOS does not ship it. +# +# A DIR that exists before the call is never taken, even with no FILE in it, so +# a lock left by a holder killed between mkdir and FILE stays held until the +# caller's own stale-lock recovery removes it, exactly as before. Callers keep +# their own waiting, staleness, takeover and release logic; the owner still +# releases with `rm -rf DIR`. Safe under set -e and set -u, and noclobber never +# leaks into the caller's shell. +gstack_lock_take() { + local _gl_dir="$1" _gl_file="${2:-pid}" _gl_content="${3:-$$}" + if [ -e "$_gl_dir" ] || [ -L "$_gl_dir" ]; then return 1; fi + mkdir "$_gl_dir" 2>/dev/null || : + if [ ! -d "$_gl_dir" ] || [ -L "$_gl_dir" ]; then + if [ -e "$_gl_dir" ] || [ -L "$_gl_dir" ]; then return 1; fi + return 2 + fi + local _gl_opened + _gl_opened=$(set -o noclobber; { echo o; printf '%s\n' "$_gl_content" >&3; } 2>/dev/null 3> "$_gl_dir/$_gl_file") && return 0 + if [ "$_gl_opened" = o ]; then + rm -f "$_gl_dir/$_gl_file"; rmdir "$_gl_dir" 2>/dev/null || : + return 3 + fi + if [ -e "$_gl_dir/$_gl_file" ] || [ -L "$_gl_dir/$_gl_file" ] || [ ! -d "$_gl_dir" ]; then return 1; fi + rmdir "$_gl_dir" 2>/dev/null || : + return 3 +} diff --git a/bin/gstack-memorable b/bin/gstack-memorable index 558767b1418..0556c010129 100755 --- a/bin/gstack-memorable +++ b/bin/gstack-memorable @@ -105,11 +105,14 @@ _lock_release() { _lock_acquire() { mkdir -p "$STATE_DIR/locks" 2>/dev/null || { _err "cannot create $STATE_DIR/locks (state directory not writable; nothing can be recorded there)"; return 5; } local tries=0 mtime now stale judged moved owner_pid - while ! mkdir "$LOCK_DIR" 2>/dev/null; do + . "$SCRIPT_DIR/gstack-lock.sh" 2>/dev/null || { _err "$SCRIPT_DIR/gstack-lock.sh is missing (fix: reinstall with ./setup or /gstack-upgrade)"; return 5; } + while ! gstack_lock_take "$LOCK_DIR" owner "$$"; do tries=$((tries + 1)) - # Staleness from the directory's own mtime (set atomically by the holder's - # mkdir), never from a file written after it: a contender that looks in - # the gap between mkdir and bookkeeping must wait, not reclaim. GNU stat + # Staleness from the directory's own mtime (set by the holder's mkdir and + # owner create), never from the owner's content: a contender that looks in + # the gap between mkdir and the owner file must wait, not reclaim. The + # owner file is the lock (gstack_lock_take creates it with O_EXCL, since + # mkdir's exit status is not a lock on Ubuntu 26.04's uutils mkdir). GNU stat # first, BSD stat second, garbage -> no takeover (same idiom as # bin/gstack-settings-hook). mtime="$(stat -c %Y "$LOCK_DIR" 2>/dev/null || stat -f %m "$LOCK_DIR" 2>/dev/null || echo "")" @@ -143,7 +146,6 @@ _lock_acquire() { if [ "$tries" -ge "$LOCK_TRIES" ]; then _err "another gstack-memorable is running (lock $LOCK_DIR; stale but not reclaimable if older than ${LOCK_STALE_S}s); try again"; return 5; fi sleep "$LOCK_SLEEP" done - printf '%s\n' "$$" > "$LOCK_DIR/owner" LOCK_HELD=1 trap _lock_release EXIT } diff --git a/bin/gstack-render-claude.sh b/bin/gstack-render-claude.sh index c7b06c4cd14..f626461cc8f 100644 --- a/bin/gstack-render-claude.sh +++ b/bin/gstack-render-claude.sh @@ -1,5 +1,6 @@ # gstack-render-claude.sh — the Claude skill render shared by ./setup and -# `gstack-config gbrain-refresh`. Source it; it only defines functions. +# `gstack-config gbrain-refresh`. Source it; it only defines functions, and +# sources bin/gstack-lock.sh beside it for the render lock. # bash-3.2-clean and safe under `set -euo pipefail`. # # Overlay selection is opt-in: the overlay is the family of the persisted @@ -26,6 +27,8 @@ # their tested copy) and may define `log` and `bun_cmd`; plain echo and bun # are used otherwise. +. "$(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { echo "gstack: $(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh is missing; reinstall with ./setup" >&2; return 2; } + _gstack_render_say() { if declare -F log >/dev/null 2>&1; then log "$@"; else echo "$@"; fi } @@ -84,12 +87,13 @@ gstack_claude_overlay_field() { } # gstack_render_lock DIR / gstack_render_unlock DIR — serialize the swap and -# record write of concurrent renders (mkdir lock, no flock). A lock whose -# holder is gone is broken; after 30 s the swap proceeds unlocked. +# record write of concurrent renders (gstack_lock_take from bin/gstack-lock.sh, +# no flock). A lock whose holder is gone is broken; after 30 s the swap +# proceeds unlocked. gstack_render_lock() { local lock="$1.lock" i=0 pid mkdir -p "$(dirname "$1")" 2>/dev/null || true - while ! mkdir "$lock" 2>/dev/null; do + while ! gstack_lock_take "$lock" pid "$$"; do pid="$(cat "$lock/pid" 2>/dev/null || true)" if [ -n "$pid" ] && ! kill -0 "$pid" 2>/dev/null; then rm -rf "$lock" @@ -99,7 +103,6 @@ gstack_render_lock() { [ "$i" -lt 300 ] || return 0 sleep 0.1 done - echo "$$" > "$lock/pid" } gstack_render_unlock() { rm -rf "$1.lock" diff --git a/bin/gstack-session-update b/bin/gstack-session-update index 60ac42c995f..78a8cdfa56b 100755 --- a/bin/gstack-session-update +++ b/bin/gstack-session-update @@ -315,7 +315,10 @@ CALLER_PID=$(gstack_harness_pid "$PPID") # holder touches the pidfile at step boundaries (after the pull, after # setup), so a legitimately-slow run keeps itself alive. The TTL also # bounds the missing/empty-pidfile states: inside the window they mean - # "just acquired, between mkdir and echo" and are respected. + # "just acquired, between mkdir and the pid write" and are respected. + # The take itself is gstack_lock_take (bin/gstack-lock.sh): it creates the + # pidfile with O_EXCL, because mkdir's exit status is not a lock on Ubuntu + # 26.04's uutils mkdir (two racing updaters both "won" it). LOCK_TTL_MINUTES=30 lock_is_expired() { _hb="$LOCK_DIR/pid" @@ -327,11 +330,18 @@ CALLER_PID=$(gstack_harness_pid "$PPID") # mkdir (one rm can land between the other's rm and mkdir). `mv` of the lock # dir is atomic — exactly one contender's mv succeeds; the loser's mv fails # (ENOENT) and it backs off. The winner reaps the moved-aside dir at leisure. - if ! mkdir "$LOCK_DIR" 2>/dev/null; then + # + # The pidfile holds the HOLDER's PID (see #2613 note above; macOS ships + # bash 3.2 with no BASHPID — the sh child's $PPID IS this subshell, so the + # fallback is exact there). MYPID is captured once, before the take, so the + # trap below can prove ownership before removing. + MYPID="${BASHPID:-$(sh -c 'echo $PPID')}" + . "$(cd "$(dirname "$0")" && pwd)/gstack-lock.sh" 2>/dev/null || { log_entry "SKIP lock_helper_missing"; exit 0; } + if ! gstack_lock_take "$LOCK_DIR" pid "$MYPID"; then if lock_is_expired; then mv "$LOCK_DIR" "$LOCK_DIR.reap.$$" 2>/dev/null || { log_entry "SKIP lock_contested"; exit 0; } rm -rf "$LOCK_DIR.reap.$$" 2>/dev/null - mkdir "$LOCK_DIR" 2>/dev/null || { log_entry "SKIP lock_contested"; exit 0; } + gstack_lock_take "$LOCK_DIR" pid "$MYPID" || { log_entry "SKIP lock_contested"; exit 0; } log_entry "RECLAIMED lock_ttl_expired" elif [ -f "$LOCK_DIR/pid" ]; then LOCK_PID=$(cat "$LOCK_DIR/pid" 2>/dev/null || echo 0) @@ -339,7 +349,7 @@ CALLER_PID=$(gstack_harness_pid "$PPID") # Stale lock — mv aside atomically (see reclaim note above), re-acquire mv "$LOCK_DIR" "$LOCK_DIR.reap.$$" 2>/dev/null || { log_entry "SKIP lock_contested"; exit 0; } rm -rf "$LOCK_DIR.reap.$$" 2>/dev/null - mkdir "$LOCK_DIR" 2>/dev/null || { log_entry "SKIP lock_contested"; exit 0; } + gstack_lock_take "$LOCK_DIR" pid "$MYPID" || { log_entry "SKIP lock_contested"; exit 0; } else # Live holder — or an empty/non-numeric pidfile inside the TTL # window (the -gt test fails on garbage, landing here by design). @@ -347,19 +357,12 @@ CALLER_PID=$(gstack_harness_pid "$PPID") exit 0 fi else - # Missing pidfile inside the TTL window: just-acquired (mkdir→echo race). + # Missing pidfile inside the TTL window: just-acquired (mkdir→pid race). log_entry "SKIP locked_no_pid" exit 0 fi fi - # Write the HOLDER's PID for stale lock detection (see #2613 note above; - # macOS ships bash 3.2 with no BASHPID — the sh child's $PPID IS this - # subshell, so the fallback is exact there). MYPID is captured once at - # write time so the trap below can prove ownership before removing. - MYPID="${BASHPID:-$(sh -c 'echo $PPID')}" - echo "$MYPID" > "$LOCK_DIR/pid" 2>/dev/null - # In-flight heartbeat: the step-boundary touches below only fire AFTER the # pull / setup return, so a legitimately-slow step (cold clone, huge setup) # older than the TTL got reclaimed while ALIVE. This background loop diff --git a/bin/gstack-settings-hook b/bin/gstack-settings-hook index f7005384cba..bf63cd84efa 100755 --- a/bin/gstack-settings-hook +++ b/bin/gstack-settings-hook @@ -47,8 +47,10 @@ # treated as an owned legacy stray. # # Mutation safety: -# - every mutation runs under a mkdir lock (.lock/) with an owner -# token; release is ownership-checked; stale locks (>30s) are taken over +# - every mutation runs under a lock directory (.lock/) whose owner +# token file is created with O_EXCL (gstack_lock_take, bin/gstack-lock.sh; +# mkdir's exit status is not a lock on Ubuntu 26.04's uutils mkdir); +# release is ownership-checked; stale locks (>30s) are taken over # via atomic rename. On lock give-up the mutation is SKIPPED with a warning # (the next setup retries — the system is convergent). # - parse failure fails CLOSED: a corrupt settings.json is never overwritten @@ -353,18 +355,18 @@ _acquire_lock() { local stale_after_s=30 # lock older than this belongs to a crashed holder local poll_ms=50 # retry cadence; sleep below derives from this token="$$-$RANDOM$RANDOM" + . "$(cd "$(dirname "$0")" && pwd)/gstack-lock.sh" 2>/dev/null || { echo "gstack-settings-hook: $(dirname "$0")/gstack-lock.sh is missing -- skipping this mutation, exit 5 (fix: reinstall with ./setup)" >&2; return 1; } while :; do - if mkdir "$_LOCK_DIR" 2>/dev/null; then - printf '%s\n' "$token" > "$_LOCK_DIR/owner" 2>/dev/null || true + if gstack_lock_take "$_LOCK_DIR" owner "$token"; then _LOCK_TOKEN="$token" trap _release_lock EXIT trap 'exit 129' INT trap 'exit 143' TERM return 0 fi - # mkdir failed but no lock dir exists: either a holder released between - # our mkdir and this check, or NOT contention (unwritable parent, read-only - # fs, missing directory). Retry mkdir once; a second failure with still no + # The take failed but no lock dir exists: either a holder released between + # our take and this check, or NOT contention (unwritable parent, read-only + # fs, missing directory). Retry the take once; a second failure with still no # lock dir is the environment, and waiting cannot help, so give up loudly # now instead of spinning out the full timeout. if [ ! -e "$_LOCK_DIR" ]; then diff --git a/bin/gstack-upgrade b/bin/gstack-upgrade index 6f933b42413..a335b0dd58b 100755 --- a/bin/gstack-upgrade +++ b/bin/gstack-upgrade @@ -251,8 +251,10 @@ if [ -n "${GSTACK_SETUP_LOCK_OWNER:-}" ] && [ "$(cat "$LOCK_DIR/pid" 2>/dev/null LOCK_HANDED=1 else mkdir -p "$GSTACK_STATE_ROOT" 2>/dev/null - mkdir "$LOCK_DIR" 2>/dev/null || refuse "another gstack updater holds $LOCK_DIR (pid $(cat "$LOCK_DIR/pid" 2>/dev/null || echo unknown))" "wait for it to finish, then re-run" - echo "$$" > "$LOCK_DIR/pid" + . "$ROOT/bin/gstack-lock.sh" 2>/dev/null || refuse "$ROOT/bin/gstack-lock.sh is missing" "reinstall with cd $ROOT && ./setup" + # gstack_lock_take creates the pid file with O_EXCL: mkdir's exit status is + # not a lock on Ubuntu 26.04's uutils mkdir. + gstack_lock_take "$LOCK_DIR" pid "$$" || refuse "another gstack updater holds $LOCK_DIR (pid $(cat "$LOCK_DIR/pid" 2>/dev/null || echo unknown))" "wait for it to finish, then re-run" trap '[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$$" ] && rm -rf "$LOCK_DIR" 2>/dev/null' EXIT fi diff --git a/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md b/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md new file mode 100644 index 00000000000..baa8e65604f --- /dev/null +++ b/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md @@ -0,0 +1,5 @@ +--- +important: blocker +--- +- **gstack's shell locks hold again on Ubuntu 26.04, where `mkdir` reports success when another process won the race (GST-2247).** Ubuntu 26.04, and GitHub's `ubuntu-latest` from 2026-11-09, ships Rust coreutils (uutils) 0.8.0 as `mkdir`. It exits 0 even when the directory already existed because a racing process just made it, so every `mkdir "$LOCK"` lock in gstack could admit two holders: two updates moving one checkout at once, or two `gstack-config set` calls where one dropped the other's key (a test with eight parallel writers under a uutils-style `mkdir` lost six of the eight keys). Every lock now goes through one helper, `gstack_lock_take` in `bin/gstack-lock.sh`: `mkdir` only makes the directory, and the holder is whoever creates the lock's pid or owner file with the shell's noclobber redirect, which bash, zsh and dash open `O_CREAT|O_EXCL`, so the kernel admits exactly one. No `flock` (macOS has none). This covers the session-start updater, `gstack-upgrade`, the Capy session pin switch, `gstack-ff-update` (inlined, pinned to the helper by a test, because it must run standalone), setup's dependency-migration and Chromium-install locks, `gstack-browser-ensure`, `gstack-config`, the install registry, the Claude render lock, the developer profile and its takeover lock, `gstack-memorable`, the settings.json hook, the brain-sync drain lock, the Codex model-probe lock and its breaker, the lease directory lock, freeze's state lock and /setup-gbrain's concurrent-run lock. The Claude Code wrapper's copied runtime (`CLAUDE_CODE_RUNTIME_FILES`) and `bin/gstack-render-claude.sh` now carry or source the helper themselves, so a copied runtime and every script that sources the render library still take the lock. Each caller keeps its own waiting, stale-lock recovery, timeout and release. If the owner file is created but can't be fully written (disk full, a quota or a file-size limit), the helper removes it and the directory again and returns 3, so a failed write never leaves a lock that nobody holds. A lock directory that already exists is still never taken, even with no owner file in it, so a lock left by a killed holder waits for the caller's existing stale rule, as before. +- `test/gstack-lock-race.test.ts` runs the old pattern and the helper against a PATH shim that behaves like uutils 0.8.0 `mkdir`, so it runs on any runner image: the old pattern lets two of four racers win, the helper admits exactly one in each of 60 races and never overlaps across take, hold and release loops, and parallel `gstack-config` writers keep every key. `test/mkdir-lock-guard.test.ts` fails when shipped shell, a template, a workflow, a Markdown bash fence or TypeScript that embeds shell decides anything on a non-`-p` `mkdir`'s exit status; it found 26 such sites before this change, 12 more than the first report listed. The /setup-gbrain lock test now expects `mkdir:` on stderr only when the parent cannot be created, because the helper never runs `mkdir` on a path that already exists; no other assertion, threshold or timeout changed. diff --git a/docs/capy-install.md b/docs/capy-install.md index 9c6e40e5a99..df3aeaac027 100644 --- a/docs/capy-install.md +++ b/docs/capy-install.md @@ -254,9 +254,11 @@ by rename, prune) and reclaim (reread, then delete only the record judged stale) run under one lock in the lease directory, a `.lock` directory whose `owner` file names its holder's pid and start identity, so a renewal is never deleted and a live lease never disappears from a concurrent scan. The lock is a -directory because `mkdir` is atomic on every host, while Git Bash on Windows -cannot `ln -s` to a target that does not exist (#3330). A taker publishes a -claim before its `mkdir` and renames it in as the owner after, so an ownerless +directory taken with `gstack_lock_take` (`bin/gstack-lock.sh`), which creates +the `owner` file with O_EXCL, because `mkdir`'s exit status is no lock on +Ubuntu 26.04's uutils `mkdir` and Git Bash on Windows cannot `ln -s` to a +target that does not exist (#3330). A taker publishes a claim before its +`mkdir` and removes it only after its owner file is written, so an ownerless lock is broken only once no claimant lives and the lock is at least 2 s old and unchanged while checked, which keeps a taker between its two steps safe. A claim that records no start identity is abandoned after 2 minutes, so a diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 84064e69a8d..49b423b6f80 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -1882,6 +1882,36 @@ A `tracked-by-project` or `version-reverted` cause has its own section: listed changes, check out the default branch, move local commits to another branch), then re-run `bin/gstack-upgrade`. A reinstall that failed after the fast-forward is completed by the next run (`reinstall pending from `). +For `another gstack updater holds /.setup-lock (pid )`, wait +for that update to finish. If no gstack update is running (`kill -0 ` +fails, or the pid reads `unknown` because the holder was killed before it +wrote one), remove the lock with `rm -rf /.setup-lock` and +re-run. See [how gstack's shell locks work](#shell-locks). + + +### Two gstack updates, setups or config writes ran at once (Ubuntu 26.04, uutils `mkdir`) + +**Meaning.** gstack's shell locks (the updater's `.setup-lock`, the config +lock `.config-yaml.lock`, the install registry, the developer profile, +settings.json, the Chromium install, the brain-sync drain, freeze and the +lease directory) are lock directories. Older gstack held one when +`mkdir ` succeeded. Rust coreutils (uutils) 0.8.0, the `mkdir` on +Ubuntu 26.04 and on GitHub's `ubuntu-latest` from 2026-11-09, reports success +even when another process created the directory first, so two racing callers +could both hold the lock: two updates moving one checkout, or two +`gstack-config set` calls where one write dropped the other's key. GNU and +BSD `mkdir` never did this. + +**Fix.** Upgrade gstack (`/gstack-upgrade`). Every lock is now taken by +`gstack_lock_take` in `bin/gstack-lock.sh`: `mkdir` only makes the +directory, and the holder is whoever creates its `pid` (or `owner`) file +with the shell's noclobber redirect, which opens it `O_CREAT|O_EXCL`, so +exactly one caller wins whatever `mkdir` reports. Waiting, stale-lock +recovery and release are unchanged. A lock directory with no owner file +inside, left by a process killed while taking it, still counts as held until +the caller's own stale-lock rule clears it; when nothing is running, remove it +with `rm -rf `. Re-set any config key you set during a concurrent write +on 26.04 (`gstack-config get ` shows what stuck). ### `gstack-upgrade: live gstack sessions hold this installation: pid

(m), ...; nothing was changed; fix: ... (UPGRADE_BUSY)` / `gstack-upgrade: a shared harness (capy-server, pid

) holds a lease m old; ... (UPGRADE_BUSY)` diff --git a/freeze/bin/freeze-state.sh b/freeze/bin/freeze-state.sh index ad61b80cd28..98582fa11a4 100755 --- a/freeze/bin/freeze-state.sh +++ b/freeze/bin/freeze-state.sh @@ -15,7 +15,8 @@ mutex="$STATE_DIR/.freeze-mutation.lock" action="${1:-}" case "$action" in acquire|set|release|clear) ;; *) echo 'Usage: freeze-state.sh acquire|set DIRECTORY | release OWNER | clear' >&2; exit 2 ;; esac -if ! mkdir "$mutex" 2>/dev/null; then +. "$_here/../../bin/gstack-lock.sh" 2>/dev/null || { echo "FREEZE_ERROR: $_here/../../bin/gstack-lock.sh is missing. No boundary changed. Fix: reinstall with ./setup or /gstack-upgrade." >&2; exit 1; } +if ! gstack_lock_take "$mutex" pid "$$"; then echo 'FREEZE_BUSY: another writer or an interrupted mutation owns the state lock. Retry after it finishes; if abandoned, inspect it with the user before recovery. No boundary changed.' >&2 exit 1 fi @@ -23,7 +24,7 @@ temp="" finish() { local rc=$? [ -z "$temp" ] || rm -f -- "$temp" - rmdir "$mutex" + rm -rf -- "$mutex" exit "$rc" } trap finish EXIT diff --git a/lib/claude-code-migration.ts b/lib/claude-code-migration.ts index 3dd45f229bd..31c7da30fee 100644 --- a/lib/claude-code-migration.ts +++ b/lib/claude-code-migration.ts @@ -9,7 +9,7 @@ const OLD = 'gstack-claude'; const NEXT = 'gstack-claude-code'; const BANNER = '\n

Agent notes\n\n" + content + "\n\n
\n"; const composed = (head: string, summary: string) => "Opening sentence.\n\n## Summary\n\n" + summary + "\n\n## Test plan\n\n- [x] bun test\n\n" + NOTES("Plan: exempt: docs-only\n\n" + RECEIPT(head).trim()); + /** The run history a /ship body post keeps right after its receipt: the replaced receipt joins the runs block (GST-2706). */ + const RUNS_AAAA = "\n```gstack-receipt-runs\n" + JSON.stringify({ head: "aaaa" }) + "\n```\n"; // Value: protects=the body /ship composes since GST-1825 (opening, sections, Agent notes last) reposts byte for byte and replaces the notes as one // section; fails_when=the receipt inside the notes is split out as its own section, or the notes stop being last; why_new=the notes section is new; // seam=none (mergeBodySections); no_claim=the gh round trip test("a full post whose notes section is last reposts byte for byte and replaces the notes, receipt included, as one section", () => { const first = mergeBodySections(composed("aaaa", "old"), composed("bbbb", "new")); - expect(first.body).toBe(composed("bbbb", "new")); + expect(first.body.replace(RUNS_AAAA, "")).toBe(composed("bbbb", "new")); + expect(receiptRuns(first.body).map(r => r.head)).toEqual(["aaaa"]); expect([first.replaced, first.kept, first.added, first.dropped]).toEqual([["leading text", "Summary", "Test plan", "Agent notes"], [], [], []]); - expect(mergeBodySections(first.body, composed("bbbb", "new")).body).toBe(composed("bbbb", "new")); + expect(mergeBodySections(first.body, composed("bbbb", "new")).body).toBe(first.body); + }); + + // Value: protects=the kept run history lands in the Agent notes the receipt is read from, and the readable part keeps its bytes; + // fails_when=keepRuns searches the whole body and splices the runs block into a receipt fence the Summary quotes; why_new=keepRuns is new + // (GST-2706); seam=none (mergeBodySections); no_claim=the gh round trip + test("a /ship body post keeps the runs block in Agent notes when the readable part quotes a receipt fence", () => { + const ex = "~~~\n" + RECEIPT("example").trim() + "\n~~~"; + const first = mergeBodySections(composed("aaaa", ex), composed("bbbb", ex)); + expect(receiptRuns(first.body).map(r => r.head)).toEqual(["aaaa"]); + expect(first.body.replace(RUNS_AAAA, "")).toBe(composed("bbbb", ex)); }); // Value: protects=a partial post keeps the current notes and they stay last, above a Capy badge that ends the body; fails_when=a new section is @@ -917,7 +930,8 @@ describe("gstack-post keeps the Agent notes section last", () => { const partial = mergeBodySections(legacy, "## Summary\n\nnew\n"); expect(partial.body).toBe(RECEIPT("aaaa") + "\n## Summary\n\nnew\n\n## Approvals\n\nPlan: exempt: docs-only\n"); const full = mergeBodySections(legacy, composed("bbbb", "new")); - expect(full.body).toBe("Opening sentence.\n\n## Summary\n\nnew\n\n## Approvals\n\nPlan: exempt: docs-only\n\n## Test plan\n\n- [x] bun test\n\n" + NOTES("Plan: exempt: docs-only\n\n" + RECEIPT("bbbb").trim())); + expect(receiptRuns(full.body).map(r => r.head)).toEqual(["aaaa"]); + expect(full.body.replace(RUNS_AAAA, "")).toBe("Opening sentence.\n\n## Summary\n\nnew\n\n## Approvals\n\nPlan: exempt: docs-only\n\n## Test plan\n\n- [x] bun test\n\n" + NOTES("Plan: exempt: docs-only\n\n" + RECEIPT("bbbb").trim())); expect(full.body.match(/```gstack-ship-receipt/g)).toHaveLength(1); expect(full.replaced).toEqual(["ship receipt", "Summary"]); }); diff --git a/test/no-stop.test.ts b/test/no-stop.test.ts index ee439d6a666..2a058f08498 100644 --- a/test/no-stop.test.ts +++ b/test/no-stop.test.ts @@ -1,7 +1,7 @@ /** - * The five no-stop defaults (GSTA-258 K1, lib/no-stop.ts, bin/gstack-no-stop): each routine stop that qualifies is + * The four no-stop defaults (GSTA-258 K1, lib/no-stop.ts, bin/gstack-no-stop): each routine stop that qualifies is * recorded as {class, reason, evidence} and the run goes on; anything that does not qualify, and any stop outside - * the five, still stops for the owner. The autoplan re-gate is covered in test/autoplan-carry.test.ts. + * the four, still stops for the owner. The autoplan re-gate is covered in test/autoplan-carry.test.ts. */ import { afterAll, describe, expect, test } from 'bun:test'; import { spawnSync } from 'node:child_process'; @@ -11,7 +11,7 @@ import * as path from 'node:path'; import { bunIsolationArgs } from '../lib/bun-isolation'; import { validateReceipt } from '../lib/ship-receipt'; import { lineDiff } from '../lib/autoplan-confirm'; -import { checkNoStop, notEli5Only, notStampOnly, parseDiff, type NoStopRecord } from '../lib/no-stop'; +import { checkNoStop, notEli5Only, parseDiff, type NoStopRecord } from '../lib/no-stop'; const ROOT = path.resolve(import.meta.dir, '..'); const BIN = path.join(ROOT, 'bin', 'gstack-no-stop'); @@ -54,16 +54,13 @@ describe('lib/no-stop: what qualifies', () => { expect(check('pregate-flake-rerun', undefined, [{ class: 'pregate-flake-rerun', reason: 'x', evidence: 'y' }])).toMatchObject({ ok: false }); }); - test('stamp-only-carry: a version-only VERSION or package.json move qualifies; a dependency or a product file stops', () => { + test('stamp-only-carry is gone (GST-2706): a refused carry already goes on to Steps 2-16, so there is no stop to record past', () => { const stamp = diff('package.json', [' "version": "1.94.41.0",'], [' "version": "1.94.42.0",']) + diff('VERSION', ['1.94.41.0'], ['1.94.42.0']); - expect(check('stamp-only-carry', stamp)).toMatchObject({ ok: true, detail: 'version stamp only in package.json, VERSION' }); - expect(notStampOnly(parseDiff(diff('package.json', [' "zod": "3.0.0",'], [' "zod": "4.0.0",'])))).toContain('changes more than the version'); - expect(check('stamp-only-carry', diff('package.json', [' "dev": "bun run a",'], [' "dev": "bun run b",']))).toMatchObject({ ok: false, reason: expect.stringContaining('more than the version') }); - expect(check('stamp-only-carry', stamp + diff('lib/worker.ts', ['a'], ['b']))).toMatchObject({ ok: false, reason: 'lib/worker.ts is not a stamp file' }); + expect(check('stamp-only-carry', stamp)).toMatchObject({ ok: false, reason: expect.stringContaining('not one of the four no-stop classes') }); }); - test('anything outside the five, a missing reason or evidence, or a hand-recorded re-gate still stops', () => { - expect(check('merge-anyway')).toMatchObject({ ok: false, reason: expect.stringContaining('not one of the five') }); + test('anything outside the four, a missing reason or evidence, or a hand-recorded re-gate still stops', () => { + expect(check('merge-anyway')).toMatchObject({ ok: false, reason: expect.stringContaining('not one of the four') }); expect(checkNoStop({ cls: 'pregate-flake-rerun', reason: ' ', evidence: 'run 1', prior: [] })).toMatchObject({ ok: false }); expect(check('autoplan-regate')).toMatchObject({ ok: false, reason: expect.stringContaining('gstack-autoplan decides') }); }); @@ -153,13 +150,13 @@ describe('gstack-no-stop record: the ledger, the grant and the receipt', () => { expect(r.stderr).toContain('the approval record already holds this branch\'s K1 grant'); }); - test('a class outside the five stops, and the range-based classes need --range-base', () => { + test('a class outside the four stops, and the range-based classes need --range-base', () => { expect(run('record', '--class', 'merge-anyway', '--reason', 'r', '--evidence', 'e').status).toBe(3); - expect(run('record', '--class', 'stamp-only-carry', '--reason', 'r', '--evidence', 'e').status).toBe(2); + expect(run('record', '--class', 'test-timeout-fix', '--reason', 'r', '--evidence', 'e').status).toBe(2); }); }); -describe('gstack-no-stop record --class stamp-only-carry --base, and import', () => { +describe('gstack-no-stop record after a base merge and a restamp, and import', () => { const work = path.join(tmp, 'stamp'); const env = { ...process.env, ...ID, GSTACK_STATE_ROOT: path.join(tmp, 'state2'), GSTACK_APPROVALS_DIR: path.join(tmp, 'approvals2') }; const git = (...args: string[]) => { @@ -182,30 +179,11 @@ describe('gstack-no-stop record --class stamp-only-carry --base, and import', () spawnSync('git', ['merge', '-q', 'main', '-m', 'merge main'], { cwd: work, encoding: 'utf8', timeout: 30_000, env }); write('VERSION', '1.0.3.0\n'); git('add', '-A'); git('commit', '-qm', 'merge main + stamp'); - test('a base merge plus a version stamp qualifies against the receipt head merged into the base', () => { - const r = run('record', '--class', 'stamp-only-carry', '--range-base', receiptHead, '--base', 'main', '--reason', 'restamp after the base moved', '--evidence', `commit ${git('rev-parse', 'HEAD').slice(0, 12)}`); - expect(r.status, r.stderr).toBe(0); - expect(r.stdout).toMatch(/^NO_STOP: stamp-only-carry recorded \(version stamp only in VERSION\)$/m); - const plain = run('record', '--class', 'stamp-only-carry', '--range-base', receiptHead, '--reason', 'r', '--evidence', 'e'); - expect(plain.status).toBe(3); - expect(plain.stderr).toContain('other.ts is not a stamp file'); - }); - - test('a product edit inside the stamp commit still stops', () => { - write('app.ts', 'export const a = 3;\n'); write('VERSION', '1.0.4.0\n'); git('commit', '-qam', 'stamp plus a sneaky edit'); - const r = run('record', '--class', 'stamp-only-carry', '--range-base', receiptHead, '--base', 'main', '--reason', 'r', '--evidence', 'e'); + test('a base merge plus a version stamp records nothing: the refused carry runs Steps 2-16 with no stop to skip (GST-2706)', () => { + const r = run('record', '--class', 'stamp-only-carry', '--range-base', receiptHead, '--reason', 'restamp after the base moved', '--evidence', `commit ${git('rev-parse', 'HEAD').slice(0, 12)}`); expect(r.status).toBe(3); - expect(r.stderr).toContain('app.ts is not a stamp file'); - }); - - test('a rename into changelog.d with an edit is a deletion plus an add, so it still stops', () => { - write('notes.md', 'one\ntwo\nthree\nfour\nfive\nsix\n'); git('add', '-A'); git('commit', '-qm', 'notes'); - const from = git('rev-parse', 'HEAD'); - fs.mkdirSync(path.join(work, 'changelog.d'), { recursive: true }); - git('mv', 'notes.md', 'changelog.d/notes.md'); write('changelog.d/notes.md', 'one\ntwo\nthree\nfour\nfive\nseven\n'); git('add', '-A'); git('commit', '-qm', 'move'); - const r = run('record', '--class', 'stamp-only-carry', '--range-base', from, '--reason', 'r', '--evidence', 'e'); - expect(r.status).toBe(3); - expect(r.stderr).toContain('notes.md is not a stamp file'); + expect(r.stderr).toContain('stamp-only-carry is not one of the four no-stop classes'); + expect(JSON.parse(run('list', '--json').stdout).records).toEqual([]); }); test('import adds an autoplan run\'s re-gate records once and skips every other class', () => { @@ -215,7 +193,7 @@ describe('gstack-no-stop record --class stamp-only-carry --base, and import', () expect(first).toMatch(/^NO_STOP: imported 1 record\(s\)/m); expect(first).toMatch(/^NO_STOP: skipped 3 record\(s\): import takes only autoplan-regate records/m); expect(run('import', '--from', src).stdout).toMatch(/^NO_STOP: imported 0 record\(s\)/m); - expect(JSON.parse(run('list', '--json').stdout).records.map((r: NoStopRecord) => r.class)).toEqual(['stamp-only-carry', 'autoplan-regate']); + expect(JSON.parse(run('list', '--json').stdout).records.map((r: NoStopRecord) => r.class)).toEqual(['autoplan-regate']); }); }); @@ -223,12 +201,16 @@ describe('the no-stop defaults in the /ship and /autoplan sources', () => { const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), 'utf8'); const ship = read('ship/sections/tests.md.tmpl'); const help = spawnSync('bun', [...bunIsolationArgs(), BIN, '--help'], { encoding: 'utf8', timeout: 60_000 }).stdout; - test.each(['scoped-fix-check', 'test-timeout-fix', 'pregate-flake-rerun', 'stamp-only-carry', 'autoplan-regate'])('the bin help and the policy say what to do on %s', cls => { + test.each(['scoped-fix-check', 'test-timeout-fix', 'pregate-flake-rerun', 'autoplan-regate'])('the bin help and the policy say what to do on %s', cls => { expect(help).toMatch(new RegExp('^ ' + cls + ' +\\S', 'm')); expect(read('docs/review-policy.md')).toContain('| `' + cls + '` |'); }); + test('neither the bin help nor the policy offers stamp-only-carry any more', () => { + expect(help).not.toContain('stamp-only-carry'); + expect(read('docs/review-policy.md')).not.toContain('| `stamp-only-carry` |'); + }); test('a refused case and any other stop still stop; the receipt write carries the ledger', () => { - expect(ship).toContain('three other routine stops go through `gstack-no-stop record` (`--help`); `recorded` goes on,\n`refused` stops.'); + expect(ship).toContain('two other routine stops go through `gstack-no-stop record` (`--help`); `recorded` goes on,\n`refused` stops.'); expect(help).toContain('NO_STOP: refused (exit 3): the stop stands. Anything else still stops.'); expect(read('ship/sections/pr-body.md.tmpl')).toContain('${NS:+--no-stop "@$NS"}'); expect(read('ship/DRIVER.md.tmpl')).toContain('end the run, except `gstack-no-stop`'); diff --git a/test/pr-review-history.test.ts b/test/pr-review-history.test.ts index 102c63ab03c..7035d75bffe 100644 --- a/test/pr-review-history.test.ts +++ b/test/pr-review-history.test.ts @@ -4,6 +4,7 @@ */ import { describe, expect, test } from 'bun:test'; import { historyLine, placeRunEntry, prReviewHistory, reviewRoute } from '../lib/pr-review-history'; +import { mergeBodySections } from '../lib/gstack-post'; import { orderReceipt, placeReceipt, receiptRun, receiptRuns } from '../lib/ship-receipt'; import type { ShipReceipt } from '../lib/headless-artifacts'; @@ -72,6 +73,18 @@ describe('prReviewHistory', () => { expect(prReviewHistory(body)).toMatchObject({ stubs: 1, full: 3 }); }); + test('a /ship body post keeps the live runs block, so history still counts every run (GST-2706)', () => { + let live = placeReceipt('## Summary\nprose\n', receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' })); + live = placeRunEntry(live, { head: sha('b'), run: 'r2', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); + live = placeRunEntry(live, { head: sha('b'), run: 'r3', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); + const composed = placeReceipt('## Summary\nnew prose\n', receipt(sha('c'), { passes: 1, rounds: 1 }, { run: 'r2' })); + const posted = mergeBodySections(live, composed).body; + expect(posted).toContain('new prose'); + expect(prReviewHistory(posted)).toMatchObject({ full: 3, runs: 2, stubs: 1, last_full: sha('c') }); + expect(receiptRuns(posted).map(r => r.run)).toEqual(['r3', 'r1']); + expect(prReviewHistory(mergeBodySections(posted, composed).body)).toEqual(prReviewHistory(posted)); + }); + test('a stub lands in a body with no receipt yet, inside the Agent notes section', () => { const body = placeRunEntry('## Summary\nprose\n', { head: sha('a'), run: 'r1', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); expect(body.startsWith('## Summary\nprose\n')).toBe(true); diff --git a/test/review-plan-pr-rounds.test.ts b/test/review-plan-pr-rounds.test.ts index 66355c3d998..170e7fa48cd 100644 --- a/test/review-plan-pr-rounds.test.ts +++ b/test/review-plan-pr-rounds.test.ts @@ -61,6 +61,18 @@ describe('PR round cap', () => { } }); + // Value: protects=the read-only stop offers only what the Captain can do: a grant recorded after that review can't buy a + // fix round (GST-2706); fails_when=the stop lists a round grant as an option; seam=nextStep; no_claim=history's grant route + test('the read-only stop offers ship-with-the-note or park, and says a later round grant buys no fix round', () => { + for (const roundGrant of [undefined, 'a-000000000001']) { + const stop = nextStep(h({ priorFull: 3, fullPasses: 1, last: 'full', fixedBlocking: true, roundGrant }), 'standard'); + expect(stop.step).toBe('stop'); + expect(stop.reason).toContain('(ship with the note, or park;'); + expect(stop.reason).not.toContain('a round grant, or park'); + expect(stop.reason).toContain('does not buy a fix round'); + } + }); + test('a round grant buys one more full round at its head, never two', () => { expect(nextStep(h({ priorFull: 2, roundGrant: 'a-1' })).step).toBe('full'); expect(nextStep(h({ priorFull: 3, roundGrant: 'a-1' }))).toMatchObject({ step: 'full', reason: expect.stringContaining('read-only final review') }); diff --git a/test/ship-receipt-carry-mixed.test.ts b/test/ship-receipt-carry-mixed.test.ts index 07409bec384..f1fa8097eae 100644 --- a/test/ship-receipt-carry-mixed.test.ts +++ b/test/ship-receipt-carry-mixed.test.ts @@ -3,16 +3,17 @@ * bounded route. RECEIPT_CARRY_SCOPED_REVIEW opened only when no path changed, and J1's scoped re-check refused whenever * base context moved, so a base merge that bumped a constant the branch also replaces (SAVE_VERSION := 82 became 83 on * the base; the branch's own `:= 84` line is byte-identical) next to a moved base block forced a full /ship every time. - * Here: a hunk whose only difference is a base-side removed line takes the scoped review with the context paths (finish - * and carry), a changed path plus context paths take one composed re-check packet bound to range_base, past the size cap - * it refuses as before, and a branch-side change to an added line still needs review. + * Here: a changed path plus context paths take one composed advisory packet bound to range_base, past the size cap it + * refuses as before, and a branch-side change to an added line still needs review. GST-2706: a hunk whose removed lines + * changed with the base (82 -> 84 reviewed, then the base took 83) is a changed path, not context, so its head gets a full + * review: the PR's own added and removed lines must both be the reviewed bytes for carry to keep the receipt. */ import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { EXIT } from '../lib/headless-artifacts'; import { comparePath } from '../lib/ship-patch'; -import { extractReceipt } from '../lib/ship-receipt'; +import { bindReceipt, extractReceipt } from '../lib/ship-receipt'; import { RECHECK_RANGE_DIFF_CAP } from '../crew/lib/ship-recheck'; import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; @@ -69,10 +70,10 @@ const scopedPacket = (err: string) => /one fix-check reviewer reads (\S+), then const eligible = (err: string) => /^RECHECK: advisory range_diff_lines=(\d+) range_diff_sha256=([0-9a-f]{64}) packet=(\S+);/m.exec(err); const recordAt = (f: ShipFx, name: string, v: object) => { const file = path.join(f.root, name); fs.writeFileSync(file, JSON.stringify(v)); return file; }; -describe('a base-side removed line next to byte-identical added lines (GST-1561 ask 2)', () => { - test('comparePath routes it with the context paths; a branch-side added-line change stays changed', () => { +describe('a base-side removed line next to byte-identical added lines (GST-1561 ask 2, GST-2706)', () => { + test('comparePath calls it changed, since the PR now removes other lines than the reviewed ones; moved context alone stays context', () => { const same = founderstar(); - expect(comparePath(same.f.work, same.sides, GAME)).toBe('context'); + expect(comparePath(same.f.work, same.sides, GAME)).toBe('changed'); expect(comparePath(same.f.work, same.sides, VESTING)).toBe('context'); const moved = founderstar(85); expect(comparePath(moved.f.work, moved.sides, GAME)).toBe('changed'); @@ -100,23 +101,18 @@ describe('a base-side removed line next to byte-identical added lines (GST-1561 } }); -describe('carry: the founderstar#563 shape takes one scoped reader, then binds', () => { - test('one packet holds the constant hunk and the moved context block; a clean record carries', () => { +describe('carry: the founderstar#563 shape gets a full review (GST-2706)', () => { + test('a removed line the base changed is a product change: no scoped route, and a clean scoped record carries nothing', () => { const { f, head, carry, body } = founderstar(); + const before = fs.readFileSync(body, 'utf8'); const ask = carry(); - expect([ask.status, ask.stdout.trim().split('\n')[0]], ask.stderr).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)']); - const packet = scopedPacket(ask.stderr); - expect(packet, ask.stderr).toBeDefined(); - const text = fs.readFileSync(packet!, 'utf8'); - for (const s of ['-const SAVE_VERSION := 82', '-const SAVE_VERSION := 83', '+const SAVE_VERSION := 84', 'was_vesting_clear', 'moved by the base']) expect(text).toContain(s); - const partial = recordAt(f, 'partial.json', { head, paths: [VESTING], reviewer: READER, verdict: 'clean' }); - expect(carry(['--scoped-review', partial]).stderr).toContain(`the scoped review does not cover ${GAME}`); - const ok = carry(['--scoped-review', recordAt(f, 'scoped.json', { head, paths: [GAME, VESTING], reviewer: READER, verdict: 'clean' })]); - expect([ok.status, ok.stderr.slice(0, 600)]).toEqual([EXIT.ok, expect.any(String)]); - const carried = extractReceipt(fs.readFileSync(body, 'utf8')).receipt!; - expect(carried.head).toBe(head); - expect(carried.carry!.reason).toContain(`scoped review by ${READER}`); - expect(carried.carry!.reason).toContain(GAME); + expect([ask.status, ask.stdout.trim().split('\n')[0]], ask.stderr).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)']); + expect(ask.stderr).toContain(GAME); + expect(scopedPacket(ask.stderr)).toBeUndefined(); + const r = carry(['--scoped-review', recordAt(f, 'scoped.json', { head, paths: [GAME, VESTING], reviewer: READER, verdict: 'clean' })]); + expect([r.status, r.stdout.trim().split('\n')[0]]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)']); + expect(fs.readFileSync(body, 'utf8')).toBe(before); + expect(extractReceipt(before).receipt!.head).not.toBe(head); }); test('a branch-side change to the added line still forces review (never the scoped context route)', () => { @@ -143,7 +139,7 @@ describe('carry: a changed path plus context paths compose into one bounded re-c const m = eligible(ask.stderr); expect(m, ask.stderr).not.toBeNull(); const text = fs.readFileSync(m![3]!, 'utf8'); - for (const s of ['var score0 := 2', 'was_vesting_clear', 'moved by the base', 'const SAVE_VERSION := 83', `range_base ${reviewedBase}`]) expect(text).toContain(s); + for (const s of ['var score0 := 2', 'was_vesting_clear', 'moved by the base', `range_base ${reviewedBase}`]) expect(text).toContain(s); const before = fs.readFileSync(body, 'utf8'); const record = { from, head, range_base: reviewedBase, range_diff_sha256: m![2], reader: READER, verdict: 'clean' }; const r = carry(['--recheck', recordAt(f, 'recheck.json', record)]); @@ -193,3 +189,45 @@ describe('finish: the founderstar#563 shape takes the scoped reader too', () => expect(ok.stdout).not.toContain('STOP: behavior'); }); }); + +describe('a receipt a scoped re-check carried never carries on or lands (GST-2706)', () => { + /** Reviewed at A, carried to B by a test-only change, then (as old gstack's J1 wrote it) relabelled a re-check hop. */ + const lineage = (recheck: boolean) => { + const x = reviewedBranch({ [SCORE]: 'var score := 1\n' }, { [SCORE]: 'var score := 2\n' }); + x.f.write({ 'test/score.test.ts': 'test("score", () => {});\n' }); x.f.commit('test: score'); + const b = x.f.git('rev-parse', 'HEAD').stdout.trim(); + const hop = x.carry(); + expect([hop.status, hop.stderr.slice(0, 400)]).toEqual([EXIT.ok, expect.any(String)]); + const text = fs.readFileSync(x.body, 'utf8'); + expect(extractReceipt(text).receipt!.carry!.reason).toBe('test-only change'); + if (recheck) fs.writeFileSync(x.body, text.replace(/("reason":\s*)"test-only change"/, `$1"scoped re-check by ${READER} (range-diff 12 lines)"`)); + expect(extractReceipt(fs.readFileSync(x.body, 'utf8')).receipt!.carry!.reason.startsWith('scoped re-check by ')).toBe(recheck); + return { ...x, b }; + }; + + test('carry refuses it at its own head and after a base merge, and the receipt stays put; an ordinary carry lineage still carries', () => { + for (const recheck of [true, false]) { + const { f, b, body, carry } = lineage(recheck); + const at = carry(); + expect(at.stdout.trim().split('\n')[0]).toBe(recheck ? 'CARRY: refused (RECEIPT_CARRY_REFUSED)' : `CARRY: current (the receipt already names ${b.slice(0, 12)})`); + f.advanceBase({ 'README.md': '# Fx moved\n' }); + mergeMain(f, {}); + const before = fs.readFileSync(body, 'utf8'); + const r = carry(); + if (!recheck) { expect([r.status, r.stderr.slice(0, 400)]).toEqual([EXIT.ok, expect.any(String)]); continue; } + expect([r.status, r.stdout.trim().split('\n')[0]]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_REFUSED)']); + expect(r.stderr).toContain('through a scoped re-check'); + expect(r.stderr).toContain('never got a full review'); + expect(fs.readFileSync(body, 'utf8')).toBe(before); + } + }); + + test('the queue refuses to bind it at its head, so READY and land need a fresh full review', () => { + for (const recheck of [true, false]) { + const { b, body } = lineage(recheck); + const bound = bindReceipt(fs.readFileSync(body, 'utf8'), '5', [b]); + if (!recheck) { expect(bound.ok).toBe(true); continue; } + expect(bound).toMatchObject({ ok: false, code: 'QUEUE_RECEIPT_STALE', message: expect.stringContaining('through a scoped re-check') }); + } + }); +}); diff --git a/test/ship-receipt-runs.test.ts b/test/ship-receipt-runs.test.ts index c40494158fb..fb7bfd55cf1 100644 --- a/test/ship-receipt-runs.test.ts +++ b/test/ship-receipt-runs.test.ts @@ -4,7 +4,10 @@ */ import { describe, expect, test } from 'bun:test'; import { extractReceipt, orderReceipt, placeReceipt, readyTailLines, receiptRuns, RECEIPT_RUNS_KEPT, validateReceipt } from '../lib/ship-receipt'; -import type { ShipReceipt } from '../lib/headless-artifacts'; +import { EXIT, type ShipReceipt } from '../lib/headless-artifacts'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { cleanup, makeFixtureRepo, runBin } from './helpers/pregate-fixture'; const receipt = (head: string, loop: Partial> = {}): ShipReceipt => orderReceipt({ schema_version: 1, head, base: 'main', version: '1.94.1.0', review_loop: { passes: 1, blocking_found: 0, deferred: 0, ...loop } }); @@ -68,4 +71,24 @@ describe('no_stop receipt field (K1)', () => { expect(validateReceipt({ ...ok, no_stop: [{ class: 'merge-anyway', reason: 'x', evidence: 'y' }] } as any).length).toBeGreaterThan(0); expect(validateReceipt({ ...ok, no_stop: [{ class: 'stamp-only-carry', reason: 'x' }] } as any).length).toBeGreaterThan(0); }); + + test('stamp-only-carry is no class any more (GST-2706), so a receipt that records one is invalid and its PR runs /ship again', () => { + const ok = orderReceipt({ ...receipt('e'.repeat(40)), no_stop: [{ class: 'pregate-flake-rerun', reason: 'r', evidence: 'run 1' }] }); + expect(validateReceipt({ ...ok, no_stop: [{ class: 'stamp-only-carry', reason: 'restamp', evidence: 'commit abc' }] } as any)).not.toEqual([]); + }); + + // Value: protects=a branch whose ledger an older gstack wrote with stamp-only-carry can still write a receipt (p3/outside-voice#1); + // fails_when=write passes the retired row through and the receipt is RECEIPT_INVALID on every /ship; why_new=the class was removed here; + // seam=none (the real bin on a fixture repo); no_claim=the gh round trip + test('write drops a retired ledger row from --no-stop, names it on stderr and keeps the current ones', () => { + const repo = makeFixtureRepo(); + try { + const ledger = path.join(repo.root, 'no-stop.json'); + fs.writeFileSync(ledger, JSON.stringify([{ class: 'stamp-only-carry', reason: 'restamp', evidence: 'commit abc' }, { class: 'pregate-flake-rerun', reason: 'r', evidence: 'run 1' }])); + const body = path.join(repo.root, 'body.md'); + const w = runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '9', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--no-stop', `@${ledger}`, '--body', body]); + expect([w.status, w.err], w.out).toEqual([EXIT.ok, expect.stringContaining('NO_STOP: dropped "stamp-only-carry"')]); + expect(extractReceipt(fs.readFileSync(body, 'utf8')).receipt!.no_stop).toEqual([{ class: 'pregate-flake-rerun', reason: 'r', evidence: 'run 1' }]); + } finally { cleanup(repo); } + }); }); diff --git a/test/size-ledger/ship/close-last-recheck-carry-paths.json b/test/size-ledger/ship/close-last-recheck-carry-paths.json new file mode 100644 index 00000000000..4176ce1e12f --- /dev/null +++ b/test/size-ledger/ship/close-last-recheck-carry-paths.json @@ -0,0 +1,4 @@ +{ + "bytes": -2, + "why": "GST-2706: one no-stop class fewer in Step 5's no-stop line" +} From c5250dedc1ef9398ff3f10519c17919aaae880dc Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 17 Nov 2026 20:02:11 +0800 Subject: [PATCH 26/62] Keep reviewer product challenges open on the approval page (#4431) * Keep reviewer product challenges open on the approval page Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Read the approvals record without writing the slug cache when building the gate Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep every reviewer challenge on the approval page, and ask again when the cut list changes A challenge with no change kind and no real owner quote now becomes a proposal instead of vanishing. An ordinary finding that only mentions an earlier challenge no longer closes it. The cut list and confirm-direction items carry their content in their origin, so an earlier answer is not reused for a changed list. Review-Finding: p1/specialist-batched#1 reader=specialist-batched Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/red-team#3 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep removed owner quotes redacted, and keep High proposals as blocking tasks when declined Public exports now redact the Owner's words from every plan text the run kept, so a quote a revision removed stays hidden in earlier reviewer results. A paired proposal takes the heaviest change either reviewer named, so an ordering-plus-scope pair is re-reviewed instead of settled. A proposal behind a Critical or High finding offers b as keep the draft and carry it into the build as a blocking task, and only a settles it. Review-Finding: p1v/outside-voice#1 reader=outside-voice Review-Finding: p1v/outside-voice#2 reader=outside-voice Review-Finding: p1v/adversarial-native#2 reader=adversarial-native Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Document owner's words, reviewer proposals and day-one items on the approval page Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * chore: changelog and TODOS Co-Authored-By: Claude Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Co-authored-by: Claude --- autoplan/DRIVER.md | 2 +- capy/skill/gstack/captain.md | 3 +- ...-keeps-reviewer-product-challenges-open.md | 1 + docs/troubleshooting.md | 11 +- docs/unattended.md | 37 +- lib/autoplan-confirm.ts | 24 +- lib/autoplan-gate-items.ts | 157 ++++++++ lib/autoplan-gate.ts | 38 +- lib/autoplan-owner-text.ts | 113 ++++++ lib/autoplan-owner-words.ts | 15 +- lib/autoplan-prompts.ts | 2 +- lib/autoplan-reconcile.ts | 8 +- lib/autoplan-revise.ts | 10 +- lib/autoplan-run.ts | 3 +- lib/captain-brief.ts | 8 +- lib/gate-list.ts | 13 +- lib/headless-artifacts.ts | 2 +- lib/owner-brief.ts | 8 + test/autoplan-carry.test.ts | 5 +- test/autoplan-day-one-gate.test.ts | 365 ++++++++++++++++++ test/captain-brief.test.ts | 6 +- test/fixtures/module-size-ratchet.json | 2 + 22 files changed, 792 insertions(+), 41 deletions(-) create mode 100644 changelog.d/approval-page-keeps-reviewer-product-challenges-open.md create mode 100644 lib/autoplan-gate-items.ts create mode 100644 lib/autoplan-owner-text.ts create mode 100644 test/autoplan-day-one-gate.test.ts diff --git a/autoplan/DRIVER.md b/autoplan/DRIVER.md index 81d661433ab..a117116ed00 100644 --- a/autoplan/DRIVER.md +++ b/autoplan/DRIVER.md @@ -102,7 +102,7 @@ RESULT FORMAT (required by gstack-autoplan; the parent binds your file by this c ```gstack-findings {"id":"F1","severity":"High","title":"","file":"","line":12,"fix":""} ``` - severity is Critical | High | Medium | Low | Informational. Add "user_challenge": true only when you recommend changing the plan's stated direction AND the change alters its scope, cost or direction (then also add "changes": "scope" | "cost" | "direction") or only its delivery packaging or ordering, with no Implementation-plan edit (then "changes": "packaging" | "ordering"). Naming and other reversible choices are ordinary findings, not user challenges. Add "urgent": true and "suggested_owner": "" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused. + severity is Critical | High | Medium | Low | Informational. Any finding that recommends changing the plan's scope, cost or direction adds "changes": "scope" | "cost" | "direction", or "packaging" | "ordering" when only its delivery packaging or build order changes, with no Implementation-plan edit; that holds at any severity. Only the owner's own words are the plan's direction: add "user_challenge": true and "owner_quote": only when the change goes against bullet n (from 1) of the plan's "Owner's words" section. Scope, order or features the planning agent wrote are proposals, so a change to them is an ordinary finding with "changes" and no user_challenge. A plan with no "Owner's words" section: add "user_challenge": true (no owner_quote) when you recommend changing its stated direction. Naming and other reversible choices are ordinary findings with no "changes". Add "urgent": true and "suggested_owner": "" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused. 3. Write the whole result to this file: ## Gate replies diff --git a/capy/skill/gstack/captain.md b/capy/skill/gstack/captain.md index d4227c769b8..7bb28aa7e78 100644 --- a/capy/skill/gstack/captain.md +++ b/capy/skill/gstack/captain.md @@ -104,7 +104,8 @@ For an autoplan run, open the plan with `## ELI5` (5-10 plain sentences), then w gstack-owner-brief render --captain --out --captain-name "" ``` -It prints a header line ("Decision needed … Reply **do it** …"), the `### ELI5` summary (on a run whose gate +It prints a header line ("Decision needed … Reply **do it** …"), the plan's `### Day one` table, `### What it won't do yet` +and the owner's words it follows (each when the plan has it), the `### ELI5` summary (on a run whose gate carries `eli5`), the four plan sections (each capped, with a pointer to the plan for the rest), and "What we need from you", one lettered line per choice in the ask format, closed by "do it", then a `### Cost` section (spent so far, worst case, and the estimate for the phases `rec` can reopen). The last line, "For the relaying agent", carries the run, `gate_rev`, `rec_hash` and the exact diff --git a/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md b/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md new file mode 100644 index 00000000000..7486b88adbf --- /dev/null +++ b/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md @@ -0,0 +1 @@ +- **/autoplan's approval page no longer hides a reviewer's product objection behind "keep your direction".** A plan can now quote its owner under `### Owner's words`, and only those quotes count as the plan's direction. When a reviewer recommends changing anything else the plan says (its scope, build order, direction, cost or packaging), at any severity and even from one reviewer, the approval page shows it as a lettered choice that recommends the reviewer's change, and the cost line says what taking it actually does. A plan with no Owner's words section keeps today's default and gets one question asking the owner to confirm the direction is theirs. A challenge raised in an earlier review round stays on the page until the owner answers it or a later round marks it fixed. App plans with a `### Day one` table (the owner's first actions, how often, the feature, the way in from the first screen, the first build that has it, and how it's checked) show it first on the approval page, turn each guessed row into a question for the owner, and letter every cut that drops a day-one row or a quoted owner line; an app plan without the table gets one item asking for it. Declining a reviewer's change on a High or Critical finding keeps the plan as written and carries the finding into the build as a blocking task. Quoted owner words, including ones a later revision removed, are redacted from public exports. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 8af57879489..4c7f040cc3e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5302,8 +5302,9 @@ directory, and this one already holds files. ### `OWNER_REPLY_REQUIRED` **Meaning.** An agent answered the gate (`--by agent:`) without recording -what the owner actually said, or answered a `uc` item (a user challenge or a -round-cap approval, which only the owner settles) in its own words +what the owner actually said, or answered a `uc` item (a user challenge, a +reviewer's proposal, a day-one or cut question, or a round-cap approval, which +only the owner settles) in its own words (`--words-by agent:`). Nothing was applied. **Fix.** Pass the owner's words verbatim: `--owner-reply ""`, @@ -5417,8 +5418,10 @@ errors. **Meaning.** A public copy of an autoplan run still quotes the owner's own words: a gate reply the private run recorded (on a decision row, the gate or -the journal), the words a carried gate reused, or a reason a human gave for -deferring a phase, in prose or in one of gstack's renderings of that reason. +the journal), the words a carried gate reused, a quote under the plan's +`### Owner's words` heading (one a later revision removed included), or a +reason a human gave for deferring a phase, in prose or in one of gstack's +renderings of that reason. Nothing a person wrote leaves without their click. A reply of 3 or more words is a quote wherever it appears whole, and from 8 words any 8 consecutive words are one, compared across punctuation, line breaks, JSON escapes, entities, HTML and diff --git a/docs/unattended.md b/docs/unattended.md index ced16925934..d9b41014b43 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -306,8 +306,10 @@ owner's own words: nothing a person wrote leaves without their click (GST-1243). - **Whose words.** Every owner reply the private run ever recorded: on decision rows, on `run.json`'s gate, and in the journal (`attempts.jsonl` keeps a reply that a later answer at the same gate replaced), the words a - carried gate reused, and the reason a human gave for `close --deferred --by - human`. A reply that parsed as gate grammar is the decision code, not owner + carried gate reused, each quote under a `### Owner's words` heading in any + plan text the run kept (the active plan, its source copies and each gate's + copy, so a quote a later revision removed stays redacted), and the reason a + human gave for `close --deferred --by human`. A reply that parsed as gate grammar is the decision code, not owner prose. An agent's own words (`answer_words`) and an agent's deferral reason stay. - **Dropped fields.** `owner_reply` anywhere, a carry record's `words`, and a @@ -524,6 +526,17 @@ The example above is the full run. The first `next` also takes `--kind`: `p1b` (approve with the recommended changes) or an explicit `a` applies a fix; a finding carried with `b` stays open, so a rerun that raises it again asks again. + With an `### Owner's words` section in the plan, only a challenge naming + one of its bullets (`owner_quote`) is a user challenge; a reviewer's + `changes` to anything else, at any severity and from one voice, is a + `proposal` approval item recommending the change, whose `b` keeps the draft + (behind a Critical or High finding, as a blocking build task). Without that + section the default stays, plus one `confirm_direction` auto item when a + one-voice challenge keeps it. An earlier round's open challenge stays until + answered or marked fixed (`resolves`). `### Day one` and `### What it won't + do yet` add `day_one` and `cut` approval items (a missing day-one page on a + UI plan, each `assumed` row, each cut that drops a day-one row or quoted + owner line) and one `cuts` auto item for the rest. 4. **Answer the gate** with the reply grammar and the revision you read: ```bash $AP answer --out --gate-rev 1 --reply "rec" --by human # every recommendation, plan changes included (APPLY: ...; amend_pending) @@ -540,7 +553,8 @@ The example above is the full run. The first `next` also takes `--kind`: are then recorded as `answer_words` with `words_by`, never as `owner_reply`; a later gate never carries them (`CARRY: no`), and `gstack-approvals import` lists that row under the agent, not the owner. - They never settle a `uc` item (a user challenge or a round-cap approval): + They never settle a `uc` item (a user challenge, a reviewer's proposal, a + day-one or cut question, or a round-cap approval): a reply in an agent's own words that would choose one, by `rec`, `as-is` or a token, is refused (`OWNER_REPLY_REQUIRED`) and nothing is applied; such a reply may still answer the `d` items and leave the `uc` items to @@ -625,9 +639,13 @@ Each prompt file ends with this contract; `submit` enforces it. 2. The review is prose, then one fenced block of canonical findings, one JSON object per line: `{"id":"F1","severity":"High","title":"...","file":"...","line":12,"fix":"..."}` inside a ```` ```gstack-findings ```` fence. `severity` is Critical | High | - Medium | Low | Informational; `"user_challenge": true` marks a recommended - change to the plan's stated direction and needs `"changes": "scope" | - "cost" | "direction"` (what accepting it changes); `"urgent": true` with + Medium | Low | Informational; a finding that recommends changing the + plan's scope, cost or direction adds `"changes": "scope" | "cost" | + "direction"` (or `"packaging" | "ordering"` when only delivery packaging or + build order changes), at any severity; `"user_challenge": true` with + `"owner_quote": ` marks a change against bullet n of the plan's + `### Owner's words` (on a plan without that section, `"user_challenge": + true` alone marks a change to its stated direction); `"urgent": true` with `"suggested_owner"` marks a security or data-loss finding the plan does not own. An empty fence means no findings; a missing fence is refused. 3. The whole result is written to the printed `result=` path. @@ -861,7 +879,8 @@ predictions with his answers. prospective evidence. - **The record.** `shadow/ceo-only.r.jsonl`, one row per gate item: the frozen item, `item_class` (`challenge2`, `challenge1`, `disagree`, `agent`, - `cap_deferred`, `cap_blocker`, `cap_delta`, `finding`, `p1`), `ceo_eligible` + `cap_deferred`, `cap_blocker`, `cap_delta`, `finding`, `proposal`, + `confirm_direction`, `day_one`, `cut`, `cuts`, `p1`), `ceo_eligible` (false for a `finding` item, which a CEO-only run leaves to the owner), the prediction, `rule_pick` (the driver's keep-direction pick, the free baseline), `rec_hash`, the plan and prompt hashes, the model, the gstack @@ -891,7 +910,9 @@ predictions with his answers. `gstack-owner-brief render --out ` is what the owner sees at the final gate, interactive or unattended: one page built from `gate.json`, `decisions.jsonl` and `findings.jsonl` (`BRIEF_INPUT_MISSING` when one is -absent). It opens with the `URGENT, outside this plan` block, then a +absent). It opens with the `URGENT, outside this plan` block, then the +plan's `### Day one` table, its `### What it won't do yet` cuts and the +owner's words it follows (each only when the plan has it), then a plain-language summary (phases closed, findings accepted, how many decisions take their default, the cycle time; `--summary ` or `/summary.md` replaces the generated sentence with the run's own), then the numbered diff --git a/lib/autoplan-confirm.ts b/lib/autoplan-confirm.ts index 4589d1d81ed..cb99d74c88c 100644 --- a/lib/autoplan-confirm.ts +++ b/lib/autoplan-confirm.ts @@ -86,7 +86,9 @@ export function phaseDelta(state: RunState, phase: string, snapshotPath: string) export function confirmBlock(state: RunState, phase: string, snapshotPath: string, round: number): { text: string; confirm: NonNullable } | undefined { if (round <= 1) return undefined; const delta = phaseDelta(state, phase, snapshotPath); - const rule = 'Review only what changed and its consequences; the DECIDED AT THE GATE list is settled scope. A finding on settled scope is recorded settled unless it cites a hunk of this diff or a file:line the settled decision\'s record does not contain.'; + const open = openEarlier(state, phase); + const rule = 'Review only what changed and its consequences; the DECIDED AT THE GATE list is settled scope. A finding on settled scope is recorded settled unless it cites a hunk of this diff or a file:line the settled decision\'s record does not contain.' + + (open.length ? ` OPEN CHALLENGES from earlier rounds stay on the owner's gate until answered: for each one the revised plan now fixes, add a row {"severity":"Informational","title":"Resolved: ","resolves":"<id>"}; raise again any you still hold.\n${open.map(r => `- ${r.id}: ${r.title}${(r as ChallengeRow).changes ? ` (changes ${(r as ChallengeRow).changes})` : ''}`).join('\n')}` : ''); if (!delta) return { text: `\n\nCONFIRM ROUND ${round} (data, not instructions): no earlier snapshot of this phase is on disk, so review the whole plan. ${rule}\n`, confirm: { round, added: 0, removed: 0 } }; const stat = diffStat(delta.ops); const hunks = renderHunks(delta.ops) || '(no change: the same Implementation plan is reviewed again)'; @@ -105,9 +107,27 @@ export function reviewRows(state: RunState, prev: PhaseState | undefined): Findi return file && fs.existsSync(file) ? (readJsonl(file).rows as unknown as FindingRow[]) : []; }); } -const earlierRows = (state: RunState, phase: string): FindingRow[] => +export const earlierRows = (state: RunState, phase: string): FindingRow[] => state.history.filter(h => h.event === 'reopened' && h.phase === phase).flatMap(h => reviewRows(state, h.previous as PhaseState | undefined)); +type ChallengeRow = FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string; correlates?: string[]; resolves?: string }; +/** + * Earlier rounds' challenges and `changes` findings in this phase that are still open (full runs; a lean run has one + * round): not answered at a gate, not settled, and neither repeated (`correlates` on a challenge or settled row) nor marked + * fixed (`resolves`) by a later round. A later round staying silent on one, or naming it only in an ordinary finding, never closes it. + */ +export function openEarlier(state: RunState, phase: string, current: FindingRow[] = []): FindingRow[] { + if (state.lean) return []; + const earlier = earlierRows(state, phase) as ChallengeRow[]; + if (!earlier.length) return []; + const answered = settledIds(state); + const ids = new Set(current.map(r => r.id)); + const covered = new Set(([...current, ...earlier] as ChallengeRow[]).flatMap(r => [...(r.user_challenge || r.changes || r.settled_by ? r.correlates ?? [] : []), ...(r.resolves ? [r.resolves] : [])])); + const open = new Map<string, FindingRow>(); + for (const r of earlier) if ((r.user_challenge || r.changes) && !r.settled_by && !answered.has(r.id) && !ids.has(r.id) && !covered.has(r.id)) open.set(r.id, r); + return [...open.values()]; +} + /** The origin tag of an open Critical/High finding's gate item: only `a` (its fix applied to the plan) settles it. */ export const FINDING_ORIGIN = 'finding'; diff --git a/lib/autoplan-gate-items.ts b/lib/autoplan-gate-items.ts new file mode 100644 index 00000000000..ce7d7a5b013 --- /dev/null +++ b/lib/autoplan-gate-items.ts @@ -0,0 +1,157 @@ +/** + * autoplan-gate-items — the gate items that keep a product challenge on the + * owner's page (GST-2947). Only the owner's own words are the plan's + * direction (lib/autoplan-owner-text.ts): a reviewer's scope, ordering, + * direction, cost or packaging change to anything else the plan says becomes + * a lettered proposal recommending the reviewer's change, at any severity and + * from one voice; a challenge that names a quoted owner line keeps today's + * keep-direction rules in buildGate (lib/autoplan-gate.ts). A plan with no + * Owner's words section keeps today's defaults and gets one item asking the + * owner to confirm its direction. The day-one items ask about every assumed + * day-one row, a missing day-one page on an app plan, and each cut that drops + * a day-one row or a quoted owner line (the other cuts are one grouped item). + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { branchKey, captainApprovalsDir } from './approval-record'; +import { cutDrops, parseCuts, parseDayOne, parseOwnerWords, wordKey, type DayOneTable, type OwnerQuote, type OwnerWordsSection } from './autoplan-owner-text'; +import { SETTLEABLE_CHANGES } from './autoplan-reconcile'; +import { readDecisions, readJournal, type RunState } from './autoplan-state'; +import { resolveStateRoot } from './state-root'; +import type { GateItem } from './gate-list'; +import type { FindingRow } from './headless-artifacts'; + +export type ChallengeRow = FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string; owner_quote?: number; resolves?: string }; +export type NewItem = Omit<GateItem, 'id'> & { idKind: 'd' | 'uc'; key: string }; +export interface GateOwnerWords { status: OwnerWordsSection['status']; quotes: Array<OwnerQuote & { verified: boolean }>; reason?: string; fix?: string } +export interface OwnerContext { words: OwnerWordsSection; verified: Set<number>; dayOne: DayOneTable; cuts: string[]; app: boolean; lean: boolean } + +/** + * The owner's words in every approvals record already on disk for the branch checked out at `cwd` (lib/approval-record.ts + * layout: <state root>/projects/<slug>/approvals/<branch key>.jsonl and its mirrors). Read-only: the slug is not resolved, + * because resolving it writes the slug cache, and building a gate must not write outside the run. + */ +export function ledgerWords(cwd: string, env: NodeJS.ProcessEnv = process.env): string[] { + const head = spawnSync('git', ['symbolic-ref', '--short', '-q', 'HEAD'], { cwd, encoding: 'utf8', timeout: 10_000 }); + const branch = head.status === 0 ? head.stdout.trim() : ''; + if (!branch) return []; + const name = `${branchKey(branch)}.jsonl`; + const files: string[] = []; + const under = (root: string, sub: string[]) => { try { for (const d of fs.readdirSync(root)) files.push(path.join(root, d, ...sub, name)); } catch { /* no such root */ } }; + under(path.join(resolveStateRoot(env), 'projects'), ['approvals']); + for (const root of [env.GSTACK_APPROVALS_DIR, captainApprovalsDir(env)]) if (root) under(root, []); + const words: string[] = []; + for (const file of files) { + let text: string; + try { text = fs.readFileSync(file, 'utf8'); } catch { continue; } + for (const line of text.split('\n')) { + try { const row = JSON.parse(line); if (typeof row?.words === 'string' && !row.words_by) words.push(row.words); } catch { /* a torn line */ } + } + } + return words; +} + +/** Every owner reply this run recorded, plus the owner's words in the approvals records for the plan's branch. */ +export function recordedOwnerWords(state: RunState, env: NodeJS.ProcessEnv = process.env): string[] { + const out: string[] = []; + for (const r of readJournal(state.out)) if (typeof r.owner_reply === 'string') out.push(r.owner_reply); + for (const d of readDecisions(state.out)) if (typeof d.owner_reply === 'string') out.push(d.owner_reply); + return [...out, ...ledgerWords(path.dirname(state.plan_input ?? state.plan_source), env)]; +} + +export function ownerContext(state: RunState, recorded: string[] = recordedOwnerWords(state)): OwnerContext { + let text = ''; + try { text = fs.readFileSync(state.active_plan, 'utf8'); } catch { /* no plan text: nothing is quoted */ } + const words = parseOwnerWords(text); + const keys = recorded.map(wordKey); + const verified = new Set(words.quotes.filter(q => keys.some(k => k.includes(wordKey(q.text)))).map(q => q.n)); + return { words, verified, dayOne: parseDayOne(text), cuts: parseCuts(text), app: !!state.scope?.ui, lean: !!state.lean }; +} + +export function gateOwnerWords(ctx: OwnerContext): GateOwnerWords { + return { status: ctx.words.status, quotes: ctx.words.quotes.map(q => ({ ...q, verified: ctx.verified.has(q.n) })), + ...(ctx.words.reason ? { reason: ctx.words.reason, fix: ctx.words.fix } : {}) }; +} + +/** The owner line a challenge names, when the plan quotes one there. */ +export const ownerQuoteOf = (ctx: OwnerContext, f: ChallengeRow | undefined): OwnerQuote | undefined => + f?.owner_quote ? ctx.words.quotes.find(q => q.n === f.owner_quote) : undefined; + +/** Today's keep-direction rules apply: the plan quotes no owner, or the challenge goes against a quoted owner line. */ +export const directionIsOwners = (ctx: OwnerContext, rows: Array<ChallengeRow | undefined>): boolean => + ctx.words.status === 'none' || rows.some(r => !!ownerQuoteOf(ctx, r)); + +/** What choosing the reviewer's change costs, as revise actually discharges it (lib/autoplan-revise.ts). */ +export function proposalCost(ctx: OwnerContext, phase: string, changes: string): string { + if (ctx.lean) return 'a applies without re-review (lean run: one gate revision)'; + if (SETTLEABLE_CHANGES.includes(changes)) return 'a is settled with revise --settle: no plan edit, no re-review'; + return `a reopens ${phase}${phase === 'eng' ? '' : ' and eng'} once the plan is revised`; +} + +/** A proposal behind a Critical or High row keeps the finding path's b: the draft stands and the finding becomes a blocking build task. */ +export const blockingProposal = (rows: ChallengeRow[]): boolean => rows.some(r => r.severity === 'Critical' || r.severity === 'High'); + +/** + * One proposal from one or both voices (a paired twin) against agent-written plan text: a takes the change, b keeps the draft. + * Its `changes` is the heaviest any row names (scope, cost, direction, then packaging or ordering), so a pair never settles a scope change. + */ +export function proposalItem(ctx: OwnerContext, phase: string, rows: ChallengeRow[], o: { carried?: boolean } = {}): NewItem { + const named: string[] = rows.flatMap(r => (r.changes ? [r.changes] : [])); + const changes = ['scope', 'cost', 'direction'].find(c => named.includes(c)) ?? named[0] ?? 'direction'; + const keep = blockingProposal(rows) ? "keep the plan's draft; carry it into the build as a blocking task (no plan change)" : "keep the plan's draft"; + const fixes = [...new Set(rows.map(r => r.resolution).filter((r): r is string => !!r))]; + const voices = rows.map(r => r.voice).join(' + '); + const ids = rows.map(r => r.id).join(' + '); + return { idKind: 'uc', key: rows.map(r => r.id).join('+'), title: `${rows[0]!.title} [${ids}]`, kind: 'approval', recommended: 'a', phase, item_class: 'proposal', changes, + recommended_basis: "the reviewer's change: only the owner's words are direction, and this changes text the planning agent wrote", + why: `${voices} recommend${rows.length > 1 ? '' : 's'} changing the plan's ${changes} (${rows[0]!.severity}); no quoted owner line says otherwise${o.carried ? '; raised in an earlier round and still open' : ''}`, + cost: proposalCost(ctx, phase, changes), + options: [{ key: 'a', text: `take the change: ${fixes.length ? fixes.join('; ') : rows[0]!.title}`, changes_plan: true }, { key: 'b', text: keep, changes_plan: false }] }; +} + +/** + * No Owner's words section: a one-voice challenge keeps the plan's direction by default, so the owner is asked to confirm + * the direction is theirs (auto: today's default stands unanswered). A two-voice challenge already recommends the change + * on a shared proposal (challengeDefault), so it adds no confirm item. + */ +export function confirmDirectionItem(challenges: string[]): NewItem { + return { idKind: 'd', key: 'confirm-direction', kind: 'auto', recommended: 'a', item_class: 'confirm_direction', + title: `Confirm the plan's direction is yours: the plan quotes no owner words, so ${challenges.join(', ')} default to the plan as written`, + recommended_basis: "today's default for a plan with no Owner's words section", + why: "only the owner's words are direction; without an Owner's words section the gate cannot tell your direction from the planning agent's draft", + options: [{ key: 'a', text: 'yes, the plan as written is what I asked for', changes_plan: false }, + { key: 'b', text: "no, it is a draft: quote what I said in an Owner's words section and revise, so the challenges are judged against it", changes_plan: true }] }; +} + +/** The day-one questions: each assumed row, a missing page on an app plan, and the plan's cuts. */ +export function dayOneItems(ctx: OwnerContext): NewItem[] { + const items: NewItem[] = []; + const reopen = ctx.lean ? 'applies without re-review (lean run)' : 'reopens ceo and eng once the plan is revised'; + if (ctx.app && ctx.dayOne.status !== 'ok') { + items.push({ idKind: 'uc', key: 'day-one-page', kind: 'approval', recommended: 'a', item_class: 'day_one', changes: 'scope', cost: `a ${reopen}`, + title: `The plan has no day-one page${ctx.dayOne.reason ? ` (${ctx.dayOne.reason})` : ''}: the first things you will do with it, how often, and which build puts each on your device`, + why: 'an app plan names what its owner does on day one so the most-used thing is built first and every feature has a way in', + options: [{ key: 'a', text: 'add it: a ### Day one table (action, frequency, source, feature, route, first build, check), then revise', changes_plan: true }, { key: 'b', text: 'approve without it', changes_plan: false }] }); + } + for (const row of ctx.dayOne.rows.filter(r => r.assumed)) { + items.push({ idKind: 'uc', key: `day-one:${wordKey(row.action).trim()}`, kind: 'approval', recommended: 'a', item_class: 'day_one', cost: `b ${reopen}`, + title: `Day one: the plan assumes you will do "${row.action.replace(/[.]$/, '')}" (${row.frequency || 'how often unstated'}); is that right?`, + why: `no owner words or owner evidence back this row; feature: ${row.feature || 'none named'}; first build: ${row.first_build || 'none named'}`, + options: [{ key: 'a', text: 'yes, I do that: keep the row', changes_plan: false }, { key: 'b', text: 'no, or not like that: say what you do instead, then revise', changes_plan: true }] }); + } + const targets = [...ctx.dayOne.rows.flatMap(r => [r.action, r.feature]), ...ctx.words.quotes.map(q => q.text)].filter(Boolean); + const named = ctx.cuts.filter(c => targets.some(t => cutDrops(c, t))); + for (const cut of named) { + items.push({ idKind: 'uc', key: `cut:${wordKey(cut).trim()}`, kind: 'approval', recommended: 'a', item_class: 'cut', changes: 'scope', cost: `b ${reopen}`, + title: `Cut: ${cut}`, why: 'this cut drops something on the day-one page or in your own words', + options: [{ key: 'a', text: 'keep the cut: not in the first build', changes_plan: false }, { key: 'b', text: 'put it back in the first build', changes_plan: true }] }); + } + const rest = ctx.cuts.filter(c => !named.includes(c)); + if (rest.length) { + items.push({ idKind: 'd', key: 'cuts', kind: 'auto', recommended: 'a', item_class: 'cuts', changes: 'scope', cost: `b ${reopen}`, + title: `${rest.length} other cut${rest.length === 1 ? '' : 's'}: ${rest.join('; ')}`, why: 'none of these drops a day-one row or a quoted owner line', + options: [{ key: 'a', text: 'keep these cuts', changes_plan: false }, { key: 'b', text: 'put some back: name them, then revise', changes_plan: true }] }); + } + return items; +} diff --git a/lib/autoplan-gate.ts b/lib/autoplan-gate.ts index 3600c6c1223..e2f4e33d29c 100644 --- a/lib/autoplan-gate.ts +++ b/lib/autoplan-gate.ts @@ -26,7 +26,8 @@ import { FILES, RunError, journal as journalRow, now, readDecisions, voiceRows, import { applyCapChoices, pendingDeltas, releaseUndispatched, roundCap, roundOf } from './autoplan-budget'; import { evaluateCarry, gateEvidence, voidPendingCheck } from './autoplan-carry'; import { buildEli5, capyRelayLine } from './captain-brief'; -import { FINDING_ORIGIN, previousReview, reviewRows, settledIds } from './autoplan-confirm'; +import { FINDING_ORIGIN, openEarlier, previousReview, reviewRows, settledIds } from './autoplan-confirm'; +import { blockingProposal, confirmDirectionItem, dayOneItems, directionIsOwners, gateOwnerWords, ownerContext, ownerQuoteOf, proposalItem, type ChallengeRow, type NewItem } from './autoplan-gate-items'; import { phaseClose } from './autoplan-timing'; import { agentWords, ANSWERED_BY_RE, applyReply, autoDefault, decisionId, decisionRows, keepDirection, legacyRecHash, parseReply, pendingHint, recHash, replyShape, validateGateList, type GateChoice, type GateItem, type GateList, type GateOption, type ParsedReply } from './gate-list'; import type { DecisionRow, FindingRow } from './headless-artifacts'; @@ -196,6 +197,15 @@ function agentDecision(id: string, title: string, phase: string, why: string): G export function buildGate(state: RunState, gateRev: number): GateList { const items: GateItem[] = []; let d = 0, uc = 0; + const owner = ownerContext(state); + const quoted = owner.words.status !== 'none'; + const kept: string[] = []; + const keptIds: string[] = []; + const add = ({ idKind, key, ...item }: NewItem, origin: (options: GateOption[]) => string): string => { + const id = idKind === 'uc' ? `uc${++uc}` : `d${++d}`; + items.push({ id, ...item, origin: origin(item.options) }); + return id; + }; for (const phase of state.phase_order) { const ps = state.phases[phase]; if (!ps?.closed_at || ps.deferred) continue; @@ -208,12 +218,19 @@ export function buildGate(state: RunState, gateRev: number): GateList { const push = (item: GateItem, ids: string, tag?: string) => items.push({ ...item, origin: [origin(ids, item.options), ...(tag ? [tag] : [])].join('|') }); const challenged = new Set<string>(); const twins = new Map(consensus.rows.filter(r => sameProblem(r) && (r.disposition === 'confirmed' || r.disposition === 'unverified')).map(r => [r.native_id!, r.outside_id])); + const carried = openEarlier(state, phase, [...native, ...outside]) as ChallengeRow[]; + for (const f of carried) byId.set(f.id, f); + const propose = (rows: ChallengeRow[], fromEarlier = false) => { + rows.forEach(r => challenged.add(r.id)); + add(proposalItem(owner, phase, rows, { carried: fromEarlier }), options => [origin(rows.map(r => r.id).join('+'), options), ...(blockingProposal(rows) ? [FINDING_ORIGIN] : [])].join('|')); + }; for (const row of consensus.rows) { const o = byId.get(row.outside_id)! as FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string }; if (o.settled_by) continue; const n = (row.native_id ? byId.get(row.native_id) : undefined) as (FindingRow & { user_challenge?: boolean; changes?: string }) | undefined; const ids = `${row.native_id}+${row.outside_id}`; if (o.user_challenge && n?.user_challenge && row.disposition !== 'new' && row.basis !== 'file') { + if (!directionIsOwners(owner, [n, o])) { propose([n, o]); continue; } challenged.add(o.id); challenged.add(n.id); const title = `${n.title} [${row.native_id} + ${row.outside_id}]`; if (reran && !n.changes && !o.changes) { push(agentDecision(`d${++d}`, title, phase, 'both voices recommend changing your stated direction'), ids); continue; } @@ -230,10 +247,18 @@ export function buildGate(state: RunState, gateRev: number): GateList { options: [{ key: 'a', text: `native position (${row.severity.native})`, changes_plan: false }, { key: 'b', text: `outside position (${row.severity.outside})`, changes_plan: true }] }, ids); } } - for (const f of [...native, ...outside] as Array<FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string }>) { - if (!f.user_challenge || challenged.has(f.id) || f.settled_by) continue; - const why = `one voice (${f.voice}) recommends changing your stated direction`; + const twinOf = (id: string) => twins.get(id) ?? [...twins].find(([, out]) => out === id)?.[0]; + for (const f of [...native, ...outside, ...carried] as ChallengeRow[]) { + if (challenged.has(f.id) || f.settled_by) continue; + if (quoted && (f.changes || f.user_challenge) && !ownerQuoteOf(owner, f)) { + const twin = twinOf(f.id) ? byId.get(twinOf(f.id)!) as ChallengeRow | undefined : undefined; + propose(twin && !twin.settled_by && !ownerQuoteOf(owner, twin) ? [f, twin] : [f], carried.includes(f)); + continue; + } + if (!f.user_challenge || !directionIsOwners(owner, [f])) continue; + const why = `one voice (${f.voice}) recommends changing your stated direction${carried.includes(f) ? '; raised in an earlier round and still open' : ''}`; if (reran && !f.changes) { push(agentDecision(`d${++d}`, `${f.title} [${f.id}]`, phase, why), f.id); continue; } + if (!quoted) { kept.push(`d${d + 1}`); keptIds.push(f.id); } push({ id: `d${++d}`, title: `${f.title} [${f.id}]`, kind: 'auto', recommended: 'a', phase, item_class: 'challenge1', why, ...(f.changes ? { changes: f.changes } : {}), cost: `b reopens ${phase}${phase === 'eng' ? '' : ' and eng'}`, options: [KEEP('keep your direction'), { key: 'b', text: 'accept the change', changes_plan: true }] }, f.id); } @@ -242,7 +267,7 @@ export function buildGate(state: RunState, gateRev: number): GateList { for (const f of [...native, ...outside] as Array<FindingRow & { user_challenge?: boolean; settled_by?: string }>) { if (f.voice === 'outside' && pairedOutside.has(f.id)) continue; const group = [f, ...(twins.has(f.id) ? [byId.get(twins.get(f.id)!)!] : [])] as Array<FindingRow & { user_challenge?: boolean; settled_by?: string }>; - if (group.some(g => challenged.has(g.id) || g.user_challenge || g.settled_by)) continue; + if (group.some(g => challenged.has(g.id) || (g.user_challenge && directionIsOwners(owner, [g])) || g.settled_by)) continue; const severity = group.some(g => g.severity === 'Critical') ? 'Critical' : group.some(g => g.severity === 'High') ? 'High' : null; if (!severity) continue; const ids = group.map(g => g.id); @@ -253,8 +278,11 @@ export function buildGate(state: RunState, gateRev: number): GateList { } } items.push(...capItems(state, { d: () => `d${++d}`, uc: () => `uc${++uc}` })); + if (!quoted && kept.length) add(confirmDirectionItem(kept), options => ['owner', 'confirm-direction', optionHash(options), keptIds.join('+')].join('|')); + for (const item of dayOneItems(owner)) add(item, options => ['owner', item.key, optionHash(options), createHash('sha256').update(item.title).digest('hex').slice(0, 16)].join('|')); items.push(planApproval(state, items)); const list: GateList = { schema_version: 1, run: state.run, gate_rev: gateRev, items, title: '/autoplan final approval gate', rec_rev: 0, rec_hash_v: 2, + ...(quoted ? { owner_words: gateOwnerWords(owner) } : {}), ...(fs.existsSync(state.active_plan) ? { eli5: buildEli5(fs.readFileSync(state.active_plan, 'utf8'), state.active_plan) } : {}) }; const problems = validateGateList(list); if (problems.length) throw new Error(`gate list invalid: ${problems.join('; ')}`); diff --git a/lib/autoplan-owner-text.ts b/lib/autoplan-owner-text.ts new file mode 100644 index 00000000000..05adcce48d1 --- /dev/null +++ b/lib/autoplan-owner-text.ts @@ -0,0 +1,113 @@ +/** + * autoplan-owner-text — the parts of a plan that say what the owner asked for + * and what they will do on day one (GST-2947). `### Owner's words` quotes the + * owner, one bullet per quote with who and when: only these lines are the + * plan's direction, so a reviewer's challenge to anything else the plan says + * is an ordinary proposal (lib/autoplan-gate-items.ts). `### Day one` is the + * table of the owner's first actions (action, frequency, source, feature, + * route, first build, check); a row whose source is `assumed` becomes an + * owner question at the gate. `### What it won't do yet` lists the plan's + * cuts. Read by the gate builder and the owner and captain briefs. + */ +import { findSection } from './markdown-sections'; + +export const OWNER_WORDS_TITLES = ["Owner's words", 'Owner words']; +export const DAY_ONE_TITLES = ['Day one', 'Day-one page', 'Day one page']; +export const CUTS_TITLES = ["What it won't do yet", 'What it will not do yet', "Won't do yet"]; +export const DAY_ONE_COLUMNS = ['action', 'frequency', 'source', 'feature', 'route', 'first build', 'check'] as const; + +export interface OwnerQuote { n: number; who: string; text: string } +export interface OwnerWordsSection { status: 'none' | 'ok' | 'malformed'; quotes: OwnerQuote[]; reason?: string; fix?: string } +export interface DayOneRow { action: string; frequency: string; source: string; feature: string; route: string; first_build: string; check: string; assumed: boolean } +export interface DayOneTable { status: 'none' | 'ok' | 'malformed'; rows: DayOneRow[]; reason?: string } + +const BULLET = /^\s*[-*+]\s+(.*)$/; +const QUOTED = /[“"](.+)[”"]/; + +/** The quotes under `### Owner's words`; a bullet with no quoted words makes the section malformed (its other quotes still count). */ +export function parseOwnerWords(planText: string): OwnerWordsSection { + const section = findSection(planText, OWNER_WORDS_TITLES); + if (!section) return { status: 'none', quotes: [] }; + const bullets = section.body.split('\n').map(l => BULLET.exec(l)?.[1]?.trim()).filter((b): b is string => !!b); + const fix = 'one bullet per quote: - <who>, <when>: "<their exact words>"'; + if (!bullets.length) return { status: 'malformed', quotes: [], reason: 'the section has no bullet list', fix }; + const quotes: OwnerQuote[] = []; + const bad: number[] = []; + bullets.forEach((b, i) => { + const m = QUOTED.exec(b); + if (!m || !m[1]!.trim()) { bad.push(i + 1); return; } + quotes.push({ n: i + 1, who: b.slice(0, m.index).replace(/[\s:,-]+$/, '').trim() || 'unattributed', text: m[1]!.trim() }); + }); + return bad.length ? { status: 'malformed', quotes, reason: `bullet ${bad.join(', ')} quotes no words`, fix } : { status: 'ok', quotes }; +} + +/** The OWNER_WORDS line `next` and the gate print. */ +export function ownerWordsLine(w: OwnerWordsSection, unverified = 0): string { + if (w.status === 'none') return "OWNER_WORDS: none (no ### Owner's words section: reviewer challenges keep the plan's direction, and the gate asks the owner to confirm it)"; + if (w.status === 'malformed') return `OWNER_WORDS: malformed (${w.reason}; fix: ${w.fix}); ${w.quotes.length} quote${w.quotes.length === 1 ? '' : 's'} read`; + return `OWNER_WORDS: ${w.quotes.length} quote${w.quotes.length === 1 ? '' : 's'}${unverified ? ` (${unverified} unverified: not found in a recorded owner reply)` : ''}`; +} + +const cells = (line: string) => line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(c => c.trim()); +const header = (c: string) => c.toLowerCase().replace(/[*_`]/g, '').replace(/[-\s]+/g, ' ').trim(); + +/** The `### Day one` table: the first table under the heading, with every DAY_ONE_COLUMNS column in any order. */ +export function parseDayOne(planText: string): DayOneTable { + const section = findSection(planText, DAY_ONE_TITLES); + if (!section) return { status: 'none', rows: [] }; + const lines = section.body.split('\n'); + const start = lines.findIndex((l, i) => /^\s*\|/.test(l) && /^\s*\|?\s*:?-{3,}/.test(lines[i + 1] ?? '')); + if (start < 0) return { status: 'malformed', rows: [], reason: `no table (columns: ${DAY_ONE_COLUMNS.join(', ')})` }; + const head = cells(lines[start]!).map(header); + const missing = DAY_ONE_COLUMNS.filter(c => !head.includes(c)); + if (missing.length) return { status: 'malformed', rows: [], reason: `the table has no ${missing.join(', ')} column` }; + const at = (row: string[], c: string) => row[head.indexOf(c)] ?? ''; + const rows: DayOneRow[] = []; + for (let i = start + 2; i < lines.length && /^\s*\|/.test(lines[i]!); i++) { + const row = cells(lines[i]!); + if (!at(row, 'action')) continue; + const source = at(row, 'source'); + rows.push({ action: at(row, 'action'), frequency: at(row, 'frequency'), source, feature: at(row, 'feature'), route: at(row, 'route'), + first_build: at(row, 'first build'), check: at(row, 'check'), assumed: /^\W*assumed\b/i.test(source) }); + } + return rows.length ? { status: 'ok', rows } : { status: 'malformed', rows: [], reason: 'the table has no rows' }; +} + +/** + * What the owner reads first at the gate (lib/captain-brief.ts, lib/owner-brief.ts): the day-one table, what the first + * build won't do yet, and the quoted owner words a reviewer needs the owner's answer to change. Empty when the plan has none. + */ +export function renderDayOne(planText: string, quotes: Array<OwnerQuote & { verified?: boolean }> = []): string[] { + const day = parseDayOne(planText); + const cuts = parseCuts(planText); + const out: string[] = []; + if (day.status === 'ok') { + out.push('### Day one', '', 'What you can do with it on day one:', '', '| What you do | How often | Feature | How you get there | First build with it | How we check it works |', '|---|---|---|---|---|---|', + ...day.rows.map(r => `| ${r.action}${r.assumed ? ' (our guess: asked below)' : ''} | ${r.frequency} | ${r.feature} | ${r.route} | ${r.first_build} | ${r.check} |`), ''); + } + if (cuts.length) out.push("### What it won't do yet", '', ...cuts.map(c => `- ${c}`), ''); + if (quotes.length) out.push('### Your words this plan follows', '', ...quotes.map(q => `- ${q.who}: “${q.text}”${q.verified === false ? ' (not found in your recorded replies)' : ''}`), '', + 'A reviewer who wants to change one of these needs your answer. Anything else in the plan was written by the planning agent, so a reviewer\'s change to it is recommended below.', ''); + return out; +} + +/** The bullets under `### What it won't do yet`. */ +export function parseCuts(planText: string): string[] { + const section = findSection(planText, CUTS_TITLES); + return section ? section.body.split('\n').map(l => BULLET.exec(l)?.[1]?.trim()).filter((b): b is string => !!b) : []; +} + +const STOP = new Set(['the', 'and', 'for', 'with', 'from', 'that', 'this', 'into', 'onto', 'its', 'not', 'yet', 'will', 'won', 'are', 'has', 'have', 'one', 'all', 'any', 'each', 'every', 'day', 'first', 'build', 'v0', 'v1']); +const words = (t: string) => [...new Set((t.toLowerCase().match(/[a-z0-9]+/g) ?? []).filter(w => w.length >= 3 && !STOP.has(w)))]; +const covers = (want: string[], have: Set<string>) => { + const hit = want.filter(w => have.has(w)).length; + return want.length > 0 && hit >= Math.min(2, want.length) && hit / want.length >= 0.6; +}; +/** A cut drops `target` (a feature, an action or a quote) when either names most of the other's words. */ +export function cutDrops(cut: string, target: string): boolean { + const c = words(cut), t = words(target); + return covers(t, new Set(c)) || covers(c, new Set(t)); +} + +/** Text compared as words: case, punctuation and spacing ignored. */ +export const wordKey = (t: string) => ` ${(t.toLowerCase().match(/[a-z0-9]+/g) ?? []).join(' ')} `; diff --git a/lib/autoplan-owner-words.ts b/lib/autoplan-owner-words.ts index 0e19c963b87..17614be1127 100644 --- a/lib/autoplan-owner-words.ts +++ b/lib/autoplan-owner-words.ts @@ -6,8 +6,10 @@ * What counts. `ownerWords` reads the private run and collects every owner * reply it ever recorded: `owner_reply` on decision rows, on run.json's gate * and on every `answered` journal row (attempts.jsonl keeps replies a later - * answer at the same gate replaced), the words a carried gate reused, and a - * reason a human gave for `close --deferred <reason> --by human`. A reply that + * answer at the same gate replaced), the words a carried gate reused, each + * quote in a `### Owner's words` section of any plan text the run kept (plan-active.md, plan-source*.md, + * plan-at-gate.r*.md, plan-file.*.md; lib/autoplan-owner-text.ts), so a quote a revision removed stays redacted, + * and a reason a human gave for `close --deferred <reason> --by human`. A reply that * parsed as gate grammar (`owner_reply_parsed`) is the decision code and is * not scanned for; `reply` and the agent's own `answer_words` stay. * @@ -52,7 +54,8 @@ */ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { readDecisions, readJournal, type RunState } from './autoplan-state'; +import { parseOwnerWords } from './autoplan-owner-text'; +import { FILES, readDecisions, readJournal, type RunState } from './autoplan-state'; export const OWNER_WORDS_MARK = '[owner words redacted]'; export const MIN_TOKENS = 3; @@ -226,7 +229,7 @@ export function redactOwnerWords(text: string, owner: OwnerWords, keep: Span[] = return { text: out, redacted: spans.length }; } -/** Drop the owner-word fields from a JSON value: `owner_reply`, a carry record's `words`, a human deferral's `reason`. */ +/** Drop the owner-word fields from a JSON value: `owner_reply`, a gate's `owner_words`, a carry record's `words`, a human deferral's `reason`. */ export function dropOwnerFields(value: unknown): { value: unknown; dropped: number } { let dropped = 0; const walk = (v: unknown): unknown => { @@ -234,6 +237,7 @@ export function dropOwnerFields(value: unknown): { value: unknown; dropped: numb if (!v || typeof v !== 'object') return v; const o: Record<string, unknown> = { ...(v as Record<string, unknown>) }; if ('owner_reply' in o) { delete o.owner_reply; dropped++; } + if ('owner_words' in o && 'gate_rev' in o) { delete o.owner_words; dropped++; } if ('verdict' in o && typeof o.words === 'string') { delete o.words; dropped++; } if (o.by === 'human' && typeof o.reason === 'string' && 'cause' in o) { o.reason = OWNER_WORDS_MARK; dropped++; } return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, walk(x)])); @@ -269,6 +273,9 @@ export function ownerWords(state: Pick<RunState, 'out' | 'phases' | 'gate' | 'ca const gate = state.gate as { owner_reply?: unknown; answered_at?: unknown; owner_reply_parsed?: unknown } | undefined; note(gate?.owner_reply, gate?.answered_at, gate?.owner_reply_parsed); note(state.carry?.words, undefined, false); + let names: string[] = []; + try { names = fs.readdirSync(out).filter(f => f === FILES.active || /^plan-source.*\.md$/.test(f) || /^plan-at-gate\.r\d+\.md$/.test(f) || /^plan-file\..+\.md$/.test(f)).sort(); } catch { /* no run directory */ } + for (const text of new Set(names.flatMap(f => parseOwnerWords(read(f) ?? '').quotes.map(q => q.text)))) note(text, undefined, false); const deferred = new Map<string, string | undefined>(); for (const r of journal) if (r.event === 'phase_deferred' && r.by === 'human' && typeof r.reason === 'string') deferred.set(r.reason, deferred.get(r.reason) ?? String(r.ts)); diff --git a/lib/autoplan-prompts.ts b/lib/autoplan-prompts.ts index 87b444f2242..fc136627f13 100644 --- a/lib/autoplan-prompts.ts +++ b/lib/autoplan-prompts.ts @@ -123,7 +123,7 @@ RESULT FORMAT (required by gstack-autoplan; the parent binds your file by this c \`\`\`gstack-findings {"id":"F1","severity":"High","title":"<one line>","file":"<path or omit>","line":12,"fix":"<the fix>"} \`\`\` - severity is Critical | High | Medium | Low | Informational. Add "user_challenge": true only when you recommend changing the plan's stated direction AND the change alters its scope, cost or direction (then also add "changes": "scope" | "cost" | "direction") or only its delivery packaging or ordering, with no Implementation-plan edit (then "changes": "packaging" | "ordering"). Naming and other reversible choices are ordinary findings, not user challenges. Add "urgent": true and "suggested_owner": "<who>" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused. + severity is Critical | High | Medium | Low | Informational. Any finding that recommends changing the plan's scope, cost or direction adds "changes": "scope" | "cost" | "direction", or "packaging" | "ordering" when only its delivery packaging or build order changes, with no Implementation-plan edit; that holds at any severity. Only the owner's own words are the plan's direction: add "user_challenge": true and "owner_quote": <n> only when the change goes against bullet n (from 1) of the plan's "Owner's words" section. Scope, order or features the planning agent wrote are proposals, so a change to them is an ordinary finding with "changes" and no user_challenge. A plan with no "Owner's words" section: add "user_challenge": true (no owner_quote) when you recommend changing its stated direction. Naming and other reversible choices are ordinary findings with no "changes". Add "urgent": true and "suggested_owner": "<who>" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused. 3. Write the whole result to this file: ${resultPath} `; diff --git a/lib/autoplan-reconcile.ts b/lib/autoplan-reconcile.ts index cda0de85453..9a7ed459d79 100644 --- a/lib/autoplan-reconcile.ts +++ b/lib/autoplan-reconcile.ts @@ -28,6 +28,10 @@ export interface CanonicalFinding { user_challenge?: boolean; urgent?: boolean; suggested_owner?: string; plan_items?: string[]; dimension?: string; /** What a user challenge changes: scope, cost or direction (plan B2a), or packaging/ordering (settled without a plan edit). */ changes?: Changes; + /** A challenge to the owner's own words: the 1-based bullet of the plan's `### Owner's words` it would change. */ + owner_quote?: number; + /** A confirm round's row naming the earlier challenge id the revised plan now fixes. */ + resolves?: string; } export const CHANGES = ['scope', 'cost', 'direction', 'packaging', 'ordering'] as const; /** Accepted changes of these kinds need no Implementation-plan edit: `revise --settle` records them. */ @@ -90,6 +94,8 @@ function parseFences(text: string, errors: string[]): { findings: CanonicalFindi if (typeof row.suggested_owner === 'string') finding.suggested_owner = row.suggested_owner; if (Array.isArray(row.plan_items)) finding.plan_items = row.plan_items.filter((p: unknown): p is string => typeof p === 'string'); if (typeof row.dimension === 'string') finding.dimension = row.dimension; + if (Number.isInteger(row.owner_quote) && row.owner_quote > 0) finding.owner_quote = row.owner_quote; + if (typeof row.resolves === 'string' && row.resolves.trim()) finding.resolves = row.resolves.trim(); if (row.changes !== undefined) { if (!(CHANGES as readonly unknown[]).includes(row.changes)) { errors.push(`findings row ${i + 1}: changes ${JSON.stringify(row.changes)} is not one of ${CHANGES.join('|')}`); return; } finding.changes = row.changes; @@ -186,7 +192,7 @@ export function canonicalRows(findings: CanonicalFinding[], ctx: { run: string; ...(f.local_id ? { source: f.local_id } : {}), ...(f.user_challenge ? { user_challenge: true } : {}), ...(f.urgent ? { urgent: true } : {}), ...(f.suggested_owner ? { suggested_owner: f.suggested_owner } : {}), ...(f.dimension ? { dimension: f.dimension } : {}), - ...(f.changes ? { changes: f.changes } : {}), + ...(f.changes ? { changes: f.changes } : {}), ...(f.owner_quote ? { owner_quote: f.owner_quote } : {}), ...(f.resolves ? { resolves: f.resolves } : {}), } as FindingRow)); } diff --git a/lib/autoplan-revise.ts b/lib/autoplan-revise.ts index 05be2e50b48..5d884614869 100644 --- a/lib/autoplan-revise.ts +++ b/lib/autoplan-revise.ts @@ -24,7 +24,7 @@ import { exportRun } from './autoplan-export'; import { applyRenames, approve, closeDraftDirections, finishGate, planReopen } from './autoplan-gate'; import { carryLines, keepPlanFile, voidPendingCheck } from './autoplan-carry'; import { atCap, pendingDeltas, roundCap, roundOf } from './autoplan-budget'; -import { diffStat, lineDiff } from './autoplan-confirm'; +import { diffStat, earlierRows, lineDiff } from './autoplan-confirm'; import { SETTLEABLE_CHANGES } from './autoplan-reconcile'; import { normalizeRevision, reviewHash, scaffold } from './autoplan-plan-text'; import { parseScopeTokens } from './autoplan-scope'; @@ -90,20 +90,22 @@ function settleEvidence(state: RunState, ids: string[], revised?: string): { pla const SEVERITY_ORDER = ['Informational', 'Low', 'Medium', 'High', 'Critical']; export const BELOW_HIGH = ['Informational', 'Low', 'Medium']; +/** A finding that changes these is re-reviewed whatever its severity: the owner took a reviewer's scope, direction or cost change. */ +const REREVIEWED_CHANGES = ['scope', 'direction', 'cost']; /** * The severity an incorporated decision resolves to: the highest of the findings its gate item named (the * decisions.jsonl origin's ids, looked up in that phase's bound rows). `unknown` when the row, its origin or a - * finding is missing; `challenge` for a user challenge, whose direction change is always re-reviewed. + * finding is missing; `challenge` for a user challenge or a scope, direction or cost change, which is always re-reviewed. */ export function decisionSeverity(state: RunState, decision: string): string { const row = readDecisions(state.out).find(d => d.id === decision); const [phase, ids] = row?.origin?.split('|') ?? []; if (!phase || !ids || !state.phases[phase]?.closed_at) return 'unknown'; - const rows = [...voiceRows(state, phase, 'native'), ...voiceRows(state, phase, 'outside')]; + const rows = [...voiceRows(state, phase, 'native'), ...voiceRows(state, phase, 'outside'), ...earlierRows(state, phase)]; const found = ids.split('+').filter(id => id && id !== 'null').map(id => rows.find(r => r.id === id)); if (!found.length || found.some(f => !f)) return 'unknown'; - if (found.some(f => (f as { user_challenge?: boolean }).user_challenge)) return 'challenge'; + if (found.some(f => (f as { user_challenge?: boolean }).user_challenge || REREVIEWED_CHANGES.includes((f as { changes?: string }).changes ?? ''))) return 'challenge'; return found.map(f => f!.severity).reduce((a, b) => (SEVERITY_ORDER.indexOf(b) > SEVERITY_ORDER.indexOf(a) ? b : a)); } diff --git a/lib/autoplan-run.ts b/lib/autoplan-run.ts index 0e78b501fe5..1a63fadc55a 100644 --- a/lib/autoplan-run.ts +++ b/lib/autoplan-run.ts @@ -35,6 +35,7 @@ import { familyConflict, modelFamily } from './outside-voice-runner'; import { SpendCapExceeded, release, renderSpend, reserve, settle, summarize, readLedger } from './spend-ledger'; import { DEFAULT_MAX_ROUNDS, attemptEstimate, overCap, resumeStop, roundCap, roundOf, roundsLine, stopForBudget, stopLines } from './autoplan-budget'; import { annotateConfirm, confirmBlock } from './autoplan-confirm'; +import { ownerWordsLine, parseOwnerWords } from './autoplan-owner-text'; import { LEAN_SKIPPED, captureDraft, checkDraftReceipt, draftLine, leanLenses, leanLine, leanMode, leanPrompt, type AutoplanKind } from './autoplan-lean'; /** An unreadable run.lock younger than this is a lock some other gstack is still writing, never a stale one. */ @@ -313,7 +314,7 @@ function recordPlanReality(state: RunState): string[] { const verdict = rows.verdict !== 'complete' ? rows.verdict : plan.verdict; state.plan_reality = { plan_sha256: sha, checker: PLAN_REALITY_CHECKER, verdict, line: `${rows.line}; ${plan.line}` }; journal(state.out, { event: 'plan_reality', plan_sha256: sha, checker: PLAN_REALITY_CHECKER, verdict }); - return [`${rows.line} (report only)`, `${plan.line} (report only)`, ...plan.numberLines]; + return [`${rows.line} (report only)`, `${plan.line} (report only)`, ...plan.numberLines, ownerWordsLine(parseOwnerWords(text))]; } function resolveAttempt(v: VoiceState, attempt: string | undefined, phase: string, voice: Voice): AttemptState { diff --git a/lib/captain-brief.ts b/lib/captain-brief.ts index fc3684a1c34..fbeac405703 100644 --- a/lib/captain-brief.ts +++ b/lib/captain-brief.ts @@ -1,7 +1,8 @@ /** * captain-brief — the plan-approval ask in the shape Capy Captains relay to * their person (capy/skill/gstack/captain.md): a two-line header with the - * one-word reply, then Before → after, Why it matters, What caused this work, + * one-word reply, then the plan's day-one table, what it won't do yet and the + * owner's words it follows when the plan has them (lib/autoplan-owner-text.ts), then Before → after, Why it matters, What caused this work, * Big decisions (each read from the reviewed plan through the shared heading * parser) and What we need from you: the owner's ask format (crew/docs/captain.md * § The ask format), one lettered line per gate choice with the Captain's name @@ -19,6 +20,7 @@ import * as path from 'node:path'; import { gateCost, gateCostSentence, priorChoices } from './autoplan-gate-cost'; import { parseReply, recHash, type GateEli5, type GateItem } from './gate-list'; import { renderUrgentBlock } from './headless-artifacts'; +import { renderDayOne } from './autoplan-owner-text'; import { findSection, firstTitle } from './markdown-sections'; import type { BriefInputs } from './owner-brief'; @@ -47,6 +49,7 @@ const stripRef = (t: string) => t.replace(/\s*\[[^\]]*\]\s*$/, '').trim(); const OPTION_WORDS: Record<string, string> = { 'keep your direction': 'keep the plan as written (a reviewer suggested changing it)', 'accept the change': "make the reviewer's change", + "keep the plan's draft": 'keep the plan as written (a reviewer suggested changing it)', }; const plainOption = (t: string) => { const s = t.replace(/\s*\([^)]*gstack-autoplan[^)]*\)/g, '').trim(); @@ -139,7 +142,8 @@ export function renderCaptainBrief(inputs: BriefInputs, o: { outDir: string; cap `\`gstack-autoplan answer --out ${o.outDir} --gate-rev ${list.gate_rev} --reply rec --rec-hash ${hash} --by agent:<id> --owner-reply "<their exact words>"\`, then \`gstack-approvals import --autoplan ${o.outDir} --by <name>\`.`; // The price sits above the trailer: the relaying agent sends everything above that line, so the person approving sees it. const cost = inputs.run ? ['### Cost', '', gateCostSentence(gateCost(o.outDir, list, { phase_order: inputs.run.phase_order ?? [], outside_enabled: inputs.run.outside_enabled !== false, spend_cap_usd: inputs.run.spend_cap_usd ?? null, scope_flags: inputs.run.scope_flags, lean: inputs.run.lean })), ''] : []; - const text = [...urgent, ...header, '', ...body, ...need, ...cost, '---', '', trailer, ''].join('\n'); + const dayOne = renderDayOne(plan.text, list.owner_words?.quotes); + const text = [...urgent, ...header, '', ...dayOne, ...body, ...need, ...cost, '---', '', trailer, ''].join('\n'); return { text, missing, pending, recHash: hash }; } diff --git a/lib/gate-list.ts b/lib/gate-list.ts index 72a53cccfb0..12759f22f1e 100644 --- a/lib/gate-list.ts +++ b/lib/gate-list.ts @@ -21,6 +21,7 @@ * Rendered by bin/gstack-gate; rows land in decisions.jsonl (lib/headless-artifacts.ts). */ import { createHash } from 'node:crypto'; +import { ownerWordsLine } from './autoplan-owner-text'; import type { DecisionRow } from './headless-artifacts'; /** `changes_plan`: choosing this option is an accepted plan change (reopens its phase plus Eng, prints APPLY:). */ @@ -47,7 +48,8 @@ export interface GateItem { /** An open Critical or High finding (its ids, a paired twin included): `a` applies the reviewer's fix to the plan. */ finding?: string[]; } -export type ItemClass = 'challenge2' | 'challenge1' | 'disagree' | 'agent' | 'cap_deferred' | 'cap_blocker' | 'cap_delta' | 'finding' | 'p1'; +export type ItemClass = 'challenge2' | 'challenge1' | 'disagree' | 'agent' | 'cap_deferred' | 'cap_blocker' | 'cap_delta' | 'finding' | 'p1' + | 'proposal' | 'confirm_direction' | 'day_one' | 'cut' | 'cuts'; export interface GateList { schema_version: 1; run: string; gate_rev: number; items: GateItem[]; title?: string; /** Bumped by every `recommend`, so a `rec` relayed before it no longer matches `recHash`. */ rec_rev?: number; @@ -55,6 +57,8 @@ export interface GateList { schema_version: 1; run: string; gate_rev: number; it rec_hash_v?: 2; /** The plan's plain-language ask, read from the reviewed plan (lib/captain-brief.ts `buildEli5`); printed first. */ eli5?: GateEli5; + /** The plan's `### Owner's words` (lib/autoplan-owner-text.ts): the quotes a challenge must name to keep the plan's direction; `verified` when a recorded owner reply holds it. */ + owner_words?: { status: 'ok' | 'malformed' | 'none'; quotes: Array<{ n: number; who: string; text: string; verified: boolean }>; reason?: string; fix?: string }; /** The one-reviewer check of an unreviewed post-cap delta before a carry (lib/autoplan-carry.ts). */ carry_check?: { attempt: string; model: string; verdict: 'passed' | 'failed' | 'unavailable'; max_severity: string; findings: number; at: string } } /** The captain approvals shape (crew/docs/captain.md § Approvals), section text taken from the reviewed plan; '' when absent. */ @@ -135,6 +139,7 @@ export function renderGate(list: GateList, page = 1, pageSize = PAGE_SIZE): stri lines.push(`GATE: run=${list.run} gate_rev=${list.gate_rev} items=${list.items.length} page=${current}/${pages}${list.title ? ` — ${list.title}` : ''}`); lines.push(''); if (list.eli5 && current === 1) lines.push(...renderEli5(list.eli5), ''); + if (list.owner_words && current === 1) lines.push(...renderOwnerWords(list.owner_words), ''); if (list.carry_check) lines.push(`Carry check ${list.carry_check.attempt}: ${list.carry_check.verdict} (${list.carry_check.model}; ${list.carry_check.findings} finding(s), highest ${list.carry_check.max_severity}).`, ''); list.items.slice(start, start + pageSize).forEach((item, i) => { const n = start + i + 1; @@ -161,6 +166,12 @@ export function renderEli5(e: GateEli5): string[] { return lines; } +/** The OWNER_WORDS line, then each quote a challenge must name to keep the plan's direction, marked when no recorded owner reply holds it. */ +export function renderOwnerWords(w: NonNullable<GateList['owner_words']>): string[] { + return [ownerWordsLine(w, w.quotes.filter(q => !q.verified).length), "Owner's words (a reviewer's challenge to one of these keeps the plan's direction; anything else the plan says is a proposal):", + ...w.quotes.map(q => `${q.n}. ${q.who}: "${q.text}"${q.verified ? '' : ' (unverified: no recorded owner reply holds it)'}`)]; +} + function exampleTokens(list: GateList): string { return list.items.slice(0, 2).map(i => `${i.id}${i.options.find(o => o.key !== i.recommended)?.key ?? i.recommended}`).join(' '); } diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 6e4c3266ba4..927970c9a90 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -30,7 +30,7 @@ export type RunStatus = ResultStatus | 'awaiting_result' | 'running'; export interface FindingRow { schema_version: 1; run: string; id: string; phase: string; voice: Voice; severity: Severity; title: string; model?: string; file?: string; line?: number; disposition?: Disposition; resolution?: string; - plan_items?: string[]; native_counterpart?: string | null; source?: string; changes?: 'scope' | 'cost' | 'direction'; + plan_items?: string[]; native_counterpart?: string | null; source?: string; changes?: 'scope' | 'cost' | 'direction' | 'packaging' | 'ordering'; } export interface DecisionRow { schema_version: 1; run: string; id: string; title: string; options: string[]; recommended: string | null; diff --git a/lib/owner-brief.ts b/lib/owner-brief.ts index 618299714af..3573527b81c 100644 --- a/lib/owner-brief.ts +++ b/lib/owner-brief.ts @@ -13,6 +13,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { gateCost, gateCostSentence } from './autoplan-gate-cost'; +import { renderDayOne } from './autoplan-owner-text'; import { decisionId, PAGE_SIZE, renderGate, type GateList } from './gate-list'; import { readJsonl, renderUrgentBlock, type DecisionRow } from './headless-artifacts'; import type { ResultCodeName } from './result-codes'; @@ -73,6 +74,12 @@ export function renderDecisions(inputs: BriefInputs, page = 1): string { }).join('\n'); } +/** The reviewed plan's text, for the day-one block; '' when the run directory is not known or has no plan. */ +function planText(outDir: string | undefined, run: Record<string, any> | undefined): string { + const file = typeof run?.active_plan === 'string' ? run.active_plan : outDir ? path.join(outDir, 'plan-active.md') : undefined; + try { return file ? fs.readFileSync(file, 'utf8') : ''; } catch { return ''; } +} + export function renderBrief(inputs: BriefInputs, o: { page?: number; summary?: string; outDir?: string } = {}): string { const pages = Math.max(1, Math.ceil(inputs.gate.items.length / PAGE_SIZE)); const page = Math.min(Math.max(1, o.page ?? 1), pages); @@ -83,6 +90,7 @@ export function renderBrief(inputs: BriefInputs, o: { page?: number; summary?: s '', renderUrgentBlock(inputs.findings).trimEnd(), '', + ...renderDayOne(planText(o.outDir, inputs.run), inputs.gate.owner_words?.quotes), '### Summary', '', plainSummary(inputs, o.summary), diff --git a/test/autoplan-carry.test.ts b/test/autoplan-carry.test.ts index 8772eb19632..04465bb9fe8 100644 --- a/test/autoplan-carry.test.ts +++ b/test/autoplan-carry.test.ts @@ -243,12 +243,13 @@ describe('carry-forward', () => { const doIt = answeredAndRevised(); phaseVia(r, doIt.out, 'ceo', NONE); const d = phaseVia(r, doIt.out, 'eng', PKG).outside; - expect(d.stdout).toMatch(/^CARRIED: gate_rev=2 <- gate_rev=1 .*reason="do it" covers \w+; plan unchanged/m); + expect(d.stdout).toMatch(/^CARRIED: gate_rev=2 <- gate_rev=1 .*reason="do it" covers [\w,]+; plan unchanged/m); + expect(d.stdout).toMatch(/^CARRIED_UNDER_DO_IT: \w+ Confirm the plan's direction is yours: .* -> yes, the plan as written is what I asked for/m); expect(d.stdout).toMatch(/^CARRIED_UNDER_DO_IT: \w+ Split the backoff into its own PR .*\(the owner has not seen this item\)$/m); expect(decisions(doIt.out).find(x => x.gate_rev === 2 && /Split the backoff/.test(x.title))).toMatchObject({ carried_under: 'do it' }); const loaded = loadBriefInputs(doIt.out); if ('error' in loaded) throw new Error(String(loaded.error)); - expect(renderCaptainBrief(loaded.inputs, { outDir: doIt.out }).text).toContain('Taken under "do it" without being shown to the owner: Split the backoff into its own PR.'); + expect(renderCaptainBrief(loaded.inputs, { outDir: doIt.out }).text).toContain('Taken under "do it" without being shown to the owner: Split the backoff into its own PR;'); const rec = answeredAndRevised([], 'rec'); phaseVia(r, rec.out, 'ceo', NONE); expect(phaseVia(r, rec.out, 'eng', PKG).outside.stdout).toMatch(/^CARRY: no \(new item \w+: Split the backoff/m); diff --git a/test/autoplan-day-one-gate.test.ts b/test/autoplan-day-one-gate.test.ts new file mode 100644 index 00000000000..8f711017f79 --- /dev/null +++ b/test/autoplan-day-one-gate.test.ts @@ -0,0 +1,365 @@ +/** + * GST-2947 PR 1: the approval page keeps a reviewer's product challenge open. + * A free, deterministic replay of a reviewed app plan's records, rebuilt as a + * synthetic, public-safe fixture (titles and fields only: no owner replies, no + * private content, no real quotes). Round 1's CEO reviewer challenged the build + * order and the promise scope; round 2 never repeated those, and its one + * challenge became "keep your direction" because the planning agent's own draft + * counted as the owner's direction. Now only the plan's `### Owner's words` + * count as direction: the three challenges come out as lettered proposals + * recommending the change. Negative controls: (a) a challenge to a quoted owner + * line keeps the keep-direction default; (b) a plan with no Owner's words + * section keeps today's default and gets one confirm-direction item; (c) a + * round-1 challenge the revision fixed (`resolves`) or the owner answered does + * not resurface. + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { applyGuidance, buildGate } from '../lib/autoplan-gate'; +import { branchKey } from '../lib/approval-record'; +import { proposalCost, proposalItem, ownerContext, recordedOwnerWords } from '../lib/autoplan-gate-items'; +import { confirmBlock, openEarlier, settledIds } from '../lib/autoplan-confirm'; +import { buildTasks } from '../lib/autoplan-export'; +import { exportPublic } from '../lib/autoplan-public'; +import * as crypto from 'node:crypto'; +import { cutDrops, parseCuts, parseDayOne, parseOwnerWords, ownerWordsLine } from '../lib/autoplan-owner-text'; +import { ownerWords, redactOwnerWords } from '../lib/autoplan-owner-words'; +import { consensusRecord, parseReviewResult, reconcile } from '../lib/autoplan-reconcile'; +import { decisionSeverity } from '../lib/autoplan-revise'; +import { writeDecisions, type RunState } from '../lib/autoplan-state'; +import { renderCaptainBrief } from '../lib/captain-brief'; +import { decisionRows, parseReply, renderGate, type GateList } from '../lib/gate-list'; +import type { FindingRow } from '../lib/headless-artifacts'; + +const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'autoplan-day-one-')); +afterAll(() => fs.rmSync(TMP, { recursive: true, force: true })); +const RUN = 'replay-20261117'; +const SHA = 'a'.repeat(64); + +const DAY_ONE = `### Day one + +| action | frequency | source | feature | route | first build | check | +|---|---|---|---|---|---|---| +| sees the day's meetings and who is coming | daily | calendar export | Today screen | root screen | build 1 | the owner's real calendar shows on the phone | +| reads the before-meeting card | several times a day | owner words 1 | Before card | Today screen, tap a meeting | build 1 | a card opens for the next meeting | +| reviews the promises made in a meeting | daily | assumed | Promise review | Today screen, Promises | build 2 | a promise from a test meeting appears | + +### What it won't do yet + +- No Today screen in the first build: notifications only +- No Android build +- No shared team calendars +`; +const planText = (o: { owner?: string | null; dayOne?: boolean } = {}) => [ + '# Meeting companion for the phone and watch (synthetic replay)', '', + '## Implementation plan', '', + ...(o.owner === null ? [] : ["### Owner's words", '', o.owner ?? '- The owner, day 0: "I want to remember what I promised people after every meeting"', '']), + ...(o.dayOne === false ? [] : [DAY_ONE]), + '### Units', '', 'U1 the live lane. U2 the transcript. U3 the before-meeting card. U4 the promise review screen.', '', + '## Review record', ''].join('\n'); + +type Row = Partial<FindingRow> & { id: string; severity: FindingRow['severity']; title: string; user_challenge?: boolean; changes?: string; owner_quote?: number; resolves?: string }; +const row = (phase: string, voice: 'native' | 'outside', r: Row): FindingRow => ({ schema_version: 1, run: RUN, phase, voice, disposition: 'open', ...r } as FindingRow); + +/** Round 1 of the CEO phase: the build-order and promise-scope challenges that round 2 never repeated. */ +const ROUND1 = { + native: [ + row('ceo', 'native', { id: `${RUN}-ceo-native-1`, severity: 'Critical', title: 'Watch cue delivery depends on a reachability the OS grants only in the foreground' }), + row('ceo', 'native', { id: `${RUN}-ceo-native-4`, severity: 'High', title: 'Build order puts the riskiest layer (the live lane) before the loop that pays off on day one (before-meeting card, promise review)', user_challenge: true, changes: 'ordering', resolution: 'build the before-meeting card and the promise review first; the live lane after' }), + row('ceo', 'native', { id: `${RUN}-ceo-native-18`, severity: 'Medium', title: 'The promise ledger learns only from in-person meetings, though the meetings archive already holds the rest', user_challenge: true, changes: 'scope', resolution: 'read promises from the meetings archive too' }), + ], + outside: [row('ceo', 'outside', { id: `${RUN}-ceo-outside-1`, severity: 'High', title: 'The scratch-server checks cannot tell client, transport or server slowness apart' })], +}; +/** Round 2: one new challenge (the replay's d1) and an ordinary High finding; nothing repeats round 1. */ +const round2 = (o: { quote?: number; resolved?: boolean } = {}) => ({ + native: [ + row('ceo', 'native', { id: `${RUN}-ceo-r2-native-1`, severity: 'High', title: 'The two checks that can redirect the plan without any build run only after three units are built', user_challenge: true, changes: 'ordering', resolution: 'run both checks before any build unit', ...(o.quote ? { owner_quote: o.quote } : {}) }), + row('ceo', 'native', { id: `${RUN}-ceo-r2-native-2`, severity: 'High', title: 'The relationship-judgment harness has no runtime home' }), + ...(o.resolved ? [row('ceo', 'native', { id: `${RUN}-ceo-r2-native-3`, severity: 'Informational', title: 'Resolved: the build order now ships the day-one loop first', resolves: `${RUN}-ceo-native-4` })] : []), + ], + outside: [row('ceo', 'outside', { id: `${RUN}-ceo-r2-outside-1`, severity: 'Medium', title: 'The upstream-edit list omits the signing settings' })], +}); + +const jsonl = (rows: unknown[]) => rows.map(r => JSON.stringify(r)).join('\n') + (rows.length ? '\n' : ''); +function makeRun(name: string, o: { plan: string; round2: ReturnType<typeof round2>; round1?: boolean; ui?: boolean; lean?: boolean; answered?: string[] }): RunState { + const out = path.join(TMP, name); + fs.mkdirSync(out, { recursive: true }); + const plan = path.join(out, 'plan-active.md'); + fs.writeFileSync(plan, o.plan); + fs.writeFileSync(path.join(out, 'plan.md'), o.plan); + const voice = (output: string) => ({ status: 'completed', output, model: 'fixture' }); + const write = (stem: string, rows: FindingRow[]) => fs.writeFileSync(path.join(out, `${stem}.findings.jsonl`), jsonl(rows)); + write('ceo-native.a3.bound.md', o.round2.native); write('ceo-outside.a4.bound.md', o.round2.outside); + const history: Array<Record<string, unknown>> = []; + if (o.round1 !== false) { + write('ceo-native.a1.bound.md', ROUND1.native); write('ceo-outside.a2.bound.md', ROUND1.outside); + history.push({ event: 'reopened', phase: 'ceo', previous: { snapshot: SHA, closed_at: '2026-11-09T01:00:00Z', native: voice('ceo-native.a1.bound.md'), outside: voice('ceo-outside.a2.bound.md') } }); + } + const rec = reconcile(o.round2.native, o.round2.outside, []); + fs.writeFileSync(path.join(out, 'ceo-consensus.json'), JSON.stringify(consensusRecord('ceo', { rows: o.round2.native, model: 'fixture' }, { rows: o.round2.outside, model: 'fixture' }, rec))); + fs.writeFileSync(path.join(out, 'attempts.jsonl'), ''); + if (o.answered?.length) writeDecisions(out, o.answered.map((id, i) => ({ schema_version: 1, run: RUN, id: `${RUN}-g1-d${i + 1}`, gate_rev: 1, label: `D${i + 1}`, title: id, status: 'overridden', chosen: 'a', origin: `ceo|${id}|2026-11-09T01:00:00Z|${SHA}|0` } as any))); + return { run: RUN, out, revision: 1, plan_source: path.join(out, 'plan.md'), active_plan: plan, restore: path.join(out, 'restore.md'), scope: { ui: o.ui !== false } as any, phase_order: ['ceo'], + phases: { ceo: { snapshot: SHA, closed_at: '2026-11-10T01:00:00Z', native: voice('ceo-native.a3.bound.md') as any, outside: voice('ceo-outside.a4.bound.md') as any } }, + outside_enabled: true, attempt_counter: 4, spend_cap_usd: null, history, created_at: '2026-11-09T00:00:00Z', updated_at: '2026-11-10T00:00:00Z', ...(o.lean ? { lean: 'lean' as any } : {}) } as unknown as RunState; +} +const byClass = (list: GateList, cls: string) => list.items.filter(i => i.item_class === cls); +const lettered = (list: GateList) => list.items.filter(i => i.id !== 'p1').length; +const covering = (list: GateList, id: string) => list.items.find(i => i.title.includes(`[${id}`) || i.title.includes(` ${id}]`) || i.title.includes(`+ ${id}`)); +const rec = (list: GateList) => Object.fromEntries(parseReply('rec', list).choices.map(c => [c.id, c.chosen])); + +describe('replay: a reviewed app plan whose product challenges were hidden', () => { + const state = makeRun('replay', { plan: planText(), round2: round2() }); + const list = buildGate(state, 1); + + test('round-1 build order (F4) and promise scope (F18) come back as lettered proposals recommending the change', () => { + for (const id of [`${RUN}-ceo-native-4`, `${RUN}-ceo-native-18`]) { + const item = covering(list, id)!; + expect(item).toBeDefined(); + expect(item.item_class).toBe('proposal'); + expect(item.kind).toBe('approval'); + expect(item.recommended).toBe('a'); + expect(item.options.find(o => o.key === 'a')!.text).toStartWith('take the change: '); + expect(item.why).toContain('raised in an earlier round and still open'); + } + }); + + test("round 2's one-voice challenge (d1) recommends the reviewer's change, not \"keep your direction\"", () => { + const d1 = covering(list, `${RUN}-ceo-r2-native-1`)!; + expect(d1.item_class).toBe('proposal'); + expect(rec(list)[d1.id]).toBe('a'); + expect(d1.options.find(o => o.key === d1.recommended)!.changes_plan).toBe(true); + expect(list.items.some(i => i.options.some(o => o.text.startsWith('keep your direction')))).toBe(false); + expect(list.items.find(i => i.id === 'p1')!.recommended).toBe('b'); + }); + + test('day one: the assumed row is an owner question, the cut that drops the Today screen is lettered, the rest are one item', () => { + expect(byClass(list, 'day_one').map(i => i.title)).toEqual(['Day one: the plan assumes you will do "reviews the promises made in a meeting" (daily); is that right?']); + expect(byClass(list, 'cut').map(i => i.title)).toEqual(['Cut: No Today screen in the first build: notifications only']); + expect(byClass(list, 'cuts').map(i => i.title)).toEqual(['2 other cuts: No Android build; No shared team calendars']); + expect(list.owner_words).toMatchObject({ status: 'ok', quotes: [{ n: 1, verified: false }] }); + }); + + test('lettered-item counts (recorded for the PR): 3 proposals, 3 day-one items, 1 High finding', () => { + expect(byClass(list, 'proposal').length).toBe(3); + expect(byClass(list, 'finding').length).toBe(1); + expect(lettered(list)).toBe(7); + }); +}); + +describe('negative controls', () => { + test('(a) a challenge to a quoted owner line keeps "keep your direction"', () => { + const owner = '- The owner, day 0: "I want to remember what I promised people after every meeting"\n- The owner, day 0: "build the live lane first, it is the whole point"'; + const list = buildGate(makeRun('control-a', { plan: planText({ owner }), round2: round2({ quote: 2 }) }), 1); + const d1 = covering(list, `${RUN}-ceo-r2-native-1`)!; + expect(d1.item_class).toBe('challenge1'); + expect(d1.recommended).toBe('a'); + expect(d1.options[0]!.text).toBe('keep your direction'); + expect(byClass(list, 'confirm_direction')).toEqual([]); + expect(byClass(list, 'proposal').length).toBe(2); + expect(lettered(list)).toBe(7); + }); + + test("(b) no Owner's words section: today's keep-direction default stays, plus one confirm-direction item", () => { + const list = buildGate(makeRun('control-b', { plan: planText({ owner: null }), round2: round2() }), 1); + expect(byClass(list, 'proposal')).toEqual([]); + const kept = byClass(list, 'challenge1'); + expect(kept.map(i => i.recommended)).toEqual(['a', 'a', 'a']); + expect(kept.every(i => i.options[0]!.text === 'keep your direction')).toBe(true); + const confirm = byClass(list, 'confirm_direction'); + expect(confirm.length).toBe(1); + expect(confirm[0]!.title).toContain(kept.map(i => i.id).join(', ')); + expect(list.owner_words).toBeUndefined(); + expect(lettered(list)).toBe(8); + }); + + test('(c) a round-1 challenge the revision fixed (resolves) or the owner answered does not resurface', () => { + const state = makeRun('control-c', { plan: planText(), round2: round2({ resolved: true }), answered: [`${RUN}-ceo-native-18`] }); + const list = buildGate(state, 2); + expect(covering(list, `${RUN}-ceo-native-4`)).toBeUndefined(); + expect(covering(list, `${RUN}-ceo-native-18`)).toBeUndefined(); + expect(openEarlier(state, 'ceo', [...round2({ resolved: true }).native])).toEqual([]); + expect(byClass(list, 'proposal').length).toBe(1); + expect(lettered(list)).toBe(5); + }); + + test('a later round staying silent never closes a challenge, and a lean run carries nothing', () => { + const state = makeRun('silent', { plan: planText(), round2: round2() }); + expect(openEarlier(state, 'ceo', round2().native).map(r => r.id)).toEqual([`${RUN}-ceo-native-4`, `${RUN}-ceo-native-18`]); + expect(openEarlier({ ...state, lean: 'lean' as any }, 'ceo', round2().native)).toEqual([]); + }); + + test('the confirm round lists the open earlier challenges and asks for resolves', () => { + const state = makeRun('confirm', { plan: planText(), round2: round2() }); + const block = confirmBlock(state, 'ceo', path.join(state.out, 'missing-snapshot.md'), 2)!.text; + expect(block).toContain(`- ${RUN}-ceo-native-4: Build order puts the riskiest layer`); + expect(block).toContain('"resolves":"<id>"'); + }); +}); + +describe('owner_quote downgrade, the day-one page requirement and the cost line', () => { + test('a challenge naming no real owner line is an ordinary proposal', () => { + const list = buildGate(makeRun('bad-quote', { plan: planText(), round2: round2({ quote: 9 }), round1: false }), 1); + expect(covering(list, `${RUN}-ceo-r2-native-1`)!.item_class).toBe('proposal'); + }); + + test('a below-High challenge with no changes and no real owner line still reaches the gate as a proposal', () => { + const native = [row('ceo', 'native', { id: `${RUN}-ceo-r2-native-9`, severity: 'Medium', title: 'Make the summary daily instead of weekly', user_challenge: true, owner_quote: 99 })]; + const list = buildGate(makeRun('challenge-no-changes', { plan: planText(), round2: { native, outside: [] }, round1: false }), 1); + const item = covering(list, `${RUN}-ceo-r2-native-9`)!; + expect(item.item_class).toBe('proposal'); + expect(item.changes).toBe('direction'); + expect(item.recommended).toBe('a'); + }); + + test('an ordinary finding that only correlates with an earlier challenge does not close it', () => { + const state = makeRun('correlated', { plan: planText(), round2: round2() }); + const naming = row('ceo', 'native', { id: `${RUN}-ceo-r2-native-8`, severity: 'Low', title: 'Build order wording', correlates: [`${RUN}-ceo-native-4`] } as Row); + expect(openEarlier(state, 'ceo', [naming]).map(r => r.id)).toContain(`${RUN}-ceo-native-4`); + const repeat = row('ceo', 'native', { id: `${RUN}-ceo-r2-native-7`, severity: 'High', title: 'Build order again', changes: 'ordering', correlates: [`${RUN}-ceo-native-4`] } as Row); + expect(openEarlier(state, 'ceo', [repeat]).map(r => r.id)).not.toContain(`${RUN}-ceo-native-4`); + }); + + test('a paired ordering and scope proposal takes scope: its cost line reopens and applyGuidance does not settle it', () => { + const state = makeRun('pair', { plan: planText(), round2: round2(), round1: false }); + const pair = [row('ceo', 'native', { id: 'n1', severity: 'Medium', title: 'Build the card first', changes: 'ordering' }), row('ceo', 'outside', { id: 'o1', severity: 'Medium', title: 'Build the card first', changes: 'scope' })] as any; + const item = proposalItem(ownerContext(state, []), 'ceo', pair); + expect(item.changes).toBe('scope'); + expect(item.cost).toBe('a reopens ceo and eng once the plan is revised'); + expect(applyGuidance({ changes: item.changes as any, item: 'uc1' })).toBe('edit the plan, then revise'); + }); + + test('a High proposal answered b keeps its finding open as a blocking task; below High keeps the plain draft option', () => { + const state = makeRun('high-b', { plan: planText(), round2: round2(), round1: false }); + const list = buildGate(state, 1); + const high = covering(list, `${RUN}-ceo-r2-native-1`)!; + expect(high.item_class).toBe('proposal'); + expect(high.recommended).toBe('a'); + expect(high.options.find(o => o.key === 'b')!.text).toBe("keep the plan's draft; carry it into the build as a blocking task (no plan change)"); + expect(high.origin).toEndWith('|finding'); + writeDecisions(state.out, [{ schema_version: 1, run: RUN, id: `${RUN}-g1-${high.id}`, gate_rev: 1, label: high.id.toUpperCase(), title: high.title, status: 'overridden', chosen: 'b', origin: high.origin } as any]); + expect(settledIds(state).has(`${RUN}-ceo-r2-native-1`)).toBe(false); + expect(buildTasks(state, round2().native).some(t => t.findings.includes(`${RUN}-ceo-r2-native-1`))).toBe(true); + const medium = buildGate(makeRun('medium-b', { plan: planText(), round2: round2() }), 1); + const scope = covering(medium, `${RUN}-ceo-native-18`)!; + expect(scope.options.find(o => o.key === 'b')!.text).toBe("keep the plan's draft"); + expect(scope.origin).not.toEndWith('|finding'); + }); + + test('a quote a revision removed stays redacted in the public export of an earlier reviewer result', () => { + const quote = 'I want to remember what I promised people after every meeting'; + const state = makeRun('revised-quote', { plan: planText({ owner: null }), round2: round2(), round1: false }); + fs.writeFileSync(path.join(state.out, 'plan-source.md'), planText()); + fs.writeFileSync(path.join(state.out, 'ceo-native.a1.bound.md'), `The owner said "${quote}", so keep the promise review.\n`); + const sha = (f: string) => crypto.createHash('sha256').update(fs.readFileSync(path.join(state.out, f))).digest('hex'); + const run = { ...state, artifacts: { 'ceo-native.a1.bound.md': { path: 'ceo-native.a1.bound.md', sha256: sha('ceo-native.a1.bound.md') } } } as RunState; + fs.writeFileSync(path.join(state.out, 'run.json'), JSON.stringify(run, null, 2)); + const pub = path.join(TMP, 'revised-quote-public'); + exportPublic(run, pub); + const text = fs.readFileSync(path.join(pub, 'ceo-native.a1.bound.md'), 'utf8'); + expect(text).not.toContain(quote); + expect(text).toContain('[owner words redacted]'); + }); + + test('a changed cut list or challenge list gets a new origin, so an earlier answer is asked again instead of carried', () => { + const origin = (list: GateList, cls: string) => byClass(list, cls)[0]!.origin; + const cuts = (extra: string) => planText().replace('- No shared team calendars\n', `- No shared team calendars\n${extra}`); + const before = buildGate(makeRun('cuts-before', { plan: cuts(''), round2: round2(), round1: false }), 1); + const after = buildGate(makeRun('cuts-after', { plan: cuts('- No web dashboard\n'), round2: round2(), round1: false }), 1); + expect(origin(after, 'cuts')).not.toBe(origin(before, 'cuts')); + const confirmOne = buildGate(makeRun('confirm-one', { plan: planText({ owner: null }), round2: round2(), round1: false }), 1); + const confirmTwo = buildGate(makeRun('confirm-two', { plan: planText({ owner: null }), round2: round2() }), 1); + expect(origin(confirmTwo, 'confirm_direction')).not.toBe(origin(confirmOne, 'confirm_direction')); + }); + + test('an app plan with no Day one table gets one item; a backend plan never does', () => { + const app = buildGate(makeRun('no-day-one-app', { plan: planText({ dayOne: false }), round2: round2(), round1: false }), 1); + expect(byClass(app, 'day_one').map(i => [i.title.slice(0, 32), i.recommended])).toEqual([['The plan has no day-one page: th', 'a']]); + const backend = buildGate(makeRun('no-day-one-backend', { plan: planText({ dayOne: false }), round2: round2(), round1: false, ui: false }), 1); + expect(byClass(backend, 'day_one')).toEqual([]); + }); + + test("the cost line states what revise does: full runs re-review scope (even below High), settle ordering, lean applies", () => { + const state = makeRun('cost', { plan: planText(), round2: round2() }); + const list = buildGate(state, 1); + writeDecisions(state.out, decisionRows(list)); + const scope = covering(list, `${RUN}-ceo-native-18`)!; + expect(scope.cost).toBe('a reopens ceo and eng once the plan is revised'); + expect(decisionSeverity(state, decisionRows(list).find(r => r.label?.toLowerCase() === scope.id)!.id)).toBe('challenge'); + const order = covering(list, `${RUN}-ceo-r2-native-1`)!; + expect(order.cost).toBe('a is settled with revise --settle: no plan edit, no re-review'); + expect(applyGuidance({ changes: order.changes, item: order.id })).toBe(`no plan edit needed: revise --settle ${order.id}`); + const lean = ownerContext({ ...state, lean: 'lean' as any }, []); + expect(proposalCost(lean, 'eng', 'scope')).toBe('a applies without re-review (lean run: one gate revision)'); + }); +}); + +describe('parsers, render and redaction', () => { + test("Owner's words: ok, none and malformed, with the OWNER_WORDS line", () => { + expect(parseOwnerWords(planText())).toEqual({ status: 'ok', quotes: [{ n: 1, who: 'The owner, day 0', text: 'I want to remember what I promised people after every meeting' }] }); + expect(ownerWordsLine(parseOwnerWords(planText({ owner: null })))).toStartWith('OWNER_WORDS: none'); + const bad = parseOwnerWords(planText({ owner: '- The owner said to ship it' })); + expect(bad.status).toBe('malformed'); + expect(ownerWordsLine(bad)).toBe('OWNER_WORDS: malformed (bullet 1 quotes no words; fix: one bullet per quote: - <who>, <when>: "<their exact words>"); 0 quotes read'); + expect(ownerWordsLine(parseOwnerWords(planText()), 1)).toBe('OWNER_WORDS: 1 quote (1 unverified: not found in a recorded owner reply)'); + }); + + test('Day one table and cuts', () => { + const day = parseDayOne(planText()); + expect(day.status).toBe('ok'); + expect(day.rows.map(r => [r.feature, r.assumed])).toEqual([['Today screen', false], ['Before card', false], ['Promise review', true]]); + expect(parseDayOne('### Day one\n\n| action | feature |\n|---|---|\n| a | b |\n')).toMatchObject({ status: 'malformed', reason: 'the table has no frequency, source, route, first build, check column' }); + expect(parseCuts(planText())).toEqual(['No Today screen in the first build: notifications only', 'No Android build', 'No shared team calendars']); + expect(cutDrops('No Today screen in the first build', 'Today screen')).toBe(true); + expect(cutDrops('No Android build', 'Today screen')).toBe(false); + }); + + test('reviewer rows carry owner_quote and resolves; bad values are dropped', () => { + const fence = (row: object) => `INPUT: ceo ${SHA}\n\n\`\`\`gstack-findings\n${JSON.stringify(row)}\n\`\`\`\n`; + const ok = parseReviewResult(fence({ severity: 'High', title: 't', user_challenge: true, owner_quote: 2, changes: 'ordering' }), { phase: 'ceo', sha256: SHA }); + expect(ok.findings[0]).toMatchObject({ owner_quote: 2, user_challenge: true, changes: 'ordering' }); + const resolved = parseReviewResult(fence({ severity: 'Informational', title: 'Resolved: t', resolves: ' x-1 ' }), { phase: 'ceo', sha256: SHA }); + expect(resolved.findings[0]!.resolves).toBe('x-1'); + const bad = parseReviewResult(fence({ severity: 'High', title: 't', owner_quote: 0, resolves: '' }), { phase: 'ceo', sha256: SHA }); + expect(bad.findings[0]!.owner_quote).toBeUndefined(); + expect(bad.findings[0]!.resolves).toBeUndefined(); + }); + + test('the gate render and the captain brief open with what the owner can do on day one and the words they are protected by', () => { + const state = makeRun('render', { plan: planText(), round2: round2() }); + const list = buildGate(state, 1); + const rendered = renderGate(list, 1, 50); + expect(rendered).toContain("OWNER_WORDS: 1 quote (1 unverified"); + expect(rendered).toContain('1. The owner, day 0: "I want to remember what I promised people after every meeting" (unverified'); + const brief = renderCaptainBrief({ gate: list, decisions: decisionRows(list), findings: [], run: { status: 'gate_pending', active_plan: state.active_plan } }, { outDir: state.out }).text; + expect(brief.indexOf('### Day one')).toBeGreaterThan(0); + expect(brief.indexOf('### Day one')).toBeLessThan(brief.indexOf("### What it won't do yet")); + expect(brief.indexOf("### What it won't do yet")).toBeLessThan(brief.indexOf('### Before → after')); + expect(brief).toContain('| reviews the promises made in a meeting (our guess: asked below) | daily |'); + }); + + test('a quote found in an approvals record on disk is verified, and reading it writes nothing to the state root', () => { + const state = makeRun('ledger', { plan: planText(), round2: round2(), round1: false }); + const repo = path.dirname(state.plan_source); + expect(spawnSync('git', ['init', '-q', '-b', 'day-one-ledger', repo], { encoding: 'utf8', timeout: 30_000 }).status).toBe(0); + const home = path.join(TMP, 'ledger-home'); + const mirror = path.join(TMP, 'ledger-mirror', 'some-slug'); + fs.mkdirSync(mirror, { recursive: true }); + fs.writeFileSync(path.join(mirror, `${branchKey('day-one-ledger')}.jsonl`), JSON.stringify({ schema_version: 1, id: 'x', words: 'The owner said: I want to remember what I promised people after every meeting' }) + '\n'); + const env = { HOME: home, GSTACK_APPROVALS_DIR: path.dirname(mirror) }; + const words = recordedOwnerWords(state, env); + expect(ownerContext(state, words).verified).toEqual(new Set([1])); + expect(fs.existsSync(home)).toBe(false); + }); + + test('quoted owner words are redacted from public copies', () => { + const state = makeRun('redact', { plan: planText(), round2: round2(), round1: false }); + const words = ownerWords(state); + const out = redactOwnerWords('The plan says: I want to remember what I promised people after every meeting.', words); + expect(out.redacted).toBe(1); + expect(out.text).not.toContain('promised people'); + }); +}); diff --git a/test/captain-brief.test.ts b/test/captain-brief.test.ts index ddbce6b1e8c..e7f2471609e 100644 --- a/test/captain-brief.test.ts +++ b/test/captain-brief.test.ts @@ -178,7 +178,7 @@ describe('carried decisions at a cap gate (#3546)', () => { const challenge = (title: string) => ({ severity: 'Medium', title, fix: `change: ${title}`, user_challenge: true, changes: 'scope' }); phaseVia(r, out, 'ceo', { native: [challenge('Use a queue table'), challenge('Add metrics')], outside: [challenge('Drop jitter')] }); phaseVia(r, out, 'eng', { native: [], outside: [] }); - const ds = JSON.parse(fs.readFileSync(path.join(out, 'gate.json'), 'utf8')).items.filter((i: any) => i.id.startsWith('d')); + const ds = JSON.parse(fs.readFileSync(path.join(out, 'gate.json'), 'utf8')).items.filter((i: any) => i.item_class === 'challenge1'); expect(ds.map((i: any) => i.recommended)).toEqual(['a', 'a', 'a']); expect(r.ap(['answer', '--by', 'human', '--out', out, '--gate-rev', '1', '--reply', `${ds.map((i: any) => `${i.id}b`).join(' ')} p1b`]).status).toBe(0); const v2 = path.join(dir, 'plan-v2.md'); @@ -203,7 +203,7 @@ describe('carried decisions at a cap gate (#3546)', () => { const { gate, gateText, briefText, gateRec, briefRec } = renders(out); expect(gate.gate_rev).toBe(2); expect(gate.items.some(i => i.cap?.kind === 'delta')).toBe(true); - const carried = gate.items.filter(i => i.carried); + const carried = gate.items.filter(i => i.carried && i.item_class === 'challenge1'); expect(carried.map(i => [i.recommended, i.carried!.chosen])).toEqual([['a', 'b'], ['a', 'b'], ['a', 'b']]); expect(briefRec).toEqual(gateRec); expect(Object.fromEntries(carried.map(i => [i.id, gateRec[i.id]]))).toEqual({ d1: 'b', d2: 'b', d3: 'b' }); @@ -213,7 +213,7 @@ describe('carried decisions at a cap gate (#3546)', () => { expect(briefText).toContain(`- ${String.fromCharCode(65 + n)}: ${item.title.replace(/\s*\[[^\]]*\]\s*$/, '')}. We could: 1) ${WORDS[text] ?? text};`); }); expect(briefText).toContain("- A: Use a queue table. We could: 1) make the reviewer's change; 2) keep the plan as written (a reviewer suggested changing it). Recommendation: make the reviewer's change (your answer at gate_rev 1, carried forward). A1 to take recommendation."); - expect(briefText).toContain('do it keeps the 3 you already answered and takes the recommendation for the rest.'); + expect(briefText).toContain('do it keeps the 4 you already answered and takes the recommendation for the rest.'); expect(briefText).toContain('Reply **do it** to keep the answers you already gave and take every other recommendation (recommended)'); }); diff --git a/test/fixtures/module-size-ratchet.json b/test/fixtures/module-size-ratchet.json index bf2786bfe59..6c062b2e304 100644 --- a/test/fixtures/module-size-ratchet.json +++ b/test/fixtures/module-size-ratchet.json @@ -148,6 +148,8 @@ { "file": "lib/autoplan-export.ts", "movedFrom": "(new: the unattended export file set, B2/B12)" }, { "file": "lib/spec-review-cap.ts", "movedFrom": "(new: the spec-review loop at the cap: numbered gaps and deterministic fix verification, B8)" }, { "file": "bin/gstack-autoplan", "movedFrom": "(new: thin entrypoint over lib/autoplan-run.ts, B2)" }, + { "file": "lib/autoplan-gate-items.ts", "movedFrom": "(new: the gate items that keep reviewer product challenges on the owner's page, GST-2947)" }, + { "file": "lib/autoplan-owner-text.ts", "movedFrom": "(new: the plan's Owner's words, Day one and cuts sections, GST-2947)" }, { "file": "lib/autoplan-plan-text.ts", "movedFrom": "(new: plan wrap, Implementation-plan review hash, scaffold and drift lines, field wave B1c)" }, { "file": "lib/autoplan-admission.ts", "movedFrom": "(new: install verdict and Bun minimum admission for mutating autoplan verbs, field wave B-core)" }, { "file": "lib/autoplan-migrate.ts", "movedFrom": "(new: gstack_version stamp and legacy decision-id migration at load, field wave B1a)" }, From a141e943887945d0a55830a70a29227e7312d5b9 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 20:05:52 +0800 Subject: [PATCH 27/62] Ask each question once and check every handed-over file, in every skill that loads the shared preamble (GST-2756) (#4383) * Load the never-print-secrets rule in every skill on every host, with the commands it missed (GST-2753) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Ask each question once and check every handed-over file, in every skill on every host (GST-2756) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Point the shared CI-wait rule at gstack-pr-wait and name the missed secret-printing commands The Ground Rules section told every skill to wait with gh pr checks --watch, which spends the shared GitHub GraphQL quota gstack moved off; it now names gstack-pr-wait. The banned list also covers ps aux and ps -ef, set -x, git config -l and an export $(...) that expands to a bare export. Size caps raised to the measured +70 bytes. Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Say which skills carry the new rule in its release note Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Say the new rules reach only skills that load the shared preamble Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * List all four shared Ground Rules in the loadouts guide Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- SKILL.md | 2 ++ autoplan/SKILL.md | 2 +- autoplan/sections/preamble.md | 4 +++- benchmark-models/SKILL.md | 2 ++ benchmark/SKILL.md | 2 ++ browse/SKILL.md | 2 ++ canary/SKILL.md | 2 +- canary/sections/preamble.md | 4 +++- captain/SKILL.md | 2 +- captain/sections/preamble.md | 4 +++- capy/skill/gstack/factory.md | 2 +- .../ask-once-and-check-handoff-files.md | 1 + codex/SKILL.md | 2 +- codex/sections/preamble.md | 4 +++- context-restore/SKILL.md | 2 +- context-restore/sections/preamble.md | 4 +++- context-save/SKILL.md | 2 +- context-save/sections/preamble.md | 4 +++- design-consultation/SKILL.md | 2 +- design-consultation/sections/preamble.md | 4 +++- design-html/SKILL.md | 2 +- design-html/sections/preamble.md | 4 +++- design-motion/SKILL.md | 2 +- design-motion/sections/preamble.md | 4 +++- design-review/SKILL.md | 2 +- design-review/sections/preamble.md | 4 +++- design-shotgun/SKILL.md | 2 +- design-shotgun/sections/preamble.md | 4 +++- devex-review/SKILL.md | 2 +- devex-review/sections/preamble.md | 4 +++- diagram/SKILL.md | 2 ++ docs/loadouts.md | 2 +- document-generate/SKILL.md | 2 +- document-generate/sections/preamble.md | 4 +++- document-release/SKILL.md | 2 +- document-release/sections/preamble.md | 4 +++- eval-plan/SKILL.md | 2 +- eval-plan/sections/preamble.md | 4 +++- health/SKILL.md | 2 +- health/sections/preamble.md | 4 +++- ios-clean/SKILL.md | 2 +- ios-clean/sections/preamble.md | 4 +++- ios-design-review/SKILL.md | 2 +- ios-design-review/sections/preamble.md | 4 +++- ios-fix/SKILL.md | 2 +- ios-fix/sections/preamble.md | 4 +++- ios-qa/SKILL.md | 2 +- ios-qa/sections/preamble.md | 4 +++- ios-sync/SKILL.md | 2 +- ios-sync/sections/preamble.md | 4 +++- land-and-deploy/SKILL.md | 2 +- land-and-deploy/sections/preamble.md | 4 +++- landing-report/SKILL.md | 2 +- landing-report/sections/preamble.md | 4 +++- learn/SKILL.md | 2 +- learn/sections/preamble.md | 4 +++- make-pdf/SKILL.md | 2 ++ modernize/SKILL.md | 2 +- modernize/sections/preamble.md | 4 +++- office-hours/SKILL.md | 2 +- office-hours/sections/preamble.md | 4 +++- open-gstack-browser/SKILL.md | 2 ++ pair-agent/SKILL.md | 2 +- pair-agent/sections/preamble.md | 4 +++- plan-ceo-review/SKILL.md | 2 +- plan-ceo-review/sections/preamble.md | 4 +++- plan-design-review/SKILL.md | 2 +- plan-design-review/sections/preamble.md | 4 +++- plan-devex-review/SKILL.md | 2 +- plan-devex-review/sections/preamble.md | 4 +++- plan-eng-review/SKILL.md | 2 +- plan-eng-review/sections/preamble.md | 4 +++- plan-tune/SKILL.md | 2 +- plan-tune/sections/preamble.md | 4 +++- qa-only/SKILL.md | 2 +- qa-only/sections/preamble.md | 4 +++- qa/SKILL.md | 2 +- qa/sections/preamble.md | 4 +++- retro/SKILL.md | 2 +- retro/sections/preamble.md | 4 +++- review/SKILL.md | 2 +- review/sections/preamble.md | 4 +++- runaway-stopper/SKILL.md | 2 ++ scrape/SKILL.md | 2 ++ .../preamble/generate-ground-rules.ts | 4 +++- setup-browser-cookies/SKILL.md | 2 ++ setup-deploy/SKILL.md | 2 +- setup-deploy/sections/preamble.md | 4 +++- setup-gbrain/SKILL.md | 2 +- setup-gbrain/sections/preamble.md | 4 +++- ship/SKILL.md | 2 +- ship/sections/preamble.md | 4 +++- skillify/SKILL.md | 2 +- skillify/sections/preamble.md | 4 +++- spec/SKILL.md | 2 +- spec/sections/preamble.md | 4 +++- sync-gbrain/SKILL.md | 2 +- sync-gbrain/sections/preamble.md | 4 +++- test-audit/SKILL.md | 2 +- test-audit/sections/preamble.md | 4 +++- test/fixtures/context-budget.json | 2 +- test/fixtures/golden/agy-ship-SKILL.md | 2 +- test/fixtures/golden/claude-ship-SKILL.md | 2 +- test/fixtures/golden/codex-ship-SKILL.md | 2 +- test/fixtures/golden/factory-ship-SKILL.md | 2 +- test/ground-rules.test.ts | 12 +++++++++++ test/helpers/carve-guards.ts | 20 +++++++++---------- .../ask-once-and-check-handoff-files.json | 4 ++++ ubicloud/SKILL.md | 2 +- ubicloud/sections/preamble.md | 4 +++- verify/SKILL.md | 2 ++ write-skill/SKILL.md | 2 +- write-skill/sections/preamble.md | 4 +++- 113 files changed, 239 insertions(+), 108 deletions(-) create mode 100644 changelog.d/ask-once-and-check-handoff-files.md create mode 100644 test/size-ledger/ship/ask-once-and-check-handoff-files.json diff --git a/SKILL.md b/SKILL.md index 300fc282e4f..58ac4edc031 100644 --- a/SKILL.md +++ b/SKILL.md @@ -98,6 +98,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/autoplan/SKILL.md b/autoplan/SKILL.md index 1eda17e558c..4dba708962b 100644 --- a/autoplan/SKILL.md +++ b/autoplan/SKILL.md @@ -34,7 +34,7 @@ hooks: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/autoplan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/autoplan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/autoplan/sections/preamble.md b/autoplan/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/autoplan/sections/preamble.md +++ b/autoplan/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/benchmark-models/SKILL.md b/benchmark-models/SKILL.md index 88f3f732147..54d2533b887 100644 --- a/benchmark-models/SKILL.md +++ b/benchmark-models/SKILL.md @@ -98,6 +98,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/benchmark/SKILL.md b/benchmark/SKILL.md index 1795f5270a8..fc6733d8e66 100644 --- a/benchmark/SKILL.md +++ b/benchmark/SKILL.md @@ -99,6 +99,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/browse/SKILL.md b/browse/SKILL.md index fbd8c6cc0fc..509263edd1b 100644 --- a/browse/SKILL.md +++ b/browse/SKILL.md @@ -98,6 +98,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/canary/SKILL.md b/canary/SKILL.md index 68d2b514fa2..a6958470518 100644 --- a/canary/SKILL.md +++ b/canary/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/canary/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/canary/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/canary/sections/preamble.md b/canary/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/canary/sections/preamble.md +++ b/canary/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/captain/SKILL.md b/captain/SKILL.md index 14d68cedb45..ff3f42283d5 100644 --- a/captain/SKILL.md +++ b/captain/SKILL.md @@ -26,7 +26,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/captain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/captain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/captain/sections/preamble.md b/captain/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/captain/sections/preamble.md +++ b/captain/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/capy/skill/gstack/factory.md b/capy/skill/gstack/factory.md index c6134b3a008..cb6aba07200 100644 --- a/capy/skill/gstack/factory.md +++ b/capy/skill/gstack/factory.md @@ -12,7 +12,7 @@ Your crew's CREW.md and recorded approvals decide who may merge, update a base, 8. **Evals decide, and losses get reported.** Preregister bars, cap and stop rule before paying [/eval-plan]. Cheap proof (a keyless fake, a smoke) first. Controls: no-skill and placebo arms, clean decoys. Report use and pass apart; quote spend from the meter. A new part needs proof it helps or a dated test plan [ETHOS.md: 9. Earn Its Place]. 9. **Flakes: one rerun, a ledger, a daily fix.** Only the policy's rerun, never for a harness or infra red; a second red is real; never loosen a test. [crew/docs/captain.md: The daily flaky pass] 10. **Quiet.** Messages wake the Captain cold: send READY, a blocker, done or a Captain or owner call, else end_turn; no acks or progress notes. Reports and replies open with `Failed or skipped:`, `Unverified:` and `Also changed:` lines (each item, or none), under 250 words; top 10 of long lists. Findings write-ups follow [ETHOS.md: 8. Explain the Number]. Broadcasts go in its notes. -11. **Ask once, plainly.** One ask per decision, explained like the owner is five: your Captain's name, then a lettered line each: "A: <code> hit problem p, which happens when h. We could do 1) x, 2) y or 3) z. Recommendation x because why. A1 to take recommendation." "do it" takes every recommendation; "A2" takes option 2. Owner tasks: the exact link (in Capy: path and field), numbered steps, the reply word. Never re-ask a standing rule; check what you can yourself. [crew/docs/captain.md: The ask format] +11. **Ask once, plainly** (every skill's Ground Rules). One ask per decision, explained like the owner is five: your Captain's name, then a lettered line each: "A: <code> hit problem p, which happens when h. We could do 1) x, 2) y or 3) z. Recommendation x because why. A1 to take recommendation." "do it" takes every recommendation; "A2" takes option 2. Owner tasks: the exact link (in Capy: path and field), numbered steps, the reply word. Never re-ask a standing rule. [crew/docs/captain.md: The ask format] 12. **Fresh threads, closed out.** One thread per unit of work. A thread keeps its PR until it merges or closes and hands off only then, never mid-PR on a token count; past 1B own tokens it checks in with its Captain once and carries on. Standing threads that wake on every event (merge lanes, watchers) rotate at 500M tokens or 3 days [/runaway-stopper]. Crew threads never create threads: ask your Captain (Captain to Captain across projects), or report one you made by code for crew.add. Its Captain archives only its crew's threads, never one holding an open PR, successor or not (R91), or an open issue; a PR closes only as landed, superseded or dropped. Threads outside every crew are the owner's, even its automation's. Size reviews to the diff. [docs/ship-budget.md; crew/docs/captain.md: New threads join the crew] 13. **The owner's model preference.** `gstack-models resolve --role agent` picks agent models, except cross-family voices and eval subjects. [docs/model-policy.md: Your model preference] 14. **Finish before starting.** No new fix thread in a repo while more than 10 finished PRs (green, reviewed, waiting only to merge) sit in its queue: merge or close them first. Severe hotfixes are exempt: security, data loss, red main, a broken install. [crew/docs/captain.md: New threads join the crew] diff --git a/changelog.d/ask-once-and-check-handoff-files.md b/changelog.d/ask-once-and-check-handoff-files.md new file mode 100644 index 00000000000..dc76b9535fe --- /dev/null +++ b/changelog.d/ask-once-and-check-handoff-files.md @@ -0,0 +1 @@ +- **Every skill that loads the shared preamble, on every host, now says to ask a question once and to check a file before handing it over.** The Ground Rules section in the shared preamble gains two lines: ask each question once, after checking what you can yourself, and until it is answered list it as one waiting line in later updates instead of asking again; and open every file you hand over and remove placeholders first (TODO, `<fill in>`, lorem ipsum, broken links and images). The ask-once rule used to live only in the Capy wrapper's "how we work" page, which now points at the shared rule. diff --git a/codex/SKILL.md b/codex/SKILL.md index b19d6ef5aef..782d64d40e3 100644 --- a/codex/SKILL.md +++ b/codex/SKILL.md @@ -20,7 +20,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/codex/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/codex/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/codex/sections/preamble.md b/codex/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/codex/sections/preamble.md +++ b/codex/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/context-restore/SKILL.md b/context-restore/SKILL.md index 68efd7af70a..6196ae5a9af 100644 --- a/context-restore/SKILL.md +++ b/context-restore/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-restore/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-restore/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/context-restore/sections/preamble.md b/context-restore/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/context-restore/sections/preamble.md +++ b/context-restore/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/context-save/SKILL.md b/context-save/SKILL.md index 28a4f9b6466..79d87921c57 100644 --- a/context-save/SKILL.md +++ b/context-save/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-save/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/context-save/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/context-save/sections/preamble.md b/context-save/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/context-save/sections/preamble.md +++ b/context-save/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/design-consultation/SKILL.md b/design-consultation/SKILL.md index adaa68b430d..ef9d9a0f517 100644 --- a/design-consultation/SKILL.md +++ b/design-consultation/SKILL.md @@ -45,7 +45,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-consultation/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-consultation/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-consultation/sections/preamble.md b/design-consultation/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/design-consultation/sections/preamble.md +++ b/design-consultation/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/design-html/SKILL.md b/design-html/SKILL.md index dee5afe1ab0..b57d25d9315 100644 --- a/design-html/SKILL.md +++ b/design-html/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-html/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-html/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-html/sections/preamble.md b/design-html/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/design-html/sections/preamble.md +++ b/design-html/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/design-motion/SKILL.md b/design-motion/SKILL.md index 9d6601577d2..2526448e247 100644 --- a/design-motion/SKILL.md +++ b/design-motion/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-motion/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-motion/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-motion/sections/preamble.md b/design-motion/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/design-motion/sections/preamble.md +++ b/design-motion/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/design-review/SKILL.md b/design-review/SKILL.md index 97749121776..83b1bfadc01 100644 --- a/design-review/SKILL.md +++ b/design-review/SKILL.md @@ -23,7 +23,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-review/sections/preamble.md b/design-review/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/design-review/sections/preamble.md +++ b/design-review/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/design-shotgun/SKILL.md b/design-shotgun/SKILL.md index a5fa30b71f3..96bfd56b532 100644 --- a/design-shotgun/SKILL.md +++ b/design-shotgun/SKILL.md @@ -39,7 +39,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-shotgun/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/design-shotgun/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/design-shotgun/sections/preamble.md b/design-shotgun/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/design-shotgun/sections/preamble.md +++ b/design-shotgun/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/devex-review/SKILL.md b/devex-review/SKILL.md index d2b158dc82e..d28cb3f57a2 100644 --- a/devex-review/SKILL.md +++ b/devex-review/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/devex-review/sections/preamble.md b/devex-review/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/devex-review/sections/preamble.md +++ b/devex-review/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/diagram/SKILL.md b/diagram/SKILL.md index 59a7e6455ea..71bb28a4c84 100644 --- a/diagram/SKILL.md +++ b/diagram/SKILL.md @@ -101,6 +101,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/docs/loadouts.md b/docs/loadouts.md index 755a700bce4..8b483e4b9df 100644 --- a/docs/loadouts.md +++ b/docs/loadouts.md @@ -9,7 +9,7 @@ One model has its own loadout: Claude Opus 5.5 gets `lite` ([below](#lite-on-cla | Term | Meaning | |---|---| | Module | One of four kinds. `skill:<dir>` is a whole skill. `section:<skill>/<id>` is one entry of `<skill>/sections/manifest.json`. `overlay:<name>` is one `model-overlays/<name>.md`; excluding a base overlay also removes the base's text from every overlay that inherits it; the inheriting overlay's own text stays. `preamble:<id>` is one piece of the shared preamble (`PREAMBLE_PIECES` in `scripts/resolvers/preamble.ts`). | -| Pinned | A module no loadout can remove where `full` renders it: the start command, plan-mode rules, the question format, completion status, the Claims Need Evidence rule, the Ground Rules (never print a whole environment, git config or process table), the unattended profile, /ship's review army and adversarial pass, the router and `/gstack-upgrade`. A skill's `preamble-tier` still applies, so a tier-1 skill has no question-format section in any loadout. | +| Pinned | A module no loadout can remove where `full` renders it: the start command, plan-mode rules, the question format, completion status, the Claims Need Evidence rule, the Ground Rules (never print a whole environment, git config or process table; wait on CI with one call; ask each question once; check every handed-over file for placeholders), the unattended profile, /ship's review army and adversarial pass, the router and `/gstack-upgrade`. A skill's `preamble-tier` still applies, so a tier-1 skill has no question-format section in any loadout. | | Rung | How much scaffolding a model gets: `frontier`, `strong`, `mid`, `light`, or `unknown`. Model ids are matched after lowercasing and stripping a `provider/` prefix (`anthropic/claude-haiku-5-5` is `mid`). Rungs are separate from the frontier/smart tiers in `lib/model-catalog.ts`, which choose which model runs a role. | | Loadout | `{ base, exclude, include, preamble_tier_max, note }`. `full` (include `*`) is always present. An unknown model gets `default.unknown`, which is `full`. | | Model map | `models` in `modules/loadouts.json`: an exact model id to a loadout, checked before rungs. The id also matches its dated snapshot (`-YYYYMMDD`) and `-latest`, never a point release or any other suffix (`claude-opus-5-5` matches `claude-opus-5-5-20261101`, not `claude-opus-5-50` or `claude-opus-5-5-1`). | diff --git a/document-generate/SKILL.md b/document-generate/SKILL.md index c8d9cdbcb57..025ab43e2e4 100644 --- a/document-generate/SKILL.md +++ b/document-generate/SKILL.md @@ -25,7 +25,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-generate/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-generate/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/document-generate/sections/preamble.md b/document-generate/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/document-generate/sections/preamble.md +++ b/document-generate/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/document-release/SKILL.md b/document-release/SKILL.md index 8047fc11e31..5519f6c2535 100644 --- a/document-release/SKILL.md +++ b/document-release/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-release/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/document-release/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/document-release/sections/preamble.md b/document-release/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/document-release/sections/preamble.md +++ b/document-release/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/eval-plan/SKILL.md b/eval-plan/SKILL.md index e5a34067e45..e6b9e95c632 100644 --- a/eval-plan/SKILL.md +++ b/eval-plan/SKILL.md @@ -24,7 +24,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/eval-plan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/eval-plan/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/eval-plan/sections/preamble.md b/eval-plan/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/eval-plan/sections/preamble.md +++ b/eval-plan/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/health/SKILL.md b/health/SKILL.md index 2a9e6b7f70e..57ac446c2e4 100644 --- a/health/SKILL.md +++ b/health/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/health/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/health/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/health/sections/preamble.md b/health/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/health/sections/preamble.md +++ b/health/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/ios-clean/SKILL.md b/ios-clean/SKILL.md index d76f480b167..197edd574be 100644 --- a/ios-clean/SKILL.md +++ b/ios-clean/SKILL.md @@ -20,7 +20,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-clean/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-clean/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-clean/sections/preamble.md b/ios-clean/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/ios-clean/sections/preamble.md +++ b/ios-clean/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/ios-design-review/SKILL.md b/ios-design-review/SKILL.md index 1d47b721903..87fbd2fe4d8 100644 --- a/ios-design-review/SKILL.md +++ b/ios-design-review/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-design-review/sections/preamble.md b/ios-design-review/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/ios-design-review/sections/preamble.md +++ b/ios-design-review/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/ios-fix/SKILL.md b/ios-fix/SKILL.md index 8771cf89ce6..a9331cba98c 100644 --- a/ios-fix/SKILL.md +++ b/ios-fix/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-fix/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-fix/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-fix/sections/preamble.md b/ios-fix/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/ios-fix/sections/preamble.md +++ b/ios-fix/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/ios-qa/SKILL.md b/ios-qa/SKILL.md index 712a3616611..5f6289805ce 100644 --- a/ios-qa/SKILL.md +++ b/ios-qa/SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-qa/sections/preamble.md b/ios-qa/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/ios-qa/sections/preamble.md +++ b/ios-qa/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/ios-sync/SKILL.md b/ios-sync/SKILL.md index 8a75aebfc38..5e1fd6a2767 100644 --- a/ios-sync/SKILL.md +++ b/ios-sync/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-sync/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ios-sync/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ios-sync/sections/preamble.md b/ios-sync/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/ios-sync/sections/preamble.md +++ b/ios-sync/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/land-and-deploy/SKILL.md b/land-and-deploy/SKILL.md index 7a12e351bef..d1e5b2f29c8 100644 --- a/land-and-deploy/SKILL.md +++ b/land-and-deploy/SKILL.md @@ -20,7 +20,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/land-and-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/land-and-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/land-and-deploy/sections/preamble.md b/land-and-deploy/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/land-and-deploy/sections/preamble.md +++ b/land-and-deploy/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/landing-report/SKILL.md b/landing-report/SKILL.md index 616a9eb4c0c..e302c7ff5f9 100644 --- a/landing-report/SKILL.md +++ b/landing-report/SKILL.md @@ -20,7 +20,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/landing-report/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/landing-report/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/landing-report/sections/preamble.md b/landing-report/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/landing-report/sections/preamble.md +++ b/landing-report/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/learn/SKILL.md b/learn/SKILL.md index 52b620d8a60..96953e0c38a 100644 --- a/learn/SKILL.md +++ b/learn/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/learn/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/learn/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/learn/sections/preamble.md b/learn/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/learn/sections/preamble.md +++ b/learn/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/make-pdf/SKILL.md b/make-pdf/SKILL.md index 99c6957f07b..0a5779c6899 100644 --- a/make-pdf/SKILL.md +++ b/make-pdf/SKILL.md @@ -136,6 +136,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/modernize/SKILL.md b/modernize/SKILL.md index e73b7b965c5..9d6547299c2 100644 --- a/modernize/SKILL.md +++ b/modernize/SKILL.md @@ -23,7 +23,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/modernize/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/modernize/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/modernize/sections/preamble.md b/modernize/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/modernize/sections/preamble.md +++ b/modernize/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/office-hours/SKILL.md b/office-hours/SKILL.md index 374b09e8a78..81fabee7358 100644 --- a/office-hours/SKILL.md +++ b/office-hours/SKILL.md @@ -49,7 +49,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/office-hours/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/office-hours/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/office-hours/sections/preamble.md b/office-hours/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/office-hours/sections/preamble.md +++ b/office-hours/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/open-gstack-browser/SKILL.md b/open-gstack-browser/SKILL.md index 41371141641..26a60673b85 100644 --- a/open-gstack-browser/SKILL.md +++ b/open-gstack-browser/SKILL.md @@ -98,6 +98,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/pair-agent/SKILL.md b/pair-agent/SKILL.md index cb3d8c48e04..e201678b5c9 100644 --- a/pair-agent/SKILL.md +++ b/pair-agent/SKILL.md @@ -18,7 +18,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/pair-agent/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/pair-agent/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/pair-agent/sections/preamble.md b/pair-agent/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/pair-agent/sections/preamble.md +++ b/pair-agent/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/plan-ceo-review/SKILL.md b/plan-ceo-review/SKILL.md index f34a1f22325..6e544cc5cbb 100644 --- a/plan-ceo-review/SKILL.md +++ b/plan-ceo-review/SKILL.md @@ -51,7 +51,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-ceo-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-ceo-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-ceo-review/sections/preamble.md b/plan-ceo-review/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/plan-ceo-review/sections/preamble.md +++ b/plan-ceo-review/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/plan-design-review/SKILL.md b/plan-design-review/SKILL.md index fe6c303e8fc..3069dc78156 100644 --- a/plan-design-review/SKILL.md +++ b/plan-design-review/SKILL.md @@ -51,7 +51,7 @@ Recommendation: A when a branch diff exists, otherwise B. Reply with A, B, or C. ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-design-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (after scope gate) diff --git a/plan-design-review/sections/preamble.md b/plan-design-review/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/plan-design-review/sections/preamble.md +++ b/plan-design-review/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/plan-devex-review/SKILL.md b/plan-devex-review/SKILL.md index d815672a511..3c7b708215f 100644 --- a/plan-devex-review/SKILL.md +++ b/plan-devex-review/SKILL.md @@ -21,7 +21,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-devex-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-devex-review/sections/preamble.md b/plan-devex-review/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/plan-devex-review/sections/preamble.md +++ b/plan-devex-review/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/plan-eng-review/SKILL.md b/plan-eng-review/SKILL.md index 79714f317b4..6bf41a9d7df 100644 --- a/plan-eng-review/SKILL.md +++ b/plan-eng-review/SKILL.md @@ -63,7 +63,7 @@ Keep the reviewed target fixed when selecting the report destination. ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-eng-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-eng-review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (after scope gate) diff --git a/plan-eng-review/sections/preamble.md b/plan-eng-review/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/plan-eng-review/sections/preamble.md +++ b/plan-eng-review/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/plan-tune/SKILL.md b/plan-tune/SKILL.md index d0a41297182..e602bd250e7 100644 --- a/plan-tune/SKILL.md +++ b/plan-tune/SKILL.md @@ -25,7 +25,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-tune/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/plan-tune/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/plan-tune/sections/preamble.md b/plan-tune/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/plan-tune/sections/preamble.md +++ b/plan-tune/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/qa-only/SKILL.md b/qa-only/SKILL.md index 23f911322c2..7e3382a6a08 100644 --- a/qa-only/SKILL.md +++ b/qa-only/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa-only/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa-only/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/qa-only/sections/preamble.md b/qa-only/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/qa-only/sections/preamble.md +++ b/qa-only/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/qa/SKILL.md b/qa/SKILL.md index c1fb54fed28..2008902979c 100644 --- a/qa/SKILL.md +++ b/qa/SKILL.md @@ -22,7 +22,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/qa/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/qa/sections/preamble.md b/qa/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/qa/sections/preamble.md +++ b/qa/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/retro/SKILL.md b/retro/SKILL.md index c4f0c624013..b0c852a3684 100644 --- a/retro/SKILL.md +++ b/retro/SKILL.md @@ -39,7 +39,7 @@ gbrain: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/retro/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/retro/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/retro/sections/preamble.md b/retro/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/retro/sections/preamble.md +++ b/retro/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/review/SKILL.md b/review/SKILL.md index eb7b4cabee5..cbe1b1f33ea 100644 --- a/review/SKILL.md +++ b/review/SKILL.md @@ -50,7 +50,7 @@ Finish only when each of these exists (contract v1): ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/review/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/review/sections/preamble.md b/review/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/review/sections/preamble.md +++ b/review/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/runaway-stopper/SKILL.md b/runaway-stopper/SKILL.md index 13b094500ca..1852de82d51 100644 --- a/runaway-stopper/SKILL.md +++ b/runaway-stopper/SKILL.md @@ -98,6 +98,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/scrape/SKILL.md b/scrape/SKILL.md index 694f7f90530..aa1be5480f3 100644 --- a/scrape/SKILL.md +++ b/scrape/SKILL.md @@ -99,6 +99,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/scripts/resolvers/preamble/generate-ground-rules.ts b/scripts/resolvers/preamble/generate-ground-rules.ts index 0cc0270e5e5..1eb8f477298 100644 --- a/scripts/resolvers/preamble/generate-ground-rules.ts +++ b/scripts/resolvers/preamble/generate-ground-rules.ts @@ -7,13 +7,15 @@ import type { TemplateContext } from '../types'; * runs, so keep each bullet to one habit and the block at or under * GROUND_RULES_MAX_BYTES; test/ground-rules.test.ts pins that budget. */ -export const GROUND_RULES_MAX_BYTES = 850; +export const GROUND_RULES_MAX_BYTES = 900; export const GROUND_RULES_HEADING = '## Ground Rules'; export const GROUND_RULES_BULLETS = [ 'Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid.', 'Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`.', + 'Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again.', + 'Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images.', ] as const; export function generateGroundRules(_ctx?: TemplateContext): string { diff --git a/setup-browser-cookies/SKILL.md b/setup-browser-cookies/SKILL.md index aaf4ca2f16a..ae681167347 100644 --- a/setup-browser-cookies/SKILL.md +++ b/setup-browser-cookies/SKILL.md @@ -97,6 +97,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/setup-deploy/SKILL.md b/setup-deploy/SKILL.md index 184cf047cf1..9451df76df5 100644 --- a/setup-deploy/SKILL.md +++ b/setup-deploy/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-deploy/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/setup-deploy/sections/preamble.md b/setup-deploy/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/setup-deploy/sections/preamble.md +++ b/setup-deploy/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.md index 0ab160dff73..e6b9db5f68e 100644 --- a/setup-gbrain/SKILL.md +++ b/setup-gbrain/SKILL.md @@ -23,7 +23,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/setup-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/setup-gbrain/sections/preamble.md b/setup-gbrain/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/setup-gbrain/sections/preamble.md +++ b/setup-gbrain/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/ship/SKILL.md b/ship/SKILL.md index 6f0453a16ca..20814e5ab15 100644 --- a/ship/SKILL.md +++ b/ship/SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ship/sections/preamble.md b/ship/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/ship/sections/preamble.md +++ b/ship/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/skillify/SKILL.md b/skillify/SKILL.md index cb169962f3e..2bc8e30092c 100644 --- a/skillify/SKILL.md +++ b/skillify/SKILL.md @@ -19,7 +19,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/skillify/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/skillify/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/skillify/sections/preamble.md b/skillify/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/skillify/sections/preamble.md +++ b/skillify/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/spec/SKILL.md b/spec/SKILL.md index 016aa36205a..55fb27c30d0 100644 --- a/spec/SKILL.md +++ b/spec/SKILL.md @@ -22,7 +22,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/spec/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/spec/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/spec/sections/preamble.md b/spec/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/spec/sections/preamble.md +++ b/spec/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/sync-gbrain/SKILL.md b/sync-gbrain/SKILL.md index 63e4054b757..21e5c3c18a8 100644 --- a/sync-gbrain/SKILL.md +++ b/sync-gbrain/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/sync-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/sync-gbrain/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/sync-gbrain/sections/preamble.md b/sync-gbrain/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/sync-gbrain/sections/preamble.md +++ b/sync-gbrain/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/test-audit/SKILL.md b/test-audit/SKILL.md index 48f3f457805..8cd08c4608b 100644 --- a/test-audit/SKILL.md +++ b/test-audit/SKILL.md @@ -21,7 +21,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/test-audit/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/test-audit/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test-audit/sections/preamble.md b/test-audit/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/test-audit/sections/preamble.md +++ b/test-audit/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/test/fixtures/context-budget.json b/test/fixtures/context-budget.json index 0ffb9e8aed8..f8ca7a8146b 100644 --- a/test/fixtures/context-budget.json +++ b/test/fixtures/context-budget.json @@ -68,7 +68,7 @@ "test-audit": 4622, "ubicloud": 3971, "unfreeze": 409, - "verify": 2896, + "verify": 2922, "write-skill": 2264 } } diff --git a/test/fixtures/golden/agy-ship-SKILL.md b/test/fixtures/golden/agy-ship-SKILL.md index d38fbc2b65d..ffefbad0766 100644 --- a/test/fixtures/golden/agy-ship-SKILL.md +++ b/test/fixtures/golden/agy-ship-SKILL.md @@ -12,7 +12,7 @@ description: | ## Shared preamble (load first) -This skill follows gstack shared preamble `673baf289542` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `de374247c8a5` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md index 6f0453a16ca..20814e5ab15 100644 --- a/test/fixtures/golden/claude-ship-SKILL.md +++ b/test/fixtures/golden/claude-ship-SKILL.md @@ -24,7 +24,7 @@ triggers: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ship/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.md index 002db2ba459..54a75dd16de 100644 --- a/test/fixtures/golden/codex-ship-SKILL.md +++ b/test/fixtures/golden/codex-ship-SKILL.md @@ -12,7 +12,7 @@ description: | ## Shared preamble (load first) -This skill follows gstack shared preamble `0876a471d87b` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `e4c5326cffc0` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.md index 1a11689c3b2..6851d66d18c 100644 --- a/test/fixtures/golden/factory-ship-SKILL.md +++ b/test/fixtures/golden/factory-ship-SKILL.md @@ -14,7 +14,7 @@ disable-model-invocation: true ## Shared preamble (load first) -This skill follows gstack shared preamble `b517469fdbdb` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `1924a0ba0228` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `sections/preamble.md` relative to the installed `gstack-ship` SKILL.md directory in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/test/ground-rules.test.ts b/test/ground-rules.test.ts index a4e1a38ee3c..e2bc427eb78 100644 --- a/test/ground-rules.test.ts +++ b/test/ground-rules.test.ts @@ -30,6 +30,18 @@ describe('Ground Rules preamble section', () => { expect(block).toContain('never a poll loop or `gh pr checks --watch`'); }); + test('asks each question once and carries it as one waiting line, and checks every handed-over file for placeholders', () => { + expect(block).toContain('Ask each question once'); + expect(block).toContain('one waiting line'); + expect(block).toContain('Open every file you hand over and remove placeholders first'); + }); + + test('the Capy factory page points at the shared ask-once rule instead of restating it', () => { + const item11 = read('capy/skill/gstack/factory.md').split('\n').find(l => l.startsWith('11. '))!; + expect(item11).toContain("(every skill's Ground Rules)"); + expect(item11).not.toContain('check what you can yourself'); + }); + test('renders inline in a tier 1 skill and in the shared preamble tier 2+ skills read', () => { expect(read('browse/SKILL.md')).toContain(block); expect(read('review/sections/preamble.md')).toContain(block); diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.ts index 6539021aaac..d45ec71e192 100644 --- a/test/helpers/carve-guards.ts +++ b/test/helpers/carve-guards.ts @@ -359,7 +359,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 43_885, // GSTA-134 skill diet (2026-10-28): lowered from 80_533 to the measured skeleton after the second opinion and visual design moved to sections, 43,885. Before: GSTA-96 hoist (2026-10-26): lowered from 95_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 952 bytes; measured 79,581. Before: Office-hours + sketch outside voices include host guards and completion checks. + v1.91.19.0 wave: Q<N> open-question prose form (#2729, approved Q3), DESIGN_READY --version probe (B4), Aside ~/.local/bin fallback (E7), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting (#3022) merged in; measured 89,684 (2026-10-03). + 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); skeleton measured 92,590 (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; skeleton measured 92,869 (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; skeleton measured 92,930 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; skeleton measured 92,756 (2026-10-07). Merged with the guard area: measured skeleton 93,099 (2026-10-07). + fix wave PR D: the Phase 4.5 builder-profile read before the session log (#2801) and the pre-telemetry design-doc check (#1049); measured skeleton 94,877 (2026-10-07). + 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). minUnionBytes: 115_800, // Phase 4 wave 4; measured union 118,175 mustContain: ['design doc', 'problem statement'], - maxSizeRatio: 1.1968, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1968 (before: 1.1922). Before that: GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the handoff menu, its default and the design-doc line name /plan-eng-review again, +42 B union; measured 156,298 / 131,110 = 1.19211, rounded up (before: 156,256 = 1.19179 on 81fb900). Before that: GSTA-134 (2026-10-28, raised from 1.1796 by GStack Minder as merge-queue owner): +1,662 B union: second-opinion question moved into the main file while CODEX_SECOND_OPINION keeps its copy; per-run load 73,248→43,885 B; measured 156,286 / 131,110 = 1.19202, rounded up. Before: + 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 149,758 / 131,110 = 1.1422 (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 150,037 / 131,110 = 1.1444 (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 150,098 / 131,110 = 1.1448 (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 150,011 / 131,110 = 1.1442 (2026-10-07). Merged with the guard area: measured 150,354 / 131,110 = 1.1468 (2026-10-07). + fix wave PR D: builder-profile read before the session log with Phase 6 using the carried values (#2801), the inline design doc before approval (#879) and the pre-telemetry design-doc check (#1049); measured 153,206 / 131,110 = 1.1685 (2026-10-07). + empty LAST_ASSIGNMENT/LAST_PROJECT guards in the welcome_back and regular greetings (backfilled profiles); measured 153,469 / 131,110 = 1.1705 (2026-10-08). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file and its own copies of shared sections; measured 160,989 / 131,110 = 1.2279 (2026-10-25). Before: 1.18. - GSTA-96 dedupe: the Q<N> open-question form is office-hours' own appended subsection, so its copies of the shared Format and fallback subsections go; measured 154,653 / 131,110 = 1.1796 (2026-10-26), 154,624 = 1.1793 after the main merge. Before: 1.2279. + maxSizeRatio: 1.1990, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1990 (before: 1.1968). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1968 (before: 1.1922). Before that: GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the handoff menu, its default and the design-doc line name /plan-eng-review again, +42 B union; measured 156,298 / 131,110 = 1.19211, rounded up (before: 156,256 = 1.19179 on 81fb900). Before that: GSTA-134 (2026-10-28, raised from 1.1796 by GStack Minder as merge-queue owner): +1,662 B union: second-opinion question moved into the main file while CODEX_SECOND_OPINION keeps its copy; per-run load 73,248→43,885 B; measured 156,286 / 131,110 = 1.19202, rounded up. Before: + 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 149,758 / 131,110 = 1.1422 (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 150,037 / 131,110 = 1.1444 (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 150,098 / 131,110 = 1.1448 (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 150,011 / 131,110 = 1.1442 (2026-10-07). Merged with the guard area: measured 150,354 / 131,110 = 1.1468 (2026-10-07). + fix wave PR D: builder-profile read before the session log with Phase 6 using the carried values (#2801), the inline design doc before approval (#879) and the pre-telemetry design-doc check (#1049); measured 153,206 / 131,110 = 1.1685 (2026-10-07). + empty LAST_ASSIGNMENT/LAST_PROJECT guards in the welcome_back and regular greetings (backfilled profiles); measured 153,469 / 131,110 = 1.1705 (2026-10-08). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file and its own copies of shared sections; measured 160,989 / 131,110 = 1.2279 (2026-10-25). Before: 1.18. - GSTA-96 dedupe: the Q<N> open-question form is office-hours' own appended subsection, so its copies of the shared Format and fallback subsections go; measured 154,653 / 131,110 = 1.1796 (2026-10-26), 154,624 = 1.1793 after the main merge. Before: 1.2279. }, 'document-release': { skill: 'document-release', @@ -419,7 +419,7 @@ do not launch the downstream skill or open a browser.`, // eureka log, the office-hours lookup and the taste-profile read; measured // 1.0834 (2026-09-30). + named design-direction defaults to avoid in the native // subagent prompt (s02 H4a); measured 1.0911 (2026-10-02). - maxSizeRatio: 1.1688, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1688 (before: 1.1623). Before that: + v1.91.19.0 wave: design --version probe (B4), taste-profile load (F3), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting and board/approval blocks (#3022) merged in; measured 100,446 / 90,375 = 1.1114 (2026-10-03). + 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 103,384 / 90,375 = 1.1439 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 103,576 / 90,375 = 1.1461 (2026-10-07). + 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 103,522 / 90,375 = 1.1455 (2026-10-07). Both merged: measured 103,726 / 90,375 = 1.1477 (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 103,466 / 90,375 = 1.1449 (2026-10-07). Merged with the guard area: measured 103,804 / 90,375 = 1.1486 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 105,039 / 90,375 = 1.1623 (2026-10-25). Before: 1.16. + maxSizeRatio: 1.1719, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1719 (before: 1.1688). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1688 (before: 1.1623). Before that: + v1.91.19.0 wave: design --version probe (B4), taste-profile load (F3), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting and board/approval blocks (#3022) merged in; measured 100,446 / 90,375 = 1.1114 (2026-10-03). + 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 103,384 / 90,375 = 1.1439 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 103,576 / 90,375 = 1.1461 (2026-10-07). + 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 103,522 / 90,375 = 1.1455 (2026-10-07). Both merged: measured 103,726 / 90,375 = 1.1477 (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 103,466 / 90,375 = 1.1449 (2026-10-07). Merged with the guard area: measured 103,804 / 90,375 = 1.1486 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 105,039 / 90,375 = 1.1623 (2026-10-25). Before: 1.16. }, cso: { skill: 'cso', @@ -493,7 +493,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 60_070, // GST-1088 lane B follow-up (raised from 60,014 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path (~/.claude/skills/gstack/bin/gstack-skill-contract) instead of a bare gstack-skill-contract that a standard install doesn't put on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 60,070. Before: GST-1088 lane B (#3909, raised from 59,774 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): CONTRACT_CHECKER_SHIPPED=true now that bin/gstack-skill-contract ships (#3912) renders the gstack-skill-contract check/waive sentence under the Done means list (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 59,073; measured 60,014. Before: GST-1088 lane B (raised from 59,073 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list rendered from it at the top of the body, plus widened triggers; F1 is a gate-rev-2 recommendation on the plan Garry approved with "do it" on gate rev 1 (2026-11-03), contingent on his gate-rev-2 answer, and lane C's diet is expected to bring /review back under 59,073; measured 59,774. Before: GSTA-96 hoist (2026-10-26): lowered from 80_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 319 bytes; measured 58,754. Before: Shared-code identity/skip/action rules + critical-severity validation; measured 74,493 (2026-09-17). + v1.91.12.0 merge of #2999 (review clarity repairs: await reads, research alongside dispatch, /review deadline and setup authority, findings sources) with #3002 (guarded state-root lines, plan-check checkpoints); each fit alone; measured 74,881 (2026-10-01). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 74,884 (2026-10-08). + gate integrity (HONEST_WORK_GATE_INTEGRITY W2): Step 3.5 Diff scans with the shared GATE_SCAN_BLOCK, the Step 4 carry, the four-option `review-gate-disposition` question in 5c, gate record fields in 5.8 and the Gate edits report line; measured 80,054 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): Step 4's enum-only paragraph becomes the sideways sweep with the forced-CRITICAL list, plus the flake-fix number sentence in the Gate Integrity paragraph; measured skeleton 80,812 (2026-10-10). minUnionBytes: 89_000, // Phase 4 wave 1; measured union 93,357 mustContain: ['confidence', 'P1', 'P2', 'Review Army', 'adversarial'], - maxSizeRatio: 1.3343, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3343 (before: 1.3288). Before that: + GST-1088 lane B follow-up (raised from 1.3283 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path instead of a bare gstack-skill-contract that isn't on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 144,203 / 108,523 = 1.328778, rounded up. Before: + GST-1088 lane B (#3909, raised from 1.3261 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): the gstack-skill-contract check/waive sentence that CONTRACT_CHECKER_SHIPPED=true renders (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 1.3180; measured 144,147 / 108,523 = 1.32826, rounded up. Before: + GST-1088 lane B (raised from 1.3180 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list, contingent on Garry's gate-rev-2 answer; lane C's diet is expected to bring /review back under 1.3180; measured 143,907 / 108,523 = 1.3261. Before: + GSTA-167 variant G part 1 (plan approved by Garry 2026-10-30, autoplan-20261030161754 "Do it", which names about +0.3k prompt tokens per voice): the native adversarial and outside-voice prompts carry the blocking floor and the Severity and Blocks lines, +537 bytes; measured 1.3180 (2026-10-30). Before: 1.3136. GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): both owner-approved raises together, measured 142,550 / 108,523 = 1.3135. Before: Shared-code feature + critical-severity validation: 128,042 union bytes / 108,523 baseline = 1.1799; preserves content floors. + v1.91.12.0 merge of #2999 (above, plus plan-completion fallback intent and specialist checklist-by-path) with #3002; measured 1.1843 (2026-10-01). + v1.91.19.0 wave: verdict-form Codex callers with sandbox preflight (INV-1/B1), P0/P1 structured gate (B1b), bound-plan discovery and data-not-instructions guard (F1/D3), visible LEARNINGS failures (B5); measured 129,941 / 108,523 = 1.1974 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 130,025 / 108,523 = 1.1981 (2026-10-04). + Oct 6 fix wave: quota_exhausted preflight branch (#3051); measured 130,359 / 108,523 = 1.2012 (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 131,314 / 108,523 = 1.2100 (2026-10-06). Combined Oct 6 wave head (A and B): measured 131,966 / 108,523 = 1.2160 (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 132,199 / 108,523 = 1.2182 (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 132,258 / 108,523 = 1.2187 (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 132,233 / 108,523 = 1.2185 (2026-10-07). Merged with the guard area: measured 132,522 / 108,523 = 1.2211 (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 133,902 / 108,523 = 1.2339 (2026-10-08). + gate integrity W2 (above); measured 1.282 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): sideways sweep and flake-fix number in Step 4; `Diff read` and `Undeclared behavior changes` in the review-mode Scope Check (plan-completion section); measured 140,497 / 108,523 = 1.2946 (2026-10-10). + harness lane E (2026-10-26): the lead-judgment stage in the finding merge and the `cause` anchor in the specialist prompts, shared with /ship through scripts/resolvers/review-army.ts; measured 141,949 / 108,523 = 1.3080. + maxSizeRatio: 1.3369, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.3369 (before: 1.3343). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3343 (before: 1.3288). Before that: + GST-1088 lane B follow-up (raised from 1.3283 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path instead of a bare gstack-skill-contract that isn't on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 144,203 / 108,523 = 1.328778, rounded up. Before: + GST-1088 lane B (#3909, raised from 1.3261 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): the gstack-skill-contract check/waive sentence that CONTRACT_CHECKER_SHIPPED=true renders (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 1.3180; measured 144,147 / 108,523 = 1.32826, rounded up. Before: + GST-1088 lane B (raised from 1.3180 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list, contingent on Garry's gate-rev-2 answer; lane C's diet is expected to bring /review back under 1.3180; measured 143,907 / 108,523 = 1.3261. Before: + GSTA-167 variant G part 1 (plan approved by Garry 2026-10-30, autoplan-20261030161754 "Do it", which names about +0.3k prompt tokens per voice): the native adversarial and outside-voice prompts carry the blocking floor and the Severity and Blocks lines, +537 bytes; measured 1.3180 (2026-10-30). Before: 1.3136. GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): both owner-approved raises together, measured 142,550 / 108,523 = 1.3135. Before: Shared-code feature + critical-severity validation: 128,042 union bytes / 108,523 baseline = 1.1799; preserves content floors. + v1.91.12.0 merge of #2999 (above, plus plan-completion fallback intent and specialist checklist-by-path) with #3002; measured 1.1843 (2026-10-01). + v1.91.19.0 wave: verdict-form Codex callers with sandbox preflight (INV-1/B1), P0/P1 structured gate (B1b), bound-plan discovery and data-not-instructions guard (F1/D3), visible LEARNINGS failures (B5); measured 129,941 / 108,523 = 1.1974 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 130,025 / 108,523 = 1.1981 (2026-10-04). + Oct 6 fix wave: quota_exhausted preflight branch (#3051); measured 130,359 / 108,523 = 1.2012 (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 131,314 / 108,523 = 1.2100 (2026-10-06). Combined Oct 6 wave head (A and B): measured 131,966 / 108,523 = 1.2160 (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 132,199 / 108,523 = 1.2182 (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 132,258 / 108,523 = 1.2187 (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 132,233 / 108,523 = 1.2185 (2026-10-07). Merged with the guard area: measured 132,522 / 108,523 = 1.2211 (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 133,902 / 108,523 = 1.2339 (2026-10-08). + gate integrity W2 (above); measured 1.282 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): sideways sweep and flake-fix number in Step 4; `Diff read` and `Undeclared behavior changes` in the review-mode Scope Check (plan-completion section); measured 140,497 / 108,523 = 1.2946 (2026-10-10). + harness lane E (2026-10-26): the lead-judgment stage in the finding merge and the `cause` anchor in the specialist prompts, shared with /ship through scripts/resolvers/review-army.ts; measured 141,949 / 108,523 = 1.3080. }, codex: { skill: 'codex', @@ -545,7 +545,7 @@ do not launch the downstream skill or open a browser.`, }, behavioral: 'prompt', maxSkeletonBytes: 32_216, // GSTA-161 skill diet (2026-10-30): lowered from 52_682 to the measured skeleton, 32,216; Step 7's canary script, the Aside contract, the browser fallback and Third-Party Web Actions moved to sections/canary.md. Before: GSTA-96 hoist (2026-10-26): lowered from 74_500 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 690 bytes; measured 51,992. Before: + Aside browser contract for Step 7 canary ({{ASIDE_SETUP}}); measured 73_523 - maxSizeRatio: 1.1318, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1318 (before: 1.1260). Before that: + #3318 Step 3.4 reads the ship policy and prints one VERSION_CHECK verdict (owner-approved raise, Garry 2026-10-24: "do it"); measured 1.1201 (2026-10-24). Before: 1.1120. + v1.81 Aside contract + gstack-browser fallback block; measured 1.077. + both untrusted-content marker formats in the browser fallback (W7f) + the readiness gate's project test command and live eval-store paths (s06 H6/H7); measured 1.1076 (2026-10-02). Re-measured 1.0943 (2026-10-03); cap = measured + 0.005 headroom. + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 115,226 / 104,578 = 1.1018 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,753 / 104,578 = 1.1260 (2026-10-25). Before: 1.125. + maxSizeRatio: 1.1344, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1344 (before: 1.1318). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1318 (before: 1.1260). Before that: + #3318 Step 3.4 reads the ship policy and prints one VERSION_CHECK verdict (owner-approved raise, Garry 2026-10-24: "do it"); measured 1.1201 (2026-10-24). Before: 1.1120. + v1.81 Aside contract + gstack-browser fallback block; measured 1.077. + both untrusted-content marker formats in the browser fallback (W7f) + the readiness gate's project test command and live eval-store paths (s06 H6/H7); measured 1.1076 (2026-10-02). Re-measured 1.0943 (2026-10-03); cap = measured + 0.005 headroom. + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 115,226 / 104,578 = 1.1018 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,753 / 104,578 = 1.1260 (2026-10-25). Before: 1.125. minUnionBytes: 91_000, // Phase 4 wave 1; estimated union ~94.9KB mustContain: ['readiness', 'merge', 'canary', 'revert', 'staging'], }, @@ -583,7 +583,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 48_175, // GSTA-96 hoist (2026-10-26): lowered from 70_000 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 4,888 bytes; measured 43,287. Before: Phase-specific outside coverage, native fallback, and harness guard. minUnionBytes: 85_000, // measured union 86,926 mustContain: ['6 Decision Principles', 'TASTE DECISION', 'USER CHALLENGE', 'consensus', 'Restore Point'], - maxSizeRatio: 1.1772, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1772 (before: 1.1723). Before that: GST-537 /autoplan --ceo-only (GStack Minder approved A1, 2026-10-31): sections/ceo-only.md (2,168 B) plus its Section index row, read only when the invocation names --ceo-only (test/autoplan-ceo-only.test.ts pins that a normal run never reads it); measured 119,545 / 101,979 = 1.1723 (2026-10-31), +2,276 B over main's 117,269 = 1.1499. Before: 1.1511. Four validated outside invocations replace raw CLI calls; phases keep independent coverage. + 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 114,297 / 101,979 = 1.1208 (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 114,533 / 101,979 = 1.1231 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site, and phase-close publishing each report with the `true autoplan-published <phase>` no-op before the next phase entry in a later message (CEO-1); measured 114,320 / 101,979 = 1.1210 (2026-10-07). Merged with the guard area: measured 115,149 / 101,979 = 1.1291 (2026-10-07). + Oct 8 wave (permission cards after a background reviewer): Step 1 puts RESTORE_PATH, and so every phase artifact, in the project's git-excluded `.gstack/tmp/autoplan/`, which Claude Code reads without a card after the skill turn ends; measured 115,270 / 101,979 = 1.1303 (2026-10-08). + fix wave PR D: the prerequisite offer is skipped in spawned/headless sessions (#1958); measured 115,267 / 101,979 = 1.1303 (2026-10-07). Both merged: measured 115,126 / 101,979 = 1.1289 (2026-10-08). + 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 B9/B10/B12: Phase 0 ESTIMATE and the phase-close timing record, the final gate as a gate list (`gstack-gate render/parse`, stable ids, gate_rev) and the URGENT block above the summary, offset by tightening the Phase 4 prose and the tasks-section; measured 114,980 / 101,979 = 1.1275 (2026-10-10). + Oct 10 multi-agent wave PR D1 (reality rows): the reality-rows check line in the CEO and Eng phase files, the Pre-Gate rule (unattended miss is `incomplete`, never a warning) and the two Pre-Gate cells; measured 117,042 / 101,979 = 1.1477 (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,388 / 101,979 = 1.1511 (2026-10-25). Before: 1.149. + maxSizeRatio: 1.1799, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1799 (before: 1.1772). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1772 (before: 1.1723). Before that: GST-537 /autoplan --ceo-only (GStack Minder approved A1, 2026-10-31): sections/ceo-only.md (2,168 B) plus its Section index row, read only when the invocation names --ceo-only (test/autoplan-ceo-only.test.ts pins that a normal run never reads it); measured 119,545 / 101,979 = 1.1723 (2026-10-31), +2,276 B over main's 117,269 = 1.1499. Before: 1.1511. Four validated outside invocations replace raw CLI calls; phases keep independent coverage. + 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 114,297 / 101,979 = 1.1208 (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 114,533 / 101,979 = 1.1231 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site, and phase-close publishing each report with the `true autoplan-published <phase>` no-op before the next phase entry in a later message (CEO-1); measured 114,320 / 101,979 = 1.1210 (2026-10-07). Merged with the guard area: measured 115,149 / 101,979 = 1.1291 (2026-10-07). + Oct 8 wave (permission cards after a background reviewer): Step 1 puts RESTORE_PATH, and so every phase artifact, in the project's git-excluded `.gstack/tmp/autoplan/`, which Claude Code reads without a card after the skill turn ends; measured 115,270 / 101,979 = 1.1303 (2026-10-08). + fix wave PR D: the prerequisite offer is skipped in spawned/headless sessions (#1958); measured 115,267 / 101,979 = 1.1303 (2026-10-07). Both merged: measured 115,126 / 101,979 = 1.1289 (2026-10-08). + 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 B9/B10/B12: Phase 0 ESTIMATE and the phase-close timing record, the final gate as a gate list (`gstack-gate render/parse`, stable ids, gate_rev) and the URGENT block above the summary, offset by tightening the Phase 4 prose and the tasks-section; measured 114,980 / 101,979 = 1.1275 (2026-10-10). + Oct 10 multi-agent wave PR D1 (reality rows): the reality-rows check line in the CEO and Eng phase files, the Pre-Gate rule (unattended miss is `incomplete`, never a warning) and the two Pre-Gate cells; measured 117,042 / 101,979 = 1.1477 (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,388 / 101,979 = 1.1511 (2026-10-25). Before: 1.149. }, spec: { skill: 'spec', @@ -612,7 +612,7 @@ do not launch the downstream skill or open a browser.`, behavioral: 'prompt', maxSkeletonBytes: 36_571, // GSTA-96 hoist (2026-10-26): lowered from 58_400 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 1,606 bytes; measured 34,965. Before: + v2.0 {{ASIDE_RESEARCH}} (Aside first, WebSearch fallback); measured 57_356 minUnionBytes: 64_500, // measured union 67,430 - maxSizeRatio: 1.0819, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.0819 (before: 1.0746). Before that: Oct 10 multi-agent wave PR E2: the lazy gate-and-file section renders {{COORDINATOR_CONTRACT}} (the block every spawned lane inherits word for word; `gstack-autoplan contract` prints the same bytes) before the --execute spawn pipe; measured 86,614 / 81,577 = 1.0617 after the contract became a fail-closed `CONTRACT=$(…)` capture (2026-10-10). The skeleton is unchanged (57,107). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 87,656 / 81,577 = 1.0745 (2026-10-25). Before: 1.07. + maxSizeRatio: 1.0853, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.0853 (before: 1.0819). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.0819 (before: 1.0746). Before that: Oct 10 multi-agent wave PR E2: the lazy gate-and-file section renders {{COORDINATOR_CONTRACT}} (the block every spawned lane inherits word for word; `gstack-autoplan contract` prints the same bytes) before the --execute spawn pipe; measured 86,614 / 81,577 = 1.0617 after the contract became a fail-closed `CONTRACT=$(…)` capture (2026-10-10). The skeleton is unchanged (57,107). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 87,656 / 81,577 = 1.0745 (2026-10-25). Before: 1.07. mustContain: ['HARD GATE', 'dedupe', 'quality gate', 'acceptance criteria', 'archive'], }, 'setup-gbrain': { @@ -677,7 +677,7 @@ do not launch the downstream skill or open a browser.`, }, behavioral: 'prompt', maxSkeletonBytes: 41_669, // GSTA-96 hoist (2026-10-26): lowered from 63_500 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 12,415 bytes; measured 29,254. Before: + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} (replaces the browse setup block); measured 61_253 - maxSizeRatio: 1.1493, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1493 (before: 1.1420). Before that: + v1.81 Aside contract + gstack-browser fallback block (1.080 on v1.91.7.0) + the shared test value bar at 8a.5 ({{TEST_VALUE_BAR:qa}}); measured 1.094 + 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.101 (2026-09-30) + v1.91.12.0 merge of #2999 (await scope/method Reads, capture --after checkpoints, browser-only empty evidence list) with #3002; measured 1.1028 (2026-10-01). + both untrusted-content marker formats in the browser fallback (W7f); measured 1.1035 (2026-10-02). Re-measured 1.1038 after the W8 probe-loop renames (2026-10-03); the cap already matches. + the annotate-every-capture and superseded rule before materialize (a ship-exploratory-late-input run published evidence that omitted older-snapshot captures); measured 1.1064 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 93,282 / 84,049 = 1.1099 (2026-10-04). + reliability follow-ups C2 (judge-named gaps after trimming the added wording: feasible 180 s Browser Quick, PROBE_DIR's source line, stop goes to the §4 report, written JSON keeps full card values; lane S's {user}/timing fields); measured 93,311 / 84,049 = 1.11020 (2026-10-04). + 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 94,486 / 84,049 = 1.1242 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 94,681 / 84,049 = 1.1265 (2026-10-07). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 94,736 / 84,049 = 1.12715 (2026-10-08). + 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). + maxSizeRatio: 1.1526, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1526 (before: 1.1493). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1493 (before: 1.1420). Before that: + v1.81 Aside contract + gstack-browser fallback block (1.080 on v1.91.7.0) + the shared test value bar at 8a.5 ({{TEST_VALUE_BAR:qa}}); measured 1.094 + 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.101 (2026-09-30) + v1.91.12.0 merge of #2999 (await scope/method Reads, capture --after checkpoints, browser-only empty evidence list) with #3002; measured 1.1028 (2026-10-01). + both untrusted-content marker formats in the browser fallback (W7f); measured 1.1035 (2026-10-02). Re-measured 1.1038 after the W8 probe-loop renames (2026-10-03); the cap already matches. + the annotate-every-capture and superseded rule before materialize (a ship-exploratory-late-input run published evidence that omitted older-snapshot captures); measured 1.1064 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 93,282 / 84,049 = 1.1099 (2026-10-04). + reliability follow-ups C2 (judge-named gaps after trimming the added wording: feasible 180 s Browser Quick, PROBE_DIR's source line, stop goes to the §4 report, written JSON keeps full card values; lane S's {user}/timing fields); measured 93,311 / 84,049 = 1.11020 (2026-10-04). + 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 94,486 / 84,049 = 1.1242 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 94,681 / 84,049 = 1.1265 (2026-10-07). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 94,736 / 84,049 = 1.12715 (2026-10-08). + 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). minUnionBytes: 69_500, // measured union 70,385 // 'aside repl' pins the Aside contract; '$B goto' pins the fallback block in the always-loaded skeleton. mustContain: ['bug', 'aside repl', '$B goto', 'fix', 'Health Score Rubric', 'regression'], @@ -714,7 +714,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, }, behavioral: 'prompt', - maxSkeletonBytes: 35_298, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 35,298 (before: 34_700). Before that: + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} skeleton + the STOP-Read pointer; measured 29_986 + 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); skeleton measured 32,532 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort), and the cookbook's silent-failure list and signed-in-tab recipe (the rule details live here, not in every browsing skill); skeleton measured 34,047 (2026-10-07). + Oct 8 wave: the tier-1 voice directive bans "load-bearing" and adds the reply-language rule (tier 1 has no closer to tighten: +158 bytes); skeleton measured 34,209 (2026-10-08). + 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). + maxSkeletonBytes: 35_574, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 35,574 (before: 35_298). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 35,298 (before: 34_700). Before that: + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} skeleton + the STOP-Read pointer; measured 29_986 + 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); skeleton measured 32,532 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort), and the cookbook's silent-failure list and signed-in-tab recipe (the rule details live here, not in every browsing skill); skeleton measured 34,047 (2026-10-07). + Oct 8 wave: the tier-1 voice directive bans "load-bearing" and adds the reply-language rule (tier 1 has no closer to tighten: +158 bytes); skeleton measured 34,209 (2026-10-08). + 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). minUnionBytes: 36_000, // skeleton + command-list section (14,240); measured union ~38.5 KB // 'BEGIN/END UNTRUSTED EXTERNAL' pins the untrusted-content warning in the // command reference; 'aside repl' pins the Aside contract in the skeleton. @@ -760,7 +760,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 85_182, // /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 85,182. Before: GSTA-134 skill diet (2026-10-28): lowered from 115_947 to the measured skeleton after the outside voices and test bootstrap moved to sections, 84,869. Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the hoisted skeleton plus main's headroom of 0 bytes; measured 115,947 on the merged tree. Before: measured 137735 on the merged tree with main f27a760 (2026-10-27, #3507); 137767 (2026-10-26; 137773 on 2026-10-25 before the shorter craft-audit trigger): the Section index the external-host carve test requires, its craft-audit row, and the STOP pointer (GSTA-92; Garry 2026-10-25 'Do it' (GSTA-92)). minUnionBytes: 136_100, // GSTA-134 skill diet (2026-10-28): measured union 137,602 (lowered from 143_300); before: measured union 144802 on the merged tree with main f27a760 (2026-10-27, #3507); 145037 (2026-10-26) mustContain: ['AI Slop Detection', 'Fix Loop', 'gstack-design-lint', 'Proof beside each claim', 'holds session data'], - maxSizeRatio: 1.3628, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3628 (before: 1.357). Before that: /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 143,620 / 105,842 = 1.35693. Before: 1.3001, GSTA-134 skill diet (2026-10-28): measured 137,602 / 105,842 = 1.30007, rounded up (lowered from 1.3739). Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the union now holds sections/preamble.md (the hoist's owner-approved raise, decision A) on top of main's 1.3681; measured 145,410 / 105,842 = 1.3739 on the merged tree. Before: first parity guard for design-review: measured 144802 / 105,842 = 1.3681 on the merged tree with main f27a760 (2026-10-27, #3507: the design lint swap); before that 145082 / 105,842 = 1.3708 (2026-10-25; 145077 after the /ship review fixes, 145068 = 1.3707 after the line-13 reword, 145049 = 1.3705 after the post-merge /ship review, 145037 = 1.3704 after its second pass, 2026-10-26), the skeleton's growth since v1.64.1.0 plus the craft audit (Garry 2026-10-25 'Do it' (GSTA-92)). + maxSizeRatio: 1.3654, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.3654 (before: 1.3628). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3628 (before: 1.357). Before that: /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 143,620 / 105,842 = 1.35693. Before: 1.3001, GSTA-134 skill diet (2026-10-28): measured 137,602 / 105,842 = 1.30007, rounded up (lowered from 1.3739). Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the union now holds sections/preamble.md (the hoist's owner-approved raise, decision A) on top of main's 1.3681; measured 145,410 / 105,842 = 1.3739 on the merged tree. Before: first parity guard for design-review: measured 144802 / 105,842 = 1.3681 on the merged tree with main f27a760 (2026-10-27, #3507: the design lint swap); before that 145082 / 105,842 = 1.3708 (2026-10-25; 145077 after the /ship review fixes, 145068 = 1.3707 after the line-13 reword, 145049 = 1.3705 after the post-merge /ship review, 145037 = 1.3704 after its second pass, 2026-10-26), the skeleton's growth since v1.64.1.0 plus the craft audit (Garry 2026-10-25 'Do it' (GSTA-92)). }, // ── Token-reduction Phase 4 wave 4 (v1.69.x branch): design doctrine carve ── @@ -900,7 +900,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, // operational skill, no plan-mode gate }, behavioral: 'prompt', - maxSkeletonBytes: 31_893, // GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 31,893 (before: 31_300). Before that: first carve: Section index, one STOP pointer and the vet rule on the 29.9k monolith; measured 30,781 (2026-10-26) + maxSkeletonBytes: 32_169, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 32,169 (before: 31_893). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 31,893 (before: 31_300). Before that: first carve: Section index, one STOP pointer and the vet rule on the 29.9k monolith; measured 30,781 (2026-10-26) minUnionBytes: 33_000, // skeleton + vet-the-number section; measured union 34,527 (2026-10-26) mustContain: ['performance.getEntries()', 'REGRESSION', 'Name the limiter', 'run-to-run variation', 'inconclusive'], // The v1.64.1.0 baseline measured the 37.2k monolith; the carved union is below it. diff --git a/test/size-ledger/ship/ask-once-and-check-handoff-files.json b/test/size-ledger/ship/ask-once-and-check-handoff-files.json new file mode 100644 index 00000000000..323a747ae20 --- /dev/null +++ b/test/size-ledger/ship/ask-once-and-check-handoff-files.json @@ -0,0 +1,4 @@ +{ + "bytes": 276, + "why": "Ground Rules: ask each question once; open every handed-over file and remove placeholders (GST-2756)" +} diff --git a/ubicloud/SKILL.md b/ubicloud/SKILL.md index c86b42b5c1e..e83959ac9ad 100644 --- a/ubicloud/SKILL.md +++ b/ubicloud/SKILL.md @@ -19,7 +19,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ubicloud/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/ubicloud/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/ubicloud/sections/preamble.md b/ubicloud/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/ubicloud/sections/preamble.md +++ b/ubicloud/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/verify/SKILL.md b/verify/SKILL.md index 6180ded2d93..cd9882c2b9d 100644 --- a/verify/SKILL.md +++ b/verify/SKILL.md @@ -103,6 +103,8 @@ The user has context you do not. Cross-model agreement is a recommendation, not - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol diff --git a/write-skill/SKILL.md b/write-skill/SKILL.md index 7d4986e2a46..02732b264c5 100644 --- a/write-skill/SKILL.md +++ b/write-skill/SKILL.md @@ -22,7 +22,7 @@ allowed-tools: ## Shared preamble (load first) -This skill follows gstack shared preamble `d56c99c92144` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/write-skill/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. +This skill follows gstack shared preamble `d8804c5ab6bf` (AskUserQuestion format, voice, writing, completeness and completion rules). If your Read of that file, headed by this id, is still in context, do not read it again; otherwise Read `~/.claude/skills/gstack/write-skill/sections/preamble.md` in full before the command below. A section or subsection here with a shared heading replaces the shared one. ## Preamble (run first) diff --git a/write-skill/sections/preamble.md b/write-skill/sections/preamble.md index a7fb731da7f..f753a5e1b1c 100644 --- a/write-skill/sections/preamble.md +++ b/write-skill/sections/preamble.md @@ -1,6 +1,6 @@ <!-- AUTO-GENERATED from scripts/resolvers/preamble-hoist.ts — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> -# gstack shared preamble d56c99c92144 +# gstack shared preamble d8804c5ab6bf ## Plan Mode Safe Operations @@ -228,6 +228,8 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST - Never print a whole environment, git config or process table; tokens ride in them. Banned: `env`, bare `printenv`, `set` or `export` (or an empty `export $(...)`), `export -p`/`-n`, `declare -p`/`-x`, `typeset -p`, `set -x`, `git config --list`/`-l`, any `ps` with full args (`aux`, `-ef`, `-o args`), `docker top ... args`, `docker inspect` Env. Read one value by name (`git config --get <name>`), check a variable with `[ -n "${NAME:-}" ] && echo set`, list processes by name or pid. - Wait on CI with one `gstack-pr-wait <n> --until green` call, never a poll loop or `gh pr checks --watch`. +- Ask each question once, after checking what you can yourself; until it is answered, list it as one waiting line in later updates instead of asking again. +- Open every file you hand over and remove placeholders first: TODO, `<fill in>`, lorem ipsum, broken links and images. ## Completion Status Protocol From e66a77272270f4a260f4bc4fcce73d116fd7fa95 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 20:18:43 +0800 Subject: [PATCH 28/62] Explain the new failed-or-skipped and also-changed report lines in the crew manuals (GST-1455) (#4432) * Name the Failed or skipped and Also changed lines in the Captain manuals (GST-1455) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> #4273 added these lines to the READY and lane report templates; crew/docs/captain.md, the /captain skill, the crew CREW.md template and the Capy captain page still named only Unverified:. They now list all three, and say a controller asks for a missing one in a follow-up, never refuses or stales a READY for it, as with Unverified:. * fix: pre-landing review fixes Review-Finding: p1/specialist-batched#1 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Add the changelog fragment for the Captain manual report lines (GST-1455) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- captain/SKILL.md | 4 +++- captain/SKILL.md.tmpl | 4 +++- captain/templates/CREW.md | 5 +++-- capy/skill/gstack/captain.md | 3 ++- changelog.d/captain-docs-report-lines.md | 1 + crew/docs/captain.md | 10 +++++++--- 6 files changed, 19 insertions(+), 8 deletions(-) create mode 100644 changelog.d/captain-docs-report-lines.md diff --git a/captain/SKILL.md b/captain/SKILL.md index ff3f42283d5..f5635fa43ce 100644 --- a/captain/SKILL.md +++ b/captain/SKILL.md @@ -191,6 +191,8 @@ and adds the lines the tool cannot know. Validate every field before the pin goe | flaky cases | each one already in the ledger, with both runs | a rerun that is not logged, or a second failure called a flake | | lane statement | "head frozen from now on" | absent | | `Unverified` | each claim the lane did not check itself, or `none` | never refused or staled; ask for it | +| `Failed or skipped` | each check, case or step that failed or never ran, or `none` | never refused or staled; ask for it | +| `Also changed` | each config, CI or out-of-scope file the PR touches, or `none` | never refused or staled; ask for it | Optional lines a crew's rules file may require: the gate run id and tree hash of the lane's own gate, the issue the PR closes, and the key before/after image. @@ -416,7 +418,7 @@ occurrence escalates. Every rerun's spend is reported. ## Reports and waves A lane that finishes writes `reports/<code>.md` (`captain/templates/report.md`): Outcome -with its `Unverified:` line, PR (number, head, version, checks), Needs (what the owner +with its `Unverified:` line (after `Failed or skipped:` and `Also changed:`), PR (number, head, version, checks), Needs (what the owner must do), Cost, Lesson, and the Approvals table. The controller reads reports before chat and turns each Lesson into a rule, a standing-rules line (`captain/templates/AGENTS.md`) or a filed tool fix. Its log (`captain/templates/NOTES.md`) is append-only and timestamped; diff --git a/captain/SKILL.md.tmpl b/captain/SKILL.md.tmpl index ae8ea7053eb..03622be328a 100644 --- a/captain/SKILL.md.tmpl +++ b/captain/SKILL.md.tmpl @@ -119,6 +119,8 @@ and adds the lines the tool cannot know. Validate every field before the pin goe | flaky cases | each one already in the ledger, with both runs | a rerun that is not logged, or a second failure called a flake | | lane statement | "head frozen from now on" | absent | | `Unverified` | each claim the lane did not check itself, or `none` | never refused or staled; ask for it | +| `Failed or skipped` | each check, case or step that failed or never ran, or `none` | never refused or staled; ask for it | +| `Also changed` | each config, CI or out-of-scope file the PR touches, or `none` | never refused or staled; ask for it | Optional lines a crew's rules file may require: the gate run id and tree hash of the lane's own gate, the issue the PR closes, and the key before/after image. @@ -344,7 +346,7 @@ occurrence escalates. Every rerun's spend is reported. ## Reports and waves A lane that finishes writes `reports/<code>.md` (`captain/templates/report.md`): Outcome -with its `Unverified:` line, PR (number, head, version, checks), Needs (what the owner +with its `Unverified:` line (after `Failed or skipped:` and `Also changed:`), PR (number, head, version, checks), Needs (what the owner must do), Cost, Lesson, and the Approvals table. The controller reads reports before chat and turns each Lesson into a rule, a standing-rules line (`captain/templates/AGENTS.md`) or a filed tool fix. Its log (`captain/templates/NOTES.md`) is append-only and timestamped; diff --git a/captain/templates/CREW.md b/captain/templates/CREW.md index eb931330f2b..93d344a2094 100644 --- a/captain/templates/CREW.md +++ b/captain/templates/CREW.md @@ -61,14 +61,15 @@ Homes are paths in the gstack checkout the lane checked at session start. 6. **Your job ends at an unstamped READY.** Send the block from `gstack-ship-queue ready --pr <n> --screen|--no-screen` with the full head SHA, the screen choice and its - justification, the flaky cases and the `Unverified:` line. Stamp only on the + justification, the flaky cases and the `Failed or skipped:`, `Also changed:` and + `Unverified:` lines (a missing one is asked for, never refused). Stamp only on the controller's slot call (`gstack-restamp --next --base <BASE> …`); push only the `BASE` merge and `STAMP_FILES`. Never merge, never enable auto-merge. Home: `crew/docs/captain.md` (The READY contract), `captain/templates/READY.md`, `captain/templates/slot-call.md`, `docs/ship-policy.md` (stamp-at-merge). 7. **Report.** `reports/<your thread code>.md` in the controller's drive: Outcome (with - its `Unverified:` line), PR, Needs, Cost, Lesson, Approvals. Home: + its `Failed or skipped:`, `Also changed:` and `Unverified:` lines), PR, Needs, Cost, Lesson, Approvals. Home: `captain/templates/report.md`. 8. **One path.** Everything goes through `CONTROLLER`, never peer to peer. Home: diff --git a/capy/skill/gstack/captain.md b/capy/skill/gstack/captain.md index 7bb28aa7e78..0e9374902cf 100644 --- a/capy/skill/gstack/captain.md +++ b/capy/skill/gstack/captain.md @@ -150,7 +150,8 @@ Every PR you send READY on, and the READY report itself, has: evidence-ladder rung that fact reached. 4. **Approvals.** `gstack-approvals render`. 5. **Evidence.** Checks green at the head, gate or train results, flaky cases, and an `Unverified:` line: - each claim you did not check yourself and why, or `none`. You write this item; /ship does not. + each claim you did not check yourself and why, or `none`; `Failed or skipped:` and `Also changed:` lines too. + A controller asks for a missing one of the three, never refuses it. You write this item; /ship does not. The READY report attaches the key image (Capy message attachment), so the Captain can show it inline. /ship does items 1-4 when `GSTACK_CAPY=1` (its `capy-pr` section). Outside Capy, the PR body is unchanged. diff --git a/changelog.d/captain-docs-report-lines.md b/changelog.d/captain-docs-report-lines.md new file mode 100644 index 00000000000..a580b24c2eb --- /dev/null +++ b/changelog.d/captain-docs-report-lines.md @@ -0,0 +1 @@ +- **The Captain manuals now name the `Failed or skipped:` and `Also changed:` lines that READY and lane reports carry.** A controller asks for a missing one in a follow-up and never refuses or stales a READY over it, the same as a missing `Unverified:` (GST-1455). diff --git a/crew/docs/captain.md b/crew/docs/captain.md index 83d81079d1e..aa3eb84fc64 100644 --- a/crew/docs/captain.md +++ b/crew/docs/captain.md @@ -68,7 +68,7 @@ surface. Keep it small and predictable: | `DIGEST.md` | the controller | Needs you / New / In progress, rewritten every turn ([template](../../captain/templates/DIGEST.md)) | | `NOTES.md` | the controller | the append-only timestamped log the digest is derived from ([template](../../captain/templates/NOTES.md)) | | `skills/<name>/SKILL.md` | the controller | crew procedures the lanes load (the runbooks) | -| `reports/<code>.md` | each lane, once | Outcome with its Unverified line, PR, Needs, Cost, Lesson, Approvals ([template](../../captain/templates/report.md)) | +| `reports/<code>.md` | each lane, once | Outcome with its Failed or skipped, Also changed and Unverified lines, PR, Needs, Cost, Lesson, Approvals ([template](../../captain/templates/report.md)) | | `reports/postmortem-<n>.md` | the controller, or a lane it names | why a reverted or S1-fixed merged PR passed every reviewer ([template](../../captain/templates/postmortem.md)) | | `handoffs/` | lanes | datasets and specs the next lane needs; `handoffs/flaky-ledger.md` is the flaky ledger ([template](../../captain/templates/flaky-ledger.md)) | | `plans/` | the controller | approved plans, with their Approvals table | @@ -106,7 +106,7 @@ Where each rule lives: | 4 | File ownership: edit only what you own; the controller routes the rest | [Lane discipline](#lane-discipline); the ownership list is the digest's **In progress** | | 5 | Standing spend and its cap per rerun | [Approvals, shape A](#approvals-three-shapes); the `SPEND` parameter | | 6 | The job ends at an unstamped READY; stamp on call; never merge | [The READY contract](#the-ready-contract), the [READY](../../captain/templates/READY.md) and [slot call](../../captain/templates/slot-call.md) templates, [ship-policy.md](../../docs/ship-policy.md#stamp-at-merge) | -| 7 | One report per lane: Outcome with its Unverified line, PR, Needs, Cost, Lesson, Approvals | [Drive layout](#drive-layout); the [report template](../../captain/templates/report.md) | +| 7 | One report per lane: Outcome with its Failed or skipped, Also changed and Unverified lines, PR, Needs, Cost, Lesson, Approvals | [Drive layout](#drive-layout); the [report template](../../captain/templates/report.md) | | 8 | One path: everything through the controller, never peer to peer | [Roles](#roles); [Lane discipline](#lane-discipline) | | 9 | Hands: a real browser, the owner's session or local work go through the controller | [The owner's device](#the-owners-device) | | 10 | Keep going; come back only for scope, a conflict, access or the owner's decision | [Lane discipline](#lane-discipline) | @@ -427,7 +427,9 @@ cases are already in the ledger; the CHANGELOG entry sits under `## [Unreleased] the version files at the base's version; the lane declares the head frozen; and an `Unverified:` line lists every claim the lane did not check itself (a local test that timed out, a paid run skipped, a number a model reported, a review finding set aside on an -assumption nobody tested), or says `none`. A green PR page is not a READY. A cheap test +assumption nobody tested), or says `none`. `Failed or skipped:` and `Also changed:` lines +name each check, case or step that failed or never ran, and each config, CI or out-of-scope +file the PR touches, or say `none`. A green PR page is not a READY. A cheap test tier is not merge evidence. The controller refuses a block that misses any of this and sends the lane back, never into a train. When the contract changes (a new required line, a new check name, a new receipt), every READY @@ -435,6 +437,8 @@ taken before the change is stale: the lane runs `ready` again at the same pin an the fresh block; the controller trains nothing older than the change. The `Unverified:` line is the one exception: the controller asks for a missing line in a follow-up message, never refuses or stales a READY for it, and the lane reruns neither `ready` nor /ship. +The same exception covers a missing `Failed or skipped:` or `Also changed:` line: the +controller asks for it in a follow-up message and never refuses or stales a READY over it. ### The lane's /ship sequence before READY From 127bcd6d55c38220d32beaa04413c90145df6f4d Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 20:22:11 +0800 Subject: [PATCH 29/62] Accept a requested docs fix when the audit names the file with a line number (#4437) finish --docs-requested refused a correct fix when the docs audit named the file as path:line ("changelog.d/engine-parity-decisions.md:8: wording") or path:line:column, because the match only allowed whitespace, quotes or punctuation right after the path. It now also allows :<line> and :<line>:<column> before those, while a different file sharing the path's prefix still doesn't match. Reported by Vorflux via FOUN-32. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- ...cs-requested-accepts-path-line-blockers.md | 1 + lib/ship-release.ts | 2 +- test/ship-rereview-triggers.test.ts | 22 +++++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 changelog.d/docs-requested-accepts-path-line-blockers.md diff --git a/changelog.d/docs-requested-accepts-path-line-blockers.md b/changelog.d/docs-requested-accepts-path-line-blockers.md new file mode 100644 index 00000000000..cdee4b9d86d --- /dev/null +++ b/changelog.d/docs-requested-accepts-path-line-blockers.md @@ -0,0 +1 @@ +- **/ship's `finish --docs-requested` now accepts a docs fix when the audit named the file with a line number.** An audit that wrote `changelog.d/engine-parity-decisions.md:8: wording` or `...md:8:12 wording` in its blockers or decisions was refused with "is not named in the audit result's blockers or decisions", even though `...md: line 8` worked. The path may now be followed by `:<line>` or `:<line>:<column>`. A different file whose name starts with the same path still doesn't match. diff --git a/lib/ship-release.ts b/lib/ship-release.ts index 442d567ac8b..e0711fe1af5 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -546,7 +546,7 @@ function docsFresh(cwd: string, base: string, postFile: string, moved: readonly try { audit = resultFile ? JSON.parse(fs.readFileSync(resultFile, 'utf8')) : null; } catch { audit = null; } for (const p of requested.filter(q => stale!.includes(q) && !carried.tests.includes(q) && !carried.base.includes(q) && !carried.accepted.includes(q))) { const asked = [...(Array.isArray(audit?.blockers) ? audit.blockers : []), ...(Array.isArray(audit?.decisions) ? audit.decisions : [])].filter((s: unknown) => typeof s === 'string'); - const token = new RegExp(`(^|[\\s\`'"(\\[])${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?=$|[\\s\`'")\\]]|[,.:;](?:$|\\s))`); + const token = new RegExp(`(^|[\\s\`'"(\\[])${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?::\\d+(?::\\d+)?)?(?=$|[\\s\`'")\\]]|[,.:;](?:$|\\s))`); const stat = git(cwd, ['diff', '--numstat', '--no-renames', record.head, '--', `:(literal)${p}`]).stdout.trim().split(/\s+/); const lines = Number(stat[0]) + Number(stat[1]); const why = !audit ? 'needs --docs-result <the audit\'s saved result JSON>' diff --git a/test/ship-rereview-triggers.test.ts b/test/ship-rereview-triggers.test.ts index e3116eb6dec..6dc0b54cfe8 100644 --- a/test/ship-rereview-triggers.test.ts +++ b/test/ship-rereview-triggers.test.ts @@ -554,6 +554,28 @@ describe('test-only and audit-requested edits after the docs audit (GST-391, gbr expect(big.stdout).toContain('STOP: --docs-requested docs/KEY_FILES.md'); }); + // Value: protects=an audit that names the requested doc as path:line or path:line:column (FOUN-32 via Vorflux at 2af3822f) + // still backs the fix, while a different file sharing the path's prefix never does; fails_when=a correct requested fix stops + // on how the audit wrote the location, or a sibling file's note waves the fix through; seam=finish --docs-requested; + // no_claim=the audit child's wording + test.each([ + ['path:line', 'docs/KEY_FILES.md:8: the src/b.ts entry is missing', true], + ['path:line:column', 'docs/KEY_FILES.md:8:12 the src/b.ts entry is missing', true], + ['path then "line"', 'docs/KEY_FILES.md: line 8 is missing the src/b.ts entry', true], + ['another file sharing the prefix', 'docs/KEY_FILES.md.tmpl:8: the src/b.ts entry is missing', false], + ])('--docs-requested matches the audit naming the doc as %s: %p', (_name, decision, named) => { + const index = Array.from({ length: 30 }, (_, i) => `- entry ${i}`).join('\n') + '\n'; + const f = fx({ 'docs/KEY_FILES.md': index }); + const reviewed = wtree(f); + const post = snapshot(f, ['docs']); + const result = path.join(f.root, 'a1-result.json'); + fs.writeFileSync(result, JSON.stringify({ schema_version: 1, audit_id: 'a1', status: 'current', files_updated: [], files_reviewed: ['docs/KEY_FILES.md'], blockers: [], decisions: [decision], documentation_section: 'x' })); + f.write({ 'docs/KEY_FILES.md': index + '- src/b.ts: the b constant\n' }); f.commit('docs: index link'); + const r = finish(f, reviewed, post, ['--reviewed-base', mergeBase(f), '--docs-rechecked', '--docs-requested', 'docs/KEY_FILES.md', '--docs-result', result]); + if (named) expect([r.status, lineOf(r.stdout, 'DOCS')]).toEqual([0, expect.stringContaining('requested=1')]); + else expect(r.stdout).toContain("STOP: --docs-requested docs/KEY_FILES.md is not named in the audit result's blockers or decisions"); + }); + // Value: protects=an audit launch the child's install check refused is not counted, once per invocation; a crashed child, // a completed audit and output that only quotes a refusal are counted, and a second refusal stops; fails_when=the refusal // burns the only retry (gbrain #8084) or refusals relaunch forever; seam=none; no_claim=the parent's launch From ab114c53080a103aa7ba2b2f7f2e07085f8e34a7 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 20:23:35 +0800 Subject: [PATCH 30/62] Say when to use each gstack skill in Claude Code's skill list (GST-2774) (#4387) * Say when to use each gstack skill in Claude Code's skill list (GST-2774) Claude Code's listing of each gstack skill now keeps a short when-to-use clause after its first sentence, so Opus 5.5 loads /review on "review my changes" and /plan-eng-review on "plan this feature" (GSTA-558). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep /review and /plan-eng-review within their size pins and refresh budgets CI on the first head found five size and fact checks the new catalog clause moved: the per-host SKILL.md size pins, the context-budget ceilings, the deslop-shared-libs catalog byte pin, the Claude ship golden and the catalog ceiling CLAUDE.md states. /review's and /plan-eng-review's full descriptions are now shorter than before, so their pins go down, and /plan-eng-review's scope gate is unchanged from main. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Say which skills keep no when-to-use clause in the changelog entry Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Update the catalog budget and voice-trigger docs for the when-to-use clause Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Drop "deploy this" from /ship's Claude Code skill list line Deploying belongs to /land-and-deploy, so /ship's when-to-use clause keeps "ship it, create a pr, push to main" only. Budgets, the size ledger and the Claude ship golden are re-measured. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: pre-landing review fixes Review-Finding: p1/specialist-batched#1 reader=specialist-batched Review-Finding: p1/red-team#1 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Re-measure the setup-gbrain size cap after merging main Main grew setup-gbrain's always-loaded part to 38,621 bytes, and this branch's when-to-use clause adds 55 more, so the cap measured on the old base (38,637) is stale. The cap is now the merged measurement, 38,676. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CLAUDE.md | 2 +- CONTRIBUTING.md | 2 +- SKILL.md | 2 +- SKILL.md.tmpl | 4 +- autoplan/SKILL.md | 2 +- benchmark-models/SKILL.md | 2 +- benchmark/SKILL.md | 2 +- browse/SKILL.md | 2 +- canary/SKILL.md | 2 +- captain/SKILL.md | 2 +- careful/SKILL.md | 2 +- ...aude-skill-descriptions-say-when-to-use.md | 1 + codex/SKILL.md | 2 +- context-restore/SKILL.md | 2 +- context-save/SKILL.md | 2 +- cso/SKILL.md | 2 +- design-html/SKILL.md | 2 +- design-motion/SKILL.md | 2 +- design-review/SKILL.md | 2 +- design-shotgun/SKILL.md | 2 +- deslop-shared-libs/SKILL.md | 2 +- devex-review/SKILL.md | 2 +- diagram/SKILL.md | 2 +- docs/CONTRIBUTOR_REFERENCE.md | 2 +- docs/voice-input.md | 9 +- document-generate/SKILL.md | 2 +- document-release/SKILL.md | 2 +- freeze/SKILL.md | 2 +- gstack-upgrade/SKILL.md | 4 +- gstack-upgrade/SKILL.md.tmpl | 2 - gstack/llms.txt | 6 +- guard/SKILL.md | 2 +- health/SKILL.md | 2 +- ios-clean/SKILL.md | 2 +- ios-design-review/SKILL.md | 2 +- ios-fix/SKILL.md | 2 +- ios-qa/SKILL.md | 2 +- ios-sync/SKILL.md | 2 +- land-and-deploy/SKILL.md | 2 +- landing-report/SKILL.md | 2 +- learn/SKILL.md | 2 +- lib/skill-triggers.ts | 8 +- make-pdf/SKILL.md | 2 +- modernize/SKILL.md | 2 +- office-hours/SKILL.md | 2 +- open-gstack-browser/SKILL.md | 2 +- pair-agent/SKILL.md | 2 +- plan-ceo-review/SKILL.md | 2 +- plan-design-review/SKILL.md | 2 +- plan-devex-review/SKILL.md | 2 +- plan-eng-review/SKILL.md | 3 +- plan-eng-review/SKILL.md.tmpl | 9 +- plan-tune/SKILL.md | 2 +- qa-only/SKILL.md | 2 +- qa/SKILL.md | 2 +- retro/SKILL.md | 2 +- review/SKILL.md | 6 +- review/SKILL.md.tmpl | 12 +- runaway-stopper/SKILL.md | 2 +- scrape/SKILL.md | 2 +- scripts/gen-skill-docs.ts | 33 +++-- setup-browser-cookies/SKILL.md | 2 +- setup-deploy/SKILL.md | 2 +- setup-gbrain/SKILL.md | 2 +- ship/SKILL.md | 3 +- ship/SKILL.md.tmpl | 1 - skillify/SKILL.md | 2 +- spec/SKILL.md | 2 +- sync-gbrain/SKILL.md | 2 +- test-audit/SKILL.md | 2 +- test/catalog-budget.test.ts | 14 +- test/catalog-trim.test.ts | 36 ++++- test/fixtures/context-budget.json | 126 +++++++++--------- test/fixtures/golden/claude-ship-SKILL.md | 3 +- test/fixtures/skill-md-size-allowlist.json | 42 +++--- test/helpers/carve-guards.ts | 38 +++--- test/shared-libs-rendering.test.ts | 7 +- ...de-skill-descriptions-say-when-to-use.json | 4 + test/skill-triggers.test.ts | 2 + ubicloud/SKILL.md | 2 +- unfreeze/SKILL.md | 2 +- verify/SKILL.md | 2 +- write-skill/SKILL.md | 2 +- 83 files changed, 277 insertions(+), 216 deletions(-) create mode 100644 changelog.d/claude-skill-descriptions-say-when-to-use.md create mode 100644 test/size-ledger/ship/claude-skill-descriptions-say-when-to-use.json diff --git a/CLAUDE.md b/CLAUDE.md index 35db4608f40..0ad5a5d004f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -147,7 +147,7 @@ a skill's own bash. **Size budgets:** generated SKILL.md files warn above 160KB (~40K tokens); `test/catalog-budget.test.ts` caps the always-loaded skill catalog at -`CATALOG_BUDGET_TOKEN_EQUIVALENTS` (1,452 today; each new skill ratchets it); and +`CATALOG_BUDGET_TOKEN_EQUIVALENTS` (2,290 today; each new skill ratchets it); and `test/context-budget-ratchet.test.ts` pins per-skill token ceilings against `test/fixtures/context-budget.json` (for legitimate growth or a landed reduction, re-run `bun test/helpers/capture-context-budget.ts` and commit the diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 56f9f0e4e64..409090f4bc4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -429,7 +429,7 @@ eval files, and misses the strict classifier. No API keys needed. - **Generator tests** (`test/gen-skill-docs.test.ts`) — Tests the template system: verifies placeholders resolve correctly, output includes value hints for flags (e.g. `-d <N>` not just `-d`), enriched descriptions for key commands (e.g. `is` lists valid states, `press` lists key examples), and that a template's `codex_default_prompt:` frontmatter key reaches the Codex `agents/openai.yaml` `default_prompt` (a template without the key keeps `Use <name> for this task.`) while no host's SKILL.md render carries the key. - **Design detector, catalog, and DESIGN.md** (`test/gstack-design-detect.test.ts`, `test/design-detect-contract.test.ts`, `test/design-catalog.test.ts`, `test/design-checklist-sync.test.ts`, `test/design-md.test.ts`, `test/frontend-scope.test.ts`, `test/impeccable-fixtures.test.ts`) — Drive `bin/gstack-design-detect.ts` through the fake engine in `test/fixtures/fake-impeccable.ts` (probe order, the never-execute-a-repository-file rule, the `--changed` target allow-list, `design_detector: off`, analytics lines, output sanitizing), pin the catalog invariants and the generated `review/design-checklist.md`, round-trip the open DESIGN.md reader/writer, and check the real engine captures (`test/fixtures/impeccable-*.json`, engine 0.1.3) against the contract. `test/dom-dump-hygiene.test.ts` runs `lib/dom-dump.js` in a real Chromium page through the built browse binary; it self-skips without the binary and is opt-in outside CI (`GSTACK_DOM_DUMP_HYGIENE=1`). - **Tier-alignment invariant** (`test/e2e-tier-alignment.test.ts`) — For every self-gated `test/skill-e2e-*.test.ts` named in a touchfiles dep list, the file's `EVALS_TIER` self-gate must match its declared tier in `E2E_TIERS`. Kills the "inert demotion" class where a test is re-tiered in `touchfiles.ts` but the file still gates on the old tier and keeps running in the wrong lane. Unmapped or mixed-tier files are reported, never silently skipped. -- **Catalog budget** (`test/catalog-budget.test.ts`) — Caps the aggregate discovery surface: the sum of every skill's frontmatter `name` + `description` (what every host loads at discovery, every session) must stay under 1,452 token-equivalents, with a 260-byte per-skill cap. Counting goes through the shared census in `test/helpers/skill-census.ts` (physical files vs authored skills vs registry entries — three deliberately different counts). Adding a skill? The failure message carries the re-measure + ratchet protocol. +- **Catalog budget** (`test/catalog-budget.test.ts`) — Caps the aggregate discovery surface: the sum of every skill's frontmatter `name` + `description` (what every host loads at discovery, every session) must stay under 2,290 token-equivalents, with a 260-byte per-skill cap. Counting goes through the shared census in `test/helpers/skill-census.ts` (physical files vs authored skills vs registry entries — three deliberately different counts). Adding a skill? The failure message carries the re-measure + ratchet protocol. - **Context-budget ratchet** (`test/context-budget-ratchet.test.ts`) — CI ceilings on the two token ledgers the catalog budget doesn't cover: the always-on full-frontmatter aggregate and each skill's per-invocation eager tokens (SKILL.md + forced-read references), graded against `test/fixtures/context-budget.json` via `lib/context-bill.ts`. New skills fail until they have a ceiling; ceilings for removed skills must be pruned. Legitimate growth or a landed reduction: re-run `bun test/helpers/capture-context-budget.ts` and commit the refreshed fixture in the same commit, so the change is a visible decision in the diff. - **Skill-to-bin drift ratchet** (`test/skill-bin-drift.test.ts`) — `scripts/skill-bin-drift.ts` statically reads every gstack bin call in skill templates, carved sections, references and the Claude-host renders (it never executes a bin) and fails with `DRIFT_UNKNOWN_BIN` or `DRIFT_UNKNOWN_FLAG` at file:line when a skill names a bin missing from `bin/` or a flag that bin's parser does not accept. Known misses live in `test/fixtures/skill-bin-drift-allowlist.json`, which only shrinks: a new finding fails, and so does an entry that no longer reproduces. Check one skill with `bun run scripts/skill-bin-drift.ts --skill <name>`; bins with permissive parsers or no usage text are reported, never failed. - **Dependency security regressions** (`test/dependency-security.test.ts`) — Run `bun test test/dependency-security.test.ts` to check the resolved `sharp`, `adm-zip`, `qs`, `@hono/node-server` and `hono` version floors, load Sharp, verify ordinary ZIP extraction, and reject extraction through destination-file and destination-directory symlinks. The symlink cases skip Windows. These checks complement the OSV scan; they do not change its existing exceptions. diff --git a/SKILL.md b/SKILL.md index 58ac4edc031..8f2d4aa713e 100644 --- a/SKILL.md +++ b/SKILL.md @@ -2,7 +2,7 @@ name: gstack preamble-tier: 1 version: 1.2.0 -description: Router for the gstack skill suite. (gstack) +description: "Picks the gstack skill that fits a request: planning, review, QA, shipping, debugging, docs, security or design. Use for: gstack, which gstack skill, route this with gstack. (gstack)" allowed-tools: - Bash - Read diff --git a/SKILL.md.tmpl b/SKILL.md.tmpl index 3f7cd498e0c..745251a6e36 100644 --- a/SKILL.md.tmpl +++ b/SKILL.md.tmpl @@ -3,8 +3,8 @@ name: gstack preamble-tier: 1 version: 1.2.0 description: | - Router for the gstack skill suite. Sends any gstack request to the right skill - (planning, review, QA, shipping, debugging, docs, security, design). Routes QA by + Picks the gstack skill that fits a request: planning, review, QA, shipping, + debugging, docs, security or design. Routes QA by intent and browser interaction to /browse. Use when you invoke gstack without a specific skill, or ask "which gstack skill fits this?". (gstack) allowed-tools: diff --git a/autoplan/SKILL.md b/autoplan/SKILL.md index 4dba708962b..fea3f5ca2c5 100644 --- a/autoplan/SKILL.md +++ b/autoplan/SKILL.md @@ -2,7 +2,7 @@ name: autoplan preamble-tier: 3 version: 1.0.0 -description: "Auto-review pipeline — runs the CEO, design, eng and DX reviews in order (lean run: one reviewer), auto-deciding. (gstack)" +description: "Auto-review pipeline — runs the CEO, design, eng and DX reviews in order (lean run: one reviewer), auto-deciding. Use for: run all reviews, automatic review pipeline. (gstack)" triggers: - run all reviews - automatic review pipeline diff --git a/benchmark-models/SKILL.md b/benchmark-models/SKILL.md index 54d2533b887..b9c310ee863 100644 --- a/benchmark-models/SKILL.md +++ b/benchmark-models/SKILL.md @@ -2,7 +2,7 @@ name: benchmark-models preamble-tier: 1 version: 1.0.0 -description: Cross-model benchmark for gstack skills. (gstack) +description: "Cross-model benchmark for gstack skills. Use for: cross model benchmark, compare claude gpt gemini. (gstack)" triggers: - cross model benchmark - compare claude gpt gemini diff --git a/benchmark/SKILL.md b/benchmark/SKILL.md index fc6733d8e66..38babc3943b 100644 --- a/benchmark/SKILL.md +++ b/benchmark/SKILL.md @@ -2,7 +2,7 @@ name: benchmark preamble-tier: 1 version: 1.0.0 -description: Web performance regression detection. (gstack) +description: "Web performance regression detection. Use for: web performance benchmark, check page speed. (gstack)" triggers: - web performance benchmark - check page speed diff --git a/browse/SKILL.md b/browse/SKILL.md index 509263edd1b..970ed2c4013 100644 --- a/browse/SKILL.md +++ b/browse/SKILL.md @@ -2,7 +2,7 @@ name: browse preamble-tier: 1 version: 2.0.0 -description: "Drive a real browser through Aside: open a page, read it, click through a flow, take screenshots, check console errors. (gstack)" +description: "Drive a real browser through Aside: open a page, read it, click through a flow, take screenshots, check console errors. Use for: browse a page, open this url, take page screenshot. (gstack)" triggers: - browse a page - open this url diff --git a/canary/SKILL.md b/canary/SKILL.md index a6958470518..9bbe4eaa95c 100644 --- a/canary/SKILL.md +++ b/canary/SKILL.md @@ -2,7 +2,7 @@ name: canary preamble-tier: 2 version: 1.0.0 -description: Post-deploy canary monitoring. (gstack) +description: "Post-deploy canary monitoring. Use for: monitor after deploy, canary check. (gstack)" allowed-tools: - Bash - Read diff --git a/captain/SKILL.md b/captain/SKILL.md index f5635fa43ce..e244f53b51f 100644 --- a/captain/SKILL.md +++ b/captain/SKILL.md @@ -2,7 +2,7 @@ name: captain preamble-tier: 2 version: 1.0.0 -description: "Run a crew of coding agents from one controller (also /crew): lanes send READY blocks and never merge; the controller merges through trains, keeps the digest, relays approvals, fixes flakes daily. (gstack)" +description: "Run a crew of coding agents from one controller (also /crew): lanes send READY blocks and never merge; the controller merges through trains, keeps the digest, relays approvals, fixes flakes daily. Use for: captain, crew. (gstack)" triggers: - captain - crew diff --git a/careful/SKILL.md b/careful/SKILL.md index bf5aaca88c8..f91af40629c 100644 --- a/careful/SKILL.md +++ b/careful/SKILL.md @@ -1,7 +1,7 @@ --- name: careful version: 0.1.0 -description: Safety guardrails for destructive commands. (gstack) +description: "Safety guardrails for destructive commands. Use for: be careful, warn before destructive, safety mode. (gstack)" triggers: - be careful - warn before destructive diff --git a/changelog.d/claude-skill-descriptions-say-when-to-use.md b/changelog.d/claude-skill-descriptions-say-when-to-use.md new file mode 100644 index 00000000000..fdef5b07e92 --- /dev/null +++ b/changelog.d/claude-skill-descriptions-say-when-to-use.md @@ -0,0 +1 @@ +- **Claude Code's skill list now says when to use each gstack skill, so Opus loads /review and /plan-eng-review when a request fits.** gstack cut every Claude Code description to its first sentence, which says what a skill is but usually not when to load it. In a test with Opus 5.5 in Claude Code, "Review my changes before I land them" loaded /review 0 of 3 times (its line read "Use when you review this PR's diff."), and "plan this feature" loaded no gstack skill in 9 tries. Almost every Claude Code description now keeps a short when-to-use clause after its first sentence. The clause is the skill's own trigger phrases ("Use for: review my changes, look over my diff, review this pr."), or its "Use when" sentence when it has no trigger list; /design-consultation and /eval-plan keep only their first sentence. /review's line no longer assumes a PR exists (local changes and a branch count), /plan-eng-review says it plans a feature before you build it, and the `gstack` router's line says what it does instead of "Router for the gstack skill suite." The skill list Claude Code loads every session grows by about 840 tokens. The clause is added only to Claude Code's trimmed list, so `--catalog-mode=full` and the other hosts don't get it. diff --git a/codex/SKILL.md b/codex/SKILL.md index 782d64d40e3..35ca6847259 100644 --- a/codex/SKILL.md +++ b/codex/SKILL.md @@ -2,7 +2,7 @@ name: codex preamble-tier: 3 version: 1.0.0 -description: OpenAI Codex CLI wrapper — three modes. (gstack) +description: "OpenAI Codex CLI wrapper — three modes. Use for: codex review, second opinion, outside voice challenge. (gstack)" triggers: - codex review - second opinion diff --git a/context-restore/SKILL.md b/context-restore/SKILL.md index 6196ae5a9af..e322d4cb518 100644 --- a/context-restore/SKILL.md +++ b/context-restore/SKILL.md @@ -2,7 +2,7 @@ name: context-restore preamble-tier: 2 version: 1.0.0 -description: Restore working context saved earlier by /context-save. (gstack) +description: "Restore working context saved earlier by /context-save. Use for: resume where i left off, restore context, where was i. (gstack)" allowed-tools: - Bash - Read diff --git a/context-save/SKILL.md b/context-save/SKILL.md index 79d87921c57..fb9b631fa5d 100644 --- a/context-save/SKILL.md +++ b/context-save/SKILL.md @@ -2,7 +2,7 @@ name: context-save preamble-tier: 2 version: 1.0.0 -description: Save working context. (gstack) +description: "Save working context. Use for: save progress, save state, save my work, context save. (gstack)" allowed-tools: - Bash - Read diff --git a/cso/SKILL.md b/cso/SKILL.md index ef9ef28f9c3..7852aecf346 100644 --- a/cso/SKILL.md +++ b/cso/SKILL.md @@ -1,7 +1,7 @@ --- name: cso version: 3.0.0 -description: "Security audit: supported static findings; qualified profiles add reproduction and repair candidates. (gstack)" +description: "Security audit: supported static findings; qualified profiles add reproduction and repair candidates. Use for: security audit, check for vulnerabilities. (gstack)" allowed-tools: - "Bash(~/.claude/skills/gstack/bin/gstack-cso-launcher *)" - "Bash(~/.claude/skills/gstack/bin/gstack-cso-launcher.exe *)" diff --git a/design-html/SKILL.md b/design-html/SKILL.md index b57d25d9315..6ea35466d56 100644 --- a/design-html/SKILL.md +++ b/design-html/SKILL.md @@ -2,7 +2,7 @@ name: design-html preamble-tier: 2 version: 1.0.0 -description: "Design finalization: generates production-quality Pretext-native HTML/CSS. (gstack)" +description: "Design finalization: generates production-quality Pretext-native HTML/CSS. Use for: build the design, code the mockup, make design real. (gstack)" triggers: - build the design - code the mockup diff --git a/design-motion/SKILL.md b/design-motion/SKILL.md index 2526448e247..46919b3b6f8 100644 --- a/design-motion/SKILL.md +++ b/design-motion/SKILL.md @@ -2,7 +2,7 @@ name: design-motion preamble-tier: 2 version: 1.0.0 -description: "Design motion: animate an approved design into a seamless MP4 and GIF loop. (gstack)" +description: "Design motion: animate an approved design into a seamless MP4 and GIF loop. Use for: animate this design, make a showcase loop. (gstack)" triggers: - animate this design - make a showcase loop diff --git a/design-review/SKILL.md b/design-review/SKILL.md index 83b1bfadc01..a35b9079526 100644 --- a/design-review/SKILL.md +++ b/design-review/SKILL.md @@ -2,7 +2,7 @@ name: design-review preamble-tier: 4 version: 2.0.0 -description: "Designer's eye QA: finds visual inconsistency, spacing issues, hierarchy problems, AI slop patterns, and slow interactions — then fixes them; --build checks UI while you build it. (gstack)" +description: "Designer's eye QA: finds visual inconsistency, spacing issues, hierarchy problems, AI slop patterns, and slow interactions — then fixes them; --build checks UI while you build it. Use for: visual design audit, design qa. (gstack)" allowed-tools: - Bash - Read diff --git a/design-shotgun/SKILL.md b/design-shotgun/SKILL.md index 96bfd56b532..1d20e76d20f 100644 --- a/design-shotgun/SKILL.md +++ b/design-shotgun/SKILL.md @@ -2,7 +2,7 @@ name: design-shotgun preamble-tier: 2 version: 1.0.0 -description: "Design shotgun: generate multiple AI design variants, open a comparison board, collect structured feedback, and iterate. (gstack)" +description: "Design shotgun: generate multiple AI design variants, open a comparison board, collect structured feedback, and iterate. Use for: explore design variants, show me design options. (gstack)" triggers: - explore design variants - show me design options diff --git a/deslop-shared-libs/SKILL.md b/deslop-shared-libs/SKILL.md index 6c65869dec0..a5988668810 100644 --- a/deslop-shared-libs/SKILL.md +++ b/deslop-shared-libs/SKILL.md @@ -1,7 +1,7 @@ --- name: deslop-shared-libs version: 1.0.0 -description: Find worthwhile shared-code extractions in recent work. (gstack) +description: "Find worthwhile shared-code extractions in recent work. Use for: find code worth sharing. (gstack)" allowed-tools: - Bash - Read diff --git a/devex-review/SKILL.md b/devex-review/SKILL.md index d28cb3f57a2..2579987b809 100644 --- a/devex-review/SKILL.md +++ b/devex-review/SKILL.md @@ -2,7 +2,7 @@ name: devex-review preamble-tier: 3 version: 1.0.0 -description: Live developer experience audit. (gstack) +description: "Live developer experience audit. Use for: live dx audit, test developer experience. (gstack)" triggers: - live dx audit - test developer experience diff --git a/diagram/SKILL.md b/diagram/SKILL.md index 71bb28a4c84..6198b894d1b 100644 --- a/diagram/SKILL.md +++ b/diagram/SKILL.md @@ -2,7 +2,7 @@ name: diagram preamble-tier: 1 version: 1.0.0 -description: "Turn an English description (or mermaid source) into a diagram triplet: the source, an editable .excalidraw file you can open on excalidraw.com, and rendered SVG + PNG. (gstack)" +description: "Turn an English description (or mermaid source) into a diagram triplet: the source, an editable .excalidraw file you can open on excalidraw.com, and rendered SVG + PNG. Use for: make a diagram, draw a diagram. (gstack)" allowed-tools: - Bash - Read diff --git a/docs/CONTRIBUTOR_REFERENCE.md b/docs/CONTRIBUTOR_REFERENCE.md index 1275bce965d..67b601729cc 100644 --- a/docs/CONTRIBUTOR_REFERENCE.md +++ b/docs/CONTRIBUTOR_REFERENCE.md @@ -20,7 +20,7 @@ cuts to the coverage audit, review army, or voice directive have real quality co A second, harder ceiling guards the DISCOVERY surface: `test/catalog-budget.test.ts` caps the aggregate frontmatter `name` + `description` across all skills at -`CATALOG_BUDGET_TOKEN_EQUIVALENTS` (1,452 today; each new skill ratchets it) +`CATALOG_BUDGET_TOKEN_EQUIVALENTS` (2,290 today; each new skill ratchets it) token-equivalents (260-byte per-skill sub-cap), counted through the shared census in `test/helpers/skill-census.ts`. This one is enforced, not a warning — every host loads the full catalog every session, so growth here taxes every diff --git a/docs/voice-input.md b/docs/voice-input.md index 3401077f6a1..e45a5867d13 100644 --- a/docs/voice-input.md +++ b/docs/voice-input.md @@ -13,7 +13,8 @@ matching surface. Claude Code and Codex choose a skill from its name and description, so a phrase that appears only under `triggers:` does not activate the skill (Codex output drops the field; the GBrain host keeps it). The four core skills (/office-hours, /review, /qa, /ship) carry their `triggers:` phrases in -the description itself: every phrase in the full description, and at least one -in the one-line catalog entry Claude Code reads ("test the site" for /qa, "ship -it" for /ship). The other skills do not, because under the `core` default they -wait for you to type them (docs/proactive.md). +the full description itself. On Claude Code, the one-line catalog entry for most +skills also ends with a short when-to-use clause built from the first few +`triggers:` phrases ("Use for: qa test this, find bugs on site, test the +site."), or from the skill's "Use when" sentence when it has no trigger list; +`--catalog-mode=full` and the other hosts don't get that clause. diff --git a/document-generate/SKILL.md b/document-generate/SKILL.md index 025ab43e2e4..bb4749ce3e7 100644 --- a/document-generate/SKILL.md +++ b/document-generate/SKILL.md @@ -2,7 +2,7 @@ name: document-generate preamble-tier: 2 version: 1.0.0 -description: Generate missing documentation from scratch for a feature, module, or entire project. (gstack) +description: "Generate missing documentation from scratch for a feature, module, or entire project. Use for: write docs for this, generate documentation. (gstack)" allowed-tools: - Bash - Read diff --git a/document-release/SKILL.md b/document-release/SKILL.md index 5519f6c2535..66d1cf4e0d9 100644 --- a/document-release/SKILL.md +++ b/document-release/SKILL.md @@ -2,7 +2,7 @@ name: document-release preamble-tier: 2 version: 1.0.0 -description: Release documentation audit. (gstack) +description: "Release documentation audit. Use for: update docs after ship, document what changed. (gstack)" allowed-tools: - Bash - Read diff --git a/freeze/SKILL.md b/freeze/SKILL.md index 39230fbb577..da4b5100801 100644 --- a/freeze/SKILL.md +++ b/freeze/SKILL.md @@ -1,7 +1,7 @@ --- name: freeze version: 0.1.0 -description: Restrict file edits to a specific directory for the session. (gstack) +description: "Restrict file edits to a specific directory for the session. Use for: freeze edits to directory, lock editing scope. (gstack)" triggers: - freeze edits to directory - lock editing scope diff --git a/gstack-upgrade/SKILL.md b/gstack-upgrade/SKILL.md index 2a3efc40d13..7c351ee1cd6 100644 --- a/gstack-upgrade/SKILL.md +++ b/gstack-upgrade/SKILL.md @@ -1,7 +1,7 @@ --- name: gstack-upgrade version: 1.1.0 -description: Upgrade gstack to the latest version. +description: "Upgrade gstack to the latest version. Use for: upgrade gstack, update gstack version." triggers: - upgrade gstack - update gstack version @@ -17,8 +17,6 @@ allowed-tools: # /gstack-upgrade -Upgrade gstack to the latest version and show what's new. - ## Inline upgrade flow This section is referenced by all skill preambles when they detect `UPGRADE_AVAILABLE`. diff --git a/gstack-upgrade/SKILL.md.tmpl b/gstack-upgrade/SKILL.md.tmpl index 04a618f9949..7b6f24dd47d 100644 --- a/gstack-upgrade/SKILL.md.tmpl +++ b/gstack-upgrade/SKILL.md.tmpl @@ -23,8 +23,6 @@ allowed-tools: # /gstack-upgrade -Upgrade gstack to the latest version and show what's new. - ## Inline upgrade flow This section is referenced by all skill preambles when they detect `UPGRADE_AVAILABLE`. diff --git a/gstack/llms.txt b/gstack/llms.txt index 41e78daf03c..c85ccfbbb81 100644 --- a/gstack/llms.txt +++ b/gstack/llms.txt @@ -33,7 +33,7 @@ Conventions: - [/document-release](document-release/SKILL.md): Release documentation audit. - [/eval-plan](eval-plan/SKILL.md): Preregister a paid eval (bars, arms, decoys, stop rules), dry-run it at zero cost, then run a three-item priced pilot whose spend table gates approval. - [/freeze](freeze/SKILL.md): Restrict file edits to a specific directory for the session. -- [/gstack](SKILL.md): Router for the gstack skill suite. +- [/gstack](SKILL.md): Picks the gstack skill that fits a request: planning, review, QA, shipping, debugging, docs, security or design. - [/gstack-upgrade](gstack-upgrade/SKILL.md): Upgrade gstack to the latest version. - [/guard](guard/SKILL.md): Full safety mode: destructive command warnings + directory-scoped edits. - [/health](health/SKILL.md): Code quality dashboard. @@ -53,12 +53,12 @@ Conventions: - [/plan-ceo-review](plan-ceo-review/SKILL.md): CEO/founder-mode plan review. - [/plan-design-review](plan-design-review/SKILL.md): Designer's eye plan review — interactive, like CEO and Eng review. - [/plan-devex-review](plan-devex-review/SKILL.md): Interactive developer experience plan review. -- [/plan-eng-review](plan-eng-review/SKILL.md): Eng manager-mode plan review. +- [/plan-eng-review](plan-eng-review/SKILL.md): Use when you plan a feature before building it, or review a plan: locks in architecture, data flow, diagrams, edge cases, test coverage and performance. - [/plan-tune](plan-tune/SKILL.md): Self-tuning question sensitivity + developer psychographic for gstack (v1: observational). - [/qa](qa/SKILL.md): Use when you test the site, API or CLI and fix bugs. - [/qa-only](qa-only/SKILL.md): Report browser/API/CLI/job/worker/webhook bugs. - [/retro](retro/SKILL.md): Weekly engineering retrospective. -- [/review](review/SKILL.md): Use when you review this PR's diff. +- [/review](review/SKILL.md): Use when you review a diff before it lands: local changes, a branch or a PR. - [/runaway-stopper](runaway-stopper/SKILL.md): Find runaway Capy threads and subagents, stop or rotate them safely, and prevent repeats. - [/scrape](scrape/SKILL.md): Pull data from a web page through the Aside browser — your real, already signed-in sessions. - [/setup-browser-cookies](setup-browser-cookies/SKILL.md): Import cookies from your real Chromium browser into the headless browse session. diff --git a/guard/SKILL.md b/guard/SKILL.md index ef4b7bd7990..58e5b7db2fb 100644 --- a/guard/SKILL.md +++ b/guard/SKILL.md @@ -1,7 +1,7 @@ --- name: guard version: 0.1.0 -description: "Full safety mode: destructive command warnings + directory-scoped edits. (gstack)" +description: "Full safety mode: destructive command warnings + directory-scoped edits. Use for: full safety mode, guard against mistakes. (gstack)" triggers: - full safety mode - guard against mistakes diff --git a/health/SKILL.md b/health/SKILL.md index 57ac446c2e4..85925eb4fbe 100644 --- a/health/SKILL.md +++ b/health/SKILL.md @@ -2,7 +2,7 @@ name: health preamble-tier: 2 version: 1.0.0 -description: Code quality dashboard. (gstack) +description: "Code quality dashboard. Use for: code health check, quality dashboard. (gstack)" triggers: - code health check - quality dashboard diff --git a/ios-clean/SKILL.md b/ios-clean/SKILL.md index 197edd574be..c196044c910 100644 --- a/ios-clean/SKILL.md +++ b/ios-clean/SKILL.md @@ -2,7 +2,7 @@ name: ios-clean preamble-tier: 2 version: 1.0.0 -description: "Remove the DebugBridge SPM package and all #if DEBUG wiring from an iOS app. (gstack)" +description: "Remove the DebugBridge SPM package and all #if DEBUG wiring from an iOS app. Use for: clean the ios debug bridge, remove debugbridge. (gstack)" allowed-tools: - Bash - Read diff --git a/ios-design-review/SKILL.md b/ios-design-review/SKILL.md index 87fbd2fe4d8..3cb8262348e 100644 --- a/ios-design-review/SKILL.md +++ b/ios-design-review/SKILL.md @@ -2,7 +2,7 @@ name: ios-design-review preamble-tier: 2 version: 1.0.0 -description: Visual design audit for iOS apps on real hardware. (gstack) +description: "Visual design audit for iOS apps on real hardware. Use for: review the ios design, audit the iphone app visuals. (gstack)" allowed-tools: - Bash - Read diff --git a/ios-fix/SKILL.md b/ios-fix/SKILL.md index a9331cba98c..8a8af4059c7 100644 --- a/ios-fix/SKILL.md +++ b/ios-fix/SKILL.md @@ -2,7 +2,7 @@ name: ios-fix preamble-tier: 2 version: 1.0.0 -description: Autonomous iOS bug fixer. (gstack) +description: "Autonomous iOS bug fixer. Use for: fix this ios bug, patch the iphone app. (gstack)" allowed-tools: - Bash - Read diff --git a/ios-qa/SKILL.md b/ios-qa/SKILL.md index 5f6289805ce..345e542ef39 100644 --- a/ios-qa/SKILL.md +++ b/ios-qa/SKILL.md @@ -2,7 +2,7 @@ name: ios-qa preamble-tier: 3 version: 1.0.0 -description: Live-device iOS QA for SwiftUI apps. (gstack) +description: "Live-device iOS QA for SwiftUI apps. Use for: ios qa, test the iphone app, test the ipad app. (gstack)" allowed-tools: - Bash - Read diff --git a/ios-sync/SKILL.md b/ios-sync/SKILL.md index 5e1fd6a2767..9fdc0db8dda 100644 --- a/ios-sync/SKILL.md +++ b/ios-sync/SKILL.md @@ -2,7 +2,7 @@ name: ios-sync preamble-tier: 2 version: 1.0.0 -description: Regenerate the iOS debug bridge against the latest upstream gstack templates. (gstack) +description: "Regenerate the iOS debug bridge against the latest upstream gstack templates. Use for: resync the ios debug bridge, regenerate ios accessors. (gstack)" allowed-tools: - Bash - Read diff --git a/land-and-deploy/SKILL.md b/land-and-deploy/SKILL.md index d1e5b2f29c8..8485425aabe 100644 --- a/land-and-deploy/SKILL.md +++ b/land-and-deploy/SKILL.md @@ -2,7 +2,7 @@ name: land-and-deploy preamble-tier: 4 version: 1.0.0 -description: Land and deploy workflow. (gstack) +description: "Land and deploy workflow. Use for: merge and deploy, land the pr, ship to production. (gstack)" allowed-tools: - Bash - Read diff --git a/landing-report/SKILL.md b/landing-report/SKILL.md index e302c7ff5f9..4f5518acd81 100644 --- a/landing-report/SKILL.md +++ b/landing-report/SKILL.md @@ -2,7 +2,7 @@ name: landing-report preamble-tier: 2 version: 0.1.0 -description: Read-only queue dashboard for workspace-aware ship. (gstack) +description: "Read-only queue dashboard for workspace-aware ship. Use for: landing report, version queue, ship queue. (gstack)" triggers: - landing report - version queue diff --git a/learn/SKILL.md b/learn/SKILL.md index 96953e0c38a..f864820565a 100644 --- a/learn/SKILL.md +++ b/learn/SKILL.md @@ -2,7 +2,7 @@ name: learn preamble-tier: 2 version: 1.1.0 -description: Manage project learnings. +description: "Manage project learnings. Use for: show learnings, what have we learned." triggers: - show learnings - what have we learned diff --git a/lib/skill-triggers.ts b/lib/skill-triggers.ts index f0052bc6cf1..b7d29d9edb9 100644 --- a/lib/skill-triggers.ts +++ b/lib/skill-triggers.ts @@ -6,8 +6,9 @@ * - Router lines (lib/harness-register.ts, 160 chars): the description's own * trigger sentence (its first sentence that starts "Use when", "Use to", * "Use for", ...), followed by the description's first sentence when both - * fit. A description with no trigger sentence (the catalog-trimmed Claude - * render) uses the triggers list below instead. + * fit. A description with no trigger sentence, or whose trigger sentence is + * the catalog-trimmed Claude render's short "Use for:" clause, uses the + * triggers list below instead. * - Hermes descriptions (scripts/gen-skill-docs.ts, hosts/hermes.ts): a lead * of at most 57 chars, the part Hermes's skills index shows: "Use for: " * and the skill's `triggers:` list in frontmatter order, as many whole @@ -63,7 +64,8 @@ export function withTriggerLead(description: string, triggers: string[], max: nu /** A router line of at most max chars: the trigger part first, then the description's first sentence when both fit. */ export function routerLine(description: string, triggers: string[], max = 160): string { const first = sentences(description)[0] ?? ''; - const trigger = triggerSentence(description) || triggerList(triggers, max); + const own = triggerSentence(description); + const trigger = (triggers.length && own.startsWith('Use for:') ? '' : own) || triggerList(triggers, max); if (!trigger) return cutWords(first, max); const both = trigger + ' ' + first; return first && first !== trigger && both.length <= max ? both : cutWords(trigger, max); diff --git a/make-pdf/SKILL.md b/make-pdf/SKILL.md index 0a5779c6899..75d94ee0c57 100644 --- a/make-pdf/SKILL.md +++ b/make-pdf/SKILL.md @@ -2,7 +2,7 @@ name: make-pdf preamble-tier: 1 version: 1.0.0 -description: Turn any markdown file into a publication-quality PDF. (gstack) +description: "Turn any markdown file into a publication-quality PDF. Use for: markdown to pdf, generate pdf, make pdf, export pdf. (gstack)" triggers: - markdown to pdf - generate pdf diff --git a/modernize/SKILL.md b/modernize/SKILL.md index 9d6547299c2..015ea7f0263 100644 --- a/modernize/SKILL.md +++ b/modernize/SKILL.md @@ -2,7 +2,7 @@ name: modernize preamble-tier: 2 version: 0.1.0 -description: "Bring an aging PR onto its current base and decide: MODERNIZE, REWORK or CLOSE. (gstack)" +description: "Bring an aging PR onto its current base and decide: MODERNIZE, REWORK or CLOSE. Use for: modernize this pr, rebase this old pr. (gstack)" triggers: - modernize this pr - rebase this old pr diff --git a/office-hours/SKILL.md b/office-hours/SKILL.md index 81fabee7358..aaeb8c89d47 100644 --- a/office-hours/SKILL.md +++ b/office-hours/SKILL.md @@ -2,7 +2,7 @@ name: office-hours preamble-tier: 3 version: 2.0.0 -description: YC Office Hours — two modes. (gstack) +description: "YC Office Hours — two modes. Use for: brainstorm this, is this worth building. (gstack)" allowed-tools: - Bash - Read diff --git a/open-gstack-browser/SKILL.md b/open-gstack-browser/SKILL.md index 26a60673b85..eb96dcb864b 100644 --- a/open-gstack-browser/SKILL.md +++ b/open-gstack-browser/SKILL.md @@ -2,7 +2,7 @@ name: open-gstack-browser preamble-tier: 1 version: 0.2.0 -description: Launch GStack Browser — AI-controlled Chromium with the sidebar extension baked in. +description: "Launch GStack Browser — AI-controlled Chromium with the sidebar extension baked in. Use for: open gstack browser, launch chromium." triggers: - open gstack browser - launch chromium diff --git a/pair-agent/SKILL.md b/pair-agent/SKILL.md index e201678b5c9..0cd6cba3fad 100644 --- a/pair-agent/SKILL.md +++ b/pair-agent/SKILL.md @@ -2,7 +2,7 @@ name: pair-agent preamble-tier: 2 version: 0.1.0 -description: Pair a remote AI agent with your browser. (gstack) +description: "Pair a remote AI agent with your browser. Use for: pair with agent, connect remote agent. (gstack)" triggers: - pair with agent - connect remote agent diff --git a/plan-ceo-review/SKILL.md b/plan-ceo-review/SKILL.md index 6e544cc5cbb..364c3c6935f 100644 --- a/plan-ceo-review/SKILL.md +++ b/plan-ceo-review/SKILL.md @@ -2,7 +2,7 @@ name: plan-ceo-review preamble-tier: 3 version: 1.0.0 -description: CEO/founder-mode plan review. (gstack) +description: "CEO/founder-mode plan review. Use for: think bigger, expand scope, strategy review. (gstack)" allowed-tools: - Read - Grep diff --git a/plan-design-review/SKILL.md b/plan-design-review/SKILL.md index 3069dc78156..488093936b6 100644 --- a/plan-design-review/SKILL.md +++ b/plan-design-review/SKILL.md @@ -2,7 +2,7 @@ name: plan-design-review preamble-tier: 3 version: 2.0.0 -description: Designer's eye plan review — interactive, like CEO and Eng review. (gstack) +description: "Designer's eye plan review — interactive, like CEO and Eng review. Use for: design plan review, review ux plan. (gstack)" allowed-tools: - Read - Edit diff --git a/plan-devex-review/SKILL.md b/plan-devex-review/SKILL.md index 3c7b708215f..b10d454774f 100644 --- a/plan-devex-review/SKILL.md +++ b/plan-devex-review/SKILL.md @@ -2,7 +2,7 @@ name: plan-devex-review preamble-tier: 3 version: 2.0.0 -description: Interactive developer experience plan review. (gstack) +description: "Interactive developer experience plan review. Use for: developer experience review, dx plan review. (gstack)" allowed-tools: - Read - Edit diff --git a/plan-eng-review/SKILL.md b/plan-eng-review/SKILL.md index 6bf41a9d7df..b1f1a2a3aed 100644 --- a/plan-eng-review/SKILL.md +++ b/plan-eng-review/SKILL.md @@ -2,7 +2,7 @@ name: plan-eng-review preamble-tier: 3 version: 1.0.0 -description: Eng manager-mode plan review. (gstack) +description: "Use when you plan a feature before building it, or review a plan: locks in architecture, data flow, diagrams, edge cases, test coverage and performance. Use for: plan a feature, review architecture, eng plan review. (gstack)" allowed-tools: - Read - Write @@ -12,6 +12,7 @@ allowed-tools: - Bash - WebSearch triggers: + - plan a feature - review architecture - eng plan review - check the implementation plan diff --git a/plan-eng-review/SKILL.md.tmpl b/plan-eng-review/SKILL.md.tmpl index 2ac3b966d35..d258ce4d3d5 100644 --- a/plan-eng-review/SKILL.md.tmpl +++ b/plan-eng-review/SKILL.md.tmpl @@ -4,10 +4,10 @@ preamble-tier: 3 interactive: true version: 1.0.0 description: | - Eng manager-mode plan review. Lock in the execution plan — architecture, - data flow, diagrams, edge cases, test coverage, performance. Walks through - issues interactively with opinionated recommendations. Use when asked to - "review the architecture", "engineering review", or "lock in the plan". (gstack) + Use when you plan a feature before building it, or review a plan: locks in + architecture, data flow, diagrams, edge cases, test coverage and performance. + Use when asked to "review the architecture", "engineering review", or "lock + in the plan". (gstack) voice-triggers: - "tech review" - "technical review" @@ -22,6 +22,7 @@ allowed-tools: - Bash - WebSearch triggers: + - plan a feature - review architecture - eng plan review - check the implementation plan diff --git a/plan-tune/SKILL.md b/plan-tune/SKILL.md index e602bd250e7..b97f1a4de88 100644 --- a/plan-tune/SKILL.md +++ b/plan-tune/SKILL.md @@ -2,7 +2,7 @@ name: plan-tune preamble-tier: 2 version: 1.0.0 -description: "Self-tuning question sensitivity + developer psychographic for gstack (v1: observational). (gstack)" +description: "Self-tuning question sensitivity + developer psychographic for gstack (v1: observational). Use for: tune questions, stop asking me that. (gstack)" triggers: - tune questions - stop asking me that diff --git a/qa-only/SKILL.md b/qa-only/SKILL.md index 7e3382a6a08..d75edf96707 100644 --- a/qa-only/SKILL.md +++ b/qa-only/SKILL.md @@ -2,7 +2,7 @@ name: qa-only preamble-tier: 4 version: 1.0.0 -description: Report browser/API/CLI/job/worker/webhook bugs. (gstack) +description: "Report browser/API/CLI/job/worker/webhook bugs. Use for: qa report only, just report bugs, test but dont fix. (gstack)" allowed-tools: - Bash - Read diff --git a/qa/SKILL.md b/qa/SKILL.md index 2008902979c..102e1d5717f 100644 --- a/qa/SKILL.md +++ b/qa/SKILL.md @@ -2,7 +2,7 @@ name: qa preamble-tier: 4 version: 2.0.0 -description: Use when you test the site, API or CLI and fix bugs. (gstack) +description: "Use when you test the site, API or CLI and fix bugs. Use for: qa test this, find bugs on site, test the site. (gstack)" allowed-tools: - Bash - Read diff --git a/retro/SKILL.md b/retro/SKILL.md index b0c852a3684..46308f6d586 100644 --- a/retro/SKILL.md +++ b/retro/SKILL.md @@ -2,7 +2,7 @@ name: retro preamble-tier: 2 version: 2.0.0 -description: Weekly engineering retrospective. (gstack) +description: "Weekly engineering retrospective. Use for: weekly retro, what did we ship. (gstack)" allowed-tools: - Bash - Read diff --git a/review/SKILL.md b/review/SKILL.md index cbe1b1f33ea..493cfbe2c3d 100644 --- a/review/SKILL.md +++ b/review/SKILL.md @@ -2,7 +2,7 @@ name: review preamble-tier: 4 version: 1.0.0 -description: Use when you review this PR's diff. (gstack) +description: "Use when you review a diff before it lands: local changes, a branch or a PR. Use for: review my changes, look over my diff, review this pr. (gstack)" allowed-tools: - Bash - Read @@ -14,11 +14,11 @@ allowed-tools: - AskUserQuestion - WebSearch triggers: - - review this pr + - review my changes - look over my diff + - review this pr - code review - check my diff - - review my changes - pre-landing review contract: version: 1 diff --git a/review/SKILL.md.tmpl b/review/SKILL.md.tmpl index 7ae3e4eef4d..958d4971433 100644 --- a/review/SKILL.md.tmpl +++ b/review/SKILL.md.tmpl @@ -3,10 +3,10 @@ name: review preamble-tier: 4 version: 1.0.0 description: | - Use when you review this PR's diff. - Checks it for SQL safety, LLM trust boundaries, conditional side effects and - bugs that pass CI and break production. Fits "look over my diff", "review my - changes", "code review", "check my diff" or "pre-landing review". + Use when you review a diff before it lands: local changes, a branch or a PR. + Finds bugs that pass CI and break production. Fits "review this PR", "look + over my diff", "review my changes", "code review", "check my diff" or + "pre-landing review". Proactively suggest before a merge. (gstack) codex_default_prompt: "Use $gstack-review to review this diff against its base before it lands: find the bugs that pass CI and break in production, fix the clear ones, and list what remains." allowed-tools: @@ -20,11 +20,11 @@ allowed-tools: - AskUserQuestion - WebSearch triggers: - - review this pr + - review my changes - look over my diff + - review this pr - code review - check my diff - - review my changes - pre-landing review contract: version: 1 diff --git a/runaway-stopper/SKILL.md b/runaway-stopper/SKILL.md index 1852de82d51..95ebd5a1e52 100644 --- a/runaway-stopper/SKILL.md +++ b/runaway-stopper/SKILL.md @@ -2,7 +2,7 @@ name: runaway-stopper preamble-tier: 1 version: 0.1.0 -description: Find runaway Capy threads and subagents, stop or rotate them safely, and prevent repeats. (gstack) +description: "Find runaway Capy threads and subagents, stop or rotate them safely, and prevent repeats. Use for: find runaway threads, stop runaway jobs. (gstack)" triggers: - find runaway threads - stop runaway jobs diff --git a/scrape/SKILL.md b/scrape/SKILL.md index aa1be5480f3..e0da85af876 100644 --- a/scrape/SKILL.md +++ b/scrape/SKILL.md @@ -2,7 +2,7 @@ name: scrape preamble-tier: 1 version: 2.0.0 -description: Pull data from a web page through the Aside browser — your real, already signed-in sessions. (gstack) +description: "Pull data from a web page through the Aside browser — your real, already signed-in sessions. Use for: scrape this page, get data from, pull from. (gstack)" allowed-tools: - Bash - Read diff --git a/scripts/gen-skill-docs.ts b/scripts/gen-skill-docs.ts index 937ad99d1e9..f9b368c8922 100644 --- a/scripts/gen-skill-docs.ts +++ b/scripts/gen-skill-docs.ts @@ -29,7 +29,7 @@ import type { ModuleFilter } from './resolvers/types'; import { insertRuntimePreludes } from './resolvers/runtime-root'; import { generateSharedPreambleFile, hoistsPreamble, SHARED_PREAMBLE_FILE } from './resolvers/preamble-hoist'; import { extractVoiceTriggers } from './resolvers/voice-triggers'; -import { frontmatterList, withTriggerLead } from '../lib/skill-triggers'; +import { cutWords, frontmatterList, triggerList, triggerSentence, withTriggerLead } from '../lib/skill-triggers'; import { ALL_HOST_NAMES, resolveHostArg, getHostConfig } from '../hosts/index'; import type { HostConfig } from './host-config'; @@ -279,11 +279,14 @@ export { extractVoiceTriggers, processVoiceTriggers }; // asked to..." voice triggers, "Proactively..." routing guidance, and a // "(gstack)" tag. This pile is the always-loaded catalog surface — every // session pays for the full text. The catalog trim splits the description -// into a one-line catalog entry (lead sentence + "(gstack)") that stays in -// the frontmatter and drops the routing/voice prose. The body is not a home -// for it: Claude Code loads a skill body only after the skill is invoked, so -// routing text there can no longer route anything. Voice triggers live on in -// the root router's routing block ({{VOICE_TRIGGER_ROUTING}}). +// into a one-line catalog entry (lead sentence + a short when-to-use clause + +// "(gstack)") that stays in the frontmatter and drops the rest of the +// routing/voice prose. The clause is built by lib/skill-triggers.ts: the +// skill's `triggers:` list ("Use for: a, b."), else its "Use when" sentence. Without it the listing says what a skill is but not when to load +// it, and Opus 5.5 skipped /review on "review my changes" (GSTA-558). The body +// is not a home for routing text: Claude Code loads a skill body only after +// the skill is invoked. Voice triggers live on in the root router's routing +// block ({{VOICE_TRIGGER_ROUTING}}). // // Opt-out: `--catalog-mode=full` keeps v1.44 behavior (no trim, full // description in frontmatter). Use when debugging routing regressions or @@ -362,11 +365,18 @@ export function splitCatalogDescription(description: string): CatalogParts { return { lead, routingProse, voiceLine, hasGstackTag }; } -/** Build the catalog-trimmed `description:` block. */ -export function buildTrimmedDescription(parts: CatalogParts): string { +/** The when-to-use clause gets at most this many chars, and the whole trimmed description at most CATALOG_DESCRIPTION_MAX (test/catalog-budget.test.ts caps name + description at 260 bytes). */ +const CATALOG_WHEN_MAX = 64; +const CATALOG_DESCRIPTION_MAX = 230; + +/** Build the catalog-trimmed `description:` block: the lead, then the when-to-use clause when it fits and adds something. */ +export function buildTrimmedDescription(parts: CatalogParts, triggers: string[] = []): string { const lead = parts.lead.trim(); const suffix = parts.hasGstackTag ? ' (gstack)' : ''; - return `${lead}${suffix}`; + const room = Math.min(CATALOG_WHEN_MAX, CATALOG_DESCRIPTION_MAX - lead.length - suffix.length - 1); + const sentence = triggerSentence(`${lead} ${parts.routingProse}`); + const when = room < 24 ? '' : triggerList(triggers, room) || (sentence && sentence !== lead ? cutWords(sentence, room) : ''); + return when ? `${lead} ${when}${suffix}` : `${lead}${suffix}`; } /** @@ -424,8 +434,8 @@ export function applyCatalogTrim(content: string, skillName: string): { content: const parts = splitCatalogDescription(descText); // If lead + (gstack) is already most of the text, no trim needed. - const trimmedLen = buildTrimmedDescription(parts).length; - if (trimmedLen >= descText.length - 20) return null; + if (buildTrimmedDescription({ ...parts, routingProse: '' }).length >= descText.length - 20) return null; + const newDesc = buildTrimmedDescription(parts, frontmatterList(content, 'triggers')); // Replace description in frontmatter — keep trailing newline so the next // YAML field doesn't collide on the same line as the description value. @@ -433,7 +443,6 @@ export function applyCatalogTrim(content: string, skillName: string): { content: // case: an interior ": " like "Ship workflow: detect..." which a strict YAML // parser reads as a nested mapping and rejects — #1778). toYamlInlineScalar // only quotes when needed, so descriptions without special chars stay plain. - const newDesc = buildTrimmedDescription(parts); // Function replacer (not a string) so a `$` in the description — e.g. a future // skill referencing `$B`/`$D` — can't be interpreted as a `$&`/`$1` replacement // pattern and silently corrupt the frontmatter. diff --git a/setup-browser-cookies/SKILL.md b/setup-browser-cookies/SKILL.md index ae681167347..821cb266467 100644 --- a/setup-browser-cookies/SKILL.md +++ b/setup-browser-cookies/SKILL.md @@ -2,7 +2,7 @@ name: setup-browser-cookies preamble-tier: 1 version: 1.0.0 -description: Import cookies from your real Chromium browser into the headless browse session. (gstack) +description: "Import cookies from your real Chromium browser into the headless browse session. Use for: import browser cookies, login to test site. (gstack)" triggers: - import browser cookies - login to test site diff --git a/setup-deploy/SKILL.md b/setup-deploy/SKILL.md index 9451df76df5..8ab73f4c6aa 100644 --- a/setup-deploy/SKILL.md +++ b/setup-deploy/SKILL.md @@ -2,7 +2,7 @@ name: setup-deploy preamble-tier: 2 version: 1.0.0 -description: Configure deployment settings for /land-and-deploy. +description: "Configure deployment settings for /land-and-deploy. Use for: configure deploy, setup deployment." triggers: - configure deploy - setup deployment diff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.md index e6b9db5f68e..f40480d6948 100644 --- a/setup-gbrain/SKILL.md +++ b/setup-gbrain/SKILL.md @@ -2,7 +2,7 @@ name: setup-gbrain preamble-tier: 2 version: 1.0.0 -description: "Set up gbrain for this coding agent: install the CLI, initialize a local PGLite or Supabase brain, register MCP, capture per-remote trust policy. (gstack)" +description: "Set up gbrain for this coding agent: install the CLI, initialize a local PGLite or Supabase brain, register MCP, capture per-remote trust policy. Use for: setup gbrain, install gbrain, connect gbrain. (gstack)" triggers: - setup gbrain - install gbrain diff --git a/ship/SKILL.md b/ship/SKILL.md index 20814e5ab15..f074c2fb91d 100644 --- a/ship/SKILL.md +++ b/ship/SKILL.md @@ -2,7 +2,7 @@ name: ship preamble-tier: 4 version: 1.0.0 -description: "Ship it: merge the base, run tests, review the diff, bump VERSION and CHANGELOG, push and create a PR. (gstack)" +description: "Ship it: merge the base, run tests, review the diff, bump VERSION and CHANGELOG, push and create a PR. Use for: ship it, create a pr, push to main. (gstack)" allowed-tools: - Bash - Read @@ -17,7 +17,6 @@ triggers: - ship it - create a pr - push to main - - deploy this --- <!-- AUTO-GENERATED from SKILL.md.tmpl — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> diff --git a/ship/SKILL.md.tmpl b/ship/SKILL.md.tmpl index 36cd8664499..a3fb3b996b4 100644 --- a/ship/SKILL.md.tmpl +++ b/ship/SKILL.md.tmpl @@ -24,7 +24,6 @@ triggers: - ship it - create a pr - push to main - - deploy this --- {{PREAMBLE}} diff --git a/skillify/SKILL.md b/skillify/SKILL.md index 2bc8e30092c..bfd4d5390ef 100644 --- a/skillify/SKILL.md +++ b/skillify/SKILL.md @@ -2,7 +2,7 @@ name: skillify preamble-tier: 2 version: 1.0.0 -description: Codify the most recent successful /scrape flow into a permanent browser-skill on disk. (gstack) +description: "Codify the most recent successful /scrape flow into a permanent browser-skill on disk. Use for: skillify, codify this scrape, save this scrape. (gstack)" allowed-tools: - Bash - Read diff --git a/spec/SKILL.md b/spec/SKILL.md index 55fb27c30d0..b546227d64b 100644 --- a/spec/SKILL.md +++ b/spec/SKILL.md @@ -2,7 +2,7 @@ name: spec preamble-tier: 3 version: 0.1.0 -description: Turn vague intent into a precise, executable spec in five phases. (gstack) +description: "Turn vague intent into a precise, executable spec in five phases. Use for: spec this out, file an issue, write up a ticket. (gstack)" allowed-tools: - Bash - Read diff --git a/sync-gbrain/SKILL.md b/sync-gbrain/SKILL.md index 21e5c3c18a8..56942cd94d8 100644 --- a/sync-gbrain/SKILL.md +++ b/sync-gbrain/SKILL.md @@ -2,7 +2,7 @@ name: sync-gbrain preamble-tier: 2 version: 1.0.0 -description: Keep gbrain current with this repo's code and refresh agent search guidance in CLAUDE.md. (gstack) +description: "Keep gbrain current with this repo's code and refresh agent search guidance in CLAUDE.md. Use for: sync gbrain, refresh gbrain, reindex repo. (gstack)" triggers: - sync gbrain - refresh gbrain diff --git a/test-audit/SKILL.md b/test-audit/SKILL.md index 8cd08c4608b..87f9ed98d16 100644 --- a/test-audit/SKILL.md +++ b/test-audit/SKILL.md @@ -2,7 +2,7 @@ name: test-audit preamble-tier: 2 version: 1.0.0 -description: Find low-value or duplicate tests and the test-only code they keep alive. (gstack) +description: "Find low-value or duplicate tests and the test-only code they keep alive. Use for: audit the test suite, find low-value tests. (gstack)" triggers: - audit the test suite - find low-value tests diff --git a/test/catalog-budget.test.ts b/test/catalog-budget.test.ts index 512639ecbe2..ce2ffbfd549 100644 --- a/test/catalog-budget.test.ts +++ b/test/catalog-budget.test.ts @@ -103,8 +103,20 @@ import { skillCensus } from './helpers/skill-census'; * New-skill ratchet: previous ceiling 1,423 + ceil(115 / 4) = 1,452 * token-equivalents (5,808 bytes), leaving 11 bytes. Existing descriptions * are unchanged. + * ref GST-2774 when-to-use clause on base 0326b14 (2026-11-14) + * result every trimmed Claude description keeps a when-to-use clause of at + * most 64 chars (its triggers list, else its "Use when" sentence; + * scripts/gen-skill-docs.ts buildTrimmedDescription), and /review, + * /plan-eng-review and the root router reworded their leads; + * measured 9,173 bytes = 2,294 token-equivalents, then 9,160 + * bytes = 2,290 after /ship's list dropped "deploy this" (it + * belongs to /land-and-deploy). Deliberate + * growth, not a new skill: in GSTA-558's trials Opus 5.5 skipped + * /review on "review my changes" (0 of 3, 3 of 3 with the full + * text) and loaded no planning skill on "plan this feature" (0 of 9). + * New ceiling: 2,290 token-equivalents (9,160 bytes), leaving 0 bytes. */ -const CATALOG_BUDGET_TOKEN_EQUIVALENTS = 1_452; +const CATALOG_BUDGET_TOKEN_EQUIVALENTS = 2_290; // Largest today: design-consultation at 229 bytes. A description that needs // more than 260 bytes is a body paragraph, not a catalog entry. diff --git a/test/catalog-trim.test.ts b/test/catalog-trim.test.ts index db130d8169c..49b8d64c2b7 100644 --- a/test/catalog-trim.test.ts +++ b/test/catalog-trim.test.ts @@ -225,6 +225,37 @@ describe('buildTrimmedDescription', () => { }); expect(out).toBe('Lead with whitespace. (gstack)'); }); + + // GSTA-558: a lead alone says what a skill is, not when to load it, so the Claude catalog keeps a when-to-use clause. + const parts = (lead: string, routingProse = '') => ({ lead, routingProse, voiceLine: null, hasGstackTag: true }); + + test('adds the triggers list as the when-to-use clause', () => { + const out = buildTrimmedDescription(parts('Pre-landing PR review.', 'Use when asked to review.'), ['review my changes', 'look over my diff']); + expect(out).toBe('Pre-landing PR review. Use for: review my changes, look over my diff. (gstack)'); + }); + + test('keeps only the triggers that fit the clause cap', () => { + const out = buildTrimmedDescription(parts('Lead.'), ['first trigger here', 'second trigger here', 'third trigger here', 'fourth trigger here']); + expect(out).toBe('Lead. Use for: first trigger here, second trigger here. (gstack)'); + }); + + test('without triggers, uses the "Use when" sentence from the routing prose', () => { + const out = buildTrimmedDescription(parts('Quick fix.', 'Applies a patch. Use when asked to fix it. Proactively suggest it.')); + expect(out).toBe('Quick fix. Use when asked to fix it. (gstack)'); + }); + + test('a lead that is already the "Use when" sentence is not repeated', () => { + expect(buildTrimmedDescription(parts('Use when you review a diff.', 'Checks it.'))).toBe('Use when you review a diff. (gstack)'); + }); + + test('without triggers or a "Use when" sentence, the lead stands alone', () => { + expect(buildTrimmedDescription(parts('A long lead sentence that says what the skill does.', 'More detail here.'))).toBe('A long lead sentence that says what the skill does. (gstack)'); + }); + + test('a lead that fills the catalog line gets no clause', () => { + const lead = 'x'.repeat(200) + '.'; + expect(buildTrimmedDescription(parts(lead), ['review my changes'])).toBe(lead + ' (gstack)'); + }); }); describe('applyCatalogTrim', () => { @@ -254,7 +285,10 @@ Original body content here. // The body gains no routing section: Claude Code reads a skill body only // after invocation, so routing prose there routes nothing. expect(content).not.toContain('## When to invoke this skill'); - expect(content).not.toContain('Use when asked to do an example task.'); + expect(content.slice(content.indexOf('\n---', 4))).not.toContain('Use when asked to do an example task.'); + // The catalog line keeps the when-to-use sentence (GSTA-558) and drops the rest of the routing prose. + expect(content).toMatch(/^description: "?Example skill:[^\n]*\. Use when asked to do an example task\. \(gstack\)"?\n/m); + expect(content).not.toContain('Proactively suggest'); // Original body still present expect(content).toContain('# Example body'); expect(content).toContain('Original body content here.'); diff --git a/test/fixtures/context-budget.json b/test/fixtures/context-budget.json index f8ca7a8146b..f952ac2fdc7 100644 --- a/test/fixtures/context-budget.json +++ b/test/fixtures/context-budget.json @@ -1,74 +1,74 @@ { "_comment": "Context-budget ratchet ceilings (~tokens). Regenerate: bun test/helpers/capture-context-budget.ts. Headroom: alwaysOnTotal x1.05, eagerPerInvocation x1.1. Graded by test/context-budget-ratchet.test.ts via lib/context-bill.ts checkBudget.", - "alwaysOnTotal": 8000, + "alwaysOnTotal": 8647, "eagerPerInvocation": { - "autoplan": 11289, - "benchmark": 8043, - "benchmark-models": 4086, - "browse": 8943, + "autoplan": 11306, + "benchmark": 8420, + "benchmark-models": 4454, + "browse": 9311, "browser-skills/hackernews-frontpage": 371, - "canary": 7738, - "captain": 7211, - "capy/skill/gstack": 5315, - "careful": 1239, - "codex": 9890, - "context-restore": 6287, - "context-save": 5101, - "cso": 4902, + "canary": 7750, + "captain": 7282, + "capy/skill/gstack": 5847, + "careful": 1255, + "codex": 9437, + "context-restore": 6305, + "context-save": 5118, + "cso": 4916, "design-consultation": 10513, - "design-html": 8896, - "design-motion": 4724, - "design-review": 22175, - "design-shotgun": 9318, - "deslop-shared-libs": 3411, - "devex-review": 15303, - "diagram": 4286, - "document-generate": 6013, - "document-release": 4454, - "eval-plan": 5700, - "freeze": 1115, - "gstack": 5350, + "design-html": 8996, + "design-motion": 4738, + "design-review": 22268, + "design-shotgun": 9333, + "deslop-shared-libs": 3420, + "devex-review": 15442, + "diagram": 4529, + "document-generate": 6027, + "document-release": 4469, + "eval-plan": 6271, + "freeze": 1163, + "gstack": 5793, "gstack-upgrade": 6297, - "guard": 1000, - "health": 5816, - "ios-clean": 2436, - "ios-design-review": 2604, - "ios-fix": 2307, - "ios-qa": 5905, - "ios-sync": 2465, - "land-and-deploy": 13585, - "landing-report": 3269, - "learn": 2124, - "make-pdf": 5204, - "modernize": 3772, - "office-hours": 11467, - "open-gstack-browser": 4872, + "guard": 1013, + "health": 5558, + "ios-clean": 2451, + "ios-design-review": 2621, + "ios-fix": 2312, + "ios-qa": 5920, + "ios-sync": 2482, + "land-and-deploy": 8433, + "landing-report": 3283, + "learn": 2198, + "make-pdf": 5493, + "modernize": 3891, + "office-hours": 11480, + "open-gstack-browser": 5118, "openclaw/skills/gstack-openclaw-ceo-review": 2764, "openclaw/skills/gstack-openclaw-office-hours": 4433, "openclaw/skills/gstack-openclaw-retro": 2542, - "pair-agent": 5293, - "plan-ceo-review": 15776, - "plan-design-review": 14687, - "plan-devex-review": 12215, - "plan-eng-review": 11369, - "plan-tune": 9215, - "qa": 7644, - "qa-only": 5726, - "retro": 13484, - "review": 15417, - "runaway-stopper": 4489, - "scrape": 7312, - "setup-browser-cookies": 3507, - "setup-deploy": 5738, - "setup-gbrain": 10009, - "ship": 15913, - "skillify": 5849, - "spec": 9136, - "sync-gbrain": 9749, - "test-audit": 4622, - "ubicloud": 3971, - "unfreeze": 409, - "verify": 2922, - "write-skill": 2264 + "pair-agent": 5375, + "plan-ceo-review": 15849, + "plan-design-review": 14698, + "plan-devex-review": 12229, + "plan-eng-review": 10875, + "plan-tune": 9304, + "qa": 7669, + "qa-only": 5743, + "retro": 13501, + "review": 15723, + "runaway-stopper": 4576, + "scrape": 7559, + "setup-browser-cookies": 3749, + "setup-deploy": 5751, + "setup-gbrain": 10106, + "ship": 16061, + "skillify": 5864, + "spec": 9152, + "sync-gbrain": 9789, + "test-audit": 4636, + "ubicloud": 4059, + "unfreeze": 423, + "verify": 3231, + "write-skill": 2386 } } diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md index 20814e5ab15..f074c2fb91d 100644 --- a/test/fixtures/golden/claude-ship-SKILL.md +++ b/test/fixtures/golden/claude-ship-SKILL.md @@ -2,7 +2,7 @@ name: ship preamble-tier: 4 version: 1.0.0 -description: "Ship it: merge the base, run tests, review the diff, bump VERSION and CHANGELOG, push and create a PR. (gstack)" +description: "Ship it: merge the base, run tests, review the diff, bump VERSION and CHANGELOG, push and create a PR. Use for: ship it, create a pr, push to main. (gstack)" allowed-tools: - Bash - Read @@ -17,7 +17,6 @@ triggers: - ship it - create a pr - push to main - - deploy this --- <!-- AUTO-GENERATED from SKILL.md.tmpl — do not edit directly --> <!-- Regenerate: bun run gen:skill-docs --> diff --git a/test/fixtures/skill-md-size-allowlist.json b/test/fixtures/skill-md-size-allowlist.json index 1933b8af51a..1935d573db3 100644 --- a/test/fixtures/skill-md-size-allowlist.json +++ b/test/fixtures/skill-md-size-allowlist.json @@ -5,53 +5,53 @@ "agy/gstack-autoplan": 109449, "agy/gstack-plan-design-review": 109103, "agy/gstack-plan-devex-review": 114944, - "agy/gstack-plan-eng-review": 143580, - "agy/gstack-review": 104735, + "agy/gstack-plan-eng-review": 143530, + "agy/gstack-review": 104723, "codex/gstack-autoplan": 108192, "codex/gstack-plan-design-review": 110460, "codex/gstack-plan-devex-review": 116452, - "codex/gstack-plan-eng-review": 144745, - "codex/gstack-review": 104119, + "codex/gstack-plan-eng-review": 144695, + "codex/gstack-review": 104107, "copilot/gstack-autoplan": 108892, "copilot/gstack-plan-design-review": 109369, "copilot/gstack-plan-devex-review": 114406, - "copilot/gstack-plan-eng-review": 143745, - "copilot/gstack-review": 104316, + "copilot/gstack-plan-eng-review": 143695, + "copilot/gstack-review": 104304, "cursor/gstack-autoplan": 108124, "cursor/gstack-plan-design-review": 107911, "cursor/gstack-plan-devex-review": 113676, - "cursor/gstack-plan-eng-review": 142335, - "cursor/gstack-review": 122788, + "cursor/gstack-plan-eng-review": 142285, + "cursor/gstack-review": 122776, "factory/gstack-autoplan": 110402, "factory/gstack-plan-design-review": 111009, "factory/gstack-plan-devex-review": 117039, - "factory/gstack-plan-eng-review": 145443, - "factory/gstack-review": 126561, + "factory/gstack-plan-eng-review": 145393, + "factory/gstack-review": 126549, "gbrain/gstack-autoplan": 108531, - "gbrain/gstack-plan-eng-review": 124963, + "gbrain/gstack-plan-eng-review": 124932, "gemini/gstack-autoplan": 108682, "gemini/gstack-plan-design-review": 109197, "gemini/gstack-plan-devex-review": 114234, - "gemini/gstack-plan-eng-review": 143578, - "gemini/gstack-review": 104138, + "gemini/gstack-plan-eng-review": 143528, + "gemini/gstack-review": 104126, "hermes/gstack-autoplan": 108536, - "hermes/gstack-plan-eng-review": 124999, + "hermes/gstack-plan-eng-review": 124885, "kiro/gstack-autoplan": 107898, "kiro/gstack-plan-design-review": 107757, "kiro/gstack-plan-devex-review": 113528, - "kiro/gstack-plan-eng-review": 142197, - "kiro/gstack-review": 122612, + "kiro/gstack-plan-eng-review": 142147, + "kiro/gstack-review": 122600, "openclaw/gstack-autoplan": 108354, - "openclaw/gstack-plan-eng-review": 123478, + "openclaw/gstack-plan-eng-review": 123428, "opencode/gstack-autoplan": 108873, "opencode/gstack-plan-design-review": 109225, "opencode/gstack-plan-devex-review": 114284, - "opencode/gstack-plan-eng-review": 143604, - "opencode/gstack-review": 123410, + "opencode/gstack-plan-eng-review": 143554, + "opencode/gstack-review": 123398, "slate/gstack-autoplan": 108011, "slate/gstack-plan-design-review": 107834, "slate/gstack-plan-devex-review": 113602, - "slate/gstack-plan-eng-review": 142266, - "slate/gstack-review": 122700 + "slate/gstack-plan-eng-review": 142216, + "slate/gstack-review": 122688 } } diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.ts index d45ec71e192..9e4940ac5fc 100644 --- a/test/helpers/carve-guards.ts +++ b/test/helpers/carve-guards.ts @@ -161,7 +161,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = { }, behavioral: 'external', externalTest: 'test/skill-e2e-ship-section-loading.test.ts', - maxSkeletonBytes: 61_438, // GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): Step 1's DIFF hint and the no-Eng-Review line name /plan-eng-review again, the wording GST-1698 removed; measured 61,438 (before: 61,417 on 81fb900). Before that: GSTA-152 token cap (2026-10-29, Garry's "Do it" on plan v3): the skeleton's Budget paragraph (the --token-cap, --resume and --continue flags, start/check/close, the budget-handoff pointer) and the section index's budget-handoff line; measured 61,420 (before: 60,958 on edf4c2e). Before that: GSTA-131 token efficiency (2026-10-27, Garry's D1): Step 1's delta carry (dry run, pregate at HEAD, then carry --pregate) and Step 11.5's fix-check and planned-skip binding, +60 bytes after tightening Step 1 and the Review policy paragraph; measured 60,960 (before: 60,900 on 10b77de4). Before that: GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): the hoisted skeleton (59,706) plus this PR's growth, keeping the hoist's 65-byte headroom; measured 60,848. Before: + 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), offset in part by tightening Steps 14, 16, 18 and 20 prose after the 2026-10-14 tightening left 2 bytes of headroom; measured 81,535. + harness lane E (2026-10-26, issue row 3: four Captains re-ran /ship on identical product code): Step 1's carry check (gstack-ship-receipt carry binds an earlier receipt to HEAD when the product patch-id is unchanged); measured 82,165. + the Review policy paragraph (the blocking floor, pass structure and cap, NO FINDINGS, the review_loop receipt counters, the review_scope knob), stated in the skeleton because gstack is the canonical holder of its review policy (docs/review-policy.md); measured 82,645. + maxSkeletonBytes: 61_467, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is), and /ship's list drops "deploy this", which belongs to /land-and-deploy; measured 61,467 (before: 61,438 on a141e94). Before that: GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): Step 1's DIFF hint and the no-Eng-Review line name /plan-eng-review again, the wording GST-1698 removed; measured 61,438 (before: 61,417 on 81fb900). Before that: GSTA-152 token cap (2026-10-29, Garry's "Do it" on plan v3): the skeleton's Budget paragraph (the --token-cap, --resume and --continue flags, start/check/close, the budget-handoff pointer) and the section index's budget-handoff line; measured 61,420 (before: 60,958 on edf4c2e). Before that: GSTA-131 token efficiency (2026-10-27, Garry's D1): Step 1's delta carry (dry run, pregate at HEAD, then carry --pregate) and Step 11.5's fix-check and planned-skip binding, +60 bytes after tightening Step 1 and the Review policy paragraph; measured 60,960 (before: 60,900 on 10b77de4). Before that: GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): the hoisted skeleton (59,706) plus this PR's growth, keeping the hoist's 65-byte headroom; measured 60,848. Before: + 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), offset in part by tightening Steps 14, 16, 18 and 20 prose after the 2026-10-14 tightening left 2 bytes of headroom; measured 81,535. + harness lane E (2026-10-26, issue row 3: four Captains re-ran /ship on identical product code): Step 1's carry check (gstack-ship-receipt carry binds an earlier receipt to HEAD when the product patch-id is unchanged); measured 82,165. + the Review policy paragraph (the blocking floor, pass structure and cap, NO FINDINGS, the review_loop receipt counters, the review_scope knob), stated in the skeleton because gstack is the canonical holder of its review policy (docs/review-policy.md); measured 82,645. 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. @@ -251,7 +251,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = { // tier-2+ skeleton (measured 89,184). Main's v1.64.0.0 adds ~340 B more // (telemetry --error-message/--failed-step preamble prose, PR #769). // Budget covers the sum of both waves. - maxSkeletonBytes: 56_209, // GSTA-134 skill diet (2026-10-28): lowered from 66_644 to the measured dieted skeleton, 56,209. Before: GSTA-96 hoist (2026-10-26): lowered from 85_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 581 bytes; measured 66,063. Before: Harness-aware outside voice: validated dispatch and provenance. + v1.91.19.0 wave: design --version probe (B4) and verdict-form outside voice (INV-1) on top of v1.91.17.0's round accounting (#3022); measured 80,443 (2026-10-03). + 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); skeleton measured 84,669 (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; skeleton measured 84,804 (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; skeleton measured 84,863 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; skeleton measured 84,748 (2026-10-07). Merged with the guard area: measured skeleton 84,945 (2026-10-07). + 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). + maxSkeletonBytes: 56_252, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 56,252 (before: 56,209 on a141e94). Before that: GSTA-134 skill diet (2026-10-28): lowered from 66_644 to the measured dieted skeleton, 56,209. Before: GSTA-96 hoist (2026-10-26): lowered from 85_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 581 bytes; measured 66,063. Before: Harness-aware outside voice: validated dispatch and provenance. + v1.91.19.0 wave: design --version probe (B4) and verdict-form outside voice (INV-1) on top of v1.91.17.0's round accounting (#3022); measured 80,443 (2026-10-03). + 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); skeleton measured 84,669 (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; skeleton measured 84,804 (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; skeleton measured 84,863 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; skeleton measured 84,748 (2026-10-07). Merged with the guard area: measured skeleton 84,945 (2026-10-07). + 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). minUnionBytes: 99_200, // token-reduction Phases 1-2 (v1.69.x branch); measured union 110,293 mustContain: ['design', 'visual'], maxSizeRatio: 1.12, // D1 1.104 + main's ~0.008 @@ -356,10 +356,10 @@ do not launch the downstream skill or open a browser.`, // the #538 opt-out + D1 evidence directive — ratio 1.104 measured. // #2499 project-scope MCP jq in the brain-sync block grew every tier-2+ // skeleton ~1.5KB (entry resolution emitted once per SKILL.md). - maxSkeletonBytes: 43_885, // GSTA-134 skill diet (2026-10-28): lowered from 80_533 to the measured skeleton after the second opinion and visual design moved to sections, 43,885. Before: GSTA-96 hoist (2026-10-26): lowered from 95_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 952 bytes; measured 79,581. Before: Office-hours + sketch outside voices include host guards and completion checks. + v1.91.19.0 wave: Q<N> open-question prose form (#2729, approved Q3), DESIGN_READY --version probe (B4), Aside ~/.local/bin fallback (E7), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting (#3022) merged in; measured 89,684 (2026-10-03). + 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); skeleton measured 92,590 (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; skeleton measured 92,869 (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; skeleton measured 92,930 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; skeleton measured 92,756 (2026-10-07). Merged with the guard area: measured skeleton 93,099 (2026-10-07). + fix wave PR D: the Phase 4.5 builder-profile read before the session log (#2801) and the pre-telemetry design-doc check (#1049); measured skeleton 94,877 (2026-10-07). + 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). + maxSkeletonBytes: 43_937, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 43,937 (before: 43,885 on a141e94). Before that: GSTA-134 skill diet (2026-10-28): lowered from 80_533 to the measured skeleton after the second opinion and visual design moved to sections, 43,885. Before: GSTA-96 hoist (2026-10-26): lowered from 95_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 952 bytes; measured 79,581. Before: Office-hours + sketch outside voices include host guards and completion checks. + v1.91.19.0 wave: Q<N> open-question prose form (#2729, approved Q3), DESIGN_READY --version probe (B4), Aside ~/.local/bin fallback (E7), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting (#3022) merged in; measured 89,684 (2026-10-03). + 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); skeleton measured 92,590 (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; skeleton measured 92,869 (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; skeleton measured 92,930 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; skeleton measured 92,756 (2026-10-07). Merged with the guard area: measured skeleton 93,099 (2026-10-07). + fix wave PR D: the Phase 4.5 builder-profile read before the session log (#2801) and the pre-telemetry design-doc check (#1049); measured skeleton 94,877 (2026-10-07). + 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). minUnionBytes: 115_800, // Phase 4 wave 4; measured union 118,175 mustContain: ['design doc', 'problem statement'], - maxSizeRatio: 1.1990, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1990 (before: 1.1968). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1968 (before: 1.1922). Before that: GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the handoff menu, its default and the design-doc line name /plan-eng-review again, +42 B union; measured 156,298 / 131,110 = 1.19211, rounded up (before: 156,256 = 1.19179 on 81fb900). Before that: GSTA-134 (2026-10-28, raised from 1.1796 by GStack Minder as merge-queue owner): +1,662 B union: second-opinion question moved into the main file while CODEX_SECOND_OPINION keeps its copy; per-run load 73,248→43,885 B; measured 156,286 / 131,110 = 1.19202, rounded up. Before: + 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 149,758 / 131,110 = 1.1422 (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 150,037 / 131,110 = 1.1444 (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 150,098 / 131,110 = 1.1448 (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 150,011 / 131,110 = 1.1442 (2026-10-07). Merged with the guard area: measured 150,354 / 131,110 = 1.1468 (2026-10-07). + fix wave PR D: builder-profile read before the session log with Phase 6 using the carried values (#2801), the inline design doc before approval (#879) and the pre-telemetry design-doc check (#1049); measured 153,206 / 131,110 = 1.1685 (2026-10-07). + empty LAST_ASSIGNMENT/LAST_PROJECT guards in the welcome_back and regular greetings (backfilled profiles); measured 153,469 / 131,110 = 1.1705 (2026-10-08). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file and its own copies of shared sections; measured 160,989 / 131,110 = 1.2279 (2026-10-25). Before: 1.18. - GSTA-96 dedupe: the Q<N> open-question form is office-hours' own appended subsection, so its copies of the shared Format and fallback subsections go; measured 154,653 / 131,110 = 1.1796 (2026-10-26), 154,624 = 1.1793 after the main merge. Before: 1.2279. + maxSizeRatio: 1.1993, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 157,236 / 131,110 = 1.19927, rounded up (before: 1.1990). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1990 (before: 1.1968). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1968 (before: 1.1922). Before that: GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the handoff menu, its default and the design-doc line name /plan-eng-review again, +42 B union; measured 156,298 / 131,110 = 1.19211, rounded up (before: 156,256 = 1.19179 on 81fb900). Before that: GSTA-134 (2026-10-28, raised from 1.1796 by GStack Minder as merge-queue owner): +1,662 B union: second-opinion question moved into the main file while CODEX_SECOND_OPINION keeps its copy; per-run load 73,248→43,885 B; measured 156,286 / 131,110 = 1.19202, rounded up. Before: + 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 149,758 / 131,110 = 1.1422 (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 150,037 / 131,110 = 1.1444 (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 150,098 / 131,110 = 1.1448 (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 150,011 / 131,110 = 1.1442 (2026-10-07). Merged with the guard area: measured 150,354 / 131,110 = 1.1468 (2026-10-07). + fix wave PR D: builder-profile read before the session log with Phase 6 using the carried values (#2801), the inline design doc before approval (#879) and the pre-telemetry design-doc check (#1049); measured 153,206 / 131,110 = 1.1685 (2026-10-07). + empty LAST_ASSIGNMENT/LAST_PROJECT guards in the welcome_back and regular greetings (backfilled profiles); measured 153,469 / 131,110 = 1.1705 (2026-10-08). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file and its own copies of shared sections; measured 160,989 / 131,110 = 1.2279 (2026-10-25). Before: 1.18. - GSTA-96 dedupe: the Q<N> open-question form is office-hours' own appended subsection, so its copies of the shared Format and fallback subsections go; measured 154,653 / 131,110 = 1.1796 (2026-10-26), 154,624 = 1.1793 after the main merge. Before: 1.2279. }, 'document-release': { skill: 'document-release', @@ -490,10 +490,10 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, // operational multi-STOP skill, like ship }, behavioral: 'plan', - maxSkeletonBytes: 60_070, // GST-1088 lane B follow-up (raised from 60,014 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path (~/.claude/skills/gstack/bin/gstack-skill-contract) instead of a bare gstack-skill-contract that a standard install doesn't put on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 60,070. Before: GST-1088 lane B (#3909, raised from 59,774 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): CONTRACT_CHECKER_SHIPPED=true now that bin/gstack-skill-contract ships (#3912) renders the gstack-skill-contract check/waive sentence under the Done means list (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 59,073; measured 60,014. Before: GST-1088 lane B (raised from 59,073 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list rendered from it at the top of the body, plus widened triggers; F1 is a gate-rev-2 recommendation on the plan Garry approved with "do it" on gate rev 1 (2026-11-03), contingent on his gate-rev-2 answer, and lane C's diet is expected to bring /review back under 59,073; measured 59,774. Before: GSTA-96 hoist (2026-10-26): lowered from 80_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 319 bytes; measured 58,754. Before: Shared-code identity/skip/action rules + critical-severity validation; measured 74,493 (2026-09-17). + v1.91.12.0 merge of #2999 (review clarity repairs: await reads, research alongside dispatch, /review deadline and setup authority, findings sources) with #3002 (guarded state-root lines, plan-check checkpoints); each fit alone; measured 74,881 (2026-10-01). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 74,884 (2026-10-08). + gate integrity (HONEST_WORK_GATE_INTEGRITY W2): Step 3.5 Diff scans with the shared GATE_SCAN_BLOCK, the Step 4 carry, the four-option `review-gate-disposition` question in 5c, gate record fields in 5.8 and the Gate edits report line; measured 80,054 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): Step 4's enum-only paragraph becomes the sideways sweep with the forced-CRITICAL list, plus the flake-fix number sentence in the Gate Integrity paragraph; measured skeleton 80,812 (2026-10-10). + maxSkeletonBytes: 60_176, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 60,176 (before: 60,070 on a141e94). Before that: GST-1088 lane B follow-up (raised from 60,014 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path (~/.claude/skills/gstack/bin/gstack-skill-contract) instead of a bare gstack-skill-contract that a standard install doesn't put on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 60,070. Before: GST-1088 lane B (#3909, raised from 59,774 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): CONTRACT_CHECKER_SHIPPED=true now that bin/gstack-skill-contract ships (#3912) renders the gstack-skill-contract check/waive sentence under the Done means list (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 59,073; measured 60,014. Before: GST-1088 lane B (raised from 59,073 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list rendered from it at the top of the body, plus widened triggers; F1 is a gate-rev-2 recommendation on the plan Garry approved with "do it" on gate rev 1 (2026-11-03), contingent on his gate-rev-2 answer, and lane C's diet is expected to bring /review back under 59,073; measured 59,774. Before: GSTA-96 hoist (2026-10-26): lowered from 80_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 319 bytes; measured 58,754. Before: Shared-code identity/skip/action rules + critical-severity validation; measured 74,493 (2026-09-17). + v1.91.12.0 merge of #2999 (review clarity repairs: await reads, research alongside dispatch, /review deadline and setup authority, findings sources) with #3002 (guarded state-root lines, plan-check checkpoints); each fit alone; measured 74,881 (2026-10-01). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 74,884 (2026-10-08). + gate integrity (HONEST_WORK_GATE_INTEGRITY W2): Step 3.5 Diff scans with the shared GATE_SCAN_BLOCK, the Step 4 carry, the four-option `review-gate-disposition` question in 5c, gate record fields in 5.8 and the Gate edits report line; measured 80,054 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): Step 4's enum-only paragraph becomes the sideways sweep with the forced-CRITICAL list, plus the flake-fix number sentence in the Gate Integrity paragraph; measured skeleton 80,812 (2026-10-10). minUnionBytes: 89_000, // Phase 4 wave 1; measured union 93,357 mustContain: ['confidence', 'P1', 'P2', 'Review Army', 'adversarial'], - maxSizeRatio: 1.3369, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.3369 (before: 1.3343). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3343 (before: 1.3288). Before that: + GST-1088 lane B follow-up (raised from 1.3283 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path instead of a bare gstack-skill-contract that isn't on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 144,203 / 108,523 = 1.328778, rounded up. Before: + GST-1088 lane B (#3909, raised from 1.3261 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): the gstack-skill-contract check/waive sentence that CONTRACT_CHECKER_SHIPPED=true renders (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 1.3180; measured 144,147 / 108,523 = 1.32826, rounded up. Before: + GST-1088 lane B (raised from 1.3180 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list, contingent on Garry's gate-rev-2 answer; lane C's diet is expected to bring /review back under 1.3180; measured 143,907 / 108,523 = 1.3261. Before: + GSTA-167 variant G part 1 (plan approved by Garry 2026-10-30, autoplan-20261030161754 "Do it", which names about +0.3k prompt tokens per voice): the native adversarial and outside-voice prompts carry the blocking floor and the Severity and Blocks lines, +537 bytes; measured 1.3180 (2026-10-30). Before: 1.3136. GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): both owner-approved raises together, measured 142,550 / 108,523 = 1.3135. Before: Shared-code feature + critical-severity validation: 128,042 union bytes / 108,523 baseline = 1.1799; preserves content floors. + v1.91.12.0 merge of #2999 (above, plus plan-completion fallback intent and specialist checklist-by-path) with #3002; measured 1.1843 (2026-10-01). + v1.91.19.0 wave: verdict-form Codex callers with sandbox preflight (INV-1/B1), P0/P1 structured gate (B1b), bound-plan discovery and data-not-instructions guard (F1/D3), visible LEARNINGS failures (B5); measured 129,941 / 108,523 = 1.1974 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 130,025 / 108,523 = 1.1981 (2026-10-04). + Oct 6 fix wave: quota_exhausted preflight branch (#3051); measured 130,359 / 108,523 = 1.2012 (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 131,314 / 108,523 = 1.2100 (2026-10-06). Combined Oct 6 wave head (A and B): measured 131,966 / 108,523 = 1.2160 (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 132,199 / 108,523 = 1.2182 (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 132,258 / 108,523 = 1.2187 (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 132,233 / 108,523 = 1.2185 (2026-10-07). Merged with the guard area: measured 132,522 / 108,523 = 1.2211 (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 133,902 / 108,523 = 1.2339 (2026-10-08). + gate integrity W2 (above); measured 1.282 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): sideways sweep and flake-fix number in Step 4; `Diff read` and `Undeclared behavior changes` in the review-mode Scope Check (plan-completion section); measured 140,497 / 108,523 = 1.2946 (2026-10-10). + harness lane E (2026-10-26): the lead-judgment stage in the finding merge and the `cause` anchor in the specialist prompts, shared with /ship through scripts/resolvers/review-army.ts; measured 141,949 / 108,523 = 1.3080. + maxSizeRatio: 1.3378, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 145,176 / 108,523 = 1.33774, rounded up (before: 1.3369). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.3369 (before: 1.3343). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3343 (before: 1.3288). Before that: + GST-1088 lane B follow-up (raised from 1.3283 to measured, no headroom): the Done-means check/waive commands run through the host-resolved bin path instead of a bare gstack-skill-contract that isn't on PATH (fix-check finding on #3909 at 58aeee7), +56 bytes; measured 144,203 / 108,523 = 1.328778, rounded up. Before: + GST-1088 lane B (#3909, raised from 1.3261 to measured, no headroom; owner ruling via GStack Minder 2026-11-03): the gstack-skill-contract check/waive sentence that CONTRACT_CHECKER_SHIPPED=true renders (renders/GSTA-256/plan-v3.md line 74, r2-d6 "Done-means list"), +240 bytes; lane C's diet is expected to bring /review back under 1.3180; measured 144,147 / 108,523 = 1.32826, rounded up. Before: + GST-1088 lane B (raised from 1.3180 to measured, no headroom): the contract: frontmatter block and the F1 "Done means" list, contingent on Garry's gate-rev-2 answer; lane C's diet is expected to bring /review back under 1.3180; measured 143,907 / 108,523 = 1.3261. Before: + GSTA-167 variant G part 1 (plan approved by Garry 2026-10-30, autoplan-20261030161754 "Do it", which names about +0.3k prompt tokens per voice): the native adversarial and outside-voice prompts carry the blocking floor and the Severity and Blocks lines, +537 bytes; measured 1.3180 (2026-10-30). Before: 1.3136. GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): both owner-approved raises together, measured 142,550 / 108,523 = 1.3135. Before: Shared-code feature + critical-severity validation: 128,042 union bytes / 108,523 baseline = 1.1799; preserves content floors. + v1.91.12.0 merge of #2999 (above, plus plan-completion fallback intent and specialist checklist-by-path) with #3002; measured 1.1843 (2026-10-01). + v1.91.19.0 wave: verdict-form Codex callers with sandbox preflight (INV-1/B1), P0/P1 structured gate (B1b), bound-plan discovery and data-not-instructions guard (F1/D3), visible LEARNINGS failures (B5); measured 129,941 / 108,523 = 1.1974 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 130,025 / 108,523 = 1.1981 (2026-10-04). + Oct 6 fix wave: quota_exhausted preflight branch (#3051); measured 130,359 / 108,523 = 1.2012 (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 131,314 / 108,523 = 1.2100 (2026-10-06). Combined Oct 6 wave head (A and B): measured 131,966 / 108,523 = 1.2160 (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 132,199 / 108,523 = 1.2182 (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 132,258 / 108,523 = 1.2187 (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 132,233 / 108,523 = 1.2185 (2026-10-07). Merged with the guard area: measured 132,522 / 108,523 = 1.2211 (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 133,902 / 108,523 = 1.2339 (2026-10-08). + gate integrity W2 (above); measured 1.282 (2026-10-10). + Oct 10 multi-agent wave PR D2 (sideways review): sideways sweep and flake-fix number in Step 4; `Diff read` and `Undeclared behavior changes` in the review-mode Scope Check (plan-completion section); measured 140,497 / 108,523 = 1.2946 (2026-10-10). + harness lane E (2026-10-26): the lead-judgment stage in the finding merge and the `cause` anchor in the specialist prompts, shared with /ship through scripts/resolvers/review-army.ts; measured 141,949 / 108,523 = 1.3080. }, codex: { skill: 'codex', @@ -544,8 +544,8 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, // operational skill }, behavioral: 'prompt', - maxSkeletonBytes: 32_216, // GSTA-161 skill diet (2026-10-30): lowered from 52_682 to the measured skeleton, 32,216; Step 7's canary script, the Aside contract, the browser fallback and Third-Party Web Actions moved to sections/canary.md. Before: GSTA-96 hoist (2026-10-26): lowered from 74_500 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 690 bytes; measured 51,992. Before: + Aside browser contract for Step 7 canary ({{ASIDE_SETUP}}); measured 73_523 - maxSizeRatio: 1.1344, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1344 (before: 1.1318). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1318 (before: 1.1260). Before that: + #3318 Step 3.4 reads the ship policy and prints one VERSION_CHECK verdict (owner-approved raise, Garry 2026-10-24: "do it"); measured 1.1201 (2026-10-24). Before: 1.1120. + v1.81 Aside contract + gstack-browser fallback block; measured 1.077. + both untrusted-content marker formats in the browser fallback (W7f) + the readiness gate's project test command and live eval-store paths (s06 H6/H7); measured 1.1076 (2026-10-02). Re-measured 1.0943 (2026-10-03); cap = measured + 0.005 headroom. + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 115,226 / 104,578 = 1.1018 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,753 / 104,578 = 1.1260 (2026-10-25). Before: 1.125. + maxSkeletonBytes: 32_273, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 32,273 (before: 32,216 on a141e94). Before that: GSTA-161 skill diet (2026-10-30): lowered from 52_682 to the measured skeleton, 32,216; Step 7's canary script, the Aside contract, the browser fallback and Third-Party Web Actions moved to sections/canary.md. Before: GSTA-96 hoist (2026-10-26): lowered from 74_500 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 690 bytes; measured 51,992. Before: + Aside browser contract for Step 7 canary ({{ASIDE_SETUP}}); measured 73_523 + maxSizeRatio: 1.1350, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 118,689 / 104,578 = 1.13493, rounded up (before: 1.1344). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1344 (before: 1.1318). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1318 (before: 1.1260). Before that: + #3318 Step 3.4 reads the ship policy and prints one VERSION_CHECK verdict (owner-approved raise, Garry 2026-10-24: "do it"); measured 1.1201 (2026-10-24). Before: 1.1120. + v1.81 Aside contract + gstack-browser fallback block; measured 1.077. + both untrusted-content marker formats in the browser fallback (W7f) + the readiness gate's project test command and live eval-store paths (s06 H6/H7); measured 1.1076 (2026-10-02). Re-measured 1.0943 (2026-10-03); cap = measured + 0.005 headroom. + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 115,226 / 104,578 = 1.1018 (2026-10-07). + 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). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,753 / 104,578 = 1.1260 (2026-10-25). Before: 1.125. minUnionBytes: 91_000, // Phase 4 wave 1; estimated union ~94.9KB mustContain: ['readiness', 'merge', 'canary', 'revert', 'staging'], }, @@ -583,7 +583,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 48_175, // GSTA-96 hoist (2026-10-26): lowered from 70_000 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 4,888 bytes; measured 43,287. Before: Phase-specific outside coverage, native fallback, and harness guard. minUnionBytes: 85_000, // measured union 86,926 mustContain: ['6 Decision Principles', 'TASTE DECISION', 'USER CHALLENGE', 'consensus', 'Restore Point'], - maxSizeRatio: 1.1799, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1799 (before: 1.1772). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1772 (before: 1.1723). Before that: GST-537 /autoplan --ceo-only (GStack Minder approved A1, 2026-10-31): sections/ceo-only.md (2,168 B) plus its Section index row, read only when the invocation names --ceo-only (test/autoplan-ceo-only.test.ts pins that a normal run never reads it); measured 119,545 / 101,979 = 1.1723 (2026-10-31), +2,276 B over main's 117,269 = 1.1499. Before: 1.1511. Four validated outside invocations replace raw CLI calls; phases keep independent coverage. + 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 114,297 / 101,979 = 1.1208 (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 114,533 / 101,979 = 1.1231 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site, and phase-close publishing each report with the `true autoplan-published <phase>` no-op before the next phase entry in a later message (CEO-1); measured 114,320 / 101,979 = 1.1210 (2026-10-07). Merged with the guard area: measured 115,149 / 101,979 = 1.1291 (2026-10-07). + Oct 8 wave (permission cards after a background reviewer): Step 1 puts RESTORE_PATH, and so every phase artifact, in the project's git-excluded `.gstack/tmp/autoplan/`, which Claude Code reads without a card after the skill turn ends; measured 115,270 / 101,979 = 1.1303 (2026-10-08). + fix wave PR D: the prerequisite offer is skipped in spawned/headless sessions (#1958); measured 115,267 / 101,979 = 1.1303 (2026-10-07). Both merged: measured 115,126 / 101,979 = 1.1289 (2026-10-08). + 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 B9/B10/B12: Phase 0 ESTIMATE and the phase-close timing record, the final gate as a gate list (`gstack-gate render/parse`, stable ids, gate_rev) and the URGENT block above the summary, offset by tightening the Phase 4 prose and the tasks-section; measured 114,980 / 101,979 = 1.1275 (2026-10-10). + Oct 10 multi-agent wave PR D1 (reality rows): the reality-rows check line in the CEO and Eng phase files, the Pre-Gate rule (unattended miss is `incomplete`, never a warning) and the two Pre-Gate cells; measured 117,042 / 101,979 = 1.1477 (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,388 / 101,979 = 1.1511 (2026-10-25). Before: 1.149. + maxSizeRatio: 1.1804, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 120,374 / 101,979 = 1.18038, rounded up (before: 1.1799). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1799 (before: 1.1772). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1772 (before: 1.1723). Before that: GST-537 /autoplan --ceo-only (GStack Minder approved A1, 2026-10-31): sections/ceo-only.md (2,168 B) plus its Section index row, read only when the invocation names --ceo-only (test/autoplan-ceo-only.test.ts pins that a normal run never reads it); measured 119,545 / 101,979 = 1.1723 (2026-10-31), +2,276 B over main's 117,269 = 1.1499. Before: 1.1511. Four validated outside invocations replace raw CLI calls; phases keep independent coverage. + 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 114,297 / 101,979 = 1.1208 (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 114,533 / 101,979 = 1.1231 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site, and phase-close publishing each report with the `true autoplan-published <phase>` no-op before the next phase entry in a later message (CEO-1); measured 114,320 / 101,979 = 1.1210 (2026-10-07). Merged with the guard area: measured 115,149 / 101,979 = 1.1291 (2026-10-07). + Oct 8 wave (permission cards after a background reviewer): Step 1 puts RESTORE_PATH, and so every phase artifact, in the project's git-excluded `.gstack/tmp/autoplan/`, which Claude Code reads without a card after the skill turn ends; measured 115,270 / 101,979 = 1.1303 (2026-10-08). + fix wave PR D: the prerequisite offer is skipped in spawned/headless sessions (#1958); measured 115,267 / 101,979 = 1.1303 (2026-10-07). Both merged: measured 115,126 / 101,979 = 1.1289 (2026-10-08). + 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 B9/B10/B12: Phase 0 ESTIMATE and the phase-close timing record, the final gate as a gate list (`gstack-gate render/parse`, stable ids, gate_rev) and the URGENT block above the summary, offset by tightening the Phase 4 prose and the tasks-section; measured 114,980 / 101,979 = 1.1275 (2026-10-10). + Oct 10 multi-agent wave PR D1 (reality rows): the reality-rows check line in the CEO and Eng phase files, the Pre-Gate rule (unattended miss is `incomplete`, never a warning) and the two Pre-Gate cells; measured 117,042 / 101,979 = 1.1477 (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 117,388 / 101,979 = 1.1511 (2026-10-25). Before: 1.149. }, spec: { skill: 'spec', @@ -612,7 +612,7 @@ do not launch the downstream skill or open a browser.`, behavioral: 'prompt', maxSkeletonBytes: 36_571, // GSTA-96 hoist (2026-10-26): lowered from 58_400 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 1,606 bytes; measured 34,965. Before: + v2.0 {{ASIDE_RESEARCH}} (Aside first, WebSearch fallback); measured 57_356 minUnionBytes: 64_500, // measured union 67,430 - maxSizeRatio: 1.0853, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.0853 (before: 1.0819). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.0819 (before: 1.0746). Before that: Oct 10 multi-agent wave PR E2: the lazy gate-and-file section renders {{COORDINATOR_CONTRACT}} (the block every spawned lane inherits word for word; `gstack-autoplan contract` prints the same bytes) before the --execute spawn pipe; measured 86,614 / 81,577 = 1.0617 after the contract became a fail-closed `CONTRACT=$(…)` capture (2026-10-10). The skeleton is unchanged (57,107). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 87,656 / 81,577 = 1.0745 (2026-10-25). Before: 1.07. + maxSizeRatio: 1.0860, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 88,590 / 81,577 = 1.08597, rounded up (before: 1.0853). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.0853 (before: 1.0819). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.0819 (before: 1.0746). Before that: Oct 10 multi-agent wave PR E2: the lazy gate-and-file section renders {{COORDINATOR_CONTRACT}} (the block every spawned lane inherits word for word; `gstack-autoplan contract` prints the same bytes) before the --execute spawn pipe; measured 86,614 / 81,577 = 1.0617 after the contract became a fail-closed `CONTRACT=$(…)` capture (2026-10-10). The skeleton is unchanged (57,107). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 87,656 / 81,577 = 1.0745 (2026-10-25). Before: 1.07. mustContain: ['HARD GATE', 'dedupe', 'quality gate', 'acceptance criteria', 'archive'], }, 'setup-gbrain': { @@ -640,7 +640,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, }, behavioral: 'prompt', - maxSkeletonBytes: 38_629, // GSTA-96 hoist (2026-10-26): lowered from 60_450 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 323 bytes; measured 38,306. Before: + v1.78 AUQ spawned-trigger objectivity (explicit declaration + interactive fence); measured 60_013 + maxSkeletonBytes: 38_676, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 38,676 (before: 38,629 on a141e94). Before that: GSTA-96 hoist (2026-10-26): lowered from 60_450 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 323 bytes; measured 38,306. Before: + v1.78 AUQ spawned-trigger objectivity (explicit declaration + interactive fence); measured 60_013 minUnionBytes: 78_300, // measured union 79,139 mustContain: ['PGLite', 'Supabase', 'claude mcp add', 'read_secret_to_env', 'pooler'], maxSizeRatio: 1.07, // measured 1.051 vs the branch monolith: index + stubs + 4 STOP pointers @@ -677,7 +677,7 @@ do not launch the downstream skill or open a browser.`, }, behavioral: 'prompt', maxSkeletonBytes: 41_669, // GSTA-96 hoist (2026-10-26): lowered from 63_500 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 12,415 bytes; measured 29,254. Before: + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} (replaces the browse setup block); measured 61_253 - maxSizeRatio: 1.1526, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1526 (before: 1.1493). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1493 (before: 1.1420). Before that: + v1.81 Aside contract + gstack-browser fallback block (1.080 on v1.91.7.0) + the shared test value bar at 8a.5 ({{TEST_VALUE_BAR:qa}}); measured 1.094 + 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.101 (2026-09-30) + v1.91.12.0 merge of #2999 (await scope/method Reads, capture --after checkpoints, browser-only empty evidence list) with #3002; measured 1.1028 (2026-10-01). + both untrusted-content marker formats in the browser fallback (W7f); measured 1.1035 (2026-10-02). Re-measured 1.1038 after the W8 probe-loop renames (2026-10-03); the cap already matches. + the annotate-every-capture and superseded rule before materialize (a ship-exploratory-late-input run published evidence that omitted older-snapshot captures); measured 1.1064 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 93,282 / 84,049 = 1.1099 (2026-10-04). + reliability follow-ups C2 (judge-named gaps after trimming the added wording: feasible 180 s Browser Quick, PROBE_DIR's source line, stop goes to the §4 report, written JSON keeps full card values; lane S's {user}/timing fields); measured 93,311 / 84,049 = 1.11020 (2026-10-04). + 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 94,486 / 84,049 = 1.1242 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 94,681 / 84,049 = 1.1265 (2026-10-07). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 94,736 / 84,049 = 1.12715 (2026-10-08). + 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). + maxSizeRatio: 1.1533, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 96,928 / 84,049 = 1.15323, rounded up (before: 1.1526). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1526 (before: 1.1493). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1493 (before: 1.1420). Before that: + v1.81 Aside contract + gstack-browser fallback block (1.080 on v1.91.7.0) + the shared test value bar at 8a.5 ({{TEST_VALUE_BAR:qa}}); measured 1.094 + 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.101 (2026-09-30) + v1.91.12.0 merge of #2999 (await scope/method Reads, capture --after checkpoints, browser-only empty evidence list) with #3002; measured 1.1028 (2026-10-01). + both untrusted-content marker formats in the browser fallback (W7f); measured 1.1035 (2026-10-02). Re-measured 1.1038 after the W8 probe-loop renames (2026-10-03); the cap already matches. + the annotate-every-capture and superseded rule before materialize (a ship-exploratory-late-input run published evidence that omitted older-snapshot captures); measured 1.1064 (2026-10-03). + v1.91.18.0 (#3023) merged into the v1.91.19.0 wave; measured 93,282 / 84,049 = 1.1099 (2026-10-04). + reliability follow-ups C2 (judge-named gaps after trimming the added wording: feasible 180 s Browser Quick, PROBE_DIR's source line, stop goes to the §4 report, written JSON keeps full card values; lane S's {user}/timing fields); measured 93,311 / 84,049 = 1.11020 (2026-10-04). + 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 94,486 / 84,049 = 1.1242 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 94,681 / 84,049 = 1.1265 (2026-10-07). + Oct 8 wave: shared voice directive bans "load-bearing" and adds the reply-language rule, offset by tightening the bounded closer (net +17 bytes per tier-2+ skill); measured 94,736 / 84,049 = 1.12715 (2026-10-08). + 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). minUnionBytes: 69_500, // measured union 70,385 // 'aside repl' pins the Aside contract; '$B goto' pins the fallback block in the always-loaded skeleton. mustContain: ['bug', 'aside repl', '$B goto', 'fix', 'Health Score Rubric', 'regression'], @@ -714,7 +714,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, }, behavioral: 'prompt', - maxSkeletonBytes: 35_574, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 35,574 (before: 35_298). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 35,298 (before: 34_700). Before that: + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} skeleton + the STOP-Read pointer; measured 29_986 + 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); skeleton measured 32,532 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort), and the cookbook's silent-failure list and signed-in-tab recipe (the rule details live here, not in every browsing skill); skeleton measured 34,047 (2026-10-07). + Oct 8 wave: the tier-1 voice directive bans "load-bearing" and adds the reply-language rule (tier 1 has no closer to tighten: +158 bytes); skeleton measured 34,209 (2026-10-08). + 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). + maxSkeletonBytes: 35_635, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 35,635 (before: 35,574 on a141e94). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 35,574 (before: 35_298). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 35,298 (before: 34_700). Before that: + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} skeleton + the STOP-Read pointer; measured 29_986 + 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); skeleton measured 32,532 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort), and the cookbook's silent-failure list and signed-in-tab recipe (the rule details live here, not in every browsing skill); skeleton measured 34,047 (2026-10-07). + Oct 8 wave: the tier-1 voice directive bans "load-bearing" and adds the reply-language rule (tier 1 has no closer to tighten: +158 bytes); skeleton measured 34,209 (2026-10-08). + 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). minUnionBytes: 36_000, // skeleton + command-list section (14,240); measured union ~38.5 KB // 'BEGIN/END UNTRUSTED EXTERNAL' pins the untrusted-content warning in the // command reference; 'aside repl' pins the Aside contract in the skeleton. @@ -733,7 +733,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, }, behavioral: 'prompt', - maxSkeletonBytes: 51_626, // GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the EUREKA example names /plan-eng-review again; measured 51,626 (before: 51,619 on 81fb900). Before that: GSTA-96 hoist (2026-10-26): lowered from 73_450 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 937 bytes; measured 50,685. Before: + v1.78 AUQ spawned-trigger objectivity (explicit declaration + interactive fence); measured 73_059 + maxSkeletonBytes: 51_669, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 51,669 (before: 51,626 on a141e94). Before that: GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the EUREKA example names /plan-eng-review again; measured 51,626 (before: 51,619 on 81fb900). Before that: GSTA-96 hoist (2026-10-26): lowered from 73_450 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 937 bytes; measured 50,685. Before: + v1.78 AUQ spawned-trigger objectivity (explicit declaration + interactive fence); measured 73_059 minUnionBytes: 66_000, // measured union 73,496 mustContain: ['retrospective', '45-minute gap', 'Ship of the week', 'Praise'], }, @@ -757,10 +757,10 @@ do not launch the downstream skill or open a browser.`, // No section-loading paid case yet: a new periodic case would push the // periodic census past its 38-slice cap (test/paid-retry-supervision.test.ts). behavioral: 'none', - maxSkeletonBytes: 85_182, // /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 85,182. Before: GSTA-134 skill diet (2026-10-28): lowered from 115_947 to the measured skeleton after the outside voices and test bootstrap moved to sections, 84,869. Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the hoisted skeleton plus main's headroom of 0 bytes; measured 115,947 on the merged tree. Before: measured 137735 on the merged tree with main f27a760 (2026-10-27, #3507); 137767 (2026-10-26; 137773 on 2026-10-25 before the shorter craft-audit trigger): the Section index the external-host carve test requires, its craft-audit row, and the STOP pointer (GSTA-92; Garry 2026-10-25 'Do it' (GSTA-92)). + maxSkeletonBytes: 85_222, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 85,222 (before: 85,182 on a141e94). Before that: /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 85,182. Before: GSTA-134 skill diet (2026-10-28): lowered from 115_947 to the measured skeleton after the outside voices and test bootstrap moved to sections, 84,869. Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the hoisted skeleton plus main's headroom of 0 bytes; measured 115,947 on the merged tree. Before: measured 137735 on the merged tree with main f27a760 (2026-10-27, #3507); 137767 (2026-10-26; 137773 on 2026-10-25 before the shorter craft-audit trigger): the Section index the external-host carve test requires, its craft-audit row, and the STOP pointer (GSTA-92; Garry 2026-10-25 'Do it' (GSTA-92)). minUnionBytes: 136_100, // GSTA-134 skill diet (2026-10-28): measured union 137,602 (lowered from 143_300); before: measured union 144802 on the merged tree with main f27a760 (2026-10-27, #3507); 145037 (2026-10-26) mustContain: ['AI Slop Detection', 'Fix Loop', 'gstack-design-lint', 'Proof beside each claim', 'holds session data'], - maxSizeRatio: 1.3654, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.3654 (before: 1.3628). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3628 (before: 1.357). Before that: /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 143,620 / 105,842 = 1.35693. Before: 1.3001, GSTA-134 skill diet (2026-10-28): measured 137,602 / 105,842 = 1.30007, rounded up (lowered from 1.3739). Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the union now holds sections/preamble.md (the hoist's owner-approved raise, decision A) on top of main's 1.3681; measured 145,410 / 105,842 = 1.3739 on the merged tree. Before: first parity guard for design-review: measured 144802 / 105,842 = 1.3681 on the merged tree with main f27a760 (2026-10-27, #3507: the design lint swap); before that 145082 / 105,842 = 1.3708 (2026-10-25; 145077 after the /ship review fixes, 145068 = 1.3707 after the line-13 reword, 145049 = 1.3705 after the post-merge /ship review, 145037 = 1.3704 after its second pass, 2026-10-26), the skeleton's growth since v1.64.1.0 plus the craft audit (Garry 2026-10-25 'Do it' (GSTA-92)). + maxSizeRatio: 1.3657, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 144,546 / 105,842 = 1.36568, rounded up (before: 1.3654). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.3654 (before: 1.3628). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.3628 (before: 1.357). Before that: /design-review --build (GST-1741 PR 2, 2026-11-07, grant: GStack Minder, 2026-11-07): --build routing, stop pointer, index row, description clause and trigger: +443 B, trimmed 130; the build-loop section is mode-loaded; measured 143,620 / 105,842 = 1.35693. Before: 1.3001, GSTA-134 skill diet (2026-10-28): measured 137,602 / 105,842 = 1.30007, rounded up (lowered from 1.3739). Before: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): the union now holds sections/preamble.md (the hoist's owner-approved raise, decision A) on top of main's 1.3681; measured 145,410 / 105,842 = 1.3739 on the merged tree. Before: first parity guard for design-review: measured 144802 / 105,842 = 1.3681 on the merged tree with main f27a760 (2026-10-27, #3507: the design lint swap); before that 145082 / 105,842 = 1.3708 (2026-10-25; 145077 after the /ship review fixes, 145068 = 1.3707 after the line-13 reword, 145049 = 1.3705 after the post-merge /ship review, 145037 = 1.3704 after its second pass, 2026-10-26), the skeleton's growth since v1.64.1.0 plus the craft audit (Garry 2026-10-25 'Do it' (GSTA-92)). }, // ── Token-reduction Phase 4 wave 4 (v1.69.x branch): design doctrine carve ── @@ -790,7 +790,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, // operational skill, no plan-mode gate }, behavioral: 'prompt', - maxSkeletonBytes: 34_410, // GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): lowered from 56_200 by the shared preamble that moved to sections/preamble.md, keeping main's headroom of 366 bytes; measured 34,044 on the merged tree. Before: measured 55,834 on the merged tree with main f27a760 (2026-10-27, #3507: the Step 4 lint line); 55,786 (2026-10-25): the craft section pointer, its index row and the Step 4 craft-check line (GSTA-92); before that 55,262 (2026-09-09): the detector install offer pointer + its sections-table row (the brief itself lives in sections/detector-install-offer.md); before that 54,545 for the review-cycle trust prose, the Slop Gate's Decisions-Log clause, and the blacklist header's override sentence + 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). + maxSkeletonBytes: 34_427, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 34,427 (before: 34,410 on a141e94). Before that: GSTA-96 hoist merged with v1.91.274.0 (#3507, 2026-10-27): lowered from 56_200 by the shared preamble that moved to sections/preamble.md, keeping main's headroom of 366 bytes; measured 34,044 on the merged tree. Before: measured 55,834 on the merged tree with main f27a760 (2026-10-27, #3507: the Step 4 lint line); 55,786 (2026-10-25): the craft section pointer, its index row and the Step 4 craft-check line (GSTA-92); before that 55,262 (2026-09-09): the detector install offer pointer + its sections-table row (the brief itself lives in sections/detector-install-offer.md); before that 54,545 for the review-cycle trust prose, the Slop Gate's Decisions-Log clause, and the blacklist header's override sentence + 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). minUnionBytes: 57_500, // Phase 4 wave 4; measured union 58,682; 78,626 on the merged tree with main f27a760 (2026-10-27, #3507) mustContain: ["Don't make me think", "Users scan, they don't read", 'The Goodwill Reservoir', 'PRETEXT API CHEATSHEET', 'Pattern 3: Text around obstacles'], }, @@ -853,7 +853,7 @@ do not launch the downstream skill or open a browser.`, }, behavioral: 'external', externalTest: 'test/skill-e2e-design.test.ts', - maxSkeletonBytes: 18_112, // GSTA-96 hoist (2026-10-27): lowered from 39_900 by the shared preamble that moved to sections/preamble.md, keeping main's headroom of 32 bytes; measured 18,080 on the v1.91.273.0 merge. Before: new skill (GSTA-92 plan item 15, Garry 2026-10-25 "Do it"); measured skeleton 39,836 (2026-10-25) + maxSkeletonBytes: 18_132, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 18,132 (before: 18,112 on a141e94). Before that: GSTA-96 hoist (2026-10-27): lowered from 39_900 by the shared preamble that moved to sections/preamble.md, keeping main's headroom of 32 bytes; measured 18,080 on the v1.91.273.0 merge. Before: new skill (GSTA-92 plan item 15, Garry 2026-10-25 "Do it"); measured skeleton 39,836 (2026-10-25) minUnionBytes: 57_500, // measured union 58,666 (2026-10-25) mustContain: ['window.__start()', 'window.__tick(dt)', 'whole milliseconds averaging 1000/60', 'Content never hides behind animation timing'], }, @@ -900,7 +900,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, // operational skill, no plan-mode gate }, behavioral: 'prompt', - maxSkeletonBytes: 32_169, // GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 32,169 (before: 31_893). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 31,893 (before: 31_300). Before that: first carve: Section index, one STOP pointer and the vet rule on the 29.9k monolith; measured 30,781 (2026-10-26) + maxSkeletonBytes: 32_225, // GST-2774 (2026-11-14): the Claude catalog description keeps a when-to-use clause (GSTA-558: Opus 5.5 skipped /review and the planning skills when the listing said only what a skill is); measured 32,225 (before: 32,169 on a141e94). Before that: GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 32,169 (before: 31_893). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 31,893 (before: 31_300). Before that: first carve: Section index, one STOP pointer and the vet rule on the 29.9k monolith; measured 30,781 (2026-10-26) minUnionBytes: 33_000, // skeleton + vet-the-number section; measured union 34,527 (2026-10-26) mustContain: ['performance.getEntries()', 'REGRESSION', 'Name the limiter', 'run-to-run variation', 'inconclusive'], // The v1.64.1.0 baseline measured the 37.2k monolith; the carved union is below it. diff --git a/test/shared-libs-rendering.test.ts b/test/shared-libs-rendering.test.ts index 07bde9b55f7..7c0a5f0c56d 100644 --- a/test/shared-libs-rendering.test.ts +++ b/test/shared-libs-rendering.test.ts @@ -167,10 +167,11 @@ describe('shared-code skill distribution', () => { } }); - test('standalone catalog entry adds exactly the approved 82 bytes', () => { + // 82 approved bytes, plus 36 for the when-to-use clause every Claude catalog entry gained in GST-2774 and the YAML quotes it needs. + test('standalone catalog entry adds exactly the approved 118 bytes', () => { const skill = readFileSync(join(output, 'deslop-shared-libs/SKILL.md'), 'utf8'); const description = skill.match(/^description: (.+)$/m)?.[1]; - expect(description).toBe('Find worthwhile shared-code extractions in recent work. (gstack)'); - expect(Buffer.byteLength('deslop-shared-libs') + Buffer.byteLength(description!)).toBe(82); + expect(description).toBe('"Find worthwhile shared-code extractions in recent work. Use for: find code worth sharing. (gstack)"'); + expect(Buffer.byteLength('deslop-shared-libs') + Buffer.byteLength(description!)).toBe(118); }); }); diff --git a/test/size-ledger/ship/claude-skill-descriptions-say-when-to-use.json b/test/size-ledger/ship/claude-skill-descriptions-say-when-to-use.json new file mode 100644 index 00000000000..0f19f9b91eb --- /dev/null +++ b/test/size-ledger/ship/claude-skill-descriptions-say-when-to-use.json @@ -0,0 +1,4 @@ +{ + "bytes": 29, + "why": "GST-2774: the Claude catalog description keeps a when-to-use clause (Use for: ship it, create a pr, push to main)" +} diff --git a/test/skill-triggers.test.ts b/test/skill-triggers.test.ts index bc53bb03f1c..daa0074feb0 100644 --- a/test/skill-triggers.test.ts +++ b/test/skill-triggers.test.ts @@ -41,6 +41,8 @@ describe('routerLine (router-mode targets)', () => { l => { expect(l).toStartWith('Use when asked to'); expect(l).not.toContain('Pre-landing'); }], ['no trigger sentence: the triggers list leads', 'Pre-landing PR review. Analyzes the diff.', TRIGGERS, 160, l => expect(l).toStartWith('Use for: review this pr, code review')], + ['the catalog-trimmed "Use for:" clause gives way to the full triggers list', 'Pre-landing PR review. Use for: review this pr, code review. (gstack)', TRIGGERS, 160, + l => expect(l).toBe('Use for: review this pr, code review, check my diff, pre-landing review. Pre-landing PR review.')], ['neither: the first sentence, cut at a word', 'A very long first sentence about a workflow that goes on and on and on.', [], 40, l => { expect(l).toStartWith('A very long first sentence'); expect(l).toEndWith('...'); }], ]; diff --git a/ubicloud/SKILL.md b/ubicloud/SKILL.md index e83959ac9ad..3999e650f3e 100644 --- a/ubicloud/SKILL.md +++ b/ubicloud/SKILL.md @@ -2,7 +2,7 @@ name: ubicloud preamble-tier: 2 version: 1.0.0 -description: "Run a heavy suite, build or eval on an ephemeral 16-vCPU Ubicloud VM: TTL-named VMs, a reaper, quota preflight and a hang watchdog. (gstack)" +description: "Run a heavy suite, build or eval on an ephemeral 16-vCPU Ubicloud VM: TTL-named VMs, a reaper, quota preflight and a hang watchdog. Use for: run on ubicloud, ubicloud vm, remote test run. (gstack)" triggers: - run on ubicloud - ubicloud vm diff --git a/unfreeze/SKILL.md b/unfreeze/SKILL.md index ca32654bd89..5c86cd3aa1b 100644 --- a/unfreeze/SKILL.md +++ b/unfreeze/SKILL.md @@ -1,7 +1,7 @@ --- name: unfreeze version: 0.1.0 -description: Clear the freeze boundary set by /freeze, allowing edits to all directories again. (gstack) +description: "Clear the freeze boundary set by /freeze, allowing edits to all directories again. Use for: unfreeze edits, unlock all directories. (gstack)" triggers: - unfreeze edits - unlock all directories diff --git a/verify/SKILL.md b/verify/SKILL.md index cd9882c2b9d..619e582fe65 100644 --- a/verify/SKILL.md +++ b/verify/SKILL.md @@ -2,7 +2,7 @@ name: verify preamble-tier: 1 version: 0.1.0 -description: "Use when coding: run the checks and tests /ship picks until green. (gstack)" +description: "Use when coding: run the checks and tests /ship picks until green. Use for: verify my change, run the checks, make the tests pass. (gstack)" triggers: - verify my change - run the checks diff --git a/write-skill/SKILL.md b/write-skill/SKILL.md index 02732b264c5..8615374ba1e 100644 --- a/write-skill/SKILL.md +++ b/write-skill/SKILL.md @@ -2,7 +2,7 @@ name: write-skill preamble-tier: 2 version: 0.1.0 -description: "Write a new agent skill or improve one without bloat: the edit ladder, levels, drift and size checks, full diets. (gstack)" +description: "Write a new agent skill or improve one without bloat: the edit ladder, levels, drift and size checks, full diets. Use for: write a skill, improve this skill. (gstack)" triggers: - write a skill - improve this skill From e8c8625bd65fdcc0f0650f982830649d326c4bf4 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 20:51:54 +0800 Subject: [PATCH 31/62] Keep checking custom skill contracts that still list the removed test-after-edit item (GST-2811) (#4439) * Keep checking a custom skill's contract when it still lists the removed test-after-edit item The Stop hook used to treat such a contract as invalid and check none of its items. It now skips only that item, warns with a line naming the file and item, and checks the rest. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Move the changelog note to its own entry, since a landed entry is never edited Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: pre-landing review fixes Test that gstack-skill-contract check warns about a removed-kind item and checks the rest. Review-Finding: p1/specialist-batched#1 reader=specialist-batched Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * chore: changelog and TODOS Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-skill-contract | 4 +++- ...keep-custom-contracts-with-removed-item.md | 1 + docs/skill-routing-and-contracts.md | 2 +- .../claude/hooks/skill-contract-stop-hook.ts | 8 ++++++-- lib/skill-contract.ts | 17 ++++++++++++++-- test/skill-contract-stop-hook.test.ts | 13 +++++++++++- test/skill-contract.test.ts | 20 ++++++++++++++++++- 7 files changed, 57 insertions(+), 8 deletions(-) create mode 100644 changelog.d/keep-custom-contracts-with-removed-item.md diff --git a/bin/gstack-skill-contract b/bin/gstack-skill-contract index 27ba75adf51..000c5ea455b 100755 --- a/bin/gstack-skill-contract +++ b/bin/gstack-skill-contract @@ -19,7 +19,7 @@ */ import { EXIT, StateError, UnknownShape, blockMessage, checkContract, isMiss, lookupContract, parseTranscript, readAllRecords, - readTranscriptFile, reportRows, type CheckResult, + readTranscriptFile, reportRows, skippedLine, type CheckResult, } from '../lib/skill-contract'; import { fileURLToPath } from 'node:url'; import { installedSkillsDir } from '../lib/skill-route'; @@ -69,6 +69,8 @@ function check(args: string[]): never { if (!transcriptPath || !skill) die(EXIT.USAGE, `SKILL_CONTRACT_USAGE: check needs --transcript and --skill\n${USAGE}`); const found = lookupContract(skill, installedSkillsDir(), flag(args, '--skill-file')); if (!('contract' in found)) die(EXIT.NO_CONTRACT, `SKILL_CONTRACT_NO_CONTRACT ${skill}: ${found.error}`); + for (const why of found.contract.skipped ?? []) process.stderr.write(`${skippedLine(found.file, why)} +`); let result: CheckResult; try { result = checkContract(parseTranscript(readTranscriptFile(transcriptPath)), skill, found.contract); diff --git a/changelog.d/keep-custom-contracts-with-removed-item.md b/changelog.d/keep-custom-contracts-with-removed-item.md new file mode 100644 index 00000000000..a8789f00190 --- /dev/null +++ b/changelog.d/keep-custom-contracts-with-removed-item.md @@ -0,0 +1 @@ +- **A skill you wrote whose contract still lists `check_after_last_edit` keeps the rest of its contract.** This corrects the entry in this release that says such a contract is now invalid and none of its items are checked. The optional Stop hook now skips only that item and keeps checking the skill's other items. Until you delete the item, the hook prints a `SKILL_CONTRACT_SKIPPED` line naming the file and the item. A contract whose only items use the removed kind is still invalid, so the hook checks nothing for that skill. diff --git a/docs/skill-routing-and-contracts.md b/docs/skill-routing-and-contracts.md index c85997cc9d4..48139e563f0 100644 --- a/docs/skill-routing-and-contracts.md +++ b/docs/skill-routing-and-contracts.md @@ -76,7 +76,7 @@ Every item has an `id` (lowercase letters, digits, `.`, `_`, `-`) and a `kind`, | `selected_specialists_dispatched` | optional `marker`, `empty_marker` | The selection line was printed in an assistant message or a Bash result (never a fetched page or file), its names are plain (letters, digits, spaces, `_`, `.`, `-`, at most 40 characters), and each specialist it names has an Agent dispatch that mentions it. The marker is literal text in which a whole-word N stands for a number; the default is `Dispatching N specialists:`. N = 0 (`Dispatching 0 specialists: (small diff)`) or a "specialists skipped" line means zero specialists were selected, which passes. Text in parentheses is not a name (`Dispatching 1 specialists: State Machines (small diff)` selects State Machines) | | `agent_dispatch` | `match` (regular expression, case-insensitive) | An Agent dispatch's description or prompt matches `match`. A `marker` is rejected until the checker can bind it to the dispatch it names (GST-1242) | -There is no item for "run a test after your last edit". /verify asks for that in its text, and Opus 5.5 and GPT-6.1 Sol already did it in 96% and 89% of runs; a Stop-hook item for it added no measurable gain (gstack-evals#356), so it was removed. +There is no item for "run a test after your last edit". /verify asks for that in its text, and Opus 5.5 and GPT-6.1 Sol already did it in 96% and 89% of runs; a Stop-hook item for it added no measurable gain (gstack-evals#356), so it was removed. A contract that still lists `check_after_last_edit` keeps its other items. The checker skips that item and prints `SKILL_CONTRACT_SKIPPED <SKILL.md>: <item id>: ...` on stderr each time it reads the contract (the Stop hook and `check`). A contract whose only items use that kind is invalid. A run the skill ended early counts as met: a final `STATUS: BLOCKED` (or `Status: BLOCKED` in the skill's report) or a final message with a line that starts "Nothing to review" (/review's early exit). diff --git a/hosts/claude/hooks/skill-contract-stop-hook.ts b/hosts/claude/hooks/skill-contract-stop-hook.ts index 709a4f8e055..80aba457498 100755 --- a/hosts/claude/hooks/skill-contract-stop-hook.ts +++ b/hosts/claude/hooks/skill-contract-stop-hook.ts @@ -33,7 +33,7 @@ import { binPath, sessionKind } from './spawn-bin'; import { appendHookTrace, installedSkillsDir, readSkillSwitch, readStdinBounded } from '../../../lib/skill-route'; import { - AGENT_STALL_MS, StateError, UnknownShape, blockMessage, bumpCanary, checkContract, isFinalTurn, lookupContract, nextOutcome, + AGENT_STALL_MS, StateError, UnknownShape, blockMessage, bumpCanary, checkContract, isFinalTurn, lookupContract, nextOutcome, skippedLine, readRecord, recordPath, runKey, sameSkill, skillLoads, stateErrorLine, writeRecord, type Contract, type Transcript, } from '../../../lib/skill-contract'; @@ -67,7 +67,11 @@ function target(t: Transcript): { skill: string; contract: Contract } | null { if (tried.some(s => sameSkill(s, load.skill))) continue; tried.push(load.skill); const found = lookupContract(load.skill, dir); - if ('contract' in found) return { skill: load.skill, contract: found.contract }; + if ('contract' in found) { + for (const why of found.contract.skipped ?? []) process.stderr.write(`${skippedLine(found.file, why)} +`); + return { skill: load.skill, contract: found.contract }; + } if (found.reason === 'invalid' && found.file) throw new StateError(found.file, found.error); } return null; diff --git a/lib/skill-contract.ts b/lib/skill-contract.ts index cdcab0fe289..a6996e2db0d 100644 --- a/lib/skill-contract.ts +++ b/lib/skill-contract.ts @@ -24,6 +24,8 @@ import { resolveStateRoot } from './state-root'; export const TRANSCRIPT_MAX_BYTES = 32 * 1024 * 1024; export const ITEM_KINDS = ['report_labels', 'selected_specialists_dispatched', 'agent_dispatch'] as const; export type ItemKind = typeof ITEM_KINDS[number]; +/** Kinds a contract may still list from an older gstack: each such item is skipped with a warning, not checked. */ +const REMOVED_KINDS = ['check_after_last_edit']; const ITEM_ID = /^[a-z0-9][a-z0-9_.-]{0,63}$/; const MAX_ITEMS = 20; @@ -42,13 +44,18 @@ export interface ContractItem { fix?: string; summary?: string; } -export interface Contract { version: 1; items: ContractItem[] } +/** skipped: one warning per item whose kind was removed from gstack; the item is not checked. */ +export interface Contract { version: 1; items: ContractItem[]; skipped?: string[] } export class StateError extends Error { constructor(readonly file: string, readonly why: string) { super(`${file}: ${why}`); } } export class UnknownShape extends Error {} +export function skippedLine(file: string, why: string): string { + return `gstack-skill-contract: SKILL_CONTRACT_SKIPPED ${file}: ${why}`; +} + export function stateErrorLine(file: string, why: string): string { return `gstack-skill-contract: SKILL_CONTRACT_STATE_ERROR ${file}: ${why}; stop allowed, miss not recorded (see ${STATE_ERROR_DOC})`; } @@ -112,11 +119,16 @@ export function validateContract(raw: unknown): { contract: Contract } | { error return { error: `contract items must be a list of 1 to ${MAX_ITEMS} items` }; } const items: ContractItem[] = []; + const skipped: string[] = []; for (const [n, item] of raw.items.entries()) { if (!isObject(item)) return { error: `items[${n}] must be a mapping` }; const id = item.id; if (typeof id !== 'string' || !ITEM_ID.test(id)) return { error: `items[${n}].id must match ${ITEM_ID}` }; if (items.some(i => i.id === id)) return { error: `duplicate item id ${id}` }; + if (REMOVED_KINDS.includes(item.kind)) { + skipped.push(`${id}: kind ${item.kind} was removed from gstack, so this item is not checked; delete it from the contract`); + continue; + } if (!(ITEM_KINDS as readonly string[]).includes(item.kind)) { return { error: `${id}: unknown kind ${JSON.stringify(item.kind)} (expected one of ${ITEM_KINDS.join(', ')})` }; } @@ -141,7 +153,8 @@ export function validateContract(raw: unknown): { contract: Contract } | { error if (out.kind === 'agent_dispatch' && out.marker) return { error: `${id}: agent_dispatch takes no marker until the checker can bind a marker to the dispatch it names (GST-1242)` }; items.push(out); } - return { contract: { version: 1, items } }; + if (!items.length) return { error: `every item uses a removed kind (${skipped.join('; ')})` }; + return { contract: skipped.length ? { version: 1, items, skipped } : { version: 1, items } }; } /** One plain phrase per item, for the routing hint's "Done means" variant. */ diff --git a/test/skill-contract-stop-hook.test.ts b/test/skill-contract-stop-hook.test.ts index adffa02a7ad..22e2d041d4a 100644 --- a/test/skill-contract-stop-hook.test.ts +++ b/test/skill-contract-stop-hook.test.ts @@ -11,10 +11,11 @@ import { bunIsolationArgs } from '../lib/bun-isolation'; import { AGENT_STALL_MS, STATE_ERROR_DOC, stateErrorLine } from '../lib/skill-contract'; import { SWITCH_DEFAULT } from '../lib/skill-route'; import { - CONTRACT_HOOK, DEBUG_REPORT, INTERACTIVE_TURNS, J1_TRANSCRIPT, ROOT, hookEnv, meta, result, runHook, say, skillsDir, slash, tmpDir, tool, user, + CONTRACT_HOOK, DEBUG_REPORT, INTERACTIVE_TURNS, J1_TRANSCRIPT, ROOT, SKILLS, hookEnv, meta, result, runHook, say, skillsDir, slash, tmpDir, tool, user, } from './helpers/skill-contract-fixture'; const BIN = path.join(ROOT, 'bin', 'gstack-skill-contract'); +const SKILLS_LEGACY = SKILLS.verify.replace(' labels: [Symptom, Root cause, Fix, Evidence]\n', ' labels: [Symptom, Root cause, Fix, Evidence]\n - id: repro-after-fix\n kind: check_after_last_edit\n'); const PINNED = fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'skill-contract', 'block-message.txt'), 'utf8').trimEnd().replace('{bin}', BIN); const STATE_ERROR = /^gstack-skill-contract: SKILL_CONTRACT_STATE_ERROR .+: .+; stop allowed, miss not recorded \(see docs\/skill-routing-and-contracts\.md#state-error\)\n$/; @@ -149,6 +150,16 @@ describe('block once, with the pinned text', () => { expect((Object.values(record().runs)[0] as any).outcome).toBe('met'); }); + test('a custom skill whose contract still lists the removed check_after_last_edit kind: warned once, the rest still blocks', () => { + const legacy = SKILLS_LEGACY.replace('name: verify', 'name: legacy'); + skills = skillsDir([], { legacy }); + const r = stop(transcript(J1_TRANSCRIPT.map(l => l.replace('"skill":"verify"', '"skill":"legacy"')))); + expect(JSON.parse(r.stdout).decision).toBe('block'); + expect(r.stderr).toBe(`gstack-skill-contract: SKILL_CONTRACT_SKIPPED ${path.join(skills, 'legacy', 'SKILL.md')}: repro-after-fix: kind check_after_last_edit was removed from gstack, so this item is not checked; delete it from the contract +`); + expect(Object.values(record().runs)[0]).toMatchObject({ skill: 'legacy', outcome: 'blocked', missing: ['debug-report'] }); + }); + test('a waiver read from the transcript satisfies the block but counts against follow', () => { const lines = [...J1_TRANSCRIPT.slice(0, -1), tool('w1', 'Bash', { command: 'gstack-skill-contract waive debug-report --reason "a docs-only change, no bug to report"' }), diff --git a/test/skill-contract.test.ts b/test/skill-contract.test.ts index 7090e5902dc..b87e6f8be30 100644 --- a/test/skill-contract.test.ts +++ b/test/skill-contract.test.ts @@ -43,7 +43,7 @@ describe('schema v1', () => { ['contract:\n version: 1\n items: [{id: a, kind: agent_dispatch}]', 'agent_dispatch needs match'], ['contract:\n version: 1\n items: [{id: a, kind: report_labels, heading: X, labels: []}]', 'needs labels'], ['contract:\n version: 1\n items: [{id: Bad_ID, kind: agent_dispatch, match: x}]', 'id must match'], - ['contract:\n version: 1\n items: [{id: a, kind: check_after_last_edit}]', 'unknown kind'], + ['contract:\n version: 1\n items: [{id: a, kind: check_after_last_edit}]', 'every item uses a removed kind'], ['contract: [unclosed', 'not valid YAML'], ]; for (const [fm, msg] of bad) { @@ -53,6 +53,14 @@ describe('schema v1', () => { }); }); +test('a contract that still lists the removed check_after_last_edit kind keeps its other items and names the skipped one', () => { + const parsed = parseContract('contract:\n version: 1\n items:\n - {id: debug-report, kind: report_labels, heading: DEBUG REPORT, labels: [Symptom]}\n - {id: repro-after-fix, kind: check_after_last_edit}'); + if (!parsed || !('contract' in parsed)) throw new Error(JSON.stringify(parsed)); + expect(parsed.contract.items.map(i => i.id)).toEqual(['debug-report']); + expect(parsed.contract.skipped).toEqual(['repro-after-fix: kind check_after_last_edit was removed from gstack, so this item is not checked; delete it from the contract']); + expect(parseContract('contract:\n version: 1\n items: [{id: a, kind: agent_dispatch, match: x}]')).toEqual({ contract: { version: 1, items: [{ id: 'a', kind: 'agent_dispatch', match: 'x' }] } }); +}); + describe('transcript parsing', () => { test('skill loads: Skill tool, typed /command, Read of a SKILL.md; sidechain records ignored', () => { const t = parseTranscript([ @@ -243,6 +251,16 @@ describe('gstack-skill-contract CLI', () => { expect(JSON.parse(unmet.stdout)).toMatchObject({ exit: 1, skill: 'verify', missing: ['debug-report'], follow: false }); }); + test('check: a contract that still lists the removed kind warns once on stderr and checks the rest', () => { + const file = path.join(work, 'SKILL.md'); + fs.writeFileSync(file, SKILLS.verify.replace(' labels: [Symptom, Root cause, Fix, Evidence]\n', ' labels: [Symptom, Root cause, Fix, Evidence]\n - id: repro-after-fix\n kind: check_after_last_edit\n')); + const r = cli('check', '--transcript', write(J1_TRANSCRIPT), '--skill', 'verify', '--skill-file', file, '--json'); + expect(r.code).toBe(EXIT.UNMET); + expect(JSON.parse(r.stdout)).toMatchObject({ missing: ['debug-report'] }); + expect(r.stderr).toBe(`gstack-skill-contract: SKILL_CONTRACT_SKIPPED ${file}: repro-after-fix: kind check_after_last_edit was removed from gstack, so this item is not checked; delete it from the contract +`); + }); + test('check: stable error exits 2, 3, 4, 5, 6', () => { expect(cli('check', '--skill', 'verify').code).toBe(EXIT.USAGE); expect(cli('check', '--transcript', path.join(work, 'none.jsonl'), '--skill', 'verify')).toMatchObject({ code: EXIT.STATE_ERROR }); From aeb74eb00b2ba35aa02eee687bd446e28a96ce44 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 21:13:19 +0800 Subject: [PATCH 32/62] /ship's test step says when it hits its time limit, and long test file lists no longer overflow the remote command (GST-2958) (#4429) * Say when /ship's test step hit its time limit, and keep long file lists off the remote test command line gstack-ship-preflight stopped gstack-pregate after a fixed hour and printed 'PREGATE: unreadable (exit 143)'. The whole step's budget is now --step-timeout <s> (default 3600), and a stop at it prints 'PREGATE: time limit hit' with the way out: push and let CI's full run carry the tests, or a larger budget. The test_backend command pregate prints for a small machine put every selected file into one argument, which Linux refuses past 128 KiB. The files now reach the VM in a setup script named by its content. Also adds an arg-limit troubleshooting entry and says the Windows job has eight shards. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Read the small-machine file list from the setup script in the hidden-folder path test The remote command now names a setup script instead of the files, so the test checks that the script lists the ./-prefixed path. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep a test path with a newline out of the remote file list A selected test path containing a newline, or equal to the list's end marker, could end the setup script's file list early and run the rest as shell on the test VM. Such paths now keep the quoted inline command. Review-Finding: p1/outside-voice#1 reader=outside-voice Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Mark the preflight half of the Step 5 time limit to-do as done Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- TODOS.md | 2 +- ...p-step-time-limit-and-remote-file-lists.md | 2 + docs/pregate.md | 12 ++++-- docs/troubleshooting.md | 19 +++++++++ lib/pregate/checks/lanes.ts | 33 +++++++++++++-- lib/ship-bin-common.ts | 5 ++- lib/ship-preflight.ts | 16 ++++++-- test/pregate-hidden-folder-paths.test.ts | 5 ++- test/pregate-lanes-arg-limit.test.ts | 40 +++++++++++++++++-- test/pregate-remote.test.ts | 12 +++++- test/ship-preflight.test.ts | 20 ++++++++++ 11 files changed, 146 insertions(+), 20 deletions(-) create mode 100644 changelog.d/ship-step-time-limit-and-remote-file-lists.md diff --git a/TODOS.md b/TODOS.md index e47fc855e15..3329db324d6 100644 --- a/TODOS.md +++ b/TODOS.md @@ -46,7 +46,7 @@ ### P2/P3: pregate head-policy follow-ups (filed 2026-10-31, from the GST-419/GST-420 /ship review) - **`finish` fallback drops head-policy lanes (P2)** — `lib/ship-release.ts` reruns pregate on the stamped tree under the base policy, so after a version bump a lane the branch added under `--policy-from head` is gone and `finish` reports `PREGATE: fail (rerun on the stamped tree)`. GSTA-194 owns that file and has the note. **Effort:** S. **Priority:** P2. -- **The 3600 s preflight and `finish` wrapper deadline (P3)** — it caps the whole pregate run, so several runners that each fit `timeout_s` can still be cut off together. Derive the wrapper deadline from `timeout_s` and the lane count, or document the cap. **Effort:** S. **Priority:** P3. +- **The 3600 s `finish` wrapper deadline (P3)** — it caps the whole pregate rerun, so several runners that each fit `timeout_s` can still be cut off together. Derive the wrapper deadline from `timeout_s` and the lane count, or document the cap. Preflight's half is done: `gstack-ship-preflight --step-timeout <s>` sets that budget and a stop prints `PREGATE: time limit hit` (#4429). **Effort:** S. **Priority:** P3. - **A bootstrap head policy can still certify itself without `--remote` (P3)** — with no trusted policy, the head file may set `remote_gate: null`, or produce an obligation that `gstack-pregate clear --receipt` accepts from the branch's own gate. Decide what a bootstrap `pregate.json` may certify, then enforce it in `verify` from the recorded policy label instead of per entry point. The `--remote` refusal also prints the generic `PREGATE_HEAD_POLICY_LOOSENS` fix line, which does not apply when there is no trusted policy. **Effort:** S. **Priority:** P3. ### P3: `/codex --effort` follow-ups (filed 2026-10-11, from the #3146 autoplan review) diff --git a/changelog.d/ship-step-time-limit-and-remote-file-lists.md b/changelog.d/ship-step-time-limit-and-remote-file-lists.md new file mode 100644 index 00000000000..243013fcbe4 --- /dev/null +++ b/changelog.d/ship-step-time-limit-and-remote-file-lists.md @@ -0,0 +1,2 @@ +- **/ship's test step says when it ran out of time, and you can set its budget.** `gstack-ship-preflight` used to stop gstack-pregate after a fixed hour and print `PREGATE: unreadable (exit 143)`, which hid the cause. The whole step's budget is now `--step-timeout <s>` (default 3600 s), and a stop at that limit prints `PREGATE: time limit hit` with the way out: push and let CI's full run carry the tests, or give the step a larger budget. +- **The remote test command no longer puts every file on one command line.** On a small machine with a remote `test_backend`, the command pregate prints for gstack's Ubicloud runner used to carry every selected test file in one argument, which Linux refuses past 128 KiB (`E2BIG`). The files now go to the VM in a setup script, so the command stays short however many files are selected. docs/troubleshooting.md has a new `arg-limit` entry for this kind of failure. diff --git a/docs/pregate.md b/docs/pregate.md index 7abffb24b3d..6a51c6acebd 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -103,7 +103,7 @@ the byte-pinned `/ship` renders in `test/fixtures/golden/`). | `sealed` | sealed or eval output that must never reach a public destination; read by the pre-push hook and `gstack-pregate sealed` (see [sealed output](#sealed)) | | `price_file` | repo-relative path of the paid gate's call-plan data file (`GSTACK_EVAL_CALLS v1`); `gstack-eval-plan price-gate` prices from it and never executes anything ([docs/eval-calls.md](eval-calls.md)) | | `stall_timeout_s` | seconds a test command may print nothing while using under a tenth of one CPU before its process group is killed and the check is `incomplete` (`PREGATE_STALLED`); default 300, `0` disables; `--stall-timeout` overrides; the `--remote` gate is exempt (see [supervision](#supervision)) | -| `timeout_s` | seconds each runner process may take (the unit-file group, each serial file, each guard without its own `timeout_s`, and the remote gate's deadline) when `--timeout` is not passed; 1 to 3600, default 600. `gstack-ship-preflight` forwards its own `--timeout`; without it, and in the `finish` fallback, this is how a repo with long lanes sets theirs | +| `timeout_s` | seconds each runner process may take (the unit-file group, each serial file, each guard without its own `timeout_s`, and the remote gate's deadline) when `--timeout` is not passed; 1 to 3600, default 600. `gstack-ship-preflight` forwards its own `--timeout`; without it, and in the `finish` fallback, this is how a repo with long lanes sets theirs. The whole pregate under `gstack-ship-preflight` has a separate budget, `--step-timeout <s>` (1 to 86400, default 3600): a pregate stopped there prints `PREGATE: time limit hit` and a STOP naming the way out, push and let CI's full run at the tree carry the tests ([CI carry](#ci-carry)), or a larger `--step-timeout` | | `remote_gate` | the repo's remote test gate command; under 8 cores the local test tier becomes a `requires-remote` obligation naming it, and `--remote` runs it (see [remote gate](#remote-gate)) | | `run_profiles` | a map from each profile name to `{ workflow, events, jobs, artifact, max_age_hours?, os?, skippable? }`: the GitHub Actions runs `clear --run` verifies as evidence on the identical tree; a profile named after a lane (`free-tests.yml/macos-named-regressions`) clears that lane (see [run evidence](#run-evidence)). `--from-run` and the reuse job verify runs against them too ([from-run](#from-run), [CI reuse](#ci-reuse)) | | `remote_gate_runs` | `{ profiles, inventory, skipped? }`: the run profiles that together clear `pregate.json/remote_gate`, the command that prints the remote gate's test files, one per line, which their runs must cover, and an optional command that prints which selected files the gate itself never runs (see [run evidence](#run-evidence)) | @@ -563,7 +563,11 @@ test_backend` is not `local`, the lanes check runs nothing locally: it records the selected local files as a `requires-remote` obligation with the command to run, `pregate.json/remote_gate` (the declared command) or `test_backend/<backend>` (gstack's `scripts/ubicloud/ubi-runner.sh run --src -<repo> -- '<runner> <files>'`). Without either, the tier runs locally under +<repo> --setup <file> -- '<runner>'`, where the setup script, kept under +`<state root>/projects/<slug>/pregate/remote-files/` and named by its content, +writes the selected files to `~/.pregate-files.txt` on the VM and the runner +reads them from there; the list never goes on the command line, which reaches +the VM as one argument, see [arg-limit](troubleshooting.md#arg-limit)). Without either, the tier runs locally under the supervision above. Close the obligation one of four ways: - by default, when the base declares `remote_gate_runs`, let CI clear it: the @@ -1000,7 +1004,7 @@ conclusion. On main the free tier's Windows smoke lane is Two narrower Windows lanes are owed only when a branch selects their own test files: `free-tests.yml/cso-windows-launcher` (cleared by a `free-tests.yml` run) and `windows-setup-e2e.yml/windows-setup` (cleared by a -`windows-setup-e2e.yml` run). The six-shard +`windows-setup-e2e.yml` run). The eight-shard `windows-free-tests.yml/windows-free-shard` job is `manual`, so it is never an obligation. A branch cut before `windows-smoke.yml` landed still owes `windows-free-tests.yml/windows-free-shard` @@ -1862,7 +1866,7 @@ failure the branch caused carries `cause: "diff"` (`PREGATE_LANE_FAILED`, | Kind | Evidence | |---|---| | `missing-binary` | exit 127, `command not found`, a spawn `ENOENT`, a runner tool `not on PATH` (dart, flutter, cargo, a package manager, `python3`, or `pytest` when python3 cannot import it), Playwright's browsers not installed | -| `arg-limit` | `E2BIG`, `Argument list too long`: a command line or environment over the system's limit. gstack splits a lane's file list to stay under it, so this is a gstack bug to report | +| `arg-limit` | `E2BIG`, `Argument list too long`: a command line or environment over the system's limit. gstack splits a lane's file list to stay under it, so this is a gstack bug to report ([troubleshooting](troubleshooting.md#arg-limit)) | | `network` | `ENOTFOUND`, `ECONNREFUSED`, `ECONNRESET`, `ETIMEDOUT`, `EAI_AGAIN`, `Could not resolve host`, `fetch failed`, a TLS handshake or certificate failure | | `quota` | `quota`, `429 Too Many Requests`, `rate limit`, `insufficient_quota` (a vCPU quota on the remote backend) | | `disk` | `ENOSPC`, `No space left on device`, `EDQUOT` | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 4c7f040cc3e..8372be81fd8 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -4360,6 +4360,25 @@ or on the comment line directly above it. The marker waives only that line, and the check lists it as `waived:`. Don't use `warn: ["literals"]` for this, since that turns the check off for every constant. +<a id="arg-limit"></a> +### `PREGATE_ENVIRONMENT` with `environment: arg-limit — E2BIG` (or `Argument list too long`) + +**Meaning.** A command gstack started had a command line or environment over +the system's limit, so it never ran and no test was counted. Linux caps one +argument at 128 KiB and a whole command line plus environment at about 2 MiB, +macOS caps the total at 1 MiB, and Windows caps a command line at 32,767 +characters. The usual trigger is a long file list: thousands of selected test +files put into one argument. + +**Fix.** gstack keeps file lists out of single arguments: a local lane splits +its files into runner processes of about 96 KB each (24 KB on Windows), and +the `test_backend` command for the remote gate passes them in a setup script +(docs/pregate.md#remote-gate). So this cause is a gstack bug: report it with +the `environment:` line and the lane or command it names. Until it is fixed, +run the lane remotely (push and let CI's full run carry it, or +`gstack-pregate --remote`), or select fewer files. When the environment, not +the file list, is what's large, unset the big variables before the run. + <a id="pregate-no-lane"></a> ### `PREGATE_NO_LANE` diff --git a/lib/pregate/checks/lanes.ts b/lib/pregate/checks/lanes.ts index 075b1bdb220..ee1a0e7362b 100644 --- a/lib/pregate/checks/lanes.ts +++ b/lib/pregate/checks/lanes.ts @@ -30,7 +30,7 @@ import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { baseInputs, sha256 } from '../context'; +import { baseInputs, defaultScratchRoot, sha256 } from '../context'; import { PREGATE_CONFIG_PATH } from '../config'; import { classifyCommandEnvironment, classifyEnvironment, environmentLine, environmentResult, launchCause } from '../environment'; import { checkScratch } from '../run-scratch'; @@ -498,12 +498,39 @@ const GSTACK_ROOT = path.resolve(import.meta.dir, '..', '..', '..'); */ function remoteObligation(ctx: PregateContext, sel: Selection): RemoteObligation { const declared = ctx.config.remote_gate; - const runner = detectRunner(ctx, sel.gateTests); - const command = declared ?? `${GSTACK_ROOT}/scripts/ubicloud/ubi-runner.sh run --src ${quote(ctx.repoRoot)} -- ${quote(runner ? runner.replace('{files}', testFileArgs(runner, sel.gateTests).map(quote).join(' ')) : '<test runner> <selected files>')}`; + const command = declared ?? backendCommand(ctx, sel.gateTests); const [workflow, job] = declared ? REMOTE_GATE_LANE.split('/') as [string, string] : ['test_backend', ctx.testBackend]; return { lane: `${workflow}/${job}`, platform: 'remote', workflow, job, tests: sel.gateTests, receipt: null, command }; } +/** + * The test backend's command: gstack's Ubicloud runner, with the selected files in a setup script that writes them one per line + * on the VM. The command reaches the VM as one argument and Linux caps one argument at 128 KiB (#4424), so the list never goes in + * it. The script lives under the state root, named by its content, so the same selection prints the same command every run and a + * same-tree clear still matches it; an unwritable state root keeps it in this run's scratch. A path the one-per-line list can't + * hold (a newline, or the list's end marker) keeps the quoted inline form, so no path can end the list early and run as shell. + */ +function backendCommand(ctx: PregateContext, files: readonly string[]): string { + const ubi = `${GSTACK_ROOT}/scripts/ubicloud/ubi-runner.sh run --src ${quote(ctx.repoRoot)}`; + const runner = detectRunner(ctx, files); + if (!runner) return `${ubi} -- ${quote('<test runner> <selected files>')}`; + const args = testFileArgs(runner, files); + if (args.some(f => f.includes('\n') || f === 'PREGATE_FILES')) return `${ubi} -- ${quote(runner.replace('{files}', () => args.map(quote).join(' ')))}`; + const setup = `cat > ~/.pregate-files.txt <<'PREGATE_FILES'\n${args.map(f => `${f}\n`).join('')}PREGATE_FILES\n`; + const name = `${sha256(setup).slice(0, 16)}.sh`; + let file: string; + try { + const dir = path.join(path.dirname(defaultScratchRoot(ctx.repoRoot, ctx.env)), 'remote-files'); + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + file = path.join(dir, name); + fs.writeFileSync(file, setup); + } catch { + file = path.join(checkScratch(ctx.scratch, 'remote'), name); + fs.writeFileSync(file, setup); + } + return `${ubi} --setup ${quote(file)} -- ${quote(`mapfile -t PREGATE_FILES < ~/.pregate-files.txt && ${runner.replace('{files}', () => '"${PREGATE_FILES[@]}"')}`)}`; +} + export const REMOTE_GATE_LANE = 'pregate.json/remote_gate'; /** How many leading lines of a remote gate's output are read for an environment cause: its preamble, before any test output could stream. */ export const REMOTE_PREAMBLE_LINES = 40; diff --git a/lib/ship-bin-common.ts b/lib/ship-bin-common.ts index 94f46da2ec8..4072a073d00 100644 --- a/lib/ship-bin-common.ts +++ b/lib/ship-bin-common.ts @@ -19,9 +19,10 @@ import { ghSpawnSync } from './gh-poll'; import { extractVersion } from './version-source'; import { BIN_DIR, runBashSync, runScriptSync, scriptInvocation } from './script-invocation'; -export interface Run { status: number | null; stdout: string; stderr: string } +/** `timedOut`: the call's own time limit stopped the process (spawnSync's ETIMEDOUT), whatever exit status it then gave. */ +export interface Run { status: number | null; stdout: string; stderr: string; timedOut?: boolean } const done = (r: { status: number | null; stdout?: string | Buffer | null; stderr?: string | Buffer | null; error?: Error }): Run => - ({ status: r.status, stdout: String(r.stdout ?? ''), stderr: String(r.stderr ?? '') + (r.error ? r.error.message : '') }); + ({ status: r.status, stdout: String(r.stdout ?? ''), stderr: String(r.stderr ?? '') + (r.error ? r.error.message : ''), ...((r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT' ? { timedOut: true } : {}) }); export function git(cwd: string, args: string[], timeout = 120_000): Run { return done(spawnSync('git', args, { cwd, encoding: 'utf8', timeout, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } })); diff --git a/lib/ship-preflight.ts b/lib/ship-preflight.ts index d026664779b..beedbd4ffc4 100644 --- a/lib/ship-preflight.ts +++ b/lib/ship-preflight.ts @@ -30,6 +30,8 @@ export const PREFLIGHT_HELP = `gstack-ship-preflight — /ship Steps 1-3 and Ste (a branch that adds the lane for a file it touches); anything else is PREGATE_HEAD_POLICY_LOOSENS --timeout <s> Step 5's pregate --timeout for each runner process, 1 to 3600; unset, the base .gstack/pregate.json timeout_s applies, else 600 s, and a longer lane is PREGATE_INCOMPLETE + --step-timeout <s> the whole Step 5 pregate's budget (every check and lane together), 1 to 86400, default 3600; at the + limit it is stopped and prints PREGATE: time limit hit with the way out (push and let CI's full run carry it) gstack-ship-preflight --tests-only --base <base> --policy-from head --simulate [--allow-repo-commands] --lane <label>=<command>... a dry run that proves a new ship_lanes_from mapping: which lanes the branch's own map would carry from a verified CI run at this tree. Every line starts SIMULATION:; no lane runs, no evidence or ledger row is written and no @@ -195,8 +197,13 @@ function merge(cwd: string, base: string, r: Report): boolean { return true; } -async function tests(cwd: string, base: string, list: { label: string; command: string }[], policyFrom: string, timeout: string | undefined, run: { concurrency: number; line: string }, r: Report): Promise<void> { - const pg = bin(cwd, 'gstack-pregate', ['--allow-repo-commands', '--base', base, '--policy-from', policyFrom, ...(timeout ? ['--timeout', timeout] : [])], 3_600_000); +async function tests(cwd: string, base: string, list: { label: string; command: string }[], policyFrom: string, timeout: string | undefined, step: { seconds: number; source: string }, run: { concurrency: number; line: string }, r: Report): Promise<void> { + const pg = bin(cwd, 'gstack-pregate', ['--allow-repo-commands', '--base', base, '--policy-from', policyFrom, ...(timeout ? ['--timeout', timeout] : [])], step.seconds * 1000); + if (pg.timedOut) { + r.add(`PREGATE: time limit hit (Step 5's whole pregate ran past its ${step.seconds} s budget, ${step.source}, and was stopped with exit ${pg.status ?? 'none'}; no verdict)`); + r.stop(`the tests are longer than this step's ${step.seconds} s budget on this machine: push, let CI's full run at this tree carry them (gstack-ci-carry wait --base ${base}, then rerun --tests-only; gbrain docs/ci-event-parity.md#ship-lanes), or rerun --tests-only with --step-timeout <s> above ${step.seconds}`); + return; + } const refusal = pg.status === 3 ? /\((PREGATE_[A-Z_]+|POLICY_[A-Z_]+)[;)]/.exec(pg.stderr)?.[1] : undefined; const verdict = refusal ? `refused (${refusal})` : /^PREGATE: (.+?) tree=/m.exec(pg.stdout + pg.stderr)?.[1] ?? `unreadable (exit ${pg.status})`; r.add(`PREGATE: ${verdict}`); @@ -263,6 +270,9 @@ export async function preflight(argv: readonly string[], cwd: string): Promise<{ if (!['base', 'head'].includes(policyFrom)) return { text: 'gstack-ship-preflight: --policy-from needs base|head\n', exit: 2 }; const timeout = flag('--timeout'); if (has('--timeout') && !(timeout && /^[1-9]\d*$/.test(timeout) && Number(timeout) <= 3600)) return { text: 'gstack-ship-preflight: --timeout needs whole seconds from 1 to 3600\n', exit: 2 }; + const stepTimeout = flag('--step-timeout'); + if (has('--step-timeout') && !(stepTimeout && /^[1-9]\d*$/.test(stepTimeout) && Number(stepTimeout) <= 86_400)) return { text: 'gstack-ship-preflight: --step-timeout needs whole seconds from 1 to 86400\n', exit: 2 }; + const step = stepTimeout ? { seconds: Number(stepTimeout), source: '--step-timeout' } : { seconds: 3600, source: 'the default; set --step-timeout' }; if (!base || typeof list === 'string') return { text: `gstack-ship-preflight: ${typeof list === 'string' ? list : '--base <base> is required'}\n`, exit: 2 }; const run = flag('--run'); if (has('--run') && !(run && RUN_ID.test(run))) return { text: 'gstack-ship-preflight: --run needs a run id: letters, digits, dot, underscore or dash, at most 128\n', exit: 2 }; @@ -273,7 +283,7 @@ export async function preflight(argv: readonly string[], cwd: string): Promise<{ if (typeof concurrency === 'string') return { text: `gstack-ship-preflight: ${concurrency}\n`, exit: 2 }; const r = new Report(); if (has('--tests-only') || integrate(cwd, base, run, r)) { - if (list.length) await tests(cwd, base, list, policyFrom, timeout, { concurrency, line: `LANES: ${concurrency === 1 ? 'serial' : 'parallel'} (${mode ? '--lanes' : `${os.availableParallelism()} cores`})` }, r); + if (list.length) await tests(cwd, base, list, policyFrom, timeout, step, { concurrency, line: `LANES: ${concurrency === 1 ? 'serial' : 'parallel'} (${mode ? '--lanes' : `${os.availableParallelism()} cores`})` }, r); else if (r.exit === 0) r.next('Step 4: confirm the test framework, then rerun with --tests-only --lane <label>=<command> per suite (Step 5)'); } return { text: r.render(), exit: r.exit }; diff --git a/test/pregate-hidden-folder-paths.test.ts b/test/pregate-hidden-folder-paths.test.ts index 3252a13ae4b..141a5ac06cf 100644 --- a/test/pregate-hidden-folder-paths.test.ts +++ b/test/pregate-hidden-folder-paths.test.ts @@ -73,8 +73,9 @@ describe.skipIf(process.platform === 'win32')('lanes check on a test under a hid const result = await lanes(DETECTED, { [TEST]: GREEN }, [], { cores: 4, testBackend: 'ubicloud' }); expect(result.status).toBe('requires-remote'); const run = result.lines?.find(l => l.startsWith('run: ')) ?? ''; - expect(run).toContain('./.github/scripts/select.test.mjs'); - expect(run).not.toMatch(/'\.github\/scripts/); + const listed = fs.readFileSync(/--setup '([^']+)'/.exec(run)![1]!, 'utf8').split('\n'); + expect(listed).toContain('./.github/scripts/select.test.mjs'); + expect(listed).not.toContain('.github/scripts/select.test.mjs'); }, 120_000); // Value: protects=the lane still runs and judges a hidden-folder test; fails_when=the fix passes the lane without running the test diff --git a/test/pregate-lanes-arg-limit.test.ts b/test/pregate-lanes-arg-limit.test.ts index 2ffb60b547e..b9a63d47406 100644 --- a/test/pregate-lanes-arg-limit.test.ts +++ b/test/pregate-lanes-arg-limit.test.ts @@ -6,6 +6,9 @@ * one test per file argument, so the lane's count proves every file reached a runner. */ import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; import { argBudget, argChunks } from '../lib/pregate/checks/lanes'; import { buildContext } from '../lib/pregate/context'; import { classifyEnvironment } from '../lib/pregate/environment'; @@ -24,18 +27,18 @@ const RUNNER = [ 'process.exit(failed ? 1 : 0);', ].join('\n'); -async function lanesOver(tests: string[]) { +async function pregateOver(tests: string[], machine: { cores: number; testBackend: string }) { const repo = makeFixtureRepo({ pregate: { ...BASE_PREGATE, runner: 'node scripts/count.js {files}', dependencies: { ...BASE_PREGATE.dependencies, 'src/big/**': tests } }, baseFiles: Object.fromEntries([...tests.map(t => [t, "require('node:test');\n"]), ['src/big/.keep', ''], ['scripts/count.js', `${RUNNER}\n`]]), }); repos.push(repo); commit(repo, { 'src/big/f.js': 'exports.n = 1;\n' }, 'touch the big tree'); - const loaded = buildContext({ repoRoot: repo.work, base: 'main', policyFrom: 'base', allowRepoCommands: true, env: { ...process.env, ...repo.env }, progress: () => {}, cores: 64, testBackend: 'local' }); + const loaded = buildContext({ repoRoot: repo.work, base: 'main', policyFrom: 'base', allowRepoCommands: true, env: { ...process.env, ...repo.env }, progress: () => {}, ...machine }); if (!('ctx' in loaded)) throw new Error('fixture context refused'); - const file = await runPregate(loaded.ctx, { stage: 'tests', only: ['lanes'] }); - return file.checks.find(c => c.id === 'lanes')!; + return runPregate(loaded.ctx, { stage: 'tests', only: ['lanes'] }); } +const lanesOver = async (tests: string[]) => (await pregateOver(tests, { cores: 64, testBackend: 'local' })).checks.find(c => c.id === 'lanes')!; describe.skipIf(process.platform === 'win32')('a local lane whose file list is over the per-argument limit', () => { // Value: protects=a unit group whose quoted file list is over Linux's 128 KiB per-argument cap still launches and every file @@ -54,6 +57,35 @@ describe.skipIf(process.platform === 'win32')('a local lane whose file list is o }, 120_000); }); +describe.skipIf(process.platform === 'win32')('the test backend command for a file list over the per-argument limit', () => { + // Value: protects=on a small machine with a remote test_backend, the printed command passes the selected files in a setup + // script, so it stays short and, run the way ubi-runner runs it on the VM (setup, then bash -c <command>), every file reaches + // the runner; fails_when=the files go back into the command, which reaches the VM as one argument (E2BIG on Linux); + // why_new=the remote-gate half of #4424; seam=runPregate --only lanes, the setup file, bash; no_claim=ubi-runner's transport + test('the files travel in the setup script, the command stays short, and running both reaches every file', async () => { + const tests = Array.from({ length: FILES }, (_, i) => name(i)); + const quoted = tests.map(t => `'${t}'`).join(' '); + expect(quoted.length).toBeGreaterThan(128 * 1024); + if (process.platform === 'linux') expect((spawnSync('bash', ['-c', `true ${quoted}`], { timeout: 30_000 }).error as NodeJS.ErrnoException | undefined)?.code).toBe('E2BIG'); + const file = await pregateOver(tests, { cores: 4, testBackend: 'ubicloud' }); + expect(file.checks.find(c => c.id === 'lanes')!.status).toBe('requires-remote'); + const command = file.requires_remote!.find(o => o.lane === 'test_backend/ubicloud')!.command!; + expect(command.length).toBeLessThan(2048); + const argv = spawnSync('bash', ['-c', 'eval "set -- $1"; printf "%s\\0" "$@"', '_', command], { encoding: 'utf8', timeout: 30_000 }).stdout.split('\0').slice(0, -1); + expect(argv.slice(1, 3)).toEqual(['run', '--src']); + expect(argv[4]).toBe('--setup'); + expect(argv[6]).toBe('--'); + const setup = fs.readFileSync(argv[5]!, 'utf8'); + expect(setup.split('\n').filter(l => l.startsWith('test/big/'))).toEqual(tests); + const vm = repos.at(-1)!; + const env = { ...process.env, HOME: fs.mkdtempSync(path.join(vm.root, 'vm-home-')) }; + expect(spawnSync('bash', [argv[5]!], { cwd: vm.work, env, timeout: 30_000 }).status).toBe(0); + const ran = spawnSync('bash', ['-c', argv[7]!], { cwd: vm.work, env, encoding: 'utf8', timeout: 60_000 }); + expect(ran.stdout).toContain(`ℹ tests ${FILES}\n`); + expect(ran.status).toBe(0); + }, 120_000); +}); + describe('argChunks and argBudget', () => { // Value: protects=the split keeps order, drops nothing and keeps each chunk's quoted text under the budget, with an oversized // argument alone in its chunk, and the budget stays under Linux's per-argument cap and shrinks with the environment; diff --git a/test/pregate-remote.test.ts b/test/pregate-remote.test.ts index 48e7d092c5e..67cd216f39d 100644 --- a/test/pregate-remote.test.ts +++ b/test/pregate-remote.test.ts @@ -68,11 +68,21 @@ describe('small machines record the test tier for the remote gate (C4)', () => { expect(viaBackend.lanes.status).toBe('requires-remote'); const obligation = viaBackend.file.requires_remote![0]!; expect(obligation.lane).toBe('test_backend/ubicloud'); - expect(obligation.command).toMatch(/scripts\/ubicloud\/ubi-runner\.sh run --src '.*\/work' -- 'node --test '\\''test\/util\.test\.js'\\'''$/); + expect(obligation.command).toMatch(/scripts\/ubicloud\/ubi-runner\.sh run --src '.*\/work' --setup '(.*\/remote-files\/[0-9a-f]{16}\.sh)' -- 'mapfile -t PREGATE_FILES < ~\/\.pregate-files\.txt && node --test "\$\{PREGATE_FILES\[@\]\}"'$/); + expect(fs.readFileSync(/--setup '([^']+)'/.exec(obligation.command!)![1]!, 'utf8')).toBe("cat > ~/.pregate-files.txt <<'PREGATE_FILES'\ntest/util.test.js\nPREGATE_FILES\n"); expect((await lanesOn(backend, { cores: 4, testBackend: 'local' })).lanes.status).toBe('pass'); expect((await lanesOn(gated(), { cores: 16, testBackend: 'local' })).lanes.status).toBe('pass'); }); + test.skipIf(process.platform === 'win32')('a selected test path the file list cannot hold (a newline) keeps the quoted inline command, so it cannot end the list and run as shell', async () => { + const backend = gated(BASE_PREGATE); + const odd = 'test/odd\nPREGATE_FILES\nname.test.js'; + commit(backend, { [odd]: "require('node:test')('ok', () => {});\n" }); + const command = (await lanesOn(backend, { cores: 4, testBackend: 'ubicloud' })).file.requires_remote![0]!.command!; + expect(command).not.toContain('--setup'); + expect(command).toContain(odd); + }); + test('`clear` on the remote_gate obligation needs the gate\'s PREGATE_REMOTE receipt for the tested tree; a run URL or a bad receipt leaves it uncleared', async () => { const repo = gated(); const fileAt = path.join(repo.work, '.gstack/tmp/pregate.json'); diff --git a/test/ship-preflight.test.ts b/test/ship-preflight.test.ts index 6c7741dca5d..5ff7850cf5a 100644 --- a/test/ship-preflight.test.ts +++ b/test/ship-preflight.test.ts @@ -412,6 +412,26 @@ describe('gstack-ship-preflight Step 5 pregate: head policy and timeout_s (GST-4 expect(u.stdout + u.stderr).toContain('--timeout needs whole seconds from 1 to 3600'); } }); + + // Value: protects=a caller sets the whole Step 5 pregate's budget, and a kill at that limit says the limit was hit and names the + // way out instead of "unreadable (exit 143)"; fails_when=the budget is a fixed hour, or a timed-out pregate reads as unreadable; + // why_new=Vorflux via FOUN-32: gbrain's unit and serial suite ran past the fixed hour on 8-core Linux; seam=gstack-pregate under + // preflight's spawn limit; no_claim=the finish fallback's own pregate limit + test('--step-timeout bounds the whole Step 5 pregate, and a kill at the limit says so with the way out', () => { + const slow = "const test = require('node:test');\ntest('slow', async () => { await new Promise(r => setTimeout(r, 30000)); });\n"; + const f = fx(base({ timeout_s: 600 }), { 'test/slow.serial.test.js': slow }); + const r = f.run(PREFLIGHT, ['--tests-only', '--base', 'main', '--step-timeout', '3', '--lane', LANE]); + expect(r.status).toBe(3); + expect(lineOf(r.stdout, 'PREGATE')).toMatch(/^PREGATE: time limit hit \(Step 5's whole pregate ran past its 3 s budget, --step-timeout, and was stopped with exit \S+; no verdict\)$/); + expect(lineOf(r.stdout, 'STOP')).toBe("STOP: the tests are longer than this step's 3 s budget on this machine: push, let CI's full run at this tree carry them (gstack-ci-carry wait --base main, then rerun --tests-only; gbrain docs/ci-event-parity.md#ship-lanes), or rerun --tests-only with --step-timeout <s> above 3"); + expect(r.stdout).not.toContain('unreadable'); + expect(r.stdout).not.toContain('LANE: tests'); + for (const bad of ['0', '86401', '1.5', 'x']) { + const u = f.run(PREFLIGHT, ['--tests-only', '--base', 'main', '--step-timeout', bad, '--lane', LANE]); + expect(u.status).toBe(2); + expect(u.stdout + u.stderr).toContain('--step-timeout needs whole seconds from 1 to 86400'); + } + }); }); describe('gstack-ship-preflight during an open /ship run (GST-1204)', () => { From c53b15c48d511d7f284f1a1b36fb81ea60742f88 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 21:14:33 +0800 Subject: [PATCH 33/62] Open pull requests with three plain lines and land each one as a single commit (GST-2737) (#4438) * WIP plain PR bodies and squash messages Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Fold PR bodies to three plain lines and land every PR as one plainly titled commit Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Expect the plain commit body in the train land tests Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Count the new policy keys in the floor tests and record the ship size change Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Let older, generated and Dependabot PRs pass the body check, and keep comments posting The opening check now follows the same date and branch exemption as the rest of the body check, Dependabot branches are exempt, the exemption only counts for branches in this repository, a merge that cannot read the PR waits instead of refusing, and a broken policy file no longer stops comments. Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/specialist-batched#2 reader=testing Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/red-team#4 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Stop re-posted PR bodies from duplicating sections, and let file names through the word check Posting an already-folded body now replaces each section once instead of keeping the old copy beside it, and listed words inside file paths or file names, such as a test file in the Tests section, no longer count as prose. Review-Finding: v2/outside-voice#3 reader=outside-voice Review-Finding: v2/adversarial-native#2 reader=adversarial-native Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Describe the folded three-line PR body in the skills guide and the prose lint help Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .github/workflows/plain-title.yml | 26 ++- .gstack/plain-titles.json | 11 +- README.md | 2 +- bin/gstack-doctor-components.sh | 1 + bin/gstack-plain-title | 23 ++- bin/gstack-ship-policy | 16 +- bin/gstack-ship-queue | 31 +++- changelog.d/plain-pr-bodies.md | 4 + crew/lib/ship-queue-train-land.ts | 21 ++- crew/test/ship-queue-train-generic.test.ts | 2 +- crew/test/ship-queue-train-land.test.ts | 2 +- docs/ship-policy.md | 28 +++- docs/skills.md | 4 +- docs/troubleshooting.md | 10 +- docs/writing-prs.md | 122 ++++++++++++++ lib/gstack-post.ts | 74 +++++++-- lib/land-merged-checks.ts | 11 +- lib/plain-title.ts | 29 ++-- lib/pr-body-shape.ts | 143 ++++++++++++++++ lib/release-stamp.ts | 31 +++- lib/result-codes-plain.ts | 9 +- lib/ship-policy-keys.ts | 3 + lib/ship-policy.ts | 19 ++- lib/ship-queue-land-direct.ts | 18 +- lib/ship-queue-land.ts | 20 ++- lib/squash-message.ts | 90 ++++++++++ ship/sections/capy-pr.md | 10 +- ship/sections/capy-pr.md.tmpl | 10 +- ship/sections/pr-body.md | 45 ++--- ship/sections/pr-body.md.tmpl | 45 ++--- test/docsync-report-interface.test.ts | 2 +- test/gate-integrity-templates.test.ts | 2 +- test/gstack-post.test.ts | 154 ++++++++++++++---- test/gstack-ship-policy.test.ts | 29 +++- test/helpers/docsync-observer.ts | 2 +- test/plain-title.test.ts | 47 +++++- test/policy-floor-stable.test.ts | 4 +- test/pr-body-shape.test.ts | 92 +++++++++++ test/prose-lint.test.ts | 6 +- test/release-stamp.test.ts | 7 + test/ship-publication-gates.test.ts | 17 +- test/ship-queue-land-direct.test.ts | 40 ++++- test/ship-queue-land.test.ts | 3 +- test/ship-receipt-depth.test.ts | 4 +- test/ship-workflow-clarity.test.ts | 2 +- .../ship/gst-2737-plain-pr-bodies.json | 4 + test/squash-message.test.ts | 115 +++++++++++++ 47 files changed, 1182 insertions(+), 208 deletions(-) create mode 100644 changelog.d/plain-pr-bodies.md create mode 100644 docs/writing-prs.md create mode 100644 lib/pr-body-shape.ts create mode 100644 lib/squash-message.ts create mode 100644 test/pr-body-shape.test.ts create mode 100644 test/size-ledger/ship/gst-2737-plain-pr-bodies.json create mode 100644 test/squash-message.test.ts diff --git a/.github/workflows/plain-title.yml b/.github/workflows/plain-title.yml index 8736d39c022..6487a52fe81 100644 --- a/.github/workflows/plain-title.yml +++ b/.github/workflows/plain-title.yml @@ -3,7 +3,8 @@ name: Plain title # Checks that a PR's title reads in everyday words (R76, docs/ship-policy.md#plain-titles). # The title is refused in the front: tracker codes, project-only words and a # type(scope): prefix. One trailing group of references like (ABC-123) or (#4122) -# is fine. The branch name, the PR opening and the commit subjects only warn. +# is fine. The body is refused when it breaks the plain shape (docs/writing-prs.md); +# the branch name and the commit subjects only warn. # PRs created before the policy's since date are exempt. # # WHY pull_request_target: it runs the base repository's copy of this workflow, @@ -77,13 +78,32 @@ jobs: bun --no-env-file --config=/dev/null bin/gstack-plain-title check \ --title-file "$RUNNER_TEMP/pr-title.txt" --created-at "$PR_CREATED_AT" --mode refuse - - name: Check the branch name, opening and commit subjects (warnings only) + # The body: its opening, at most three lines before the first fold, and no + # listed word above the Agent notes fold (docs/writing-prs.md). A PR created + # before the policy's body_since date, or from a generated branch the policy + # exempts (release notes repeat CHANGELOG text), only gets warnings. Only a + # branch in this repository counts as exempt: a fork names its own branches. + - name: Check the body if: ${{ !cancelled() }} env: PR_BRANCH: ${{ github.event.pull_request.head.ref }} + PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} PR_CREATED_AT: ${{ github.event.pull_request.created_at }} run: | set -euo pipefail + exempt_branch="" + if [ "$PR_HEAD_REPO" = "$GITHUB_REPOSITORY" ]; then exempt_branch="$PR_BRANCH"; fi bun --no-env-file --config=/dev/null bin/gstack-plain-title check \ - --branch "$PR_BRANCH" --body-file "$RUNNER_TEMP/pr-body.txt" \ + --body-file "$RUNNER_TEMP/pr-body.txt" --head-branch "$exempt_branch" \ + --created-at "$PR_CREATED_AT" --mode refuse + + - name: Check the branch name and commit subjects (warnings only) + if: ${{ !cancelled() }} + env: + PR_BRANCH: ${{ github.event.pull_request.head.ref }} + PR_CREATED_AT: ${{ github.event.pull_request.created_at }} + run: | + set -euo pipefail + bun --no-env-file --config=/dev/null bin/gstack-plain-title check \ + --branch "$PR_BRANCH" \ --commits-file "$RUNNER_TEMP/pr-commits.txt" --created-at "$PR_CREATED_AT" --mode warn diff --git a/.gstack/plain-titles.json b/.gstack/plain-titles.json index 05a4746b1ac..71d9799495c 100644 --- a/.gstack/plain-titles.json +++ b/.gstack/plain-titles.json @@ -23,7 +23,12 @@ "no-stop", "GStack Minder", "Capy Workflow Improver", - "Captain" + "Captain", + "Captains", + "crew", + "crews", + "lander", + "landers" ], "allow": [ { @@ -32,9 +37,11 @@ } ], "since": "2026-11-08", + "body_since": "2026-11-18", "exempt_branch_prefixes": [ "release/", "wave/", - "gstack-land-repair/" + "gstack-land-repair/", + "dependabot/" ] } diff --git a/README.md b/README.md index 11ebe35ed80..9935ca7cdcd 100644 --- a/README.md +++ b/README.md @@ -167,7 +167,7 @@ Each skill feeds into the next. `/office-hours` writes a design doc that `/plan- | `/qa-only` | **QA Reporter** | Explore and report with replayable evidence. Suggest regression cases without changing product code or tests. | | `/pair-agent` | **Multi-Agent Coordinator** | Share gstack's own browser with any AI agent. One command, one paste, connected. Works with OpenClaw, Hermes, Codex, Cursor, or anything that can curl. Each agent gets its own tab. Auto-launches headed mode so you watch everything. Auto-starts ngrok tunnel for remote agents. Scoped tokens, tab isolation, rate limiting, activity attribution. (Runs on the bundled browser — the fallback engine; agents driving Aside just open their own tabs.) | | `/cso` | **Chief Security Officer** | Security audit with an application model, supported findings, independent challenge, and explicit coverage. Static assessment remains available without catalog profiles. With matching qualified profiles, comprehensive mode adds contained runtime/scanner execution and reviewable repair candidates for Node/Bun, Python, and Rails. Qualified runtime and scanner images are published for linux/amd64 and linux/arm64. Without Docker, audits run static assessment only. Runtime-tested bundles authenticate separate external assertions. Project-test completion remains `self_reported` because target code controls the test process; `tested` is reserved for a future target-independent completion witness. | -| `/ship` | **Release Engineer** | Sync main, run tests, explore changed behavior, audit coverage, gate integrity and docs, then verify, push and open a PR. | +| `/ship` | **Release Engineer** | Sync main, run tests, explore changed behavior, audit coverage, gate integrity and docs, then verify, push and open a PR whose body opens with three plain lines ([how gstack writes PRs and commits](docs/writing-prs.md)). | | `/land-and-deploy` | **Release Engineer** | Merge the PR, wait for CI and deploy, verify production health. One command from "approved" to "verified in production." | | `/modernize` | **Stale-PR Maintainer** | Bring an aging PR onto its current base and say whether it should still exist: MODERNIZE (rebase, `git range-diff` proof, push with a lease pinned to the observed head), REWORK (the problem stands, the diff does not) or CLOSE (recommended, never done without permission). Reads the base's moved range for conflicts in meaning, not only in text. | | `/canary` | **SRE** | Post-deploy monitoring loop. Watches for console errors, performance regressions, and page failures. | diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index e65205dc075..2b5bb7d3251 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -440,6 +440,7 @@ gstack_result_anchor() { PLAIN_TITLE_REFUSED) printf '%s' 'plain-title-refused' ;; PLAIN_BRANCH_REFUSED) printf '%s' 'plain-branch-refused' ;; PLAIN_OPENING_REFUSED) printf '%s' 'plain-opening-refused' ;; + PLAIN_BODY_REFUSED) printf '%s' 'plain-body-refused' ;; PLAIN_CHANGELOG_REFUSED) printf '%s' 'plain-changelog-refused' ;; PLAIN_COMMIT_REFUSED) printf '%s' 'plain-commit-refused' ;; PLAIN_POLICY_INVALID) printf '%s' 'plain-policy-invalid' ;; diff --git a/bin/gstack-plain-title b/bin/gstack-plain-title index bdbe0dbfe00..655c4d4a5b0 100755 --- a/bin/gstack-plain-title +++ b/bin/gstack-plain-title @@ -10,15 +10,20 @@ import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import { bodyFindingLine, checkBodyShape, foldSections, type BodyFinding } from '../lib/pr-body-shape'; import { PLAIN_TITLE_POLICY_PATH, checkBranch, checkChangelogEntry, checkCommitSubject, checkOpening, checkTitle, loadPlainTitlePolicy, type PlainFinding, type PlainTitlePolicy } from '../lib/plain-title'; import { resultLine } from '../lib/result-codes'; const HELP = `gstack-plain-title — check that titles, branch names, PR openings and changelog entries read in plain words (docs/ship-policy.md#plain-titles) - check [--title <t> | --title-file <f>] [--branch <b>] [--body-file <f>] [--changelog <f>] + check [--title <t> | --title-file <f>] [--branch <b>] [--body-file <f> [--head-branch <b>]] [--changelog <f>] [--commits-file <f>] [--created-at <iso>] [--mode refuse|warn] [--json] check each input against ${PLAIN_TITLE_POLICY_PATH}; --commits-file holds one commit - subject per line and only ever warns; a PR created before the policy's since date is exempt + subject per line and only ever warns; a PR created before the policy's since date is exempt; + --body-file also checks the body's shape once folded (docs/writing-prs.md: at most 3 lines + and 600 characters before the first fold, listed words below the Agent notes fold), printed as + PLAIN_BODY: lines, which only warn for a PR created before the policy's body_since date or + whose --head-branch starts with one of its exempt_branch_prefixes (a generated release PR) validate check ${PLAIN_TITLE_POLICY_PATH} against its schema init [--force] write an example ${PLAIN_TITLE_POLICY_PATH} @@ -34,7 +39,7 @@ const EXAMPLE = { exempt_branch_prefixes: ['release/'], }; -const VALUE_FLAGS = ['--title', '--title-file', '--branch', '--body-file', '--changelog', '--commits-file', '--created-at', '--mode']; +const VALUE_FLAGS = ['--head-branch', '--title', '--title-file', '--branch', '--body-file', '--changelog', '--commits-file', '--created-at', '--mode']; function usage(message: string): number { process.stderr.write(`gstack-plain-title: ${message}\n${HELP}\n`); @@ -80,7 +85,7 @@ function check(args: string[]): number { const policy = loadPolicy(repoRoot(), 'gstack-plain-title check'); if (policy === 'invalid') return 3; - const done = (status: string, findings: Array<PlainFinding & { severity: string }> = []) => { + const done = (status: string, findings: Array<(PlainFinding | BodyFinding) & { severity: string }> = []) => { const refused = findings.filter(f => f.severity === 'refused').length; process.stdout.write(json ? JSON.stringify({ status, refused, warned: findings.length - refused, findings }) + '\n' : `PLAIN_TITLE: ${status}\n`); return refused ? 1 : 0; @@ -90,16 +95,22 @@ function check(args: string[]): number { const title = opts['--title'] ?? read['--title-file']?.replace(/\r?\n+$/, ''); const severity = mode === 'warn' ? 'warned' : 'refused'; - const findings = [ + const older = (createdAt !== undefined && Date.parse(createdAt) < Date.parse(policy.body_since)) || policy.exempt_branch_prefixes.some(p => (opts['--head-branch'] ?? '').startsWith(p)); + const findings: Array<(PlainFinding | BodyFinding) & { severity: string }> = [ ...(title !== undefined ? checkTitle(title, policy) : []), ...(opts['--branch'] !== undefined ? checkBranch(opts['--branch'], policy) : []), - ...(read['--body-file'] !== undefined ? checkOpening(read['--body-file'], policy) : []), ...(read['--changelog'] !== undefined ? checkChangelogEntry(read['--changelog'], policy) : []), ].map(f => ({ ...f, severity })); + if (read['--body-file'] !== undefined) findings.push(...checkOpening(read['--body-file'], policy).map(f => ({ ...f, severity: older ? 'warned' : severity }))); for (const line of (read['--commits-file'] ?? '').split(/\r?\n/)) { if (line.trim()) findings.push(...checkCommitSubject(line, policy).map(f => ({ ...f, severity: 'warned' }))); } if (!json) for (const f of findings) process.stdout.write(`PLAIN_TITLE: ${f.code} ${f.kind} "${clean(f.match)}" — ${f.hint}${f.severity === 'warned' ? ' (warning only)' : ''}\n`); + if (read['--body-file'] !== undefined) { + const shape = checkBodyShape(foldSections(read['--body-file']), policy.terms); + if (!json) for (const f of shape) process.stdout.write(bodyFindingLine(f, older || severity === 'warned') + '\n'); + findings.push(...shape.map(f => ({ ...f, severity: older ? 'warned' : severity }))); + } const refused = findings.filter(f => f.severity === 'refused').length; const warned = findings.length - refused; return done(refused ? `refused=${refused}${warned ? ` warned=${warned}` : ''}` : warned ? `warned=${warned}` : 'ok', findings); diff --git a/bin/gstack-ship-policy b/bin/gstack-ship-policy index 41d56846ff1..aa39e97dd5c 100755 --- a/bin/gstack-ship-policy +++ b/bin/gstack-ship-policy @@ -122,21 +122,25 @@ function main(argv: string[]): number { const result: Record<string, unknown> = { history: policy, branch: branch || null, plan }; let verdict: string; let code = EXIT.ok; - if (policy !== 'merge-only') verdict = `HISTORY: squash-ok (no check; policy history=${policy}; plan=${plan})`; - else if (plan !== 'merge') { + if (policy === 'squash-ok') verdict = `HISTORY: squash-ok (no check; policy history=${policy}; plan=${plan})`; + else if (policy === 'no-rewrite' && plan === 'rebase') { + verdict = 'HISTORY: refused (plan=rebase rewrites the branch; policy history=no-rewrite keeps every pushed commit reachable until land squashes the PR into one commit) — fix: merge origin/<base> into the branch instead (HISTORY_POLICY_VIOLATION)'; + code = EXIT.refused; + } + else if (policy === 'merge-only' && plan !== 'merge') { verdict = `HISTORY: refused (plan=${plan} rewrites history; policy history=merge-only keeps every reviewed commit reachable so gate evidence and preregistration ancestry stay bound to the shas that were gated) — fix: integrate with a merge commit, or set history: squash-ok in .gstack/ship-policy.json on the base branch (HISTORY_POLICY_VIOLATION)`; code = EXIT.refused; } - else if (!branch) { verdict = 'HISTORY: merge-only (detached HEAD; no pushed branch to compare)'; } + else if (!branch) { verdict = `HISTORY: ${policy} (detached HEAD; no pushed branch to compare)`; } else { const remote = spawnSync('git', ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`], { cwd: root, encoding: 'utf8', timeout: 15_000 }); - if (remote.status !== 0) verdict = `HISTORY: merge-only (origin/${branch} not pushed yet; nothing to rewrite)`; + if (remote.status !== 0) verdict = `HISTORY: ${policy} (origin/${branch} not pushed yet; nothing to rewrite)`; else { const anc = spawnSync('git', ['merge-base', '--is-ancestor', remote.stdout.trim(), 'HEAD'], { cwd: root, timeout: 15_000 }); result.remote = remote.stdout.trim(); - if (anc.status === 0) verdict = `HISTORY: ok (merge-only; origin/${branch} is an ancestor of HEAD)`; + if (anc.status === 0) verdict = `HISTORY: ok (${policy}; origin/${branch} is an ancestor of HEAD)`; else { - verdict = `HISTORY: rewritten (origin/${branch} ${remote.stdout.trim().slice(0, 12)} is not an ancestor of HEAD) — fix: ${'merge origin/<base> instead of rebasing or squashing; never force-push under history: merge-only'} (HISTORY_POLICY_VIOLATION)`; + verdict = `HISTORY: rewritten (origin/${branch} ${remote.stdout.trim().slice(0, 12)} is not an ancestor of HEAD) — fix: ${`merge origin/<base> instead of rebasing or squashing; never force-push under history: ${policy}`} (HISTORY_POLICY_VIOLATION)`; code = EXIT.fail; } } diff --git a/bin/gstack-ship-queue b/bin/gstack-ship-queue index 3da9e6ce931..b8bcd618063 100755 --- a/bin/gstack-ship-queue +++ b/bin/gstack-ship-queue @@ -32,6 +32,7 @@ * (loaded only on the train paths). */ import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; import * as path from 'node:path'; import { ghSpawnSync } from '../lib/gh-poll'; import { EXIT, exitTableHelp, formatResult } from '../lib/headless-artifacts'; @@ -66,7 +67,7 @@ const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (doc verify --pr <n> --screen (train policy) the PR head's screen verdict read from its run (SCREEN_VERDICT) verify --post-merge <sha> [--timeout <s>] wait for every check run at a merged commit to settle: POST_MERGE: green|red|pending and one CHECK: line per workflow; resumable, default timeout 2700 s - land --pr <n> --pin <sha> [--accept-gate-disposition <id>]... [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] + land --pr <n> --pin <sha> [--accept-gate-disposition <id>]... [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] [--body-file <f>] merge: direct: merge the PR at its own green head (receipt and READY at the pin, no stamp files, checks green, mergeable clean), verify the tree, write a land note; a stale base runs land.merged_checks, repo commands, only with --allow-repo-commands (never --dry-run); @@ -74,9 +75,12 @@ const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (doc --repair: while frozen, land the one repair PR the freeze admits (recorded under the lock); an owner gate disposition the approval store applies at the pin merges only when the lander passes --accept-gate-disposition <its approval id> (docs/ship-policy.md#gate-dispositions) - land --pr <n> [--dry-run] [--no-wait] [--timeout <min>] [--break-lock [--break-train-lock]] [--allow-repo-commands] + land --pr <n> [--dry-run] [--no-wait] [--timeout <min>] [--break-lock [--break-train-lock]] [--allow-repo-commands] [--body-file <f>] the merge step: lock, merge the base, stamp (fragments folded), push the stamp commit, wait for its checks, squash with --match-head-commit, confirm the base tree; resumable + Both forms merge as one commit titled "<PR title> (#n)" whose body is the PR body's opening + lines (at most 3) plus the branch's trailers; --body-file replaces the opening lines; METHOD, + SUBJECT and BODY lines show it first (docs/writing-prs.md#the-commit-on-main) land --pr <n> --repair after QUEUE_LAND_DRIFT: open the PR that gives the merge outside land its own release; /ship and land it, which releases the lock land --census what land would do with every open PR (read-only) @@ -90,6 +94,12 @@ const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (doc refs/notes/gstack-land lock), ready under changelog_fragments (its READY receipt note) and merge trains. ${exitTableHelp()}`; +/** land --body-file: the plain lines that replace the PR body's opening in the merge commit; land scans them like the rest of the message. */ +function landBody(file: string | undefined): { text?: string } | { error: string } { + if (file === undefined) return {}; + try { return { text: fs.readFileSync(path.resolve(file), 'utf8') }; } catch (e) { return { error: `cannot read --body-file ${file}: ${(e as NodeJS.ErrnoException).code ?? String(e)}` }; } +} + function flag(args: string[], name: string): string | undefined { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; @@ -173,10 +183,19 @@ function gateAhead(ctx: QueueContext, args: string[]): number { }); } +/** Which land form this checkout's base policy takes, so a lander never guesses between the two. */ +function landFormLine(repoRoot: string): string { + const loaded = loadBasePolicy({ repoRoot, base: resolveBaseBranch(repoRoot), gh: () => ({ ok: false, out: '', err: 'no gh in --help' }) }); + if ('message' in loaded) return ''; + return loaded.policy.merge === 'direct' + ? `\nThis repository (merge: direct): land each READY PR with gstack-ship-queue land --pr <n> --pin <the READY's head sha>.\n` + : `\nThis repository (merge: ${loaded.policy.merge}): land with gstack-ship-queue land --pr <n>${loaded.policy.train ? ', or train land for a built train' : ''}; --pin is the merge: direct form.\n`; +} + async function main(argv: string[]): Promise<number> { const [cmd, ...args] = argv; - if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; } const probe = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 }); + if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n' + (probe.status === 0 ? landFormLine(probe.stdout.trim()) : '')); return cmd ? EXIT.ok : EXIT.usage; } if (probe.status !== 0) return usage('not inside a git repository'); const repoRoot = probe.stdout.trim(); const gh = (a: string[]) => { const r = ghSpawnSync(a, { cwd: repoRoot, encoding: 'utf8', timeout: 60_000 }); return { ok: r.status === 0, out: r.stdout ?? '', err: r.stderr ?? (r.error ? String(r.error.message) : '') }; }; @@ -196,15 +215,17 @@ async function main(argv: string[]): Promise<number> { const l = await import('../lib/ship-queue-land'); if (args.includes('--census')) return finish('land', l.census(ctx)); if (!pr || !/^\d+$/.test(pr)) return usage('land needs --pr <number> (or --census)'); + const body = landBody(flag(args, '--body-file')); + if ('error' in body) return usage(body.error); if (args.includes('--pin')) { const pin = flag(args, '--pin') ?? ''; if (!/^[0-9a-f]{40,64}$/.test(pin)) return usage('--pin needs the full head sha the READY names'); const accept = acceptedIds(args); if (accept.bad !== undefined) return usage(`--accept-gate-disposition needs an approval id (a-<12 hex>), not ${JSON.stringify(accept.bad)}`); - return finish('land', (await import('../lib/ship-queue-land-direct')).landDirect(ctx, { pr, pin, acceptGateDispositions: accept.ids, dryRun: args.includes('--dry-run'), allowRepoCommands: args.includes('--allow-repo-commands'), breakLock: args.includes('--break-lock'), repair: args.includes('--repair') })); + return finish('land', (await import('../lib/ship-queue-land-direct')).landDirect(ctx, { pr, pin, body: body.text, acceptGateDispositions: accept.ids, dryRun: args.includes('--dry-run'), allowRepoCommands: args.includes('--allow-repo-commands'), breakLock: args.includes('--break-lock'), repair: args.includes('--repair') })); } const timeout = flag(args, '--timeout'); - return finish('land', l.land(ctx, { pr, repair: args.includes('--repair'), dryRun: args.includes('--dry-run'), noWait: args.includes('--no-wait'), breakLock: args.includes('--break-lock'), breakTrainLock: args.includes('--break-train-lock'), allowRepoCommands: args.includes('--allow-repo-commands'), waitTimeoutMin: timeout && /^\d+$/.test(timeout) ? Number(timeout) : undefined })); + return finish('land', l.land(ctx, { pr, body: body.text, repair: args.includes('--repair'), dryRun: args.includes('--dry-run'), noWait: args.includes('--no-wait'), breakLock: args.includes('--break-lock'), breakTrainLock: args.includes('--break-train-lock'), allowRepoCommands: args.includes('--allow-repo-commands'), waitTimeoutMin: timeout && /^\d+$/.test(timeout) ? Number(timeout) : undefined })); } if (!pr || !/^\d+$/.test(pr)) return usage(`${cmd} needs --pr <number>`); const gateExit = flag(args, '--gate-exit'); diff --git a/changelog.d/plain-pr-bodies.md b/changelog.d/plain-pr-bodies.md new file mode 100644 index 00000000000..a73331f9f50 --- /dev/null +++ b/changelog.d/plain-pr-bodies.md @@ -0,0 +1,4 @@ +--- +bump: minor +--- +- **Pull requests from /ship now open with at most three plain lines, and every merge lands as one commit titled with the PR title.** /ship writes `## ` sections and `gstack-post` folds each into a collapsed section when it posts, so a reader sees what changed, why, and what they have to do, with the rest one click away and the Agent notes section last. `gstack-post fold --body-file F` shows the folded body without posting it. In a repository with `.gstack/plain-titles.json`, `gstack-post` and the Plain title check refuse a body that shows more than three lines (or 600 characters) before its first fold, or uses a listed in-house word above the Agent notes section (`PLAIN_BODY_REFUSED`); gstack now ships a default word list (outside voice, pregate, receipt, carry, stamp, train, lane, soak and more), which a policy extends or replaces with `replace_default_terms`, and `body_since` keeps PRs opened before that date to warnings. Every `gstack-ship-queue land` form now passes the subject `<title> (#n)` and a body of the PR's opening lines plus the branch's `Co-authored-by:` and other trailers, so GitHub no longer writes its commit list; `--dry-run` prints it and `--body-file` replaces the opening. Release PRs list one plain line per change with its PR. Two new policy settings: `history: no-rewrite` (squash landings, never a rebased or force-pushed branch) and `land.merge_commit_paths` (keep a merge commit for PRs that change those paths, such as eval results). See docs/writing-prs.md. diff --git a/crew/lib/ship-queue-train-land.ts b/crew/lib/ship-queue-train-land.ts index 94d2a99ed83..f5dc11afa3d 100644 --- a/crew/lib/ship-queue-train-land.ts +++ b/crew/lib/ship-queue-train-land.ts @@ -35,6 +35,7 @@ import { verifyPostMerge } from './ship-queue-post-merge'; import { bindTrainReceipt } from './ship-queue-train-gate'; import { checkRun, prInfo, type PrInfo } from './ship-queue-train-github'; import { landPlan } from '../../lib/plan-record'; +import { landMessage, mergeArgs, messageLines } from '../../lib/squash-message'; import { TERMINAL_STATES, activeFreeze, attemptsOf, freezeLockCleared, loadReady, nowIso, trainFile, type LandingRecord, type TrainRecord } from './ship-queue-train-record'; import { fetchBase, fetchTrainBranch, findTrain, frozenLines, nextFor, outFailed, outPending, outRefused, save, trainEnv, type TrainEnv, type TrainOut } from './ship-queue-train'; import { confirmMerged, stopped } from './ship-queue-train-verify'; @@ -133,7 +134,7 @@ function chooseMode(ctx: QueueContext, s: Slot, mainSha: string, conditional: bo return { mode: 'update', why: `the pin's own checks are not green (${ci.line}${missing.length ? `; missing ${missing.join(', ')}` : ''}); they ran against an older base` }; } -/** Merge with the policy's method at an exact head, the PR title as the commit subject (a rebase has none), then confirm main's tree is the slot's prefix. */ +/** Merge with the policy's method at an exact head and lib/squash-message.ts's subject and body (a rebase has none; a land.merge_commit_paths match turns a squash into a merge), then confirm main's tree is the slot's prefix. */ async function mergeAt(ctx: QueueContext, s: Slot, head: string, base: string): Promise<TrainOut> { const pr = s.t.slots[s.i]!.pr; const method = s.env.train.land?.merge_method ?? 'squash'; @@ -143,13 +144,23 @@ async function mergeAt(ctx: QueueContext, s: Slot, head: string, base: string): const target = prInfo(ctx, pr); if ('error' in target) return outPending({ code: 'QUEUE_PROOF_MISSING', message: target.error }, s.lines, s.rerun, s.run); if (target.baseRefName && target.baseRefName !== ctx.base) return retargeted(s, target.baseRefName, ctx.base); + let args = ['pr', 'merge', pr, '--rebase', '--match-head-commit', head]; + if (method !== 'rebase') { + const viewed = ctx.gh(['pr', 'view', pr, '--json', 'title,body']); + if (!viewed.ok) return outPending({ code: 'QUEUE_PROOF_MISSING', message: `cannot read #${pr}'s title and body: ${(viewed.err ?? viewed.out).trim().slice(0, 200)}` }, s.lines, s.rerun, s.run); + let view: { title?: unknown; body?: unknown } = {}; + try { view = viewed.ok ? JSON.parse(viewed.out) : {}; } catch {} + const root = ctx.repoRoot; + const msg = landMessage(root, { pr, title: String(view.title ?? ''), prBody: String(view.body ?? ''), mergeBase: git(root, ['merge-base', base, head]).out, pin: head, tip: base, policy: s.env.policy.policy }); + if ('error' in msg) return outFailed({ code: 'QUEUE_NOT_READY', message: msg.error }, s.lines, s.rerun, s.run); + const m = method === 'merge' ? { ...msg, method: 'merge' as const, why: 'train.land.merge_method: merge' } : msg; + s.lines.push(...messageLines(m)); + args = mergeArgs(pr, head, m); + } const moved = lockPhase(s, 'merging'); if (moved) return outFailed(moved, s.lines, s.rerun, s.run); s.lock.effect = true; - const viewed = method === 'rebase' ? null : ctx.gh(['pr', 'view', pr, '--json', 'title']); - let title = ''; - try { title = viewed?.ok ? String(JSON.parse(viewed.out).title ?? '').trim() : ''; } catch {} - const m = ctx.gh(['pr', 'merge', pr, `--${method}`, '--match-head-commit', head, ...(title ? ['--subject', `${title} (#${pr})`] : [])]); + const m = ctx.gh(args); if (!m.ok) return outFailed({ code: 'QUEUE_NOT_READY', message: `gh pr merge refused: ${(m.err ?? m.out).trim().slice(0, 200)}` }, s.lines, s.rerun, s.run); main = mainNow(ctx, s.env); if ('error' in main) return outPending({ code: 'QUEUE_PROOF_MISSING', message: `merged; ${main.error}` }, s.lines, s.rerun, s.run); diff --git a/crew/test/ship-queue-train-generic.test.ts b/crew/test/ship-queue-train-generic.test.ts index bab6e218094..596b784839f 100644 --- a/crew/test/ship-queue-train-generic.test.ts +++ b/crew/test/ship-queue-train-generic.test.ts @@ -248,7 +248,7 @@ describe('generic trains end to end (fixture repos)', () => { expect(origin('rev-parse', 'main^{tree}')).toBe(t.gated[2].tree); expect(trainJson(fx, nonce)).toMatchObject({ state: 'merged', landing: { 1: { mode: 'direct', update: null }, 2: { mode: 'direct' } } }); const merges = fx.read().log.filter(l => l.cmd === 'pr merge').map(l => (l.args as string[]).join(' ')); - expect(merges[0]).toMatch(/^pr merge 1 --squash --match-head-commit [0-9a-f]{40} --subject Change from #1 \(#1\)$/); + expect(merges[0]).toMatch(/^pr merge 1 --squash --match-head-commit [0-9a-f]{40} --subject Change from #1 \(#1\) --body $/); }, 300_000); test('strict protection forces update; a rebase method refuses it; a fork head is refused', () => { diff --git a/crew/test/ship-queue-train-land.test.ts b/crew/test/ship-queue-train-land.test.ts index fcb73231d68..46f737a343c 100644 --- a/crew/test/ship-queue-train-land.test.ts +++ b/crew/test/ship-queue-train-land.test.ts @@ -62,7 +62,7 @@ describe('stamped trains: build and land', () => { expect(trainJson(fx, nonce)).toMatchObject({ state: 'merged' }); expect(fx.read().prs['2']).toMatchObject({ state: 'MERGED' }); expect((fx.read() as any).labels).toEqual({ 1: 'evals-no-debounce', 2: 'evals-no-debounce' }); - expect((fx.read() as any).mergeArgs['1']).toEqual(['--squash', '--match-head-commit', stamp, '--subject', 'Change from #1 (#1)']); + expect((fx.read() as any).mergeArgs['1']).toEqual(['--squash', '--match-head-commit', stamp, '--subject', 'Change from #1 (#1)', '--body', '']); void h2; }, 300_000); diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 84e4a683441..c2692252d68 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -60,7 +60,7 @@ branch that changes the policy. | `stamp_paths` | globs | `[]` | Where exact `(was X)`, `since: X` and `vX` mentions of the branch's tentative version (quoted or bare: `since: 'X'` counts) are rewritten on a restamp. | | `changelog` | path or `null` | `CHANGELOG.md` | Re-headed on a restamp: the PR's `## [Unreleased]` (or old-version) section moves to the top as `## [<version>] - <date>`. | | `mirror` | relative path or `null` | `null` | A paired checkout to restamp identically (tier 2: validated and confined today, not yet run). | -| `history` | `merge-only` \| `squash-ok` | `squash-ok` | `merge-only` makes `/ship` refuse a squash or rebase plan; `gstack-ship-policy check-history` reports a rewritten branch (`HISTORY_POLICY_VIOLATION`). | +| `history` | `merge-only` \| `squash-ok` \| `no-rewrite` | `squash-ok` | `merge-only` makes `/ship` refuse a squash or rebase plan and land keep a merge commit; `gstack-ship-policy check-history` reports a rewritten branch (`HISTORY_POLICY_VIOLATION`). `no-rewrite` refuses a rebase or force-push the same way but lands each PR as one squashed commit ([writing-prs.md](writing-prs.md#the-commit-on-main)); it needs `min_gstack_version` at its own release (`HISTORY_NO_REWRITE_KEY_VERSION`). | | `preregistration_shas` | commit ids | `[]` | Each must be an ancestor of HEAD before push: `gstack-evidence ancestor --from-policy`; the ship receipt records the result. | | `stamp_sensitive_gates` | evidence labels | `[]` | Gates that read VERSION or generated bytes (gstack's own `tests` lane does, through the agents-digest freshness test). The tree receipt never marks them reusable. | | `pr_count` | `{ default_pr_count, split_requires_owner }` | `{1, true}` | The PR-count row in plan reviews. | @@ -80,7 +80,7 @@ branch that changes the policy. | `docs` | `{ caps: [{ path, max_bytes }] }` or `null` | `null` | Documentation files with a byte cap. `/ship` Step 14.5 runs `gstack-ship-receipt docs-caps --base <base>` (the caps come from `origin/<base>`'s policy, never the branch's copy; `--policy <file>` is for a repository bootstrapping its policy) before the verification gate and prints one `DOCS_CAP: <path> <bytes>/<max> ok\|over` line per cap; any `over` (an absent file counts) exits 1 and blocks the ship until the file is trimmed or the cap raised on the base branch (`DOCS_AUDIT_BLOCKED`). At most 64 caps, each path contained. See [the ship receipt](#ship-receipt). Needs `min_gstack_version`. | | `train` | `{ gate_workflow, free_workflow, full_gate_check, record_artifact, max_size, fill_hours, screen_selection, trial_reservation_usd, land? }`, `{ gates, land, max_size, fill_hours }` or `null` | `null` | Turns on [merge trains](#run-a-merge-train), read from the base revision only. Every field is required and an unknown field is `POLICY_INVALID`: `max_size` 1 to 6, `fill_hours` above 0 and at most 24, `screen_selection` `gstack-paid` \| `none`, `trial_reservation_usd` above 0 and at most 100. A block with `gates` ([any repository](#train-gates)) takes `max_size` 1 to 5 and needs `min_gstack_version` at least `TRAIN_GATES_KEY_VERSION`. `null` keeps the per-PR queue exactly as it is. Needs `min_gstack_version`. | | `merge` | `train` \| `direct` | `train` | `direct` lands each READY PR at its own green head with [`land --pr <n> --pin <sha>`](#land-direct): no train and no stamp commit, and `train build` refuses. A PR then leaves VERSION, the `package.json` version and the CHANGELOG at its merge base, and the release sets them. Needs `changelog_fragments`, and the stamping `land --pr <n>` refuses under it. `train` keeps merge trains. Read from the base revision only. Needs `min_gstack_version`. | -| `land` | `{ merged_checks, docs_only_skip? }` or `null` | `null` | Under `merge: direct`, the shell commands (1 to 16, one line of at most 512 characters each, 15 minutes each) [`land --pin`](#land-direct) runs on the pin merged onto the base tip when the base moved past the pin's merge base; it lands only when every one exits 0. They are repo commands, so land runs them only with `--allow-repo-commands`, never under `--dry-run`. `null` lands a stale base untested with a `STALE_BASE: warn` line. `docs_only_skip` lists `merged_checks` commands to skip for a docs-only pin ([pregate.md](pregate.md#docs-only)) and needs `min_gstack_version` at its own release (`LAND_DOCS_ONLY_SKIP_KEY_VERSION`), because older releases refuse it. Any other key under `land` is a warning, ignored. Read from the base revision only. Needs `min_gstack_version`. | +| `land` | `{ merged_checks?, docs_only_skip?, merge_commit_paths? }` or `null` | `null` | Under `merge: direct`, the shell commands (1 to 16, one line of at most 512 characters each, 15 minutes each) [`land --pin`](#land-direct) runs on the pin merged onto the base tip when the base moved past the pin's merge base; it lands only when every one exits 0. They are repo commands, so land runs them only with `--allow-repo-commands`, never under `--dry-run`. `null` lands a stale base untested with a `STALE_BASE: warn` line. `docs_only_skip` lists `merged_checks` commands to skip for a docs-only pin ([pregate.md](pregate.md#docs-only)) and needs `min_gstack_version` at its own release (`LAND_DOCS_ONLY_SKIP_KEY_VERSION`), because older releases refuse it. `merge_commit_paths` (1 to 64 git glob pathspecs, no `..`) makes every land form keep a merge commit, with the plain subject and body, for a PR that changes a matching path, such as an eval results PR whose run records point to its own commits; with it, `merged_checks` may be left out, and it needs `min_gstack_version` at its own release (`LAND_MERGE_COMMIT_PATHS_KEY_VERSION`). Any other key under `land` is a warning, ignored. Read from the base revision only. Needs `min_gstack_version`. | | `docs_only` | `{ allow, deny?, tests? }` or `null` | `null` | Human-docs paths beyond `README.md`, `docs/**.md` and `changelog.d/*.md` for the [docs-only class](pregate.md#repo-docs-paths) (`{ "allow": ["wiki/board/**.md"] }`). `allow` (1 to 16) takes narrow Markdown globs: each ends in `.md`, starts with a literal directory or file name, and passes through no hidden, code, test or agent directory; `**`, `*`, `*.md` and patterns naming agent files are `POLICY_INVALID` with an example of a narrow one. `deny` (up to 64 globs) removes paths, built-in ones included. `tests` (up to 16 test files) are the repository's checks for those directories: the docs lane runs them, and a non-prose file that reads an allowed directory refuses the class unless it is tied to one; a listed test missing from the branch refuses it too. The built-in deny list always wins. Any other key under `docs_only` is a warning, and the classifier then ignores `allow`. Read from the base revision only; a pull request that edits this file is never docs-only. Needs `min_gstack_version`. | | `release_gate` | `{ cadence_hours, gate_workflow, branch, stable_ref, check_name, on_red, bisect_spend_cap_usd }` or `null` | `null` | One full paid gate on main every `cadence_hours` (8 to 168) instead of the per-push main backstop, feeding the stable release; see [release_gate](#release-gate). Every field is required: `on_red` is `hold-release`, `bisect_spend_cap_usd` 0 to 500 (0 skips the bisect). `null` keeps the per-push backstop. Needs `min_gstack_version`. | | `bookkeeping` | glob list | `[]` | <a id="bookkeeping"></a>Root-anchored globs of bookkeeping tables a verify or ratchet step rewrites (size baselines, serial lists, limits), each ending in `.tsv`, `.csv` or `.txt` and never under `.gstack/` or `.github/` (`["scripts/*-baseline.tsv"]`). A matching file changed at most 20 lines after review binds, first touched or not, takes finish's [one scoped reader](review-policy.md#bounded-post-review-edits) instead of Steps 5–11.5; the reader still reads every changed row. Read from the base revision only. Needs `min_gstack_version`. | @@ -2655,7 +2655,10 @@ unless: - the /ship receipt in the PR body and a READY note are both bound to the pin. After merging, it checks that main's tree is exactly the pin merged onto the -commit before it (`QUEUE_LAND_UNVERIFIED` otherwise). A script that reads +commit before it (`QUEUE_LAND_UNVERIFIED` otherwise). The merge is one commit +titled `<PR title> (#n)` with the PR body's opening lines and the branch's +trailers as its body ([the commit on main](writing-prs.md#the-commit-on-main)); +`--dry-run` prints it. A script that reads these before calling land adds nothing; read land's output instead. Every check, with its refusal code, is in [the table below](#land-direct-contract). @@ -2984,10 +2987,12 @@ example "Stop gstack from hitting GitHub's rate limit while it waits on PRs". A title may end with one group of references, such as `(GST-1713)`, `(GST-1808, GST-1809)` or `(#4122)`; that group is never checked. A branch may end with one tracker code (`capy/github-rate-limit-gst-1713`). A PR body -opens with one or two plain sentences (what changed and which goal of the -project it serves) and keeps tracker codes, the ship record and other -machine-read lines in the Agent notes section at the end, below the -`<!-- gstack:agent-notes -->` marker. The checker skips that section. +shows at most three plain lines before its first collapsed section (what +changed, why, and what the reader has to do), folds everything else, and keeps +tracker codes, the ship record and other machine-read lines in the Agent notes +section at the end, below the `<!-- gstack:agent-notes -->` marker. The checker +skips that section. [writing-prs.md](writing-prs.md) has the whole shape, the +default word list and the commit every merge makes. What the checker refuses in the front: @@ -2998,7 +3003,10 @@ What the checker refuses in the front: usually an internal module name. A bare `fix:` or `docs:` is allowed, and so is a leading version such as `v1.98.0.0 release`; - in the PR opening, a first block that is a heading, code block, list, table, - HTML or image, or a paragraph longer than two sentences; + HTML or image; +- in the PR body once folded (`PLAIN_BODY_REFUSED`), more than three lines or 600 + characters before the first fold, text outside a fold below it, a listed word + above the Agent notes section, or a /ship record outside that section; - in a changelog entry, a tracker code anywhere, and a listed word in the bold lead. Code spans, code blocks, links and quoted words are skipped. @@ -3016,7 +3024,9 @@ another project. The keys: | `terms` | The project's own words that mean nothing to an outside reader. | | `allow` | `{ "text", "reason" }` entries. A refused match inside an allowed phrase passes. Every entry says why. | | `since` | A date (`YYYY-MM-DD`, midnight UTC). PRs created before it are exempt, so nothing already open breaks. | -| `exempt_branch_prefixes` | Branch prefixes that gstack's own tools generate; those branches are not checked. | +| `exempt_branch_prefixes` | Branch prefixes that gstack's own tools generate; those branches are not checked, and their bodies only warn. | +| `replace_default_terms` | `true` uses `terms` alone; by default gstack's own list (outside voice, pregate, receipt, ledger, fix-check, carry, stamp, restamp, train, lane, soak and their plurals) is added to it. | +| `body_since` | A date: the body shape refuses only for PRs created on or after it (default: `since`), so open PRs are not broken by the new rule. | gstack's own file lists its tracker prefixes (GST, GSTA, GBRA, GEVA, FOUN, HARN, ALPH) and R-numbers (`R76`), the crew and Captain names, and the words last diff --git a/docs/skills.md b/docs/skills.md index 29d28087808..468f6cfcdd9 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -752,14 +752,14 @@ A lot of branches die when the interesting work is done and only the boring rele ### The PR body -`/ship` writes the PR body from the diff, the receipt and the review, and a reader who was not in the session decides the merge from it. The front is for people and the end is for machines: the body opens with one or two plain sentences saying what changed for someone using the project and which README goal it serves, and it ends with one collapsed **Agent notes** section (`<!-- gstack:agent-notes -->` then `<details><summary>Agent notes</summary>`) that holds the ship receipt, the approval and Plan lines, issue codes and the review-loop lines gstack's tools read. The title follows the same shape: plain words first, an issue code only at the end (`Stop gstack from hitting GitHub's rate limit while it waits on PRs (GST-1713)`), checked by `gstack-plain-title` (see [Plain titles](ship-policy.md#plain-titles)). On Capy (`CAPY_PR: on`) the opening is followed by three sections, in this order, before the standard Summary, Test plan and Documentation sections: +`/ship` writes the PR body from the diff, the receipt and the review, and a reader who was not in the session decides the merge from it. The front is for people and the end is for machines: the body opens with at most three plain lines (600 characters) saying what changed for someone using the project, why (the README goal it serves) and what the reader has to do, every other section sits under a `## ` heading that `gstack-post` folds into a collapsed section ([writing-prs.md](writing-prs.md)), and it ends with one collapsed **Agent notes** section (`<!-- gstack:agent-notes -->` then `<details><summary>Agent notes</summary>`) that holds the ship receipt, the approval and Plan lines, issue codes and the review-loop lines gstack's tools read. The title follows the same shape: plain words first, an issue code only at the end (`Stop gstack from hitting GitHub's rate limit while it waits on PRs (GST-1713)`), checked by `gstack-plain-title` (see [Plain titles](ship-policy.md#plain-titles)). On Capy (`CAPY_PR: on`) the opening is followed by three sections, in this order, before the standard sections (Documentation, Tests and the rest); `## What changed` holds the pictures, then the template's themes: 1. **`## What changed`**: one to three captioned before/after images from `gstack-pr-shots` or a UI screenshot, highest-signal first, with a collapsed text version under each. 2. **`## Why`**: two or three sentences. The first states the problem in the person's words (the issue, the message, the failing run), then the cause and the user-visible effect. 3. **`## Blast radius`**: what else the change touches and the one fact that makes that safe, with the evidence-ladder rung that fact reached (a test that exercises the shared path, a grep over every caller, a measured run). A change to a shared helper, a generated file, a selection list or a policy default always has one; a leaf fix says so in one line. `## Approvals`, the output of `gstack-approvals render` verbatim, goes inside Agent notes. On a private repository that is the table; on a public repository, or one whose visibility gh cannot read, it is only `Approved: yes|no (record <id>)`, because GitHub keeps every earlier version of a PR description. The table shows each local path in Asked, Covers and Still pending as `…/<file name>`, so the home directory, user name and Drive folder in those paths stay out of the body; Exact words stays verbatim, and `gstack-approvals list` keeps the full path. For a private repository that may go public, `render --redacted` prints the public form, byte for byte; `--redacted` with `--full` is refused. -Before the body is composed, `gstack-prose-lint` reads the Why, Summary and Blast radius drafts (`--sections 'Why,Summary,Blast radius' --gate`) and the CHANGELOG entry (`--base origin/<base> --gate`), and a `PROSE_LINT_FOUND` line names the sentence to rewrite; the rest of the body is advisory. The Captain's merge-ask template (`captain/templates/merge-ask.md`) carries the same sections, so a READY report and its PR say the same thing. +Before the body is composed, `gstack-prose-lint` reads the Why, What changed and Blast radius drafts (`--sections 'Why,What changed,Blast radius' --gate`) and the CHANGELOG entry (`--base origin/<base> --gate`), and a `PROSE_LINT_FOUND` line names the sentence to rewrite; the rest of the body is advisory. The Captain's merge-ask template (`captain/templates/merge-ask.md`) carries the same sections, so a READY report and its PR say the same thing. ### Versions: where `/ship` looks, and when it ships without one diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 8372be81fd8..1357386a7f5 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -7513,8 +7513,7 @@ every flag and code. `bin/gstack-prose-lint` reads the prose /ship is about to publish, a CHANGELOG entry (Step 13) and the sections the author writes in the PR body (Step 19: -`## Why`, `## Summary` and `## Blast radius`, through `--sections`; the -`## What changed` captions and image text stay a report), and the quality-gate +`## Why`, `## What changed` and `## Blast radius`, through `--sections`), and the quality-gate workflow runs it over `CHANGELOG.md`'s `[Unreleased]` block. It decides only what a regular expression can: autopilot vocabulary, "not just X, but Y", metaphor nouns, a colon used as a conjunction, a bold label that restates its @@ -7893,7 +7892,12 @@ These codes come from `bin/gstack-plain-title`, which /ship, gstack-post and the <a id="plain-opening-refused"></a> ### `PLAIN_TITLE: PLAIN_OPENING_REFUSED <kind> "<match>" — …` -**Meaning.** The readable part of the PR body (everything above the `<!-- gstack:agent-notes -->` marker) does not start with a plain paragraph: it starts with a heading, code block, list, table, HTML or image, runs past two sentences, or names a tracker code or listed word. /ship refuses it; CI only warns. **Fix.** Start the body with one or two sentences saying what changed and which goal of the project it serves. Move codes and records into the Agent notes section at the end. +**Meaning.** The readable part of the PR body (everything above the `<!-- gstack:agent-notes -->` marker) does not start with a plain paragraph: it starts with a heading, code block, list, table, HTML or image, or names a tracker code or listed word. /ship refuses it, and so does CI in a repository with a policy for PRs created on or after its `body_since` date. **Fix.** Start the body with up to three plain lines: what changed for a user, why, and anything the reader has to do. Move codes and records into the Agent notes section at the end. + +<a id="plain-body-refused"></a> +### `PLAIN_BODY: PLAIN_BODY_REFUSED <kind> "<match>" — …` + +**Meaning.** The PR body, folded the way gstack-post posts it, breaks the plain shape (docs/writing-prs.md). `visible-lines`: more than three lines or 600 characters show before the first fold. `unfolded`: text sits outside a fold between the first fold and the Agent notes section. `term`: a listed word appears above the Agent notes section (code spans, code blocks, links and quotes are skipped). `receipt-placement`: the /ship receipt sits outside the Agent notes section, or text follows that section. gstack-post exits 4 and posts nothing, and the Plain title CI check fails, in a repository with `.gstack/plain-titles.json` and for a PR created on or after its `body_since` date; everywhere else, and for comments, these are warnings. **Fix.** Rewrite the body file the way the line says: up to three plain lines first, every other section under a `## ` heading (gstack-post folds it; `gstack-post fold --body-file F` shows the result without posting), and records in the Agent notes section. Then post it again; an edited body reruns the CI check. <a id="plain-changelog-refused"></a> ### `PLAIN_TITLE: PLAIN_CHANGELOG_REFUSED <kind> "<match>" — …` diff --git a/docs/writing-prs.md b/docs/writing-prs.md new file mode 100644 index 00000000000..5c7c697ed5e --- /dev/null +++ b/docs/writing-prs.md @@ -0,0 +1,122 @@ +# Writing pull requests and the commits they land as + +People outside a project read its pull requests, its commit log and its release +notes to decide whether the project is worth using. So everything gstack writes +there, and everything you write there with gstack, follows the same few rules. +`/ship` writes it this way for you, and the checks below catch what slips through. + +## The title + +The title says what changed for someone using the project, in everyday words: +"Stop gstack from hitting GitHub's rate limit while it waits on PRs". One group +of issue references may close it, such as `(GST-1713)` or `(#4122)`. No +`fix(module):` prefix, no tracker code in the front, no in-house words. + +## The body + +A reader sees at most **three lines** (and 600 characters) before anything +collapsed: + +1. what changed for a user; +2. why it matters: the project goal it serves or the problem it fixes; +3. anything the reader has to do, or "Nothing to do". + +Everything else goes under a `## ` heading. `gstack-post` turns each heading +into a collapsed section (a `<details>` fold) when it posts, so you never write +HTML by hand. Say each thing once. Link long logs and review output instead of +pasting them. + +The last section is **Agent notes**, which `/ship` adds. It holds the lines +gstack's tools read: issue links, approvals, review counts and the `/ship` +record. Nothing comes after it except a bot's badge. + +Here is how a body looks on GitHub before anyone clicks: + +``` +/ship's reviewers now end their reply with one count line, and gstack checks it against the findings it read. + +Why: the findings reader misread free-form review prose, so a real problem could be lost. + +Nothing to do: replies without the line are read exactly as before. + +▸ What changed +▸ Tests +▸ Agent notes +``` + +To see a body folded without posting it, run +`gstack-post fold --body-file body.md`. Use its output whenever you post a body +some other way, such as a web editor or another tool. + +## Words to keep out of the front + +Some words mean something only inside the team that uses gstack. Keep them out +of the title, the commit subject and everything above the Agent notes section, +and say what the thing does instead: + +| Instead of | Write | +|------------|-------| +| outside voice | second-model review | +| pregate | the checks that run before a PR opens | +| receipt, ledger | the record of what was checked | +| fix-check | the re-check of a fix | +| carry | reuse a result from an earlier commit | +| stamp, restamp | set the version | +| train, lane, soak | merge several PRs together; the job that runs one part of the work; the wait before a release goes out to everyone | + +gstack ships that list as the default. A project adds its own words in +`.gstack/plain-titles.json` (`terms`), and gstack's own file adds its team names. +Code spans, code blocks, links and quotes are never checked, and the Agent +notes section may use any word. + +<a id="the-commit-on-main"></a> +## The commit on main + +Every gstack merge (`gstack-ship-queue land`, in each of its forms) lands a PR +as **one commit**: + +- the subject is the PR title with GitHub's number, `<title> (#1234)`; +- the body is the PR body's opening lines (at most three, links reduced to their + text), then every trailer the branch's commits carry (`Co-authored-by:`, + `Removed-test:` and any other `Key: value` line), each once, plus a + `Co-authored-by:` for every other commit author. + +So `git log --oneline` reads as a list of changes, with no "Merge pull request" +lines and none of the branch's housekeeping commits. A release PR's commit body +is its release notes instead, one plain line per change with the PR that made it. +Commits from a stacked PR that already landed are left out. + +`gstack-ship-queue land --dry-run` prints the `METHOD:`, `SUBJECT:` and `BODY:` +lines before anything merges, and `--body-file <file>` replaces the opening lines +when the PR body's opening does not suit a commit. Land checks the whole message +for secrets first: a key or token refuses the land, and anything that only looks +private drops the opening and keeps the trailers. + +These settings keep a merge commit instead of a squash, with the same subject and +body ([ship-policy.md](ship-policy.md)): + +- `history: merge-only`, for a repository whose branch rules allow only merge + commits; +- `land.merge_commit_paths`, for PRs that change matching paths, such as an + eval results PR whose run records point to commits on its own branch; +- a merge train whose `train.land.merge_method` is `merge`. + +`history: no-rewrite` is the setting for a repository that wants squash +landings but never a rebased or force-pushed branch: +`gstack-ship-policy check-history --plan rebase` refuses there. + +## Comments and release notes + +GitHub comments and release notes follow the same rules: plain words, the short +version first, details linked. `gstack-post` warns about listed words in a +comment but never refuses one. A published release carries real notes, one +plain line per change, never just a link to the CHANGELOG. + +## When a check refuses + +In a repository with `.gstack/plain-titles.json`, `gstack-post` refuses a body +that breaks these rules (exit 4, `PLAIN_BODY:` lines, nothing posted), and so +does the **Plain title** CI check for PRs opened on or after the policy's +`body_since` date. Each line says what to change; see +[troubleshooting](troubleshooting.md#plain-body-refused). Without the file, +the same findings are warnings only. diff --git a/lib/gstack-post.ts b/lib/gstack-post.ts index 30fb4524fd5..4259790410b 100644 --- a/lib/gstack-post.ts +++ b/lib/gstack-post.ts @@ -13,7 +13,10 @@ * its first `## ` section replaces the text between the receipt and the * first heading while the opening text above the receipt is kept; * the Agent notes section (lib/agent-notes.ts) is one section that always - * stays last; `--replace` overwrites instead. + * stays last; `--replace` overwrites instead. Folds in the current body merge by + * their summary, and every body is folded before it is sent (lib/pr-body-shape.ts: + * three visible lines, every `## ` section collapsed), then checked; `fold` + * prints the folded body and posts nothing. * `pr-title` and `pr-create` first check the title against the repository's * plain-title policy (lib/plain-title.ts); a refused title posts nothing. * The scan runs on the merged bytes, which are the bytes sent. @@ -22,7 +25,8 @@ * 2 MEDIUM findings need confirmation, printed as `RULE:` lines plus a * `TOKEN:` that binds the bytes, destination, operation and findings; * 3 `gh`/`glab` failed; 4 the title breaks the plain-title policy, printed as - * `PLAIN_TITLE:` lines; 64 usage or invalid input. Nothing is posted on any + * `PLAIN_TITLE:` lines, or the body breaks the shape, printed as `PLAIN_BODY:` + * lines (title and body are checked in one pass); 64 usage or invalid input. Nothing is posted on any * non-zero exit. bin/gstack-post is the CLI; tests drive `runPost` with a fake * runner so the logic is covered on every platform. */ @@ -30,14 +34,15 @@ import { createHash } from "crypto"; import { scan, type Finding, type RepoVisibility } from "./redact-engine"; import { CI_RUN_WORD_BEFORE } from "./redact-patterns"; import { agentNotesLines, splitAgentNotes } from "./agent-notes"; -import { checkTitle, loadPlainTitlePolicy, PLAIN_TITLE_POLICY_PATH } from "./plain-title"; +import { checkTitle, loadPlainTitlePolicy, PLAIN_TITLE_POLICY_PATH, type PlainTitlePolicy } from "./plain-title"; +import { bodyFindingLine, checkBodyShape, foldSections, unfoldSections } from "./pr-body-shape"; import { RECEIPT_FENCE, RUNS_FENCE, extractReceipt, placeReceipt, renderReceiptBlock, validateReceipt } from "./ship-receipt"; import type { ShipReceipt } from "./headless-artifacts"; import { canonicalRemote } from "./remote-identity"; import { parseChangelog } from "./changelog-check"; import { versionWidth } from "./version-source"; -export const OPS = ["pr-comment", "issue-comment", "reply", "pr-title", "pr-body", "pr-create", "issue-create"] as const; +export const OPS = ["pr-comment", "issue-comment", "reply", "pr-title", "pr-body", "pr-create", "issue-create", "fold"] as const; export type Op = (typeof OPS)[number]; export type HostKind = "github" | "gitlab"; @@ -61,6 +66,7 @@ export const USAGE = `usage: gstack-post <op> [<target>] [options] gstack-post pr-body <pr> --body-file F [--replace] gstack-post pr-create --base <branch> [--head <branch>] [--draft] --title-file F --body-file F gstack-post issue-create --title-file F --body-file F + gstack-post fold --body-file F (prints the folded body; posts nothing) <pr>/<issue> is a number or a URL of this repository on the same host. Options: --host github|gitlab (default: detected from the origin remote) @@ -79,8 +85,11 @@ export const USAGE = `usage: gstack-post <op> [<target>] [options] Exit: 0 posted · 1 HIGH finding refused · 2 MEDIUM findings need confirmation (RULE:/TOKEN: lines on stdout) · 3 gh/glab failed · - 4 the title is not plain words (PLAIN_TITLE: lines on stdout; rewrite the - title file and rerun) or the plain-title policy is invalid; nothing posted · 64 usage + 4 the title is not plain words (PLAIN_TITLE: lines; rewrite the title file) + or the body breaks the shape (PLAIN_BODY: lines; rewrite the body file), or + the plain-title policy is invalid; nothing posted · 64 usage + Every PR body is folded before it is sent: the lines above the first ## stay + visible (at most 3, docs/writing-prs.md), each ## section becomes a fold. `; interface Request { @@ -156,10 +165,10 @@ function parseArgs(argv: string[]): Request { if (!req.attribute || /[\r\n\u0000-\u001f]/.test(req.attribute)) throw new UsageError("--attribute needs one line of text, like \"<model> on behalf of <login>\""); if (req.attribute.length > 200) throw new UsageError("--attribute must be 200 characters or fewer"); } - const creates = req.op === "pr-create" || req.op === "issue-create"; + const creates = req.op === "pr-create" || req.op === "issue-create" || req.op === "fold"; if (positional.length > (creates ? 0 : 1)) throw new UsageError(`unexpected argument "${positional[creates ? 0 : 1]}"`); if (!creates && !req.target) throw new UsageError(`${req.op} needs a target (a number or a URL)`); - const needsTitle = req.op === "pr-title" || creates; + const needsTitle = req.op === "pr-title" || (creates && req.op !== "fold"); const needsBody = req.op !== "pr-title"; if (needsTitle !== !!req.titleFile) throw new UsageError(needsTitle ? `${req.op} needs --title-file` : `${req.op} takes no --title-file`); if (needsBody !== !!req.bodyFile) throw new UsageError(needsBody ? `${req.op} needs --body-file` : `${req.op} takes no --body-file (use --title-file)`); @@ -663,15 +672,21 @@ function send(env: PostEnv, kind: HostKind, req: Request, n: string | undefined, * title passes or the repository has no policy. A finding prints one `PLAIN_TITLE:` line each, in gstack-plain-title's * format, then `PLAIN_TITLE: refused=<n>`; an invalid policy refuses too, so nothing is posted until it is fixed. */ -function plainTitle(env: PostEnv, title: string): boolean { +function plainPolicy(env: PostEnv, comment = false): PlainTitlePolicy | null | "invalid" { const top = env.run("git", ["rev-parse", "--show-toplevel"]); const root = top.status === 0 ? top.stdout.trim() : ""; - if (!root) return true; - let findings; - try { findings = checkTitle(title, loadPlainTitlePolicy(root)); } catch (e) { - env.err(`gstack-post: ${e instanceof Error ? e.message : String(e)} (PLAIN_POLICY_INVALID); nothing was posted. Fix the policy (gstack-plain-title validate), then rerun.\n`); - return false; + if (!root) return null; + try { return loadPlainTitlePolicy(root); } catch (e) { + const why = `gstack-post: ${e instanceof Error ? e.message : String(e)} (PLAIN_POLICY_INVALID)`; + if (comment) { env.err(`${why}; the comment is posted unchecked. Fix the policy (gstack-plain-title validate).\n`); return null; } + env.err(`${why}; nothing was posted. Fix the policy (gstack-plain-title validate), then rerun.\n`); + return "invalid"; } +} + +function plainTitle(env: PostEnv, title: string, policy: PlainTitlePolicy | null | "invalid"): boolean { + if (policy === "invalid") return false; + const findings = checkTitle(title, policy); if (!findings.length) return true; const clean = (s: string) => s.replace(/[\u0000-\u001f\u007f"]/g, " ").slice(0, 80); for (const f of findings) env.out(`PLAIN_TITLE: ${f.code} ${f.kind} "${clean(f.match)}" — ${f.hint}\n`); @@ -680,6 +695,23 @@ function plainTitle(env: PostEnv, title: string): boolean { return false; } +/** + * The body shape check (lib/pr-body-shape.ts) on the folded bytes: one `PLAIN_BODY:` line per finding, then + * `PLAIN_BODY: refused=<n>` or `warned=<n>`. Findings refuse only with a policy file and for a PR created on or after + * its body_since (an existing PR's date is read only when a finding needs it); anything else, comments included, warns. + */ +function plainBody(env: PostEnv, body: string, policy: PlainTitlePolicy | null | "invalid", createdAt: () => string | undefined, comment = false): boolean { + if (policy === "invalid") return false; + const findings = comment ? (policy ? checkBodyShape(`<details>\n\n${body}\n\n</details>`, policy.terms).filter(f => f.kind === "term") : []) : checkBodyShape(body, policy?.terms ?? []); + if (!findings.length) return true; + const when = comment || !policy ? undefined : createdAt(); + const refuse = !!policy && !comment && (when === undefined || Date.parse(when) >= Date.parse(policy.body_since ?? policy.since)); + for (const f of findings) env.out(bodyFindingLine(f, !refuse) + "\n"); + env.out(`PLAIN_BODY: ${refuse ? "refused" : "warned"}=${findings.length}\n`); + if (refuse) env.err("gstack-post: the body does not have the plain shape; nothing was posted. Rewrite the body file the way each PLAIN_BODY: line says (docs/writing-prs.md), then rerun.\n"); + return !refuse; +} + export function runPost(argv: string[], env: PostEnv, configBin = "gstack-config"): number { if (argv.length === 0 || ["help", "--help", "-h"].includes(argv[0]!)) { (argv.length === 0 ? env.err : env.out)(USAGE); @@ -687,11 +719,17 @@ export function runPost(argv: string[], env: PostEnv, configBin = "gstack-config } try { const req = parseArgs(argv); + if (req.op === "fold") { + const folded = foldSections(readText(env, req.bodyFile!, "body")); + env.out(folded.endsWith("\n") ? folded : folded + "\n"); + return plainBody({ ...env, out: env.err }, folded, plainPolicy(env), () => undefined) ? EXIT.posted : EXIT.plainTitle; + } const remote = resolveRemote(env, req.host); if (req.op === "reply" && remote.kind !== "github") throw new UsageError("reply is supported on GitHub only"); const n = req.target === undefined ? undefined : targetNumber(req.target, req.op, remote); const title = req.titleFile ? readText(env, req.titleFile, "title") : undefined; - if (title !== undefined && (req.op === "pr-title" || req.op === "pr-create") && !plainTitle(env, title)) return EXIT.plainTitle; + const policy = req.op === "issue-create" ? null : plainPolicy(env, COMMENT_OPS.has(req.op)); + const titleOk = title === undefined || !(req.op === "pr-title" || req.op === "pr-create") || plainTitle(env, title, policy); let body = req.bodyFile ? readText(env, req.bodyFile, "body") : undefined; if (req.op === "pr-body" && !req.replace) { const current = currentBody(env, remote.kind, n!); @@ -699,11 +737,15 @@ export function runPost(argv: string[], env: PostEnv, configBin = "gstack-config env.err(`gstack-post: cannot read PR ${n}'s current body to merge into (${current.error}); nothing was posted. Rerun with --replace to overwrite the whole body.\n`); return EXIT.cliFailed; } - const m = mergeBodySections(current.body, body!); + const m = mergeBodySections(unfoldSections(current.body), unfoldSections(body!)); body = m.body; const list = (names: string[]) => (names.length ? names.join(", ") : "none"); env.err(`gstack-post: pr-body merged by section: replaced ${list(m.replaced)}; kept ${list(m.kept)}; added ${list(m.added)}${m.dropped.length ? `; dropped ${m.dropped.join(", ")}` : ""}\n`); } + if (body !== undefined && (req.op === "pr-body" || req.op === "pr-create")) body = foldSections(body); + const createdAt = () => { const r = env.run("gh", ["pr", "view", n!, "--json", "createdAt", "--jq", ".createdAt"]); return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : undefined; }; + const bodyOk = body === undefined || req.op === "issue-create" || plainBody(env, body, policy, req.op === "pr-create" ? () => undefined : createdAt, COMMENT_OPS.has(req.op)); + if (!titleOk || !bodyOk) return EXIT.plainTitle; if (body !== undefined && req.attribute) body = attributionCallout(req.attribute) + body; const parts: Array<[Part, string]> = []; if (title !== undefined) parts.push(["title", title]); diff --git a/lib/land-merged-checks.ts b/lib/land-merged-checks.ts index 3d042161293..fdd731a9512 100644 --- a/lib/land-merged-checks.ts +++ b/lib/land-merged-checks.ts @@ -32,7 +32,9 @@ function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv): { ok: boolea export interface LandPolicy { /** Shell commands run in the pin merged onto the base tip, in order; each must exit 0. */ - merged_checks: string[]; + merged_checks?: string[]; + /** Git glob pathspecs: a PR that changes one lands as a merge commit, not a squash, so commits a receipt points to stay on the base (lib/squash-message.ts). */ + merge_commit_paths?: string[]; } const MAX_CHECKS = 16, MAX_COMMAND = 512, CHECK_TIMEOUT_MS = 900_000; @@ -40,16 +42,19 @@ const KEPT_ENV = ['PATH', 'LANG', 'LC_ALL', 'TERM', 'TMPDIR']; /** No hook or fsmonitor from the repository's config or the merged tree runs in the git calls around the checks. */ const NO_HOOKS = ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false']; -export const LAND_EXPLANATION = '{ merged_checks, docs_only_skip? } or null, read from the base revision only: under merge: direct, when the base moved past a pin\'s merge base, `land --pin` builds the pin merged onto the base tip in a throwaway worktree (the checkout\'s node_modules linked in) and runs each merged_checks command there (at most 16, 512 characters each, 15 minutes each); it lands only when every one exits 0, and refuses on a conflict (QUEUE_LAND_NOT_CLEAN) or a failure (QUEUE_LAND_MERGED_CHECKS). They are repo commands: land runs them only with --allow-repo-commands (else REPO_COMMANDS_NOT_ALLOWED), never under --dry-run, with PATH and locale as the only environment and a throwaway HOME. null lands a stale base unchecked with a STALE_BASE: warn line. docs_only_skip names merged_checks commands land skips for a pin lib/docs-only.ts calls human docs only (docs/pregate.md#docs-only) and needs min_gstack_version at its own introducing release. An unknown key under land is a warning, ignored.'; +export const LAND_EXPLANATION = '{ merged_checks, docs_only_skip? } or null, read from the base revision only: under merge: direct, when the base moved past a pin\'s merge base, `land --pin` builds the pin merged onto the base tip in a throwaway worktree (the checkout\'s node_modules linked in) and runs each merged_checks command there (at most 16, 512 characters each, 15 minutes each); it lands only when every one exits 0, and refuses on a conflict (QUEUE_LAND_NOT_CLEAN) or a failure (QUEUE_LAND_MERGED_CHECKS). They are repo commands: land runs them only with --allow-repo-commands (else REPO_COMMANDS_NOT_ALLOWED), never under --dry-run, with PATH and locale as the only environment and a throwaway HOME. null lands a stale base unchecked with a STALE_BASE: warn line. docs_only_skip names merged_checks commands land skips for a pin lib/docs-only.ts calls human docs only (docs/pregate.md#docs-only) and needs min_gstack_version at its own introducing release. merge_commit_paths lists git glob pathspecs (at most 64, 256 characters each, no `..`): a PR that changes one lands as a merge commit instead of a squash, so an eval results PR keeps the commits its run receipts point to (docs/writing-prs.md#the-commit-on-main); it needs min_gstack_version at its own introducing release, and with it merged_checks may be left out. An unknown key under land is a warning, ignored.'; /** The keys this gstack reads under land; any other is a warning (lib/ship-policy.ts policyWarnings), never an error. */ -export const LAND_KEYS: readonly string[] = ['merged_checks', 'docs_only_skip']; +export const LAND_KEYS: readonly string[] = ['merged_checks', 'docs_only_skip', 'merge_commit_paths']; export function landPolicyErrors(raw: unknown): PolicyError[] { const l = raw as Record<string, unknown> | null; if (!l || typeof l !== 'object' || Array.isArray(l)) return [{ code: 'POLICY_INVALID', path: 'land', message: 'must be { merged_checks } or null' }]; const out: PolicyError[] = []; + const paths = l.merge_commit_paths; + if (paths !== undefined && (!Array.isArray(paths) || !paths.length || paths.length > 64 || paths.some(p => typeof p !== 'string' || !p.trim() || p.length > 256 || /[\0\r\n]/.test(p) || p.startsWith('/') || p.split(/[\\/]+/).includes('..')))) out.push({ code: 'POLICY_INVALID', path: 'land.merge_commit_paths', message: 'must list 1 to 64 relative git glob pathspecs of at most 256 characters, with no `..`' }); const c = l.merged_checks; + if (c === undefined && paths !== undefined && l.docs_only_skip === undefined) return out; if (!Array.isArray(c) || !c.length || c.length > MAX_CHECKS) return [...out, { code: 'POLICY_INVALID', path: 'land.merged_checks', message: `must list 1 to ${MAX_CHECKS} commands` }]; const skip = l.docs_only_skip; if (skip !== undefined && (!Array.isArray(skip) || skip.some(s => !c.includes(s)) || skip.length >= c.length)) out.push({ code: 'POLICY_INVALID', path: 'land.docs_only_skip', message: 'must list merged_checks commands, leaving at least one to run' }); diff --git a/lib/plain-title.ts b/lib/plain-title.ts index f659d7f16d9..ff43edacfee 100644 --- a/lib/plain-title.ts +++ b/lib/plain-title.ts @@ -6,7 +6,9 @@ * tracker-code regexes, `terms` are the project's own coined words, `allow` * entries (each with a reason) suppress a match they contain, `since` exempts * PRs created before that date, and `exempt_branch_prefixes` names generated - * branches. Front for humans, end for machines: one trailing group of + * branches. DEFAULT_TERMS (the words gstack's own tools print) join `terms` + * unless `replace_default_terms` is true; `body_since` exempts older PRs from + * the body shape check (lib/pr-body-shape.ts) only. Front for humans, end for machines: one trailing group of * references such as `(GST-1713)` or `(#4122)` is never checked. A repository * without the file gets no findings. Callers: bin/gstack-plain-title, * gstack-post and the "Plain title" CI check. @@ -17,11 +19,14 @@ import { splitAgentNotes } from './agent-notes'; import { maskProse } from './prose-lint'; import { redactFindingSpans } from './redact-engine'; -export interface PlainTitlePolicy { codes: string[]; terms: string[]; allow: { text: string; reason: string }[]; since: string; exempt_branch_prefixes: string[] } +export interface PlainTitlePolicy { codes: string[]; terms: string[]; allow: { text: string; reason: string }[]; since: string; exempt_branch_prefixes: string[]; body_since?: string } export interface PlainFinding { code: 'PLAIN_TITLE_REFUSED' | 'PLAIN_BRANCH_REFUSED' | 'PLAIN_OPENING_REFUSED' | 'PLAIN_CHANGELOG_REFUSED' | 'PLAIN_COMMIT_REFUSED'; kind: 'code' | 'term' | 'scope-prefix' | 'opening-shape'; match: string; hint: string } export const PLAIN_TITLE_POLICY_PATH = '.gstack/plain-titles.json'; -const KEYS = ['$schema', 'codes', 'terms', 'allow', 'since', 'exempt_branch_prefixes']; +const KEYS = ['$schema', 'codes', 'terms', 'allow', 'since', 'exempt_branch_prefixes', 'replace_default_terms', 'body_since']; +/** Words gstack's own tools print into PR text, which mean nothing to an outside reader; a policy's `terms` add to them. */ +export const DEFAULT_TERMS: readonly string[] = ['outside voice', 'pregate', 'receipt', 'receipts', 'ledger', 'ledgers', 'fix-check', 'carry', 'stamp', 'restamp', 'train', 'trains', 'lane', 'lanes', 'soak']; +const isDate = (v: unknown) => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v) && !Number.isNaN(Date.parse(v)); const HINTS = { code: 'move the tracker code to one trailing group like (ABC-123)', PLAIN_BRANCH_REFUSED: 'keep at most one tracker code, at the very end of the branch name', @@ -29,7 +34,7 @@ const HINTS = { PLAIN_CHANGELOG_REFUSED: 'leave tracker codes out of changelog entries', term: 'say what it does for someone using the project, in everyday words', 'scope-prefix': 'drop the type(scope): prefix and start with what changed', - 'opening-shape': 'open with one or two plain sentences: what changed and which goal of the project it serves', + 'opening-shape': 'open with plain lines: what changed for a user, why, and anything the reader has to do', } as const; type Code = PlainFinding['code']; @@ -63,10 +68,13 @@ export function loadPlainTitlePolicy(repoRoot: string): PlainTitlePolicy | null if (typeof entry.text !== 'string' || !entry.text.trim()) throw bad(`allow[${i}].text`, 'must be a non-empty string'); if (typeof entry.reason !== 'string' || !entry.reason.trim()) throw bad(`allow[${i}].reason`, 'must say why the entry is allowed'); }); - if (typeof obj.since !== 'string' || !/^\d{4}-\d{2}-\d{2}/.test(obj.since) || Number.isNaN(Date.parse(obj.since))) throw bad('since', 'must be a date like 2026-11-08'); + if (!isDate(obj.since)) throw bad('since', 'must be a date like 2026-11-08'); + if (obj.body_since !== undefined && !isDate(obj.body_since)) throw bad('body_since', 'must be a date like 2026-11-20'); + if (obj.replace_default_terms !== undefined && typeof obj.replace_default_terms !== 'boolean') throw bad('replace_default_terms', 'must be true or false'); + const terms = obj.replace_default_terms ? obj.terms : [...new Set([...obj.terms, ...DEFAULT_TERMS])]; const prefixes = obj.exempt_branch_prefixes ?? []; if (!Array.isArray(prefixes) || !prefixes.every(p => typeof p === 'string' && p.length > 0)) throw bad('exempt_branch_prefixes', 'must be a list of non-empty strings'); - return { codes: obj.codes, terms: obj.terms, allow: allow as PlainTitlePolicy['allow'], since: obj.since, exempt_branch_prefixes: prefixes as string[] }; + return { codes: obj.codes, terms, allow: allow as PlainTitlePolicy['allow'], since: obj.since as string, exempt_branch_prefixes: prefixes as string[], body_since: (obj.body_since as string | undefined) ?? (obj.since as string) }; } /** A whole-word, case-insensitive regex for a term; a space in the term matches any run of spaces. */ @@ -159,7 +167,7 @@ function openingShape(line: string): string | null { return null; } -/** The readable part (above the Agent notes marker) opens with a prose paragraph of at most two sentences and no refused code or term. */ +/** The readable part (above the Agent notes marker) opens with a prose paragraph with no refused code or term; how long the opening may run is lib/pr-body-shape.ts's check. */ export function checkOpening(body: string, policy: PlainTitlePolicy | null): PlainFinding[] { if (!policy) return []; const code: Code = 'PLAIN_OPENING_REFUSED'; @@ -173,12 +181,7 @@ export function checkOpening(body: string, policy: PlainTitlePolicy | null): Pla const paragraph = lines.slice(start, end < 0 ? undefined : end).join(' ') .replace(/\]\([^)\s]*\)/g, m => ']' + ' '.repeat(m.length - 1)) .replace(/https?:\/\/\S+/g, 'URL'); - const sentences = paragraph.replace(/`[^`]*`/g, 'x').replace(/\b(?:e\.g|i\.e|etc|vs)\./gi, 'x') - .split(/[.!?]+["')\]]*(?:\s+|$)/).filter(s => s.trim()).length; - return [ - ...(sentences > 2 ? [shapeFinding(`${sentences} sentences`)] : []), - ...toFindings(code, scan(paragraph.replace(/`/g, ' '), policy)), - ]; + return toFindings(code, scan(paragraph.replace(/`[^`]*`/g, ' '), policy)); } /** No tracker code anywhere in the entry; refused terms only in its bold lead. Fenced and inline code, URLs and quoted words are skipped. */ diff --git a/lib/pr-body-shape.ts b/lib/pr-body-shape.ts new file mode 100644 index 00000000000..83980851900 --- /dev/null +++ b/lib/pr-body-shape.ts @@ -0,0 +1,143 @@ +/** + * pr-body-shape — the shape every PR body takes (R76 as amended 2026-11-15, docs/writing-prs.md): at most three + * visible lines before anything folded (what changed for a user, why, and anything the reader has to do), every + * other section folded into a `<details>` block, and the Agent notes section (lib/agent-notes.ts), which holds the + * /ship receipt, last. /ship and people write `## ` sections; gstack-post folds them on publish (foldSections), so + * nobody writes HTML by hand. checkBodyShape is the check gstack-post, gstack-plain-title and the Plain title CI check + * share; a finding refuses only in a repository with `.gstack/plain-titles.json`, and warns everywhere else. + */ +import { AGENT_NOTES_MARKER } from './agent-notes'; +import { maskProse } from './prose-lint'; + +export const VISIBLE_LINES = 3; +export const VISIBLE_CHARS = 600; +export interface BodyFinding { code: 'PLAIN_BODY_REFUSED'; kind: 'visible-lines' | 'unfolded' | 'term' | 'receipt-placement'; match: string; hint: string } + +const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/; +const closesFence = (fence: string, line: string) => new RegExp(`^ {0,3}${fence[0] === '`' ? '`' : '~'}{${fence.length},}\\s*$`).test(line); +const FOLD_OPEN = /^<details>\s*<summary>([^<]*)<\/summary>\s*$/i; +const escape = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); +const unescape = (s: string) => s.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&'); +const tagDelta = (line: string) => { const prose = line.replace(/`[^`]*`/g, ''); return (prose.match(/<details\b/gi)?.length ?? 0) - (prose.match(/<\/details>/gi)?.length ?? 0); }; + +/** One line of a body with what the shape rules need to know about it. */ +interface Line { text: string; depth: number; fenced: boolean; notes: boolean; opensFence?: boolean } + +/** Every line of the body, marking those inside a code fence, inside a `<details>` block (depth before the line) and from the Agent notes marker on. */ +function classify(body: string): Line[] { + const out: Line[] = []; + let fence: string | null = null, depth = 0, notes = false; + for (const text of body.replace(/\r\n?/g, '\n').split('\n')) { + if (!notes && fence === null && depth === 0 && text.trim() === AGENT_NOTES_MARKER) notes = true; + const line: Line = { text, depth, fenced: fence !== null, notes }; + out.push(line); + if (fence !== null) { if (closesFence(fence, text)) fence = null; continue; } + const open = FENCE_OPEN.exec(text); + if (open) { fence = open[1]!; line.fenced = true; line.opensFence = true; continue; } + depth = Math.max(0, depth + tagDelta(text)); + } + return out; +} + +/** HTML comments render as nothing, so they never count as text; the Agent notes marker, itself a comment, is kept. */ +const stripComments = (body: string) => body.replace(/<!--[\s\S]*?-->/g, m => (m === AGENT_NOTES_MARKER ? m : m.replace(/[^\n]/g, ''))); +const blankRun = (lines: string[]) => { while (lines.length && !lines[0]!.trim()) lines.shift(); while (lines.length && !lines.at(-1)!.trim()) lines.pop(); return lines; }; + +/** + * Every top-level `## ` section above the Agent notes marker becomes a fold titled by its heading; the opening above + * the first heading, existing folds, fenced code, the Agent notes section and anything after it are kept byte for + * byte. Folding a folded body changes nothing. + */ +export function foldSections(body: string): string { + const lines = classify(body); + const out: string[] = []; + let section: { title: string; body: string[] } | null = null; + const flush = () => { + if (!section) return; + out.push(`<details><summary>${escape(section.title)}</summary>`, '', ...blankRun(section.body), '', '</details>', ''); + section = null; + }; + for (const l of lines) { + const heading = !l.notes && !l.fenced && l.depth === 0 ? /^ {0,3}## (.+)$/.exec(l.text) : null; + if (heading) { flush(); section = { title: heading[1]!.trim(), body: [] }; continue; } + if (l.notes && section) flush(); + if (section) section.body.push(l.text); + else out.push(l.text); + } + flush(); + return out.join('\n').replace(/\n{3,}(?=<details>)/g, '\n\n').replace(/\n+$/, body.endsWith('\n') ? '\n' : ''); +} + +/** The inverse of foldSections for top-level folds above the Agent notes marker, so a body merges by section title (lib/gstack-post.ts). */ +export function unfoldSections(body: string): string { + const lines = classify(body); + const out: string[] = []; + for (let i = 0; i < lines.length; i++) { + const l = lines[i]!; + const open = !l.notes && !l.fenced && l.depth === 0 ? FOLD_OPEN.exec(l.text.trim()) : null; + const end = open ? lines.findIndex((m, j) => j > i && !m.fenced && m.depth === 1 && m.text.trim() === '</details>') : -1; + if (!open || end < 0) { out.push(l.text); continue; } + out.push(`## ${unescape(open[1]!.trim())}`, '', ...blankRun(lines.slice(i + 1, end).map(m => m.text)), ''); + i = end; + while (i + 1 < lines.length && !lines[i + 1]!.text.trim() && lines[i + 2] && !lines[i + 2]!.notes) i++; + } + return out.join('\n'); +} + +/** The visible opening: the lines above the first fold and the Agent notes marker, HTML comments removed, blank lines dropped; `prose` also drops code blocks, which a commit message never carries. */ +export function visibleOpening(body: string, prose = false): string[] { + const lines = classify(stripComments(body)); + const first = lines.findIndex(l => l.notes || (!l.fenced && l.depth === 0 && /^<details\b/i.test(l.text.trim()))); + return lines.slice(0, first < 0 ? undefined : first).filter(l => !(prose && l.fenced)).map(l => l.text).filter(t => t.trim()); +} + +/** A whole-word, case-insensitive matcher for a listed word; a space in it matches any run of spaces. */ +const wordRe = (term: string) => { + const t = term.trim(); + const edge = (c: string) => (/[A-Za-z0-9_]/.test(c) ? '\\b' : ''); + return new RegExp(`${edge(t[0]!)}${t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+')}${edge(t.slice(-1))}`, 'gi'); +}; + +/** + * The shape findings for a body as it will be posted (fold it first): more than VISIBLE_LINES lines or VISIBLE_CHARS + * characters before the first fold, text outside a fold between the first fold and the Agent notes marker, a listed + * word anywhere above the marker (code, quotes and URLs skipped), and a receipt outside the Agent notes section or text + * after it other than a Capy badge. + */ +export function checkBodyShape(body: string, terms: readonly string[] = []): BodyFinding[] { + const out: BodyFinding[] = []; + const add = (kind: BodyFinding['kind'], match: string, hint: string) => out.push({ code: 'PLAIN_BODY_REFUSED', kind, match, hint }); + const opening = visibleOpening(body); + const chars = [...opening.join('\n')].length; + if (opening.length > VISIBLE_LINES || chars > VISIBLE_CHARS) { + add('visible-lines', `${opening.length} lines, ${chars} characters before the first fold`, `keep at most ${VISIBLE_LINES} lines and ${VISIBLE_CHARS} characters above the first fold (what changed for a user, why, what the reader has to do); move the rest into a ## section, which gstack-post folds`); + } + const lines = classify(stripComments(body)); + const firstFold = lines.findIndex(l => !l.notes && !l.fenced && l.depth === 0 && /^<details\b/i.test(l.text.trim())); + const loose = firstFold < 0 ? [] : lines.slice(firstFold).filter(l => !l.notes && l.depth === 0 && l.text.trim() && !/^<\/?details\b/i.test(l.text.trim())); + if (loose.length) add('unfolded', loose[0]!.text.trim().slice(0, 80), 'everything below the opening sits in a fold: put it under a ## heading, which gstack-post folds'); + const notesAt = lines.findIndex(l => l.notes); + if (lines.some((l, i) => (notesAt < 0 || i < notesAt) && l.opensFence && /^ {0,3}`{3,}gstack-ship-receipt\s*$/.test(l.text))) add('receipt-placement', 'gstack-ship-receipt', 'the /ship receipt belongs in the closing Agent notes section; let gstack-ship-receipt write place it'); + if (notesAt >= 0) { + const close = lines.findIndex((l, i) => i > notesAt && !l.fenced && l.text.trim() === '</details>' && l.depth === 1); + const after = close < 0 ? '' : lines.slice(close + 1).map(l => l.text).join('\n').replace(/<a href="https:\/\/capy\.ai\/[\s\S]*?<\/a>/g, '').trim(); + if (after) add('receipt-placement', after.split('\n')[0]!.slice(0, 80), 'the Agent notes section ends the body; move this text above it'); + } + if (terms.length) { + const readable = lines.slice(0, notesAt < 0 ? undefined : notesAt).map(l => l.fenced ? '' : l.text).join('\n'); + const masked = maskProse(readable.replace(/<summary>([^<]*)<\/summary>/gi, ' $1 ')).masked.replace(/<[^>]+>/g, ' ').replace(/[^\s()[\]<>"'`]*\/[^\s()[\]<>"'`]*|[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,5}\b/g, m => ' '.repeat(m.length)); + const seen = new Set<string>(); + for (const term of terms) for (const m of masked.matchAll(wordRe(term))) { + if (seen.has(m[0].toLowerCase())) continue; + seen.add(m[0].toLowerCase()); + add('term', m[0], 'say what it does for someone using the project, in everyday words (the Agent notes section may keep it)'); + } + } + return out; +} + +/** One `PLAIN_BODY:` line per finding, in gstack-plain-title's format. */ +export function bodyFindingLine(f: BodyFinding, warnOnly: boolean): string { + const clean = f.match.replace(/[\u0000-\u001f\u007f"]/g, ' ').slice(0, 80); + return `PLAIN_BODY: ${f.code} ${f.kind} "${clean}" — ${f.hint}${warnOnly ? ' (warning only)' : ''}`; +} diff --git a/lib/release-stamp.ts b/lib/release-stamp.ts index e86c447c21f..7bff7905597 100644 --- a/lib/release-stamp.ts +++ b/lib/release-stamp.ts @@ -13,6 +13,8 @@ import * as path from 'node:path'; import { parseChangelog } from './changelog-check'; import { effectiveBump, readFragments } from './changelog-fragments'; import { restamp, versionAtRef, type RestampResult } from './restamp'; +import { withAgentNotes } from './agent-notes'; +import { foldSections } from './pr-body-shape'; import { matchesAny, type ShipPolicy } from './ship-policy'; import { buildReceipt } from './tree-receipt'; import { regeneratedAtBase } from '../crew/lib/version-gate-train'; @@ -20,6 +22,23 @@ import { bumpVersion, cmpVersion, fmtVersion, parseVersion, versionWidth } from export const RELEASE_BRANCH = /^release\/(\d+(?:\.\d+){2,3})$/; +/** + * The release notes (R76): one plain line per change the release folds, from each changelog fragment's entries (a + * fragment may hold several `- ` entries): the bold lead sentence, or else the first sentence, with the pull request + * whose squash commit added the fragment (`(#n)` at the end of its subject) when git finds one. + */ +export function releaseNoteLines(root: string, ref: string, fragments: readonly string[]): string[] { + return fragments.flatMap(file => { + const pr = /\(#(\d+)\)\s*$/.exec(git(root, ['log', '-1', '--diff-filter=A', '--format=%s', ref, '--', file]).out)?.[1]; + const text = git(root, ['show', `${ref}:${file}`]).out.replace(/^---\n[\s\S]*?\n---\n/, '').trim(); + return text.split(/\n(?=- )/).map(entry => { + const first = entry.replace(/^- +/, '').replace(/\s+/g, ' ').trim(); + const lead = (/^\*\*(.+?)\*\*/.exec(first)?.[1] ?? first.split(/(?<=[.!?])\s/)[0] ?? '').replace(/\*\*/g, '').trim(); + return lead ? `- ${lead}${pr ? ` (#${pr})` : ''}` : ''; + }).filter(Boolean); + }); +} + export type ReleaseVerdict = { ok: true; version: string; fragments: string[] } | { ok: false; reason: string }; function git(cwd: string, args: string[]): { ok: boolean; out: string; err: string } { @@ -132,16 +151,22 @@ export function openRelease(o: OpenOptions): OpenResult { if (!r.ok) return fail('RELEASE_STAMP_INVALID', `git ${step[0]} failed in the release worktree: ${r.err.split('\n')[0]}`); } const head = git(dir, ['rev-parse', 'HEAD']).out; + const notes = releaseNoteLines(dir, baseSha, git(dir, ['diff', '--name-only', '--diff-filter=D', baseSha, head]).out.split('\n').filter(f => f.endsWith('.md'))); const push = git(dir, ['push', '-q', '--force', 'origin', `HEAD:refs/heads/${branch}`]); if (!push.ok) return fail('RELEASE_STAMP_INVALID', `git push origin ${branch} failed: ${push.err.split('\n')[0]}`); lines.push(`PUSHED: ${branch} ${head}`); - const body = [ + const body = withAgentNotes([ + `v${version} ships ${notes.length} user-visible change${notes.length === 1 ? '' : 's'}, listed one per line under Release notes with the pull request that made each.`, + '', 'It changes only the version, the CHANGELOG and the files generated from them, so it needs no review: merge it once its checks are green.', + '', '## Release notes', '', ...(notes.length ? notes : ['- No user-visible changes.']), '', + ].join('\n'), [ `Release stamp for v${version}, made by \`gstack-release-stamp open\` (\`gstack-restamp --release\`) on origin/${o.base} ${baseSha.slice(0, 12)}: VERSION, the package.json version, the CHANGELOG and the release outputs.`, '', `Folds: ${folded}`, '', `Land it with \`gstack-ship-queue land --pr <this PR> --pin ${head}\` once its checks are green. land checks that this head is exactly the release stamp of its merge base (RELEASE_STAMP_INVALID otherwise), so a release PR needs no /ship receipt.`, - ].join('\n'); + ].join('\n')); + const posted = foldSections(body); const open = gh(['pr', 'list', '--head', branch, '--state', 'open', '--json', 'url,isCrossRepository', '--jq', '[.[] | select(.isCrossRepository | not)][0].url // ""'], dir); - const pr = open.ok && open.out.trim() ? open : gh(['pr', 'create', '--base', o.base, '--head', branch, '--title', `v${version} release`, '--body', body], dir); + const pr = open.ok && open.out.trim() ? open : gh(['pr', 'create', '--base', o.base, '--head', branch, '--title', `v${version} release`, '--body', posted], dir); if (!pr.ok) return fail('RELEASE_STAMP_INVALID', `gh pr create failed (${pr.err.trim().split('\n')[0]}); ${branch} is pushed, so open its PR by hand`); const url = pr.out.trim().split('\n').pop() ?? ''; const n = /\/pull\/(\d+)/.exec(url)?.[1]; diff --git a/lib/result-codes-plain.ts b/lib/result-codes-plain.ts index e2c4497c238..931f5baf82f 100644 --- a/lib/result-codes-plain.ts +++ b/lib/result-codes-plain.ts @@ -20,8 +20,13 @@ export const PLAIN_RESULT_CODES = { }, PLAIN_OPENING_REFUSED: { anchor: 'plain-opening-refused', - summary: 'the PR body does not open with one or two plain sentences', - fix: 'start the body with one or two sentences saying what changed and which goal of the project it serves; move codes and records to the Agent notes section at the end', + summary: 'the PR body does not open with a plain paragraph of at most three lines', + fix: 'start the body with up to three plain lines: what changed for a user, why, and anything the reader has to do; move codes and records to the Agent notes section at the end', + }, + PLAIN_BODY_REFUSED: { + anchor: 'plain-body-refused', + summary: 'the PR body, once folded, shows more than three lines or 600 characters before its first fold, leaves text outside a fold, uses a listed word above the Agent notes section, or does not end with that section', + fix: 'keep the opening to three plain lines, put everything else under ## headings (gstack-post folds them), say listed words in everyday words, and let gstack place the receipt in the Agent notes section at the end', }, PLAIN_CHANGELOG_REFUSED: { anchor: 'plain-changelog-refused', diff --git a/lib/ship-policy-keys.ts b/lib/ship-policy-keys.ts index c10bd928225..ec89c1c7e9d 100644 --- a/lib/ship-policy-keys.ts +++ b/lib/ship-policy-keys.ts @@ -54,6 +54,9 @@ export const PLAN_RECORD_KEY_VERSION = '1.98.0.0'; export const DOCS_ONLY_KEY_VERSION = '1.99.0.0'; /** `land.docs_only_skip` is a field of the older land key, so compatErrors and minimumReader check it by value, as for bump: never. */ export const LAND_DOCS_ONLY_SKIP_KEY_VERSION = '1.99.0.0'; +/** `history: no-rewrite` and `land.merge_commit_paths` are a value and a field of older keys, checked by value like bump: never. */ +export const HISTORY_NO_REWRITE_KEY_VERSION = '1.100.0.0'; +export const LAND_MERGE_COMMIT_PATHS_KEY_VERSION = '1.100.0.0'; export const POLICY_KEY_INTRODUCED: Record<PolicyKey, string> = { bump: '1.91.73.0', queue_mode: '1.91.73.0', release_tool: '1.91.73.0', release_outputs: '1.91.73.0', stamp_paths: '1.91.73.0', changelog: '1.91.73.0', mirror: '1.91.73.0', history: '1.91.73.0', preregistration_shas: '1.91.73.0', stamp_sensitive_gates: '1.91.73.0', diff --git a/lib/ship-policy.ts b/lib/ship-policy.ts index c2e6d98fa1f..b5731248e58 100644 --- a/lib/ship-policy.ts +++ b/lib/ship-policy.ts @@ -23,7 +23,7 @@ import { RESULT_CODES, type ResultCodeName } from './result-codes'; import { reviewErrors, type ReviewPolicy } from './ship-policy-review'; import { READERS_EXPLANATION, readersErrors, type ReadersPolicy } from './ship-policy-readers'; import { cmpVersion, parseVersion } from './version-source'; -import { POLICY_COMPAT_FLOOR, BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, POLICY_KEY_INTRODUCED, LAND_DOCS_ONLY_SKIP_KEY_VERSION } from './ship-policy-keys'; +import { POLICY_COMPAT_FLOOR, BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, POLICY_KEY_INTRODUCED, LAND_DOCS_ONLY_SKIP_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION } from './ship-policy-keys'; import { placeholderErrors, templateErrors } from './ship-policy-stamps'; import { bookkeepingGlobError, globError } from './ship-policy-bookkeeping'; import { MECHANICAL_EXPLANATION, mechanicalErrors, type MechanicalConstant } from './ship-policy-mechanical'; @@ -34,7 +34,7 @@ export const SHIP_POLICY_SCHEMA = 'https://github.com/garrytan/gstack/docs/ship- export type BumpPolicy = 'patch' | 'ask' | 'never'; export type QueueMode = 'claim-at-open' | 'stamp-at-merge'; -export type HistoryPolicy = 'merge-only' | 'squash-ok'; +export type HistoryPolicy = 'merge-only' | 'squash-ok' | 'no-rewrite'; /** `frozen`: /ship fixes the diff in pass 1, defers unchanged code to the PR body and reviews only the range after; `all`: every finding is fixed now. */ export type ReviewScope = 'frozen' | 'diff-plus-blocking' | 'all'; @@ -56,7 +56,7 @@ export interface ShipPolicy { changelog_fragments: { dir: string; required_checks?: string[] } | null; /** Path of a paired repo to restamp identically (tier 2). */ mirror: string | null; - /** `merge-only` refuses a squash or rebase plan in /ship. */ + /** `merge-only` refuses a squash or rebase plan in /ship; `no-rewrite` refuses a rebase or force-push and lands by squash. */ history: HistoryPolicy; /** Each must be an ancestor of HEAD before push (`gstack-evidence ancestor`). */ preregistration_shas: string[]; @@ -212,7 +212,7 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = { changelog: 'CHANGELOG path re-headed on a restamp (the PR’s `[Unreleased]` or old-version section moves to the top under the new version). null to skip.', changelog_fragments: '{ dir, required_checks? } or null: a PR adds one unversioned `<dir>/<slug>.md` fragment (optional `bump: minor|major` front matter) instead of an `[Unreleased]` section and leaves VERSION, the manifest version and released CHANGELOG sections at its merge base; the restamp folds every fragment under the allocated version and deletes the files (docs/ship-policy.md#changelog-fragments). `required_checks` lists the check runs or status contexts `train land` requires present and green on a stamp commit. null keeps `[Unreleased]`.', mirror: 'Relative path of a paired repo to restamp identically; writes are confined to it. null to skip.', - history: 'merge-only | squash-ok. merge-only makes /ship refuse a squash or rebase plan.', + history: 'merge-only | squash-ok | no-rewrite. merge-only makes /ship refuse a squash or rebase plan and land with a merge commit; no-rewrite refuses a rebase or force-push of the branch but lands by squash, titled with the PR title (docs/writing-prs.md#the-commit-on-main), and needs min_gstack_version.', preregistration_shas: 'Commits that must be ancestors of HEAD before push (preregistered evals); checked by `gstack-evidence ancestor`.', stamp_sensitive_gates: 'Evidence labels (gstack-evidence --label) that read VERSION or generated bytes; the tree receipt never marks them reusable.', review_scope: 'frozen | diff-plus-blocking | all. frozen (default): /ship Step 9 fixes findings in the diff on pass 1, files blocking findings in code the PR did not change as issues, and later passes read only the range since the previous pass and fix only blocking findings; diff-plus-blocking: the same, but a blocking finding in code the PR did not change is fixed in this PR instead of filed; all: every finding is fixed now (the pre-1.91.249 loop).', @@ -260,18 +260,19 @@ export function installedGstackVersion(): string { */ export function runningGstackVersion(): string { const own = installedGstackVersion(); - const known = [...Object.values(POLICY_KEY_INTRODUCED), BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION].reduce((a, b) => (newer(b, a) ? b : a)); + const known = [...Object.values(POLICY_KEY_INTRODUCED), BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION].reduce((a, b) => (newer(b, a) ? b : a)); return parseVersion(own) && !newer(known, own) ? own : known; } /** The newest introducing version among the keys a parsed policy sets: the gstack a crew needs to read it. */ export function minimumReader(raw: Record<string, unknown>): string { return Object.keys(raw).filter((k): k is PolicyKey => POLICY_KEYS.includes(k as PolicyKey)) - .map(k => (k === 'bump' && raw.bump === 'never' ? BUMP_NEVER_KEY_VERSION : k === 'land' && landSkips(raw.land) ? LAND_DOCS_ONLY_SKIP_KEY_VERSION : k === 'train' && genericTrainKeys(raw.train) ? TRAIN_GATES_KEY_VERSION : POLICY_KEY_INTRODUCED[k])).reduce((a, b) => (newer(b, a) ? b : a), POLICY_KEY_INTRODUCED.bump); + .map(k => (k === 'bump' && raw.bump === 'never' ? BUMP_NEVER_KEY_VERSION : k === 'history' && raw.history === 'no-rewrite' ? HISTORY_NO_REWRITE_KEY_VERSION : k === 'land' && landPaths(raw.land) ? LAND_MERGE_COMMIT_PATHS_KEY_VERSION : k === 'land' && landSkips(raw.land) ? LAND_DOCS_ONLY_SKIP_KEY_VERSION : k === 'train' && genericTrainKeys(raw.train) ? TRAIN_GATES_KEY_VERSION : POLICY_KEY_INTRODUCED[k])).reduce((a, b) => (newer(b, a) ? b : a), POLICY_KEY_INTRODUCED.bump); } export interface PolicyError { code: ResultCodeName; path: string; message: string } const landSkips = (land: unknown): boolean => !!land && typeof land === 'object' && 'docs_only_skip' in land; +const landPaths = (land: unknown): boolean => !!land && typeof land === 'object' && 'merge_commit_paths' in land; /** Unknown keys under land and docs_only: ignored with a warning so a newer gstack can add one (docs/ship-policy.md#schema-v1). */ export function policyWarnings(raw: Record<string, unknown>): PolicyWarning[] { @@ -469,7 +470,7 @@ export function validatePolicy(raw: unknown, opts: { gstackVersion?: string } = if (stamps.length) errors.push({ code: 'POLICY_INVALID', path: 'bump', message: `never keeps VERSION on every PR, but ${stamps.join(' and ')} stamps a version at every merge; drop one` }); } oneOf('queue_mode', ['claim-at-open', 'stamp-at-merge']); - oneOf('history', ['merge-only', 'squash-ok']); + oneOf('history', ['merge-only', 'squash-ok', 'no-rewrite']); oneOf('review_scope', ['frozen', 'diff-plus-blocking', 'all']); oneOf('merge', ['direct', 'train']); if ('review_exclude_paths' in obj) excludeErrors(obj.review_exclude_paths, errors); @@ -560,6 +561,9 @@ function compatErrors(obj: Record<string, unknown>, running: string, errors: Pol if (landSkips(obj.land) && !(typeof min === 'string' && !newer(LAND_DOCS_ONLY_SKIP_KEY_VERSION, min))) { errors.push({ code: 'POLICY_INVALID', path: 'land.docs_only_skip', message: `introduced in gstack ${LAND_DOCS_ONLY_SKIP_KEY_VERSION}; set min_gstack_version to ${LAND_DOCS_ONLY_SKIP_KEY_VERSION} or later so an older gstack refuses this policy by name` }); } + for (const [on, path, since] of [[obj.history === 'no-rewrite', 'history', HISTORY_NO_REWRITE_KEY_VERSION], [landPaths(obj.land), 'land.merge_commit_paths', LAND_MERGE_COMMIT_PATHS_KEY_VERSION]] as const) { + if (on && !(typeof min === 'string' && !newer(since, min))) errors.push({ code: 'POLICY_INVALID', path, message: `${path === 'history' ? 'no-rewrite was introduced' : 'introduced'} in gstack ${since}; set min_gstack_version to ${since} or later so an older gstack refuses this policy by name` }); + } if (obj.bump === 'never' && !(typeof min === 'string' && !newer(BUMP_NEVER_KEY_VERSION, min))) { errors.push({ code: 'POLICY_INVALID', path: 'bump', message: `never was introduced in gstack ${BUMP_NEVER_KEY_VERSION}; set min_gstack_version to ${BUMP_NEVER_KEY_VERSION} or later so an older gstack refuses this policy by name` }); } @@ -741,6 +745,7 @@ export function renderEffective(load: LoadedPolicy, opts: { base?: string } = {} export function shipConsequences(policy: ShipPolicy, base: string): string[] { const out: string[] = []; if (policy.history === 'merge-only') out.push('history merge-only: never rebase, squash or force-push this branch; `gstack-ship-policy check-history --plan <merge|squash|rebase>` refuses a rewrite plan (HISTORY_POLICY_VIOLATION)'); + if (policy.history === 'no-rewrite') out.push('history no-rewrite: never rebase or force-push this branch (merge the base in instead); land squashes it into one commit titled with the PR title; `gstack-ship-policy check-history --plan <merge|squash|rebase>` refuses a rebase plan (HISTORY_POLICY_VIOLATION)'); if (policy.queue_mode === 'stamp-at-merge') { out.push(`queue_mode stamp-at-merge: Step 12 items 1-4 are replaced by \`gstack-restamp --next --base ${base} --pr <pr-number> --expect-base <base-sha>\` when this PR is next in the queue (\`--after <predecessor-pr>\` gates ahead in a throwaway worktree when it is not); follow its next: line; claims are ignored`); out.push(`shared merge queue: when a coordinator runs the queue, \`gstack-ship-queue ready --pr <n>\`, \`gate-ahead --after <pr> --pr <n>\` and \`stamp --pr <n> --version <X> --expect-gated <sha> --expect-base <sha>\` replace the calls above; stamp only when your slot is called, send the READY block and the QUEUE_STAMP: line; the coordinator runs \`gstack-ship-queue verify\` (docs/ship-policy.md#run-a-shared-merge-queue)${policy.gate_command ? `; gate command: \`${policy.gate_command}\`` : ''}`); diff --git a/lib/ship-queue-land-direct.ts b/lib/ship-queue-land-direct.ts index 98a0e4ee09d..d86ab7a527c 100644 --- a/lib/ship-queue-land-direct.ts +++ b/lib/ship-queue-land-direct.ts @@ -8,8 +8,10 @@ * moved past the pin's merge base, the checks at the pin never saw the tree that would land (GST-1316), so land builds * the pin merged onto the base tip and runs the base policy's land.merged_checks there (lib/land-merged-checks.ts; * repo commands, so only under --allow-repo-commands and never under --dry-run), refusing on a conflict or a failure; - * with no list it prints a STALE_BASE: warn line and lands. Then gh pr merge --squash --match-head-commit <pin> with the - * PR title as the commit subject (`--subject "<title> (#<n>)"`, so the checked title is main's history title), a check + * with no list it prints a STALE_BASE: warn line and lands. Then gh pr merge --match-head-commit <pin> with the message + * lib/squash-message.ts builds (subject `<title> (#<n>)`, so the checked title is main's history title, and a body of + * the PR body's opening lines plus the branch's trailers; `--squash`, or `--merge` under history: merge-only or a + * land.merge_commit_paths match), a check * that the merge commit's tree is the pin merged onto that commit's parent (its merged checks rerun when that parent is * neither the base land checked nor in the pin), a land note on refs/notes/gstack-trains, and the lock's release. A * rerun after GitHub merged goes straight to the tree check. @@ -28,9 +30,10 @@ import * as os from 'node:os'; import { activeFreeze, loadReady, persist, rebuildFromNotes, repoIdentity, type FreezeRecord } from '../crew/lib/ship-queue-train-record'; import { bindShippedReceipt } from './ship-receipt-depth'; import { gateAcceptance } from './gate-dispositions'; +import { landMessage, mergeArgs, messageLines, sectionText } from './squash-message'; interface DirectPr { state: string; baseRefName?: string; headRefName: string; headRefOid: string; isCrossRepository: boolean; body: string; title?: string; mergeable?: string; mergeStateStatus?: string; mergeCommit?: { oid: string } | null } -export interface DirectOptions { pr: string; pin: string; dryRun?: boolean; allowRepoCommands?: boolean; breakLock?: boolean; repair?: boolean; now?: () => Date; acceptGateDispositions?: readonly string[] } +export interface DirectOptions { pr: string; pin: string; body?: string; dryRun?: boolean; allowRepoCommands?: boolean; breakLock?: boolean; repair?: boolean; now?: () => Date; acceptGateDispositions?: readonly string[] } /** * The pin's /ship receipt bound to it, and every owner gate disposition the approval store applies at the pin accepted by the @@ -238,7 +241,6 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput { if ('failure' in got) return fail(lines, got.failure); held = got.held; } - const subject = info.title?.trim() ? ['--subject', `${info.title.trim()} (#${o.pr})`] : []; const locked = (): StepOutput => { if (held && !git(root, ['fetch', '-q', 'origin', ctx.base]).ok) return fail(lines, { code: 'QUEUE_NOT_READY', message: `cannot re-fetch origin/${ctx.base} under the land lock`, fix: 'fix the fetch, then rerun land' }); const tip = git(root, ['rev-parse', `origin/${ctx.base}`]).out; @@ -260,7 +262,10 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput { lines.push(`MERGED_CHECKS: pass tree=${mc.tree} base=${tip} pin=${o.pin.slice(0, 12)} checks: ${checks.join('; ')}`); } } - if (o.dryRun) return { ok: true, run, lines: [...lines, `DRY-RUN: nothing merged (would run gh pr merge ${o.pr} ${policy.history === 'merge-only' ? '--merge' : '--squash'} --match-head-commit ${o.pin}${subject.length ? ` --subject ${JSON.stringify(subject[1])}` : ''})`] }; + const msg = landMessage(root, { pr: o.pr, title: info.title ?? '', prBody: info.body ?? '', mergeBase, pin: o.pin, tip, policy, override: o.body ?? (release ? sectionText(info.body ?? '', 'Release notes') || undefined : undefined) }); + if ('error' in msg) return fail(lines, { code: 'QUEUE_NOT_READY', message: msg.error, fix: 'rewrite the PR title or the opening lines of its body, or pass land --body-file <file> with the plain lines to use; then rerun land' }); + lines.push(...messageLines(msg)); + if (o.dryRun) return { ok: true, run, lines: [...lines, `DRY-RUN: nothing merged (would run gh pr merge ${o.pr} --${msg.method} --match-head-commit ${o.pin} with the SUBJECT and BODY above)`] }; if (o.repair) { if (!rebuildFromNotes(root, remote).fetched) return fail(lines, { code: 'QUEUE_NOT_READY', message: `cannot fetch refs/notes/gstack-trains under the land lock, so the freeze's repair slot cannot be read; nothing merged`, fix: 'fix the fetch, then rerun land' }); const frozen = activeFreeze(keys); @@ -275,10 +280,9 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput { lines.push(`REPAIR: #${o.pr}@${o.pin.slice(0, 12)} admitted under the land lock; the freeze stays active until the main backstop is green on a main that contains this merge`); } - const method = policy.history === 'merge-only' ? '--merge' : '--squash'; const lost = held!.set('merging'); if (lost) return fail(lines, lost); - const m = ctx.gh(['pr', 'merge', o.pr, method, '--match-head-commit', o.pin, ...subject]); + const m = ctx.gh(mergeArgs(o.pr, o.pin, msg)); let merge: string | undefined; for (let i = 0; i < (m.ok ? 3 : 1) && !isSha(merge); i++) { if (i) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, pollDelayMs(MIN_POLL_MS)); diff --git a/lib/ship-queue-land.ts b/lib/ship-queue-land.ts index d8232fc6c5a..aa8f2d6f2d2 100644 --- a/lib/ship-queue-land.ts +++ b/lib/ship-queue-land.ts @@ -23,6 +23,8 @@ import { matchesAny, type ShipPolicy } from './ship-policy'; import { ciAtHead, loadBasePolicy, type QueueContext, type StepOutput } from './ship-queue'; import { QUEUE_DIR_REL, git, writeJsonAtomic, type QueueFailure } from '../crew/lib/ship-queue-gate'; import { landPlan } from './plan-record'; +import { landMessage, mergeArgs, messageLines } from './squash-message'; +import { withAgentNotes } from './agent-notes'; import { bindShippedReceipt } from './ship-receipt-depth'; import { TERMINAL_STATES, freezeLockCleared, loadReady, loadTrain, rebuildFromNotes, repoIdentity } from '../crew/lib/ship-queue-train-record'; @@ -51,9 +53,10 @@ export interface LandJournal { drift_main?: string; repair_pr?: string; phase: 'locked' | 'stamped' | 'pushed' | 'merged' | 'landed' | 'drift'; } -export interface LandOptions { pr: string; repair?: boolean; dryRun?: boolean; noWait?: boolean; breakLock?: boolean; breakTrainLock?: boolean; allowRepoCommands?: boolean; waitTimeoutMin?: number; now?: () => Date; holder?: string } +export interface LandOptions { pr: string; body?: string; repair?: boolean; dryRun?: boolean; noWait?: boolean; breakLock?: boolean; breakTrainLock?: boolean; allowRepoCommands?: boolean; waitTimeoutMin?: number; now?: () => Date; holder?: string } const fail = (lines: string[], failure: QueueFailure, run: string): StepOutput => ({ ok: false, lines, failure, run }); +const MESSAGE_FIX = 'rewrite the PR title or the opening lines of its body, or pass land --body-file <file> with the plain lines to use; then rerun land'; export const landJournalRel = (pr: string) => `${QUEUE_DIR_REL}/land/${pr}.json`; function readJson<T>(file: string): T | null { try { return JSON.parse(fs.readFileSync(file, 'utf8')) as T; } catch { return null; } } @@ -303,7 +306,7 @@ function repair(ctx: QueueContext, policy: ShipPolicy, j: LandJournal | null, fi pushed = remote[0]!; lines.push(`branch: ${branch} already on origin at ${pushed.slice(0, 12)} (an earlier --repair pushed it); opening or finding its PR`); } - const pr = ctx.gh(['pr', 'create', '--base', ctx.base, '--head', branch, '--title', `Add a changelog entry for changes merged by hand next to #${j.pr}`, '--body', `QUEUE_LAND_DRIFT repair (docs/troubleshooting.md#queue-land-drift). Outside commits: ${outside.join(', ') || 'unknown'}.`]); + const pr = ctx.gh(['pr', 'create', '--base', ctx.base, '--head', branch, '--title', `Add a changelog entry for changes merged by hand next to #${j.pr}`, '--body', withAgentNotes(`Adds a CHANGELOG entry for ${outside.length || 'the'} change${outside.length === 1 ? '' : 's'} merged into ${ctx.base} by hand next to #${j.pr}, so the next release lists ${outside.length === 1 ? 'it' : 'them'}.\n\nMerge it like any other pull request; nothing else to do.\n`, `QUEUE_LAND_DRIFT repair (docs/troubleshooting.md#queue-land-drift). Outside commits: ${outside.join(', ') || 'unknown'}.`)]); const n = /\/pull\/(\d+)/.exec(`${pr.out}\n${pr.err ?? ''}`)?.[1]; if (!n) return fail(lines, { code: 'QUEUE_NOT_READY', message: `gh pr create failed: ${(pr.err ?? pr.out).trim().slice(0, 160)}` }, run); j.repair_pr = n; writeJsonAtomic(file, j); @@ -355,6 +358,10 @@ export function land(ctx: QueueContext, o: LandOptions): StepOutput { if (plan.line) lines.push(plan.line); if (plan.failure) return fail(lines, plan.failure, run); } + const message = (reviewed: string) => { + const tip = git(root, ['rev-parse', `origin/${ctx.base}`]).out; + return landMessage(root, { pr: o.pr, title: info.title ?? '', prBody: info.body ?? '', mergeBase: git(root, ['merge-base', tip, reviewed]).out, pin: reviewed, tip, policy, override: o.body }); + }; if (!j) { const ci = ciAtHead(ctx, pin); lines.push(`CI: ${ci.line}`, ...ci.superseded); @@ -364,7 +371,9 @@ export function land(ctx: QueueContext, o: LandOptions): StepOutput { git(root, ['fetch', '-q', 'origin', ctx.base]); const s = buildStamp(ctx, policy, { pin, baseSha: git(root, ['rev-parse', `origin/${ctx.base}`]).out, pr: o.pr, title: info.title, allowRepoCommands: !!o.allowRepoCommands, now: now() }); if ('code' in s) return fail(lines, s, run); - return { ok: true, run, lines: [...lines, ...s.lines, `STAMP_VERSION: ${s.version}`, `STAMP_TREE: ${s.tree}`, 'DRY-RUN: nothing locked, pushed or merged'] }; + const msg = message(pin); + if ('error' in msg) return fail(lines, { code: 'QUEUE_NOT_READY', message: msg.error, fix: MESSAGE_FIX }, run); + return { ok: true, run, lines: [...lines, ...s.lines, `STAMP_VERSION: ${s.version}`, `STAMP_TREE: ${s.tree}`, ...messageLines(msg), 'DRY-RUN: nothing locked, pushed or merged'] }; } let driftOf: string | undefined; @@ -443,9 +452,12 @@ export function land(ctx: QueueContext, o: LandOptions): StepOutput { const ci = ciAtHead(ctx, j.stamp_commit!); lines.push(`CI: ${ci.line}`); if (!ci.green) return { ok: !ci.line.startsWith('red'), run, lines: [...lines, `NEXT: gstack-pr-wait ${o.pr} --until green && gstack-ship-queue land --pr ${o.pr}`], failure: ci.line.startsWith('red') ? { code: 'QUEUE_NOT_READY', message: `a check failed on the stamp commit ${j.stamp_commit!.slice(0, 12)}` } : undefined }; + const msg = message(j.reviewed_pin); + if ('error' in msg) return fail(lines, { code: 'QUEUE_NOT_READY', message: msg.error, fix: MESSAGE_FIX }, run); + lines.push(...messageLines(msg)); const fm = setLock('merging'); if (fm) return fail(lines, fm, run); - const m = ctx.gh(['pr', 'merge', o.pr, policy.history === 'merge-only' ? '--merge' : '--squash', '--match-head-commit', j.stamp_commit!]); + const m = ctx.gh(mergeArgs(o.pr, j.stamp_commit!, msg)); if (!m.ok) return fail(lines, { code: 'QUEUE_NOT_READY', message: `gh pr merge refused: ${(m.err ?? m.out).trim().slice(0, 200)}` }, run); j.phase = 'merged'; save(); } diff --git a/lib/squash-message.ts b/lib/squash-message.ts new file mode 100644 index 00000000000..c577a680e28 --- /dev/null +++ b/lib/squash-message.ts @@ -0,0 +1,90 @@ +/** + * squash-message — the commit a PR lands as (R76 as amended 2026-11-15, docs/writing-prs.md#the-commit-on-main). The + * subject is the PR title with GitHub's ` (#n)` suffix; the body is the PR body's visible opening (at most three lines + * and 600 characters, the part above the first fold) followed by every distinct `Key: value` trailer the branch's + * commits carry (Co-authored-by, Removed-test and the rest) plus a Co-authored-by for every commit author other than + * the first, so main's one-line log reads as a list of changes and credit survives the squash. A MEDIUM redaction + * finding drops the opening and keeps the trailers; a HIGH one refuses the land. Commits of a stacked parent that already landed are left out (landedStackParent), and the + * whole message passes the shared redaction scan before gh sees it. Every gstack merge (land --pin, the stamping + * land --pr, train land) builds its message here and picks its method with landMethod. + */ +import { spawnSync } from 'node:child_process'; +import type { ShipPolicy } from './ship-policy'; +import { AGENT_NOTES_MARKER } from './agent-notes'; +import { foldSections, unfoldSections, visibleOpening, VISIBLE_CHARS, VISIBLE_LINES } from './pr-body-shape'; +import { scan, type RepoVisibility } from './redact-engine'; +import { landedStackParent } from './ship-receipt'; + +export interface LandMessage { subject: string; body: string; method: 'merge' | 'squash'; why: string; skippedParent: string | null } + +const git = (root: string, args: string[]) => spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 120_000, maxBuffer: 64 * 1024 * 1024 }); + +/** Text wrapped at 72 columns between words, the width git log and GitHub's commit view expect. */ +const wrap = (text: string) => text.split(' ').reduce<string[]>((lines, w) => { const last = lines.at(-1); if (last !== undefined && [...last].length + 1 + [...w].length <= 72) lines[lines.length - 1] = `${last} ${w}`; else lines.push(w); return lines; }, []).join('\n'); + +/** The body's visible opening, at most VISIBLE_LINES lines and VISIBLE_CHARS characters, cut between lines (a first line that alone is too long is cut short), links reduced to their text and each line wrapped at 72. */ +export function openingLines(body: string): string { + const out: string[] = []; + for (const line of visibleOpening(foldSections(body), true).slice(0, VISIBLE_LINES).map(l => l.replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim()).filter(Boolean)) { + if ([...[...out, line].join('\n\n')].length <= VISIBLE_CHARS) { out.push(line); continue; } + if (!out.length) out.push([...line].slice(0, VISIBLE_CHARS - 1).join('') + '…'); + break; + } + return out.map(wrap).join('\n\n'); +} + +/** Every distinct trailer git's own parser finds on the non-merge commits in from..to, oldest first (the first spelling wins); null when git cannot read the range. */ +export function branchTrailers(root: string, from: string, to: string): string[] | null { + const r = git(root, ['log', '--reverse', '--no-merges', '--format=%(trailers:only,unfold)', `${from}..${to}`]); + if (r.status !== 0) return null; + const authors = git(root, ['log', '--reverse', '--no-merges', '--format=%an <%ae>', `${from}..${to}`]); + if (authors.status !== 0) return null; + const others = authors.stdout.split('\n').filter(Boolean).filter((a, _, all) => a !== all[0]).map(a => `Co-authored-by: ${a}`); + const seen = new Map<string, string>(); + for (const line of [...r.stdout.split('\n').map(l => l.trim()), ...others]) if (/^[A-Za-z][A-Za-z0-9-]*: \S/.test(line) && !seen.has(line.toLowerCase())) seen.set(line.toLowerCase(), line); + return [...seen.values()]; +} + +/** merge under history: merge-only or when the PR changes a land.merge_commit_paths pathspec (a commit a receipt points to must stay on the base); squash otherwise. */ +export function landMethod(root: string, policy: Pick<ShipPolicy, 'history' | 'land'>, mergeBase: string, pin: string): { method: 'merge' | 'squash'; why: string } { + if (policy.history === 'merge-only') return { method: 'merge', why: 'history: merge-only' }; + const paths = policy.land?.merge_commit_paths ?? []; + if (!paths.length) return { method: 'squash', why: `history: ${policy.history}` }; + const r = git(root, ['diff', '--name-only', mergeBase, pin, '--', ...paths.map(p => `:(glob)${p}`)]); + if (r.status !== 0) return { method: 'merge', why: 'git could not read the changed paths, so land.merge_commit_paths may match' }; + const hit = r.stdout.split('\n').find(Boolean); + return hit ? { method: 'merge', why: `land.merge_commit_paths matches ${hit}` } : { method: 'squash', why: 'no land.merge_commit_paths match' }; +} + +/** + * The subject and body `gh pr merge` gets. `override` (land --body-file) replaces the opening, never the trailers. + * Refuses (error) when git cannot read the branch's commits or the message holds a HIGH redaction finding. + */ +export function landMessage(root: string, o: { pr: string; title: string; prBody: string; mergeBase: string; pin: string; tip: string; policy: Pick<ShipPolicy, 'history' | 'land'>; override?: string; visibility?: RepoVisibility }): LandMessage | { error: string } { + const parent = landedStackParent(root, { rangeBase: o.mergeBase, reviewed: o.pin, currentBase: o.tip }, ['.']); + const trailers = branchTrailers(root, parent ?? o.mergeBase, o.pin); + if (!o.title.trim()) return { error: `#${o.pr} has no title to use as the commit subject` }; + if (!trailers) return { error: `git cannot read #${o.pr}'s commits ${(parent ?? o.mergeBase).slice(0, 12)}..${o.pin.slice(0, 12)}` }; + const subject = `${o.title.trim()} (#${o.pr})`; + const opening = o.override?.trim() ?? openingLines(o.prBody); + const findings = (text: string) => scan(text, { repoVisibility: o.visibility ?? 'unknown' }).findings; + const high = findings([subject, opening, ...trailers].join('\n\n')).filter(f => f.severity === 'HIGH'); + if (high.length) return { error: `the merge commit message holds ${high.map(f => f.id).join(', ')}; nothing merged` }; + const kept = opening && findings(opening).some(f => f.severity === 'MEDIUM') ? '' : opening; + return { subject, body: [kept, trailers.join('\n')].filter(Boolean).join('\n\n'), ...landMethod(root, o.policy, o.mergeBase, o.pin), skippedParent: parent }; +} + +/** The text of a body's `## <title>` section, or of its fold with that summary; '' when it has none. A release PR's squash body is its Release notes section. */ +export function sectionText(body: string, title: string): string { + const lines = unfoldSections(body).split('\n'); + const start = lines.findIndex(l => l.trim() === `## ${title}`); + if (start < 0) return ''; + const end = lines.findIndex((l, i) => i > start && (/^## /.test(l) || l.trim() === AGENT_NOTES_MARKER)); + return lines.slice(start + 1, end < 0 ? undefined : end).join('\n').trim(); +} + +/** What land prints before it merges: the method (and why), the subject, each body line, and a skipped stacked parent. */ +export const messageLines = (m: LandMessage): string[] => [`METHOD: ${m.method} (${m.why})`, `SUBJECT: ${m.subject}`, ...m.body.split('\n').map(l => `BODY: ${l}`), ...(m.skippedParent ? [`STACK_PARENT: ${m.skippedParent.slice(0, 12)} already landed; its commits' trailers are left out`] : [])]; + +/** The gh pr merge argv for a message: the method, the exact head, and for a merge or squash the subject and body. */ +export const mergeArgs = (pr: string, head: string, m: LandMessage): string[] => ['pr', 'merge', pr, `--${m.method}`, '--match-head-commit', head, '--subject', m.subject, '--body', m.body]; diff --git a/ship/sections/capy-pr.md b/ship/sections/capy-pr.md index e9cd5581a62..42923fb1793 100644 --- a/ship/sections/capy-pr.md +++ b/ship/sections/capy-pr.md @@ -6,9 +6,13 @@ Read only when Step 19 printed `CAPY_PR: on`. Under Capy a person decides the me the READY report, through a Captain, so the body shows what changed in pictures, why, and who approved what. Guide: `captain.md` beside the Capy `gstack` skill's SKILL.md. -**Order.** The plain opening sentences come first, then `## What changed`, `## Why` and `## Blast radius`, -then the standard sections below. `## Approvals` goes inside the closing Agent notes section, where -`gstack-ship-receipt write` also puts the receipt. Keep `## Summary` to commit themes; do not repeat the captions. +**Order.** The plain opening lines come first (at most three), then `## What changed`, `## Why` and `## Blast radius`, +then the standard sections. `## What changed` holds the pictures below, then the template's themes, without +repeating the captions. gstack-post folds each into a collapsed section. `## Approvals` goes inside the closing +Agent notes section, where `gstack-ship-receipt write` also puts the receipt. A body posted any other way, +Capy's PR tool included, is folded first: pass the output of +`~/.claude/skills/gstack/bin/gstack-post fold --body-file "$PR_BODY_FILE"` (it posts nothing, and exit 4 +with `PLAIN_BODY:` lines means rewrite the body file first). 1. **Pick the evidence:** one to three before/after pairs, highest-signal first. The first is the key image. diff --git a/ship/sections/capy-pr.md.tmpl b/ship/sections/capy-pr.md.tmpl index 41a36d84fe1..35f3928fc62 100644 --- a/ship/sections/capy-pr.md.tmpl +++ b/ship/sections/capy-pr.md.tmpl @@ -4,9 +4,13 @@ Read only when Step 19 printed `CAPY_PR: on`. Under Capy a person decides the me the READY report, through a Captain, so the body shows what changed in pictures, why, and who approved what. Guide: `captain.md` beside the Capy `gstack` skill's SKILL.md. -**Order.** The plain opening sentences come first, then `## What changed`, `## Why` and `## Blast radius`, -then the standard sections below. `## Approvals` goes inside the closing Agent notes section, where -`gstack-ship-receipt write` also puts the receipt. Keep `## Summary` to commit themes; do not repeat the captions. +**Order.** The plain opening lines come first (at most three), then `## What changed`, `## Why` and `## Blast radius`, +then the standard sections. `## What changed` holds the pictures below, then the template's themes, without +repeating the captions. gstack-post folds each into a collapsed section. `## Approvals` goes inside the closing +Agent notes section, where `gstack-ship-receipt write` also puts the receipt. A body posted any other way, +Capy's PR tool included, is folded first: pass the output of +`~/.claude/skills/gstack/bin/gstack-post fold --body-file "$PR_BODY_FILE"` (it posts nothing, and exit 4 +with `PLAIN_BODY:` lines means rewrite the body file first). 1. **Pick the evidence:** one to three before/after pairs, highest-signal first. The first is the key image. diff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.md index 18d7e926c7c..87bf1c6af1a 100644 --- a/ship/sections/pr-body.md +++ b/ship/sections/pr-body.md @@ -80,15 +80,19 @@ Run `[ "${GSTACK_CAPY:-}" = 1 ] && echo 'CAPY_PR: on' || echo 'CAPY_PR: off'`. O lead; `## Approvals` goes into the Agent notes. On `CAPY_PR: off`, skip it. The PR/MR body should contain these sections (never reuse a prior run's body). The front is for people, -the end is for machines: the body opens with one or two plain sentences (what changed for someone using -the project, and which goal from the project's README it serves; with no stated goals, the user-visible -benefit), with no heading above them. Tracker codes, receipts, approval and Plan lines, review-loop and -gate lines and every other machine-read line go only in the closing Agent notes section, never above it. +the end is for machines (docs/writing-prs.md): the body opens with at most three plain lines and 600 +characters, with no heading above them: what changed for someone using the project, why (the README goal it +serves, or the user-visible benefit), and anything the reader has to do. Everything else goes under a `## ` +heading, which gstack-post folds into a collapsed section on publish, each thing said once, with long logs +and review output linked rather than pasted. Tracker codes, receipts, approval and Plan lines, review-loop +and gate lines and every other machine-read line go only in the closing Agent notes section, never above it, +and so do in-house words such as the ones docs/writing-prs.md lists. ``` -<One or two plain sentences: what changed for a user, and the README goal it serves.> +<Up to three plain lines, 600 characters in all: what changed for a user; why (the README goal it +serves); and what the reader has to do, or "Nothing to do".> -## Summary +## What changed <Open with the problem in the user's words (what they hit, saw or asked), then the fix and what they get now; themes from `git log origin/<base>..HEAD --oneline` after that, minus VERSION/CHANGELOG bookkeeping. Never an inventory or a commit list. BAD: "Adds @@ -102,6 +106,7 @@ files, hosts) and the one fact that makes that safe, with the rung of the eviden ladder the fact reached (file:line read, walked failure path, script ran, repro).> ## Test Coverage +<Only when Step 7 ran or found gaps; otherwise omit (the Tests section says what ran).> <coverage diagram from Step 7, or "All new code paths have test coverage."> <If Step 7 ran: "Tests: {before} → {after} (+{delta} new)"> <If Step 7 ran: "Coverage: {X}% value-weighted ({Y}% including {W} weakly covered paths)"> @@ -114,10 +119,10 @@ details for cards whose file type has no known comment syntax.> ZERO-RUN lane never reaches this body unresolved.> ## Pre-Landing Review -<findings from Step 9 code review, or "No issues found."; then Step 9.4's `REVIEW_LOOP:` line.> -<Each `Ruled note: …` line `gstack-approvals rulings` prints, verbatim: a finding the owner ruled a disclosed note, +<findings from Step 9 code review in plain words, or "No issues found."; link long review output instead of pasting it.> +<In the Agent notes section, never here: Step 9.4's `REVIEW_LOOP:` line, each `Ruled note: …` line `gstack-approvals rulings` prints, verbatim: a finding the owner ruled a disclosed note, with its ruler and reason; each `Gate disposition: …` line `gstack-approvals dispositions` prints, verbatim; finish's `MECHANICAL: x` as `Mechanical retake: x` and its `UID_SIDECAR: x (beside y)` as `Godot UID sidecar: x (beside y)`. `gstack-ship-receipt write --body` refuses a body missing one.> -<Gate edits: Step 9's latest `Gate edits:` line verbatim — `none detected (...)`, +<Gate edits: in the Agent notes section, Step 9's latest `Gate edits:` line verbatim — `none detected (...)`, `N listed, M read, K findings — J kept, R restored, O open`, `partial (...)` or `UNAVAILABLE — ...`; never `none detected` for partial or UNAVAILABLE. Under it, each kept finding's `gate`, path and `reason`, and each open finding's `gate` and path. @@ -185,15 +190,13 @@ word for word as Step 14.5 saved it in `.gstack/tmp/docs-audit.json`: the receipt write below refuses (`DOCS_AUDIT_BLOCKED`) when the body lacks it.> <Always include the status and reviewed scope: updated, current, or blocked with the actual user's named risk exception. Never omit this section or reuse another invocation's audit.> -## Test plan -- [x] <Each executed test lane's command>: <observed passing summary> - -🤖 Generated with [Claude Code](https://claude.com/claude-code) +## Tests +- [x] <Each executed test command>: <observed passing summary> <!-- gstack:agent-notes --> <details><summary>Agent notes</summary> -<Machine-read lines, last: `Refs <issue codes>`, the `## Approvals` output (Capy) with its Plan line, +<Machine-read lines, last: "🤖 Generated with Claude Code", `Refs <issue codes>`, the `## Approvals` output (Capy) with its Plan line, and the Pre-Landing Review section's `REVIEW_LOOP:`, `Gate edits:`, `Ruled note:`, `Gate disposition:`, `Review-loop exception:` and exception lines. `gstack-ship-receipt write` adds the receipt here; never type it.> @@ -209,8 +212,9 @@ tool-attributed fences (` ```codex-review ` / ` ```review-bot `) so the scanner WARN-degrades the example credentials those tools quote instead of blocking the PR (a live-format credential inside the fence still blocks). -Write the body from above into two private files: the first through the -`## Documentation` heading line, the second from `## Test plan` on, ending with the Agent notes section. +Write the body from above into two private files, with plain `## ` headings (gstack-post folds them; +never write `<details>` by hand): the first through the `## Documentation` heading line, the second +from `## Tests` on, ending with the Agent notes section. ```bash _GT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp" @@ -232,8 +236,8 @@ PR_BODY_FILE=$(mktemp "${TMPDIR:-/tmp}/gstack-pr-body.XXXXXX") || { echo "ERROR: BODY_TOP_FILE="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp/<body-top-file-name>" BODY_REST_FILE="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp/<body-rest-file-name>" [ -s "$BODY_TOP_FILE" ] && [ -s "$BODY_REST_FILE" ] || { echo "Not composed: $BODY_TOP_FILE or $BODY_REST_FILE is empty, so the body was never written. Write both, then rerun." >&2; exit 1; } -~/.claude/skills/gstack/bin/gstack-prose-lint "$BODY_TOP_FILE" --sections 'Why,Summary,Blast radius' --gate >&2 || { echo "Not composed: fix what gstack-prose-lint printed above (a PROSE: line is a sentence to rewrite in the draft; a usage line means the draft lost a heading), then rerun." >&2; exit 1; } -~/.claude/skills/gstack/bin/gstack-plain-title check --body-file "$BODY_TOP_FILE" >&2 || { echo "Not composed: rewrite the opening the PLAIN_TITLE: lines above name (one or two plain sentences, no heading or code above them), then rerun." >&2; exit 1; } +~/.claude/skills/gstack/bin/gstack-prose-lint "$BODY_TOP_FILE" --sections 'Why,What changed,Blast radius' --gate >&2 || { echo "Not composed: fix what gstack-prose-lint printed above (a PROSE: line is a sentence to rewrite in the draft; a usage line means the draft lost a heading), then rerun." >&2; exit 1; } +~/.claude/skills/gstack/bin/gstack-plain-title check --body-file "$BODY_TOP_FILE" >&2 || { echo "Not composed: rewrite what the PLAIN_TITLE: and PLAIN_BODY: lines above name (at most three plain lines before the first ## heading, no listed word above the Agent notes section), then rerun." >&2; exit 1; } { awk 1 "$BODY_TOP_FILE" && cat -- "$DOCS_SECTION_FILE" && echo && awk 1 "$BODY_REST_FILE"; } > "$PR_BODY_FILE" || exit 1 rm -f "$BODY_TOP_FILE" "$BODY_REST_FILE" echo "PR_BODY_FILE: $PR_BODY_FILE" @@ -325,8 +329,9 @@ With open gate findings the same command carries `--draft` before `--title-file` Branch on the exit code of either block: - **0** posted. Remove `$PR_BODY_FILE` and the title file. -- **4** `PLAIN_TITLE_REFUSED`: nothing was posted, body included. Rewrite the title file's front the way - each `PLAIN_TITLE:` line says (Step 18 item 5) and rerun the same block. +- **4** nothing was posted, title and body checked in one pass. For each `PLAIN_TITLE:` line, rewrite the + title file's front the way it says (Step 18 item 5); for each `PLAIN_BODY:` line, rewrite `$PR_BODY_FILE` + the way it says (docs/troubleshooting.md#plain-body-refused). Then rerun the same block. - **1** HIGH finding: BLOCKED — do not publish. Rotate and redact at the source, then compose fresh files. - **2** MEDIUM findings, printed as `RULE:` lines with a `TOKEN:`. AskUserQuestion per diff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmpl index af7ed820eef..c0bfb63ad70 100644 --- a/ship/sections/pr-body.md.tmpl +++ b/ship/sections/pr-body.md.tmpl @@ -71,15 +71,19 @@ Run `[ "${GSTACK_CAPY:-}" = 1 ] && echo 'CAPY_PR: on' || echo 'CAPY_PR: off'`. O lead; `## Approvals` goes into the Agent notes. On `CAPY_PR: off`, skip it. The PR/MR body should contain these sections (never reuse a prior run's body). The front is for people, -the end is for machines: the body opens with one or two plain sentences (what changed for someone using -the project, and which goal from the project's README it serves; with no stated goals, the user-visible -benefit), with no heading above them. Tracker codes, receipts, approval and Plan lines, review-loop and -gate lines and every other machine-read line go only in the closing Agent notes section, never above it. +the end is for machines (docs/writing-prs.md): the body opens with at most three plain lines and 600 +characters, with no heading above them: what changed for someone using the project, why (the README goal it +serves, or the user-visible benefit), and anything the reader has to do. Everything else goes under a `## ` +heading, which gstack-post folds into a collapsed section on publish, each thing said once, with long logs +and review output linked rather than pasted. Tracker codes, receipts, approval and Plan lines, review-loop +and gate lines and every other machine-read line go only in the closing Agent notes section, never above it, +and so do in-house words such as the ones docs/writing-prs.md lists. ``` -<One or two plain sentences: what changed for a user, and the README goal it serves.> +<Up to three plain lines, 600 characters in all: what changed for a user; why (the README goal it +serves); and what the reader has to do, or "Nothing to do".> -## Summary +## What changed <Open with the problem in the user's words (what they hit, saw or asked), then the fix and what they get now; themes from `git log origin/<base>..HEAD --oneline` after that, minus VERSION/CHANGELOG bookkeeping. Never an inventory or a commit list. BAD: "Adds @@ -93,6 +97,7 @@ files, hosts) and the one fact that makes that safe, with the rung of the eviden ladder the fact reached (file:line read, walked failure path, script ran, repro).> ## Test Coverage +<Only when Step 7 ran or found gaps; otherwise omit (the Tests section says what ran).> <coverage diagram from Step 7, or "All new code paths have test coverage."> <If Step 7 ran: "Tests: {before} → {after} (+{delta} new)"> <If Step 7 ran: "Coverage: {X}% value-weighted ({Y}% including {W} weakly covered paths)"> @@ -105,10 +110,10 @@ details for cards whose file type has no known comment syntax.> ZERO-RUN lane never reaches this body unresolved.> ## Pre-Landing Review -<findings from Step 9 code review, or "No issues found."; then Step 9.4's `REVIEW_LOOP:` line.> -<Each `Ruled note: …` line `gstack-approvals rulings` prints, verbatim: a finding the owner ruled a disclosed note, +<findings from Step 9 code review in plain words, or "No issues found."; link long review output instead of pasting it.> +<In the Agent notes section, never here: Step 9.4's `REVIEW_LOOP:` line, each `Ruled note: …` line `gstack-approvals rulings` prints, verbatim: a finding the owner ruled a disclosed note, with its ruler and reason; each `Gate disposition: …` line `gstack-approvals dispositions` prints, verbatim; finish's `MECHANICAL: x` as `Mechanical retake: x` and its `UID_SIDECAR: x (beside y)` as `Godot UID sidecar: x (beside y)`. `gstack-ship-receipt write --body` refuses a body missing one.> -<Gate edits: Step 9's latest `Gate edits:` line verbatim — `none detected (...)`, +<Gate edits: in the Agent notes section, Step 9's latest `Gate edits:` line verbatim — `none detected (...)`, `N listed, M read, K findings — J kept, R restored, O open`, `partial (...)` or `UNAVAILABLE — ...`; never `none detected` for partial or UNAVAILABLE. Under it, each kept finding's `gate`, path and `reason`, and each open finding's `gate` and path. @@ -176,15 +181,13 @@ word for word as Step 14.5 saved it in `.gstack/tmp/docs-audit.json`: the receipt write below refuses (`DOCS_AUDIT_BLOCKED`) when the body lacks it.> <Always include the status and reviewed scope: updated, current, or blocked with the actual user's named risk exception. Never omit this section or reuse another invocation's audit.> -## Test plan -- [x] <Each executed test lane's command>: <observed passing summary> - -🤖 Generated with [Claude Code](https://claude.com/claude-code) +## Tests +- [x] <Each executed test command>: <observed passing summary> <!-- gstack:agent-notes --> <details><summary>Agent notes</summary> -<Machine-read lines, last: `Refs <issue codes>`, the `## Approvals` output (Capy) with its Plan line, +<Machine-read lines, last: "🤖 Generated with Claude Code", `Refs <issue codes>`, the `## Approvals` output (Capy) with its Plan line, and the Pre-Landing Review section's `REVIEW_LOOP:`, `Gate edits:`, `Ruled note:`, `Gate disposition:`, `Review-loop exception:` and exception lines. `gstack-ship-receipt write` adds the receipt here; never type it.> @@ -200,8 +203,9 @@ tool-attributed fences (` ```codex-review ` / ` ```review-bot `) so the scanner WARN-degrades the example credentials those tools quote instead of blocking the PR (a live-format credential inside the fence still blocks). -Write the body from above into two private files: the first through the -`## Documentation` heading line, the second from `## Test plan` on, ending with the Agent notes section. +Write the body from above into two private files, with plain `## ` headings (gstack-post folds them; +never write `<details>` by hand): the first through the `## Documentation` heading line, the second +from `## Tests` on, ending with the Agent notes section. {{FREE_TEXT_FILE:BODY_TOP_FILE=pr-body-top:BODY_REST_FILE=pr-body-rest}} @@ -215,8 +219,8 @@ PR_BODY_FILE=$(mktemp "${TMPDIR:-/tmp}/gstack-pr-body.XXXXXX") || { echo "ERROR: BODY_TOP_FILE="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp/<body-top-file-name>" BODY_REST_FILE="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp/<body-rest-file-name>" [ -s "$BODY_TOP_FILE" ] && [ -s "$BODY_REST_FILE" ] || { echo "Not composed: $BODY_TOP_FILE or $BODY_REST_FILE is empty, so the body was never written. Write both, then rerun." >&2; exit 1; } -~/.claude/skills/gstack/bin/gstack-prose-lint "$BODY_TOP_FILE" --sections 'Why,Summary,Blast radius' --gate >&2 || { echo "Not composed: fix what gstack-prose-lint printed above (a PROSE: line is a sentence to rewrite in the draft; a usage line means the draft lost a heading), then rerun." >&2; exit 1; } -~/.claude/skills/gstack/bin/gstack-plain-title check --body-file "$BODY_TOP_FILE" >&2 || { echo "Not composed: rewrite the opening the PLAIN_TITLE: lines above name (one or two plain sentences, no heading or code above them), then rerun." >&2; exit 1; } +~/.claude/skills/gstack/bin/gstack-prose-lint "$BODY_TOP_FILE" --sections 'Why,What changed,Blast radius' --gate >&2 || { echo "Not composed: fix what gstack-prose-lint printed above (a PROSE: line is a sentence to rewrite in the draft; a usage line means the draft lost a heading), then rerun." >&2; exit 1; } +~/.claude/skills/gstack/bin/gstack-plain-title check --body-file "$BODY_TOP_FILE" >&2 || { echo "Not composed: rewrite what the PLAIN_TITLE: and PLAIN_BODY: lines above name (at most three plain lines before the first ## heading, no listed word above the Agent notes section), then rerun." >&2; exit 1; } { awk 1 "$BODY_TOP_FILE" && cat -- "$DOCS_SECTION_FILE" && echo && awk 1 "$BODY_REST_FILE"; } > "$PR_BODY_FILE" || exit 1 rm -f "$BODY_TOP_FILE" "$BODY_REST_FILE" echo "PR_BODY_FILE: $PR_BODY_FILE" @@ -308,8 +312,9 @@ With open gate findings the same command carries `--draft` before `--title-file` Branch on the exit code of either block: - **0** posted. Remove `$PR_BODY_FILE` and the title file. -- **4** `PLAIN_TITLE_REFUSED`: nothing was posted, body included. Rewrite the title file's front the way - each `PLAIN_TITLE:` line says (Step 18 item 5) and rerun the same block. +- **4** nothing was posted, title and body checked in one pass. For each `PLAIN_TITLE:` line, rewrite the + title file's front the way it says (Step 18 item 5); for each `PLAIN_BODY:` line, rewrite `$PR_BODY_FILE` + the way it says (docs/troubleshooting.md#plain-body-refused). Then rerun the same block. - **1** HIGH finding: BLOCKED — do not publish. Rotate and redact at the source, then compose fresh files. - **2** MEDIUM findings, printed as `RULE:` lines with a `TOKEN:`. AskUserQuestion per diff --git a/test/docsync-report-interface.test.ts b/test/docsync-report-interface.test.ts index 821094e8096..99ebd8058e3 100644 --- a/test/docsync-report-interface.test.ts +++ b/test/docsync-report-interface.test.ts @@ -73,7 +73,7 @@ mock.module(path.join(root, 'test/helpers/session-runner.ts'), () => ({ } else { const prBody = fs.readFileSync(path.join(fixture.skills, 'ship/sections/pr-body.md'), 'utf8'); const start = prBody.indexOf('## Documentation'); - const end = prBody.indexOf('## Test plan', start); + const end = prBody.indexOf('## Tests', start); expect(start).toBeGreaterThan(0); expect(end).toBeGreaterThan(start); expect(phase).toContain(prBody.slice(start, end)); diff --git a/test/gate-integrity-templates.test.ts b/test/gate-integrity-templates.test.ts index 3a9dd3018e6..f0d8b4c5577 100644 --- a/test/gate-integrity-templates.test.ts +++ b/test/gate-integrity-templates.test.ts @@ -94,7 +94,7 @@ test('/ship Step 16 stage 5 reports each gate finding with disposition, reason a test('/ship PR body carries the Gate edits line and per-lane counts, and an open finding keeps a new PR a draft', () => { const body = read('ship/sections/pr-body.md.tmpl'); - const skeleton = between(body, '## Summary', '#### Compose the body'); + const skeleton = between(body, '## What changed', '#### Compose the body'); const coverage = between(skeleton, '## Test Coverage', '## Pre-Landing Review'); expectTokens(coverage, ['Tests ran: <lane> N', 'Tests ran: <lane> count unavailable', '`tests_ran`'], 'PR body Test Coverage'); const review = between(skeleton, '## Pre-Landing Review', '## Exploratory QA'); diff --git a/test/gstack-post.test.ts b/test/gstack-post.test.ts index 56f0440c143..9ab7dd55335 100644 --- a/test/gstack-post.test.ts +++ b/test/gstack-post.test.ts @@ -13,6 +13,7 @@ import * as path from "node:path"; import { EXIT, attributionCallout, mergeBodySections, runPost, type PostEnv } from "../lib/gstack-post"; import { extractReceipt, orderReceipt, placeReceipt, receiptRuns } from "../lib/ship-receipt"; import type { ShipReceipt } from "../lib/headless-artifacts"; +import { foldSections, unfoldSections } from "../lib/pr-body-shape"; interface Call { cmd: string; args: string[]; input?: string } @@ -348,7 +349,7 @@ describe("gstack-post owns the redaction scan", () => { ); for (const [name, text, needle] of holds) { const { code, phones, f } = post(text); - expect([name, phones, code]).toEqual([name, [`RULE: pii.phone.e164 LINE: ${lineOf(text, needle)} PART: body`], EXIT.confirm]); + expect([name, phones, code]).toEqual([name, [`RULE: pii.phone.e164 LINE: ${lineOf(foldSections(text), needle)} PART: body`], EXIT.confirm]); expect(f.posts()).toEqual([]); } }); @@ -494,23 +495,33 @@ describe("gstack-post pr-body merges the PR body by section", () => { test("a first-section-only body keeps the other sections and the receipt; a same-titled section is replaced in place; new sections are appended", () => { const f = withBody(CURRENT, { "/b": "## What Changed\n\n- the new summary\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], f)).toBe(EXIT.posted); - expect(sent(f).input).toBe(RECEIPT("aaaa") + "\n## What Changed\n\n- the new summary\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n"); + expect(sent(f).input).toBe(foldSections(RECEIPT("aaaa") + "\n## What Changed\n\n- the new summary\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n")); expect(f.stderr()).toBe("gstack-post: pr-body merged by section: replaced What changed; kept ship receipt, Why, Approvals; added none\n"); expect(f.calls.find(c => c.cmd === "gh" && c.args[1] === "view")!.args).toEqual(["pr", "view", "5", "--json", "body", "--jq", ".body"]); const receipt = withBody(CURRENT, { "/b": RECEIPT("bbbb") }); expect(run(["pr-body", "5", "--body-file", "/b"], receipt)).toBe(EXIT.posted); - expect(sent(receipt).input).toBe(CURRENT.replace(RECEIPT("aaaa"), RECEIPT("bbbb"))); + expect(sent(receipt).input).toBe(foldSections(CURRENT.replace(RECEIPT("aaaa"), RECEIPT("bbbb")))); expect(receipt.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt; kept What changed, Why, Approvals; added none\n"); const added = withBody(CURRENT, { "/b": "## Why\n\nStill because.\n\n## Tests\n\n- one\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], added)).toBe(EXIT.posted); - expect(sent(added).input).toBe(RECEIPT("aaaa") + "\n## What changed\n\n- the old summary\n\n## Why\n\nStill because.\n\n## Approvals\n\n- owner: do it\n\n## Tests\n\n- one\n"); + expect(sent(added).input).toBe(foldSections(RECEIPT("aaaa") + "\n## What changed\n\n- the old summary\n\n## Why\n\nStill because.\n\n## Approvals\n\n- owner: do it\n\n## Tests\n\n- one\n")); expect(added.stderr()).toBe("gstack-post: pr-body merged by section: replaced Why; kept ship receipt, What changed, Approvals; added Tests\n"); const fenced = withBody("## Notes\n\n```md\n## not a heading\n```\n\n## Why\n\nold\n", { "/b": "## Why\n\nnew\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], fenced)).toBe(EXIT.posted); - expect(sent(fenced).input).toBe("## Notes\n\n```md\n## not a heading\n```\n\n## Why\n\nnew\n"); + expect(sent(fenced).input).toBe(foldSections("## Notes\n\n```md\n## not a heading\n```\n\n## Why\n\nnew\n")); + }); + + // Value: protects=re-posting an already-folded body (the live body, or gstack-post fold output) replaces each section once instead of keeping the + // old sections beside it; fails_when=the incoming folds are read as leading text and every section ends up twice; why_new=GST-2737 review (granted fix-check) + test("a folded incoming body replaces the folded sections it names; nothing is duplicated", () => { + const current = foldSections("Opening.\n\n## Tests\n\nOld\n\n## Why\n\nBecause.\n"); + const f = withBody(current, { "/b": foldSections("Opening.\n\n## Tests\n\nNew\n") }); + expect(run(["pr-body", "5", "--body-file", "/b"], f)).toBe(EXIT.posted); + expect(sent(f).input).toBe(foldSections("Opening.\n\n## Tests\n\nNew\n\n## Why\n\nBecause.\n")); + expect(f.stderr()).toContain("replaced leading text, Tests; kept Why"); }); // Value: protects=a fence closes only on a run of its own character at least as long as the opener with nothing after it, so a ``` line inside a @@ -522,31 +533,31 @@ describe("gstack-post pr-body merges the PR body by section", () => { const long = "## Notes\n\n````md\n```\n## Tests\nfake\n```\n````\n\n## Tests\n\nold\n"; const four = withBody(long, { "/b": "## Tests\n\nnew\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], four)).toBe(EXIT.posted); - expect(sent(four).input).toBe("## Notes\n\n````md\n```\n## Tests\nfake\n```\n````\n\n## Tests\n\nnew\n"); + expect(sent(four).input).toBe(foldSections("## Notes\n\n````md\n```\n## Tests\nfake\n```\n````\n\n## Tests\n\nnew\n")); expect(four.stderr()).toBe("gstack-post: pr-body merged by section: replaced Tests; kept Notes; added none\n"); const info = withBody("## Notes\n\n```sh\n```js\n## Tests\n~~~\n```\n\n## Tests\n\nold\n", { "/b": "## Tests\n\nnew\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], info)).toBe(EXIT.posted); - expect(sent(info).input).toBe("## Notes\n\n```sh\n```js\n## Tests\n~~~\n```\n\n## Tests\n\nnew\n"); + expect(sent(info).input).toBe(foldSections("## Notes\n\n```sh\n```js\n## Tests\n~~~\n```\n\n## Tests\n\nnew\n")); const unclosed = "```gstack-ship-receipt\nSHIP_RECEIPT: pr=5 head=aaaa\n\n## Summary\n\nold\n\n## Approvals\n\n- owner: do it\n"; const open = withBody(unclosed, { "/b": RECEIPT("bbbb") + "\n## Summary\n\nnew\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], open)).toBe(EXIT.posted); - expect(sent(open).input).toBe(RECEIPT("bbbb") + "\n" + unclosed + "\n## Summary\n\nnew\n"); + expect(sent(open).input).toBe(foldSections(RECEIPT("bbbb") + "\n" + unclosed + "\n## Summary\n\nnew\n")); expect(open.stderr()).toBe("gstack-post: pr-body merged by section: replaced none; kept unclosed receipt fence; added ship receipt, Summary\n"); const prose = withBody(unclosed, { "/b": "Updated introduction\n\n## Summary\n\nnew\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], prose)).toBe(EXIT.posted); - expect(sent(prose).input).toBe("Updated introduction\n\n" + unclosed + "\n## Summary\n\nnew\n"); + expect(sent(prose).input).toBe(foldSections("Updated introduction\n\n" + unclosed + "\n## Summary\n\nnew\n")); const inside = withBody("Intro\n\n## Notes\n\n" + unclosed, { "/b": "New intro\n\n## Notes\n\nnew notes\n\n## Approvals\n\n- owner: still\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], inside)).toBe(EXIT.posted); - expect(sent(inside).input).toBe("New intro\n\n## Notes\n\nnew notes\n\n" + unclosed + "\n## Approvals\n\n- owner: still\n"); + expect(sent(inside).input).toBe(foldSections("New intro\n\n## Notes\n\nnew notes\n\n" + unclosed + "\n## Approvals\n\n- owner: still\n")); expect(inside.stderr()).toBe("gstack-post: pr-body merged by section: replaced leading text, Notes; kept unclosed receipt fence; added Approvals\n"); const after = withBody(RECEIPT("aaaa") + "\n## Why\n\nold\n\n" + unclosed, { "/b": RECEIPT("bbbb") + "\n## Why\n\nnew\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], after)).toBe(EXIT.posted); - expect(sent(after).input).toBe(RECEIPT("bbbb") + "\n## Why\n\nnew\n\n" + unclosed); + expect(sent(after).input).toBe(foldSections(RECEIPT("bbbb") + "\n## Why\n\nnew\n\n" + unclosed)); expect(after.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, Why; kept unclosed receipt fence; added none\n"); }); @@ -560,18 +571,18 @@ describe("gstack-post pr-body merges the PR body by section", () => { const intro = "Draft intro from gh pr create, long enough to need truncation in the summary line\nsecond line\n\n"; const stale = withBody(intro + CURRENT, { "/b": RECEIPT("bbbb") + "\n## What changed\n\n- new\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], stale)).toBe(EXIT.posted); - expect(sent(stale).input).toBe(intro + RECEIPT("bbbb") + "\n## What changed\n\n- new\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n"); + expect(sent(stale).input).toBe(foldSections(intro + RECEIPT("bbbb") + "\n## What changed\n\n- new\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: do it\n")); expect(stale.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, What changed; kept leading text, Why, Approvals; added none\n"); const between = withBody(RECEIPT("aaaa") + "Old note under the receipt\n\n## What changed\n\n- old\n", { "/b": RECEIPT("bbbb") + "## What changed\n\n- new\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], between)).toBe(EXIT.posted); - expect(sent(between).input).toBe(RECEIPT("bbbb") + "\n## What changed\n\n- new\n"); + expect(sent(between).input).toBe(foldSections(RECEIPT("bbbb") + "\n## What changed\n\n- new\n")); expect(between.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, What changed; kept none; added none; dropped trailing text (\"Old note under the receipt\")\n"); const own = withBody("Stale intro\n\n" + RECEIPT("aaaa") + "Stale note\n\n## Why\n\nold\n", { "/b": "Fresh intro\n\n" + RECEIPT("bbbb") + "Fresh note\n\n## Why\n\nnew\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], own)).toBe(EXIT.posted); - expect(sent(own).input).toBe("Fresh intro\n\n" + RECEIPT("bbbb") + "\nFresh note\n\n## Why\n\nnew\n"); - expect(mergeBodySections(sent(own).input!, "Fresh intro\n\n" + RECEIPT("bbbb") + "Fresh note\n\n## Why\n\nnew\n").body).toBe(sent(own).input!); + expect(sent(own).input).toBe(foldSections("Fresh intro\n\n" + RECEIPT("bbbb") + "\nFresh note\n\n## Why\n\nnew\n")); + expect(foldSections(mergeBodySections(unfoldSections(sent(own).input!), "Fresh intro\n\n" + RECEIPT("bbbb") + "Fresh note\n\n## Why\n\nnew\n").body)).toBe(sent(own).input!); expect(own.stderr()).toBe("gstack-post: pr-body merged by section: replaced leading text, ship receipt, trailing text, Why; kept none; added none\n"); }); @@ -585,17 +596,17 @@ describe("gstack-post pr-body merges the PR body by section", () => { const PREAMBLE = BADGE + "\nThis PR stops the login retry from looping.\n\n"; const first = withBody(PREAMBLE + "## What changed\n\n- the old summary\n\n## Why\n\nBecause.\n", { "/b": RECEIPT("bbbb") + "\n## What changed\n\n- new\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], first)).toBe(EXIT.posted); - expect(sent(first).input).toBe(PREAMBLE + RECEIPT("bbbb") + "\n## What changed\n\n- new\n\n## Why\n\nBecause.\n"); + expect(sent(first).input).toBe(foldSections(PREAMBLE + RECEIPT("bbbb") + "\n## What changed\n\n- new\n\n## Why\n\nBecause.\n")); expect(first.stderr()).toBe("gstack-post: pr-body merged by section: replaced What changed; kept leading text, Why; added ship receipt\n"); const again = withBody(sent(first).input!, { "/b": RECEIPT("cccc") + "\n## What changed\n\n- newer\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], again)).toBe(EXIT.posted); - expect(sent(again).input).toBe(PREAMBLE + RECEIPT("cccc") + "\n## What changed\n\n- newer\n\n## Why\n\nBecause.\n"); + expect(sent(again).input).toBe(foldSections(PREAMBLE + RECEIPT("cccc") + "\n## What changed\n\n- newer\n\n## Why\n\nBecause.\n")); expect(again.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, What changed; kept leading text, Why; added none\n"); const trailing = withBody(CURRENT + "\n" + BADGE, { "/b": RECEIPT("bbbb") + "\n## Approvals\n\n- owner: ship it\n\n## Tests\n\n- one\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], trailing)).toBe(EXIT.posted); - expect(sent(trailing).input).toBe(RECEIPT("bbbb") + "\n## What changed\n\n- the old summary\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: ship it\n\n## Tests\n\n- one\n\n" + BADGE); + expect(sent(trailing).input).toBe(foldSections(RECEIPT("bbbb") + "\n## What changed\n\n- the old summary\n\n## Why\n\nBecause.\n\n## Approvals\n\n- owner: ship it\n\n## Tests\n\n- one\n\n" + BADGE)); expect(trailing.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt, Approvals; kept What changed, Why, capy-badge block; added Tests\n"); }); @@ -655,7 +666,7 @@ describe("gstack-post pr-body merges the PR body by section", () => { test("a partial post keeps the current intro and the note under the receipt", () => { const partial = withBody("Human intro\n\n" + RECEIPT("aaaa") + "Review-loop exception: accepted by owner\n\n## What changed\n\n- old\n", { "/b": "## Screenshots\n\n![shot](u)\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], partial)).toBe(EXIT.posted); - expect(sent(partial).input).toBe("Human intro\n\n" + RECEIPT("aaaa") + "Review-loop exception: accepted by owner\n\n## What changed\n\n- old\n\n## Screenshots\n\n![shot](u)\n"); + expect(sent(partial).input).toBe(foldSections("Human intro\n\n" + RECEIPT("aaaa") + "Review-loop exception: accepted by owner\n\n## What changed\n\n- old\n\n## Screenshots\n\n![shot](u)\n")); expect(partial.stderr()).toBe("gstack-post: pr-body merged by section: replaced none; kept leading text, ship receipt, trailing text, What changed; added Screenshots\n"); for (const file of ["Screenshots below.\n\n## Screenshots\n\n![shot](u)\n", "## Screenshots\n\n![shot](u)\n\n" + RECEIPT("bbbb")]) { @@ -678,12 +689,12 @@ describe("gstack-post pr-body merges the PR body by section", () => { const lead = "Human intro\n\n" + CURRENT; const receiptOnly = withBody(lead, { "/b": RECEIPT("bbbb") }); expect(run(["pr-body", "5", "--body-file", "/b"], receiptOnly)).toBe(EXIT.posted); - expect(sent(receiptOnly).input).toBe(lead.replace(RECEIPT("aaaa"), RECEIPT("bbbb"))); + expect(sent(receiptOnly).input).toBe(foldSections(lead.replace(RECEIPT("aaaa"), RECEIPT("bbbb")))); expect(receiptOnly.stderr()).toBe("gstack-post: pr-body merged by section: replaced ship receipt; kept leading text, What changed, Why, Approvals; added none\n"); const textOnly = withBody(RECEIPT("aaaa") + "Old note\n\n## Why\n\nx\n", { "/b": "New intro\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], textOnly)).toBe(EXIT.posted); - expect(sent(textOnly).input).toBe("New intro\n\n" + RECEIPT("aaaa") + "Old note\n\n## Why\n\nx\n"); + expect(sent(textOnly).input).toBe(foldSections("New intro\n\n" + RECEIPT("aaaa") + "Old note\n\n## Why\n\nx\n")); expect(textOnly.stderr()).toBe("gstack-post: pr-body merged by section: replaced none; kept ship receipt, trailing text, Why; added leading text\n"); const composed = "Intro\n\n" + RECEIPT("bbbb") + "\n## Summary\n\nnew\n\n## Test plan\n\n- [x] bun test\n"; @@ -707,22 +718,22 @@ describe("gstack-post pr-body merges the PR body by section", () => { test("--replace overwrites; a body without H2 headings is kept above a new receipt by any file; the merged bytes are what is scanned; a failed read refuses", () => { const replaced = withBody(CURRENT, { "/b": "## What changed\n\nonly this\n" }); expect(run(["pr-body", "5", "--replace", "--body-file", "/b"], replaced)).toBe(EXIT.posted); - expect(sent(replaced).input).toBe("## What changed\n\nonly this\n"); + expect(sent(replaced).input).toBe(foldSections("## What changed\n\nonly this\n")); expect(replaced.stderr()).toBe(""); expect(replaced.calls.some(c => c.cmd === "gh" && c.args[1] === "view")).toBe(false); const plain = withBody("Just a paragraph.\nAnother line.", { "/b": RECEIPT("bbbb") + "\n## Tests\n\n- one\n" }); expect(run(["pr-body", "5", "--body-file", "/b"], plain)).toBe(EXIT.posted); - expect(sent(plain).input).toBe("Just a paragraph.\nAnother line.\n\n" + RECEIPT("bbbb") + "\n## Tests\n\n- one\n"); + expect(sent(plain).input).toBe(foldSections("Just a paragraph.\nAnother line.\n\n" + RECEIPT("bbbb") + "\n## Tests\n\n- one\n")); expect(plain.stderr()).toBe("gstack-post: pr-body merged by section: replaced none; kept leading text; added ship receipt, Tests\n"); const plainText = withBody("Just a paragraph.\nAnother line.", { "/b": RECEIPT("bbbb") }); expect(run(["pr-body", "5", "--body-file", "/b"], plainText)).toBe(EXIT.posted); - expect(sent(plainText).input).toBe("Just a paragraph.\nAnother line.\n\n" + RECEIPT("bbbb")); + expect(sent(plainText).input).toBe(foldSections("Just a paragraph.\nAnother line.\n\n" + RECEIPT("bbbb"))); expect(plainText.stderr()).toBe("gstack-post: pr-body merged by section: replaced none; kept leading text; added ship receipt\n"); const empty = withBody("", { "/b": "new body" }); expect(run(["pr-body", "6", "--body-file", "/b"], empty)).toBe(EXIT.posted); - expect(sent(empty).input).toBe("new body"); + expect(sent(empty).input).toBe(foldSections("new body")); const secret = fakeEnv({ files: { "/b": "## What changed\n\nclean\n" }, respond: c => (c.cmd === "gh" && c.args[1] === "view" ? { status: 0, stdout: "## Keys\n\n" + AWS + "\n" } : undefined) }); expect(run(["pr-body", "5", "--body-file", "/b"], secret)).toBe(EXIT.refused); @@ -747,15 +758,15 @@ describe("gstack-post pr-body merges the PR body by section", () => { const merged = fakeEnv({ remote, files: { "/b": "## Why\n\nnew\n" }, respond: view(JSON.stringify({ iid: 8, description: "## What changed\n\n- old\n\n## Why\n\nold\n" }) + "\n") }); expect(run(["pr-body", "8", "--body-file", "/b"], merged)).toBe(EXIT.posted); expect(merged.calls.find(c => c.cmd === "glab" && c.args[1] === "view")!.args).toEqual(["mr", "view", "8", "--output", "json"]); - expect(merged.posts()).toEqual([{ cmd: "glab", args: ["mr", "update", "8", "--description=## What changed\n\n- old\n\n## Why\n\nnew\n"], input: undefined }]); + expect(merged.posts()).toEqual([{ cmd: "glab", args: ["mr", "update", "8", "--description=" + foldSections("## What changed\n\n- old\n\n## Why\n\nnew\n")], input: undefined }]); expect(merged.stderr()).toBe("gstack-post: pr-body merged by section: replaced Why; kept What changed; added none\n"); const empty = fakeEnv({ remote, files: { "/b": "## Why\n\nnew\n" }, respond: view("") }); expect(run(["pr-body", "8", "--body-file", "/b"], empty)).toBe(EXIT.posted); - expect(empty.posts()[0]!.args).toEqual(["mr", "update", "8", "--description=## Why\n\nnew\n"]); + expect(empty.posts()[0]!.args).toEqual(["mr", "update", "8", "--description=" + foldSections("## Why\n\nnew\n")]); const nullDescription = fakeEnv({ remote, files: { "/b": "## Why\n\nnew\n" }, respond: view('{"iid":8,"description":null}\n') }); expect(run(["pr-body", "8", "--body-file", "/b"], nullDescription)).toBe(EXIT.posted); - expect(nullDescription.posts()[0]!.args).toEqual(["mr", "update", "8", "--description=## Why\n\nnew\n"]); + expect(nullDescription.posts()[0]!.args).toEqual(["mr", "update", "8", "--description=" + foldSections("## Why\n\nnew\n")]); const garbled = fakeEnv({ remote, files: { "/b": "## Why\n\nnew\n" }, respond: view("<html>502</html>\n") }); expect(run(["pr-body", "8", "--body-file", "/b"], garbled)).toBe(EXIT.cliFailed); @@ -809,7 +820,7 @@ describe("gstack-post pr-body merges the PR body by section", () => { const replaced = withBody(current, { "/b": fresh }); expect(run(["pr-body", "5", "--body-file", "/b", "--replace"], replaced)).toBe(EXIT.posted); - expect(sent(replaced).input).toBe(fresh); + expect(sent(replaced).input).toBe(foldSections(fresh)); }); // Value: protects=a current body holding two ship-receipt blocks (an old receipt pasted below) refuses like a doubled title, so the stale @@ -984,6 +995,18 @@ describe("gstack-post refuses a title that is not in plain words (exit 4)", () = } finally { fs.rmSync(none, { recursive: true, force: true }); fs.rmSync(broken, { recursive: true, force: true }); } }); + // Value: protects=a comment is never held back by a broken policy file, which it never needed before the body check; + // fails_when=an invalid policy stops pr-comment, issue-comment and reply; why_new=comments now read the policy for warnings (GST-2737 review) + test("an invalid policy file warns and still posts a comment", () => { + const broken = repoWith("{ not json"); + try { + const c = fakeEnv({ root: broken, files: { "/b": "The pregate passed.\n" } }); + expect(run(["pr-comment", "7", "--body-file", "/b"], c)).toBe(EXIT.posted); + expect(c.posts()).toHaveLength(1); + expect(c.stderr()).toContain("(PLAIN_POLICY_INVALID); the comment is posted unchecked"); + } finally { fs.rmSync(broken, { recursive: true, force: true }); } + }); + test("the help names exit 4", () => { const f = fakeEnv(); expect(run(["--help"], f)).toBe(EXIT.posted); @@ -991,3 +1014,76 @@ describe("gstack-post refuses a title that is not in plain words (exit 4)", () = }); }); + +describe("gstack-post refuses a PR body that breaks the plain shape (exit 4)", () => { + const repoWith = (policy: string | null) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "gstack-post-body-")); + if (policy !== null) { fs.mkdirSync(path.join(root, ".gstack")); fs.writeFileSync(path.join(root, ".gstack", "plain-titles.json"), policy); } + return root; + }; + const POLICY = JSON.stringify({ codes: ["\\bGST-\\d+\\b"], terms: ["pregate"], allow: [], since: "2026-11-08", body_since: "2026-11-17", exempt_branch_prefixes: [], replace_default_terms: true }); + const TITLE = "Stop gstack from hitting GitHub's rate limit (GST-1713)"; + const LONG = "One.\n\nTwo.\n\nThree.\n\nFour, and the pregate said so.\n\n## Tests\n\n- one\n"; + const created = (at: string) => (c: Call) => (c.cmd === "gh" && c.args[1] === "view" && c.args.includes("createdAt") ? { status: 0, stdout: at + "\n" } : undefined); + + // Value: protects=a body with more than three visible lines or a listed word above the Agent notes fold posts nothing under a policy, + // with title and body findings printed in one pass; fails_when=the body is checked after posting, unfolded, or not at all; + // why_new=R76 as amended 2026-11-15; seam=a real policy file under the fake root; no_claim=real gh + test("a body with four visible lines and a listed word posts nothing; title and body findings print in one pass", () => { + const root = repoWith(POLICY); + try { + const f = fakeEnv({ root, files: { "/t": "Make the pregate quieter", "/b": LONG } }); + expect(run(["pr-create", "--base", "main", "--title-file", "/t", "--body-file", "/b"], f)).toBe(EXIT.plainTitle); + expect(f.calls.filter(c => c.cmd === "gh" || c.cmd === "glab")).toEqual([]); + expect(f.stdout()).toContain("PLAIN_TITLE: refused=1\n"); + expect(f.stdout()).toContain('PLAIN_BODY: PLAIN_BODY_REFUSED visible-lines "4 lines'); + expect(f.stdout()).toContain('PLAIN_BODY: PLAIN_BODY_REFUSED term "pregate"'); + expect(f.stdout()).toContain("PLAIN_BODY: refused=2\n"); + expect(f.stderr()).toContain("the body does not have the plain shape; nothing was posted"); + const edit = fakeEnv({ root, files: { "/b": LONG }, respond: created("2026-11-18T00:00:00Z") }); + expect(run(["pr-body", "7", "--body-file", "/b", "--replace"], edit)).toBe(EXIT.plainTitle); + expect(edit.posts()).toEqual([]); + } finally { fs.rmSync(root, { recursive: true, force: true }); } + }); + + // Value: protects=PRs opened before body_since, repositories without a policy and comments only warn, and still post; + // fails_when=old PRs or other repositories start refusing; why_new=A1 (refusals need a policy) and J1 (comments warn); + // seam=a real policy file and a fake createdAt; no_claim=real gh + test("an older PR, a repository without the policy and a comment get warnings and still post", () => { + const root = repoWith(POLICY); + const none = repoWith(null); + try { + const old = fakeEnv({ root, files: { "/b": LONG }, respond: created("2026-11-10T00:00:00Z") }); + expect(run(["pr-body", "7", "--body-file", "/b", "--replace"], old)).toBe(EXIT.posted); + expect(old.stdout()).toContain("(warning only)"); + expect(old.stdout()).toContain("PLAIN_BODY: warned=2\n"); + const free = fakeEnv({ root: none, files: { "/t": TITLE, "/b": LONG } }); + expect(run(["pr-create", "--base", "main", "--title-file", "/t", "--body-file", "/b"], free)).toBe(EXIT.posted); + expect(free.stdout()).toContain("PLAIN_BODY: warned=1\n"); + const comment = fakeEnv({ root, files: { "/b": "One.\nTwo.\nThree.\nFour: the pregate passed.\n" } }); + expect(run(["pr-comment", "7", "--body-file", "/b"], comment)).toBe(EXIT.posted); + expect(comment.stdout()).toContain('PLAIN_BODY: PLAIN_BODY_REFUSED term "pregate"'); + expect(comment.stdout()).not.toContain("visible-lines"); + } finally { fs.rmSync(root, { recursive: true, force: true }); fs.rmSync(none, { recursive: true, force: true }); } + }); + + // Value: protects=bodies go out folded, a ## section replaces the same-titled fold already on the PR, and fold posts nothing; + // fails_when=a body is posted with open sections or the merge duplicates a folded section; why_new=E1; seam=the fake gh pr view body; no_claim=real gh + test("a body is posted folded, a ## Tests section replaces the Tests fold, and fold prints without posting", () => { + const root = repoWith(POLICY); + try { + const current = "What changed for a user.\n\n<details><summary>Tests</summary>\n\n- old\n\n</details>\n"; + const f = fakeEnv({ root, files: { "/b": "## Tests\n\n- new\n" }, respond: c => (c.cmd === "gh" && c.args[1] === "view" && c.args.includes("body") ? { status: 0, stdout: current } : undefined) }); + expect(run(["pr-body", "7", "--body-file", "/b"], f)).toBe(EXIT.posted); + expect(f.posts().find(c => c.args[1] === "edit")!.input).toBe("What changed for a user.\n\n<details><summary>Tests</summary>\n\n- new\n\n</details>\n"); + const fold = fakeEnv({ root, files: { "/b": "Opening.\n\n## Tests\n\n- one\n" } }); + expect(run(["fold", "--body-file", "/b"], fold)).toBe(EXIT.posted); + expect(fold.stdout()).toBe("Opening.\n\n<details><summary>Tests</summary>\n\n- one\n\n</details>\n"); + expect(fold.calls.filter(c => c.cmd === "gh" || c.cmd === "glab")).toEqual([]); + const bad = fakeEnv({ root, files: { "/b": LONG } }); + expect(run(["fold", "--body-file", "/b"], bad)).toBe(EXIT.plainTitle); + expect(bad.stderr()).toContain("PLAIN_BODY: refused=2"); + } finally { fs.rmSync(root, { recursive: true, force: true }); } + }); +}); + diff --git a/test/gstack-ship-policy.test.ts b/test/gstack-ship-policy.test.ts index d66d2c25eee..b30c5617436 100644 --- a/test/gstack-ship-policy.test.ts +++ b/test/gstack-ship-policy.test.ts @@ -9,7 +9,7 @@ import * as path from 'node:path'; import { spawnSync } from 'node:child_process'; import { EXIT } from '../lib/headless-artifacts'; import { BUMP_NEVER_KEY_VERSION, CHANGELOG_FRAGMENTS_KEY_VERSION, DEFAULT_POLICY, POLICY_KEYS, POLICY_KEY_INTRODUCED, REVIEW_SCOPE_KEY_VERSION, STAMP_PLACEHOLDERS_KEY_VERSION, globToRegExp, matchesAny, minimumReader, shipConsequences, validatePolicy } from '../lib/ship-policy'; -import { PLAN_RECORD_KEY_VERSION } from '../lib/ship-policy-keys'; +import { HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION, PLAN_RECORD_KEY_VERSION } from '../lib/ship-policy-keys'; import { fillDue } from '../crew/lib/ship-queue-train'; import { cmpVersion, parseVersion } from '../lib/version-source'; import { BASE_POLICY, cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; @@ -346,4 +346,31 @@ describe('gstack-ship-policy (bin)', () => { expect(runBin(lax, 'gstack-ship-policy', ['check-history', '--base', 'main']).out).toBe('HISTORY: squash-ok (no check; policy history=squash-ok; plan=merge)\n'); expect(runBin(lax, 'gstack-ship-policy', ['check-history', '--base', 'main', '--plan', 'rebase']).status).toBe(EXIT.ok); }); + + // Value: protects=history: no-rewrite refuses a rebase plan or a rewritten branch but allows a squash landing, and an + // older gstack refuses the value and land.merge_commit_paths by name; fails_when=no-rewrite acts like squash-ok or + // merge-only, or a policy without min_gstack_version validates; why_new=I1 and G1 (GST-2737) + test('history: no-rewrite refuses a rebase plan and a rewritten branch, allows squash; it and land.merge_commit_paths need min_gstack_version', () => { + const repo = fixture({ policy: { ...BASE_POLICY, history: 'no-rewrite', min_gstack_version: HISTORY_NO_REWRITE_KEY_VERSION } }); + repo.git('checkout', '-q', '-b', 'pr'); + fs.writeFileSync(path.join(repo.work, 'a.txt'), 'a\n'); + repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'a'); + repo.git('push', '-q', '-u', 'origin', 'pr'); + expect(runBin(repo, 'gstack-ship-policy', ['check-history', '--base', 'main', '--plan', 'squash']).out).toMatch(/^HISTORY: ok \(no-rewrite; origin\/pr is an ancestor of HEAD\)$/m); + const rebase = runBin(repo, 'gstack-ship-policy', ['check-history', '--base', 'main', '--plan', 'rebase']); + expect(rebase.status).toBe(EXIT.refused); + expect(rebase.out).toMatch(/^HISTORY: refused \(plan=rebase rewrites the branch; .*\(HISTORY_POLICY_VIOLATION\)$/m); + repo.git('commit', '-q', '--amend', '-m', 'a, amended'); + expect(runBin(repo, 'gstack-ship-policy', ['check-history', '--base', 'main']).status).toBe(EXIT.fail); + const codes = (p: Record<string, unknown>) => validatePolicy(p, { gstackVersion: HISTORY_NO_REWRITE_KEY_VERSION }).map(e => `${e.code}:${e.path}`); + expect(codes({ history: 'no-rewrite' })).toEqual(['POLICY_INVALID:history']); + expect(codes({ history: 'no-rewrite', min_gstack_version: HISTORY_NO_REWRITE_KEY_VERSION })).toEqual([]); + expect(codes({ land: { merge_commit_paths: ['evals/**'] }, min_gstack_version: '1.99.0.0' })).toEqual(['POLICY_INVALID:land.merge_commit_paths']); + expect(codes({ land: { merge_commit_paths: ['evals/**'] }, min_gstack_version: LAND_MERGE_COMMIT_PATHS_KEY_VERSION })).toEqual([]); + expect(codes({ land: { merge_commit_paths: ['../out'] }, min_gstack_version: LAND_MERGE_COMMIT_PATHS_KEY_VERSION })).toEqual(['POLICY_INVALID:land.merge_commit_paths']); + expect(validatePolicy({ history: 'no-rewrite', min_gstack_version: HISTORY_NO_REWRITE_KEY_VERSION }, { gstackVersion: '1.99.5.0' }).map(e => e.code)).toContain('POLICY_GSTACK_TOO_OLD'); + expect(minimumReader({ history: 'no-rewrite' })).toBe(HISTORY_NO_REWRITE_KEY_VERSION); + expect(minimumReader({ land: { merge_commit_paths: ['evals/**'] } })).toBe(LAND_MERGE_COMMIT_PATHS_KEY_VERSION); + expect(shipConsequences({ ...DEFAULT_POLICY, history: 'no-rewrite' }, 'main').join('\n')).toContain('never rebase or force-push this branch'); + }); }); diff --git a/test/helpers/docsync-observer.ts b/test/helpers/docsync-observer.ts index 00ac6a56a74..c86a1975153 100644 --- a/test/helpers/docsync-observer.ts +++ b/test/helpers/docsync-observer.ts @@ -179,7 +179,7 @@ export function docsPreambleCommands(fixture: ReturnType<typeof fixtureDocs>): s export function docsShipPhase(skeleton: string, prBody: string, scenario: DocsScenario, storePointer: string): string { if (scenario === 'store') return storePointer; - return `${sliceBetween(skeleton, '## Step 14.5: Documentation audit (every ship)', '## Step 15: Commit')}\n\n${sliceBetween(prBody, '## Documentation', '## Test plan')}`; + return `${sliceBetween(skeleton, '## Step 14.5: Documentation audit (every ship)', '## Step 15: Commit')}\n\n${sliceBetween(prBody, '## Documentation', '## Tests')}`; } type DocsSessionOptionsInput = { diff --git a/test/plain-title.test.ts b/test/plain-title.test.ts index ae709cbd98a..b1e7ea97305 100644 --- a/test/plain-title.test.ts +++ b/test/plain-title.test.ts @@ -10,7 +10,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { bunIsolationArgs } from '../lib/bun-isolation'; -import { PLAIN_TITLE_POLICY_PATH, checkBranch, checkChangelogEntry, checkCommitSubject, checkOpening, checkTitle, loadPlainTitlePolicy, splitTitle, type PlainFinding } from '../lib/plain-title'; +import { DEFAULT_TERMS, PLAIN_TITLE_POLICY_PATH, checkBranch, checkChangelogEntry, checkCommitSubject, checkOpening, checkTitle, loadPlainTitlePolicy, splitTitle, type PlainFinding } from '../lib/plain-title'; const ROOT = path.resolve(import.meta.dir, '..'); const BIN = path.join(ROOT, 'bin/gstack-plain-title'); @@ -26,7 +26,7 @@ const MAIN_SUBJECTS: Array<[string, string[]]> = [ ['fix(ship): record-ci reuses its own CI row at the same tree, run and selection (GST-1795)', ['scope-prefix:fix(ship):']], ['v1.98.0.0 release: fold the changelog fragments', []], ['ship tooling: post-review voices dispatch, same-tree pregate clears, fix-check p<N> ledgers (GST-1775)', ['term:voices', 'term:pregate', 'term:fix-check', 'term:ledgers']], - ["feat: crew PRs carry their brief's Plan line; ship-queue ready and land check it (GST-1751)", []], + ["feat: crew PRs carry their brief's Plan line; ship-queue ready and land check it (GST-1751)", ['term:crew', 'term:carry']], ['Require the daemon secret and loopback Host/Origin on the design and iOS QA daemons', []], ["browse: keep tunnel-paired agents on web URLs and away from the daemon's disk", []], ['feat(diff-scope): template UI in .ts/.js counts as frontend; receipt records the static design pass (GST-1718)', ['scope-prefix:feat(diff-scope):', 'term:receipt']], @@ -34,7 +34,7 @@ const MAIN_SUBJECTS: Array<[string, string[]]> = [ ['fix(ship-receipt): name the non-ancestor targeted-read commit in RECEIPT_INVALID (GST-1700)', ['scope-prefix:fix(ship-receipt):', 'term:receipt']], ['fix: release stamps and a docs-audit edit after the last fix-check are no gate-class edit (GST-1702)', ['term:fix-check']], ["fix(ship): a cleared remote gate for HEAD's exact tree satisfies a lane whose inventory refuses that tree (GST-1688)", ['scope-prefix:fix(ship):', 'term:lane']], - ['fix: the receipt and the review plan agree on stamp and docs carry for review_targeted (GST-1689)', ['term:receipt']], + ['fix: the receipt and the review plan agree on stamp and docs carry for review_targeted (GST-1689)', ['term:receipt', 'term:carry', 'term:stamp']], ['Capy session: defer the upgrade while a /ship or review run is open; upgrade-path fixes (GST-1677, GST-1658)', []], ['Playwright 1.65.0: bundled Chromium 158 drops the distrusted eMudhra root (#3338)', []], ['changelog.d: a second GST-1631 fragment names what the audit redaction does not cover yet (GST-1635)', ['code:GST-1631']], @@ -143,7 +143,8 @@ describe('checkBranch', () => { expect(src('lib/release-stamp.ts')).toContain('`release/${version}`'); expect(src('crew/lib/ship-queue-wave.ts')).toContain("startsWith('wave/')"); expect(src('lib/ship-queue-land.ts')).toContain('`gstack-land-repair/${j.pr}`'); - expect(policy.exempt_branch_prefixes).toEqual(['release/', 'wave/', 'gstack-land-repair/']); + expect(fs.existsSync(path.join(ROOT, '.github/dependabot.yml'))).toBe(true); + expect(policy.exempt_branch_prefixes).toEqual(['release/', 'wave/', 'gstack-land-repair/', 'dependabot/']); }); }); @@ -163,15 +164,15 @@ describe('checkOpening', () => { expect(brief(checkOpening(NOTES, policy))).toEqual(['opening-shape:no opening paragraph']); }); - test('more than two sentences, or a code or term in the opening, is refused', () => { - expect(brief(checkOpening('One thing. Two things. Three things.', policy))).toEqual(['opening-shape:3 sentences']); + test('three lines of sentences pass (the body shape check owns length); a code or term in the opening is refused', () => { + expect(checkOpening('One thing. Two things. Three things.', policy)).toEqual([]); expect(checkOpening('This changes the setup, e.g. the default. It is plain.', policy)).toEqual([]); expect(brief(checkOpening('The pregate clears faster (GST-1713).', policy))).toEqual(['code:GST-1713', 'term:pregate']); }); test('a marker quoted inline in the opening does not end it; only the section marker on its own line does', () => { const opening = 'Readers find the `<!-- gstack:agent-notes -->` section at the end. It holds the checks. It stays collapsed.\n\n'; - expect(brief(checkOpening(opening + NOTES, policy))).toEqual(['opening-shape:3 sentences']); + expect(checkOpening(opening + NOTES, policy)).toEqual([]); }); }); @@ -206,7 +207,10 @@ describe('policy', () => { expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, allow: [{ text: 'R2' }] })))).toThrow(/allow\[0\]\.reason/); expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, since: 'soon' })))).toThrow(/since/); expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, extra: 1 })))).toThrow(/extra is not a known key/); - expect(loadPlainTitlePolicy(withPolicy(JSON.stringify(base)))).toEqual(base); + expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, body_since: 'later' })))).toThrow(/body_since/); + expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, replace_default_terms: 'yes' })))).toThrow(/replace_default_terms/); + expect(loadPlainTitlePolicy(withPolicy(JSON.stringify(base)))).toEqual({ ...base, terms: ['a', ...DEFAULT_TERMS], body_since: base.since }); + expect(loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, replace_default_terms: true, body_since: '2026-11-20' })))).toEqual({ ...base, body_since: '2026-11-20' }); }); test("gstack's policy loads and every allow entry says why", () => { @@ -254,6 +258,33 @@ describe('bin/gstack-plain-title', () => { expect([both.status, both.last]).toEqual([1, 'PLAIN_TITLE: refused=1 warned=1']); }); + // Value: protects=--body-file checks the folded shape (three visible lines, no listed word above Agent notes) and refuses + // only for a PR created on or after body_since on a branch the policy does not exempt; fails_when=an unfolded /ship draft + // is refused for its ## sections, or older and generated PRs start failing CI; why_new=R76 as amended 2026-11-15 (GST-2737) + test('a body file is checked once folded; an older PR or an exempt branch only warns', () => { + const draft = file('draft.md', 'What changed.\n\nWhy it helps.\n\nNothing to do.\n\n## What changed\n\n- one\n\n## Tests\n\n- two\n'); + expect(run(dirs.policy, ['check', '--body-file', draft])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: ok' }); + const long = file('long.md', 'One.\n\nTwo.\n\nThree.\n\nFour.\n\n## Tests\n\n- the pregate passed\n'); + const r = run(dirs.policy, ['check', '--body-file', long, '--created-at', '2026-11-20T00:00:00Z']); + expect([r.status, r.last]).toEqual([1, 'PLAIN_TITLE: refused=2']); + expect(r.stdout).toContain('PLAIN_BODY: PLAIN_BODY_REFUSED visible-lines "4 lines'); + expect(r.stdout).toContain('PLAIN_BODY: PLAIN_BODY_REFUSED term "pregate"'); + expect(run(dirs.policy, ['check', '--body-file', long, '--created-at', '2026-11-10T00:00:00Z'])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: warned=2' }); + expect(run(dirs.policy, ['check', '--body-file', long, '--head-branch', 'release/1.2.3.0'])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: warned=2' }); + }); + + // Value: protects=the opening's own findings follow the same body_since and exempt-branch downgrade as the shape findings; + // fails_when=an older PR, a release/ PR or a Dependabot PR fails the required check for a listed word in its opening; + // why_new=the opening moved from the warn step to the refusing body step (GST-2737 review) + test('an older PR or an exempt branch only warns about its opening too', () => { + const body = file('lane.md', 'This lane makes the merge faster for users.\n'); + expect(run(dirs.policy, ['check', '--body-file', body, '--created-at', '2026-11-20T00:00:00Z'])).toMatchObject({ status: 1, last: 'PLAIN_TITLE: refused=2' }); + expect(run(dirs.policy, ['check', '--body-file', body, '--created-at', '2026-11-10T00:00:00Z'])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: warned=2' }); + expect(run(dirs.policy, ['check', '--body-file', body, '--head-branch', 'release/1.2.3.4', '--created-at', '2026-11-20T00:00:00Z'])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: warned=2' }); + expect(run(dirs.policy, ['check', '--body-file', body, '--head-branch', 'dependabot/bun/production-dependencies-ea1c777f8f', '--created-at', '2026-11-20T00:00:00Z'])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: warned=2' }); + expect(run(dirs.policy, ['check', '--body-file', body, '--head-branch', '', '--created-at', '2026-11-20T00:00:00Z'])).toMatchObject({ status: 1, last: 'PLAIN_TITLE: refused=2' }); + }); + test('a changelog entry is checked', () => { const r = run(dirs.policy, ['check', '--changelog', file('frag.md', '**Plain lead (GST-1774).**\n')]); expect([r.status, r.last]).toEqual([1, 'PLAIN_TITLE: refused=1']); diff --git a/test/policy-floor-stable.test.ts b/test/policy-floor-stable.test.ts index b90af5d2908..fab31784463 100644 --- a/test/policy-floor-stable.test.ts +++ b/test/policy-floor-stable.test.ts @@ -10,7 +10,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { EXIT } from '../lib/headless-artifacts'; -import { BUMP_NEVER_KEY_VERSION, POLICY_KEY_INTRODUCED, runningGstackVersion, TRAIN_GATES_KEY_VERSION, validatePolicy } from '../lib/ship-policy'; +import { BUMP_NEVER_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION, POLICY_KEY_INTRODUCED, runningGstackVersion, TRAIN_GATES_KEY_VERSION, validatePolicy } from '../lib/ship-policy'; import { cmpVersion, parseVersion } from '../lib/version-source'; import { useDoctorCleanup, REPO, makeFixture, doctor, write as writeFile } from './helpers/doctor-fixture'; import { cleanup as cleanupPregate, commit, makeFixtureRepo as makePregateRepo, runBin as runPregateBin, type FixtureRepo as PregateRepo } from './helpers/pregate-fixture'; @@ -189,7 +189,7 @@ describe('gstack-doctor --check floor row', () => { const f = makeFixture(); fs.copyFileSync(path.join(REPO, 'lib/ship-policy-keys.ts'), path.join(f.root, 'lib/ship-policy-keys.ts')); const newer = (a: string, b: string) => cmpVersion(parseVersion(a)!, parseVersion(b)!) > 0; - const known = [...Object.values(POLICY_KEY_INTRODUCED), BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION].reduce((a, b) => (newer(b, a) ? b : a)); + const known = [...Object.values(POLICY_KEY_INTRODUCED), BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION].reduce((a, b) => (newer(b, a) ? b : a)); const dir = project(f, known); const at = floorRow(f, dir); expect(validatePolicy({ min_gstack_version: known })).toEqual([]); diff --git a/test/pr-body-shape.test.ts b/test/pr-body-shape.test.ts new file mode 100644 index 00000000000..e4dcd07d2a1 --- /dev/null +++ b/test/pr-body-shape.test.ts @@ -0,0 +1,92 @@ +/** + * lib/pr-body-shape.ts (R76 as amended 2026-11-15): a PR body shows at most three lines before anything folded, + * every other section sits in a fold, listed words stay below the Agent notes fold, and the /ship receipt ends the + * body inside Agent notes. The #4353 case is the shape of the real body that PR was opened with: a long opening and + * open sections, with its receipt in the Agent notes section. + */ +import { describe, expect, test } from 'bun:test'; +import { withAgentNotes } from '../lib/agent-notes'; +import { checkBodyShape, foldSections, unfoldSections, visibleOpening, VISIBLE_CHARS, VISIBLE_LINES } from '../lib/pr-body-shape'; +import { renderReceiptBlock } from '../lib/ship-receipt'; +import type { ShipReceipt } from '../lib/headless-artifacts'; + +const RECEIPT = renderReceiptBlock({ schema_version: 1, pr: 4353, head: '0d6e4079e3aa', base: 'main' } satisfies ShipReceipt); +const kinds = (body: string, terms: string[] = []) => checkBodyShape(body, terms).map(f => `${f.kind}:${f.match}`); +const OPENING = "/ship's reviewers end their reply with one count line, and gstack checks it against the findings it read.\n\nWhy: a blocker a reviewer reports must never vanish.\n\nNothing to do: replies without the line read as before.\n"; + +describe('the visible opening', () => { + test('three lines fit; a fourth line, or 700 characters on three lines, is refused', () => { + expect(kinds(OPENING)).toEqual([]); + expect(kinds(OPENING + '\nOne more line.\n')).toEqual([`visible-lines:4 lines, ${[...visibleOpening(OPENING + '\nOne more line.\n').join('\n')].length} characters before the first fold`]); + const long = ['a'.repeat(240), 'b'.repeat(240), 'c'.repeat(220)].join('\n\n'); + expect(visibleOpening(long)).toHaveLength(VISIBLE_LINES); + expect(kinds(long)[0]).toStartWith('visible-lines:3 lines, 702 characters'); + expect(VISIBLE_CHARS).toBe(600); + }); + + test('HTML comments and folds never count as visible; text left between folds is refused', () => { + expect(kinds('<!-- a note for tools -->\n' + OPENING + '\n<details><summary>Tests</summary>\n\n- one\n- two\n\n</details>\n')).toEqual([]); + expect(kinds(OPENING + '\n<details><summary>Tests</summary>\n\n- one\n\n</details>\n\nLoose paragraph.\n')).toEqual(['unfolded:Loose paragraph.']); + }); + + test('nested folds stay inside their parent and a fenced <details> is code, not a fold', () => { + const nested = OPENING + '\n<details><summary>Tests</summary>\n\n<details><summary>Logs</summary>\n\nlog\n\n</details>\n\nAfter the inner fold.\n\n</details>\n'; + expect(kinds(nested)).toEqual([]); + expect(foldSections(nested)).toBe(nested); + const fenced = OPENING + '\n## Example\n\n```html\n<details>\n## not a heading\n```\n'; + expect(foldSections(fenced)).toBe(OPENING + '\n<details><summary>Example</summary>\n\n```html\n<details>\n## not a heading\n```\n\n</details>\n'); + expect(kinds(foldSections(fenced))).toEqual([]); + }); +}); + +describe('listed words', () => { + const body = withAgentNotes(OPENING.replace('Why:', 'Why: the outside voice and the pregate said so;') + '\n## Tests\n\n- `lane` stays in code\n', 'Lane notes are fine here.\n\n' + RECEIPT); + test('a listed word above the Agent notes fold is found once per spelling; code and the notes section are skipped', () => { + expect(kinds(foldSections(body), ['outside voice', 'pregate', 'lane'])).toEqual(['term:outside voice', 'term:pregate']); + expect(kinds(foldSections(body))).toEqual([]); + }); + + // Value: protects=a listed word inside a file path or file name is not prose, so a Tests line naming test/ship-receipt-depth.test.ts passes while the + // same word in a sentence is still refused; fails_when=bare paths in the Tests section refuse routine /ship bodies; why_new=GST-2737 review (granted fix-check) + test('a listed word inside a file path or file name is skipped; the same word in a sentence is still found', () => { + const tests = withAgentNotes(OPENING + '\n## Tests\n\n- [x] bun test test/ship-receipt-depth.test.ts: 12 pass\n- [x] bun test release-stamp.test.ts docs/lane.md: pass\n', RECEIPT); + expect(kinds(foldSections(tests), ['receipt', 'stamp', 'lane'])).toEqual([]); + const prose = withAgentNotes(OPENING + '\n## Tests\n\n- the receipt was written after test/ship-receipt-depth.test.ts passed\n', RECEIPT); + expect(kinds(foldSections(prose), ['receipt'])).toEqual(['term:receipt']); + }); +}); + +describe('the Agent notes section ends the body', () => { + test('a receipt outside the notes, or text after them, is refused; a Capy badge after them is fine', () => { + expect(kinds(withAgentNotes(OPENING, RECEIPT))).toEqual([]); + expect(kinds(OPENING + '\n' + RECEIPT)).toContain('receipt-placement:gstack-ship-receipt'); + expect(kinds(withAgentNotes(OPENING, RECEIPT) + '\nA trailing note.\n')).toEqual(['receipt-placement:A trailing note.']); + expect(kinds(withAgentNotes(OPENING, RECEIPT) + '\n<a href="https://capy.ai/x"><img src="b"></a>\n')).toEqual([]); + }); +}); + +describe('folding', () => { + const original = OPENING.split('\n\n')[0] + '\n\n## Why\n\nThe parser read prose and guessed.\n\n## What changed\n\n- The ask.\n- The check.\n\n## Tests\n\n- 52 pass\n\n'; + const body = withAgentNotes(original, 'Plan: plans/gst-2737.md\n\n' + RECEIPT); + test("a #4353-shaped body folds every section, keeps the opening and the receipt byte for byte, and passes", () => { + const folded = foldSections(body); + expect(folded.startsWith(OPENING.split('\n\n')[0] + '\n\n<details><summary>Why</summary>\n\nThe parser read prose and guessed.\n\n</details>\n\n<details><summary>What changed</summary>\n\n- The ask.\n- The check.\n\n</details>\n\n<details><summary>Tests</summary>\n\n- 52 pass\n\n</details>\n')).toBe(true); + expect(folded.slice(folded.indexOf('<!-- gstack:agent-notes -->'))).toBe(body.slice(body.indexOf('<!-- gstack:agent-notes -->'))); + expect(folded).toContain(RECEIPT); + expect(kinds(folded)).toEqual([]); + expect(kinds(body)[0]).toStartWith('visible-lines:8 lines'); + }); + + test('folding is idempotent and unfolding then folding gives the same bytes', () => { + const folded = foldSections(body); + expect(foldSections(folded)).toBe(folded); + expect(foldSections(unfoldSections(folded))).toBe(folded); + expect(unfoldSections(folded)).toContain('## What changed\n\n- The ask.'); + }); + + test('a heading with markup is escaped in the summary and restored on unfold', () => { + const folded = foldSections('Opening.\n\n## Notes <b>&</b>\n\nx\n'); + expect(folded).toBe('Opening.\n\n<details><summary>Notes <b>&</b></summary>\n\nx\n\n</details>\n'); + expect(unfoldSections(folded)).toContain('## Notes <b>&</b>'); + }); +}); diff --git a/test/prose-lint.test.ts b/test/prose-lint.test.ts index 04a8f19a7f7..84b1e9db37d 100644 --- a/test/prose-lint.test.ts +++ b/test/prose-lint.test.ts @@ -307,8 +307,8 @@ describe('wiring', () => { expect(changelog).toContain('gstack-prose-lint CHANGELOG.md --base origin/<base> --gate'); const prBody = read('ship/sections/pr-body.md.tmpl'); const compose = prBody.slice(prBody.indexOf(': "${DOCS_SECTION_FILE:?'), prBody.indexOf('echo "PR_BODY_FILE: $PR_BODY_FILE"')); - expect(compose).toContain(`gstack-prose-lint "$BODY_TOP_FILE" --sections 'Why,Summary,Blast radius' --gate`); - expect(compose).not.toContain('What changed,'); + expect(compose).toContain(`gstack-prose-lint "$BODY_TOP_FILE" --sections 'Why,What changed,Blast radius' --gate`); + expect(compose).not.toContain('Summary,'); expect(compose).not.toContain('"$BODY_REST_FILE" --gate'); expect(compose.indexOf('gstack-prose-lint')).toBeGreaterThan(compose.indexOf('is empty, so the body was never written')); expect(compose.indexOf('gstack-prose-lint')).toBeLessThan(compose.indexOf('{ awk 1 "$BODY_TOP_FILE"')); @@ -317,7 +317,7 @@ describe('wiring', () => { test('the PR body leads with the problem and carries a Blast radius item, on both the standard and the Capy path', () => { const prBody = read('ship/sections/pr-body.md.tmpl'); - const summary = prBody.slice(prBody.indexOf('## Summary'), prBody.indexOf('## Test Coverage')); + const summary = prBody.slice(prBody.indexOf('## What changed'), prBody.indexOf('## Test Coverage')); expect(summary).toContain("Open with the problem in the user's words"); expect(summary).toContain('Never an inventory or a commit list.'); expect(summary).toMatch(/BAD: ".+" GOOD: "/s); diff --git a/test/release-stamp.test.ts b/test/release-stamp.test.ts index 2e47150dae7..6dd05da047c 100644 --- a/test/release-stamp.test.ts +++ b/test/release-stamp.test.ts @@ -7,6 +7,9 @@ import { afterEach, describe, expect, test } from 'bun:test'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { classifyRelease, openRelease } from '../lib/release-stamp'; +import { checkBodyShape, visibleOpening } from '../lib/pr-body-shape'; +import { DEFAULT_TERMS } from '../lib/plain-title'; +import { sectionText } from '../lib/squash-message'; import { loadPolicyFromBase, MERGE_KEY_VERSION } from '../lib/ship-policy'; import { classifyTrainHead } from '../crew/lib/version-gate-train'; import { BASE_POLICY, cleanup, makeFixtureRepo, readFile, runBin, type FixtureRepo } from './helpers/restamp-fixture'; @@ -133,6 +136,10 @@ describe('gstack-release-stamp open', () => { expect(repo.git('--git-dir', repo.origin, 'rev-parse', 'refs/heads/main')).toBe(repo.git('rev-parse', 'origin/main')); expect(calls.map(a => a[1])).toEqual(['list', 'create']); expect(calls[1]!.slice(0, 7)).toEqual(['pr', 'create', '--base', 'main', '--head', 'release/1.3.0.0', '--title']); + const body = calls[1]![calls[1]!.indexOf('--body') + 1]!; + expect(checkBodyShape(body, DEFAULT_TERMS)).toEqual([]); + expect(visibleOpening(body)[0]).toBe('v1.3.0.0 ships 2 user-visible changes, listed one per line under Release notes with the pull request that made each.'); + expect(sectionText(body, 'Release notes')).toBe('- a change\n- b feature'); expect(r.lines.join('\n')).toContain('NEXT: gstack-ship-queue land --pr 42 --pin ' + r.head); expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: repo.git('rev-parse', 'origin/main'), head: r.head! }).ok).toBe(true); expect(repo.git('branch', '--show-current')).toBe('elsewhere'); diff --git a/test/ship-publication-gates.test.ts b/test/ship-publication-gates.test.ts index 08db7e73fa2..72e4606a888 100644 --- a/test/ship-publication-gates.test.ts +++ b/test/ship-publication-gates.test.ts @@ -2,13 +2,14 @@ import { expect, test } from 'bun:test'; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; +import { foldSections } from '../lib/pr-body-shape'; import { killGroup } from '../lib/pregate/supervise'; import { expectMentions } from './helpers/prompt-structure'; const template = readFileSync(new URL('../ship/sections/pr-body.md.tmpl', import.meta.url), 'utf8'); /** The agent writes the body drafts with its file-write tool; the block reads them by printed name. */ -function writeDrafts(root: string, top = '## Summary\n\n## Documentation', rest = '## Test plan\n- [x] bun test: pass'): (block: string) => string { +function writeDrafts(root: string, top = '## What changed\n\n## Documentation', rest = '## Tests\n- [x] bun test: pass'): (block: string) => string { mkdirSync(join(root, '.gstack/tmp'), { recursive: true }); writeFileSync(join(root, '.gstack/tmp/pr-body-top.abc123'), top); writeFileSync(join(root, '.gstack/tmp/pr-body-rest.abc123'), rest); @@ -124,17 +125,17 @@ for (const failure of ['none', 'body', 'title'] as const) { try { const secret = 'AKIA' + '1234567890ABCDEF'; const c = await composed(root, { - top: failure === 'body' ? `## Summary\nkey ${secret}\n\n## Documentation` : undefined, + top: failure === 'body' ? `## What changed\nkey ${secret}\n\n## Documentation` : undefined, title: failure === 'title' ? `v1.2.3.4 fix: ${secret}` : undefined, }); const result = await c.publish(createBlock); if (failure === 'none') { expect(result.exitCode, result.stderr.toString()).toBe(0); expect(result.stdout.toString()).toContain('https://github.com/o/r/pull/9'); - expect(c.calls()).toEqual([{ args: ['pr', 'create', '--base=main', '--title=v1.2.3.4 fix: publication checks', '--body-file=-'], stdin: readFileSync(c.bodyFile, 'utf8') }]); + expect(c.calls()).toEqual([{ args: ['pr', 'create', '--base=main', '--title=v1.2.3.4 fix: publication checks', '--body-file=-'], stdin: foldSections(readFileSync(c.bodyFile, 'utf8')) }]); } else { expect(result.exitCode).toBe(1); - expect(result.stdout.toString()).toContain(`HIGH RULE: aws.access_key LINE: ${failure === 'body' ? 2 : 1} PART: ${failure}`); + expect(result.stdout.toString()).toContain(`HIGH RULE: aws.access_key LINE: ${failure === 'body' ? 3 : 1} PART: ${failure}`); expect(c.calls()).toEqual([]); } } finally { @@ -184,10 +185,10 @@ test.skipIf(process.platform === 'win32')('a block whose background child holds test.skipIf(process.platform === 'win32')('MEDIUM findings publish nothing until the block reruns with the printed token', async () => { const root = mkdtempSync(join(tmpdir(), 'ship-post-medium-')); try { - const c = await composed(root, { top: '## Summary\nThanks jane.roe@acme-corp.io\n\n## Documentation' }); + const c = await composed(root, { top: '## What changed\nThanks jane.roe@acme-corp.io\n\n## Documentation' }); const first = await c.publish(editBlock); expect(first.exitCode).toBe(2); - expect(first.stdout.toString()).toContain('RULE: pii.email LINE: 2 PART: body'); + expect(first.stdout.toString()).toContain('RULE: pii.email LINE: 3 PART: body'); expect(c.calls()).toEqual([]); const token = /^TOKEN: (\S+)$/m.exec(first.stdout.toString())![1]!; const flagged = 'pr-body <pr-number> --body-file "${PR_BODY_FILE:?restore the composed body path}"'; @@ -199,7 +200,7 @@ test.skipIf(process.platform === 'win32')('MEDIUM findings publish nothing until ['pr', 'edit', '9', '--body-file=-'], ['pr', 'edit', '9', '--title=v1.2.3.4 fix: publication checks'], ]); - expect(calls[0]!.stdin).toBe(readFileSync(c.bodyFile, 'utf8')); + expect(calls[0]!.stdin).toBe(foldSections(readFileSync(c.bodyFile, 'utf8'))); } finally { rmSync(root, { recursive: true, force: true }); } @@ -218,7 +219,7 @@ test('publication composes the saved documentation section unchanged and refuses }); const composed = run(join(root, 'section.md')); expect(composed.exitCode).toBe(0); - expect(composed.stdout.toString()).toBe(`## Summary\n\n## Documentation\n${section}\n## Test plan\n- [x] bun test: pass\n`); + expect(composed.stdout.toString()).toBe(`## What changed\n\n## Documentation\n${section}\n## Tests\n- [x] bun test: pass\n`); expect(existsSync(join(root, '.gstack/tmp/pr-body-top.abc123'))).toBe(false); expect(existsSync(join(root, '.gstack/tmp/pr-body-rest.abc123'))).toBe(false); const missing = run(join(root, 'absent.md')); diff --git a/test/ship-queue-land-direct.test.ts b/test/ship-queue-land-direct.test.ts index 4b83b19ea22..d1dd4b2c266 100644 --- a/test/ship-queue-land-direct.test.ts +++ b/test/ship-queue-land-direct.test.ts @@ -12,6 +12,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { EXIT } from '../lib/headless-artifacts'; import { LAND_KEY_VERSION, MERGE_KEY_VERSION, RELEASE_GATE_KEY_VERSION, validatePolicy } from '../lib/ship-policy'; +import { LAND_MERGE_COMMIT_PATHS_KEY_VERSION } from '../lib/ship-policy-keys'; import { BASE_POLICY, cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; import { shippedBody } from './helpers/ship-queue-train-fixture'; import { persist, repoIdentity } from '../crew/lib/ship-queue-train-record'; @@ -109,6 +110,8 @@ function openPr(fx: Fx, pr: string, opts: { edit?: (work: string) => void; shipp repo.git('checkout', '-q', '--detach', 'origin/main'); return head; } +/** The gh pr merge arguments land sends for a fixture PR: the title subject, and a body of the opening lines plus trailers (none here: the fixture body is only a receipt). */ +const merged = (pr: string, pin: string, method = '--squash', body = '') => [pr, method, '--match-head-commit', pin, '--subject', `PR ${pr} (#${pr})`, '--body', body]; const land = (fx: Fx, pr: string, pin: string, extra: string[] = []) => runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', pr, '--pin', pin, '--base', 'main', ...extra], fx.env); const remote = (fx: Fx, ref: string) => { fx.repo.git('fetch', '-q', 'origin', '+refs/heads/*:refs/remotes/origin/*'); return fx.repo.git('rev-parse', 'origin/' + ref); }; const show = (fx: Fx, rev: string) => fx.repo.git('show', rev); @@ -147,7 +150,7 @@ describe('land --pin: direct merge at the PR\'s own green head', () => { const r = land(fx, '7', pin); expect(r.err).toBe(''); expect(r.status).toBe(EXIT.ok); - expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin, '--subject', 'PR 7 (#7)']); + expect(fx.read().mergeArgs).toEqual(merged('7', pin)); const main = remote(fx, 'main'); expect(fx.repo.git('rev-parse', main + '^1')).toBe(base); expect(r.out).toContain('MERGED: #7 as ' + main); @@ -159,6 +162,33 @@ describe('land --pin: direct merge at the PR\'s own green head', () => { expect(notes[0]).toMatchObject({ kind: 'land', pr: '7', pin, merge_sha: main, base_sha: base }); }, 90_000); + // Value: protects=land sends the plain message (title subject, opening lines plus trailers), prints it under --dry-run, + // takes --body-file, and keeps a merge commit for a land.merge_commit_paths match; fails_when=land drops --body (GitHub then + // writes its commit list), ignores the override, or squashes an eval results PR; why_new=R76 as amended 2026-11-15 (GST-2737) + test('the merge commit is the title plus the opening lines; --dry-run prints it, --body-file replaces the opening, a merge_commit_paths match merges', () => { + const fx = setup({ ...POLICY, land: { merge_commit_paths: ['evals/**'] }, min_gstack_version: LAND_MERGE_COMMIT_PATHS_KEY_VERSION }); + const pin = openPr(fx, '31'); + fx.write(d => { d.prs['31'].body = 'Land now writes a plain commit.\n\nWhy: main\'s log should read as a list of changes.\n\n' + d.prs['31'].body; }); + const dry = land(fx, '31', pin, ['--dry-run']); + expect(dry.status).toBe(EXIT.ok); + expect(dry.out).toContain('METHOD: squash (no land.merge_commit_paths match)\nSUBJECT: PR 31 (#31)\nBODY: Land now writes a plain commit.\nBODY: \nBODY: Why: main\'s log should read as a list of changes.\n'); + expect(fx.read().mergeArgs).toBeUndefined(); + const file = path.join(fx.repo.root, 'commit-body.txt'); + fs.writeFileSync(file, 'The line I picked.\n'); + expect(land(fx, '31', pin, ['--body-file', file]).status).toBe(EXIT.ok); + expect(fx.read().mergeArgs).toEqual(merged('31', pin, '--squash', 'The line I picked.')); + const evals = openPr(fx, '32', { edit: w => { fs.mkdirSync(path.join(w, 'evals'), { recursive: true }); fs.writeFileSync(path.join(w, 'evals', 'run.json'), '{}\n'); } }); + const r = land(fx, '32', evals); + expect(r.out).toContain('METHOD: merge (land.merge_commit_paths matches evals/run.json)'); + expect(fx.read().mergeArgs).toEqual(merged('32', evals, '--merge')); + }, 120_000); + + test('--help names the land form this repository takes', () => { + const fx = setup(); + expect(runBin(fx.repo, 'gstack-ship-queue', ['--help'], fx.env).out).toContain('This repository (merge: direct): land each READY PR with gstack-ship-queue land --pr <n> --pin'); + }); + + test('GST-1316: the base moved after the pin\'s CI, so land runs land.merged_checks on the pin merged onto main: a failure refuses with QUEUE_LAND_MERGED_CHECKS and merges nothing, a pass lands and names the merged tree, and a rerun checks again', () => { const fx = setup(CHECKED); const red = openPr(fx, '8', { edit: w => fs.writeFileSync(path.join(w, 'budget.md'), 'pr line\n') }); @@ -761,7 +791,7 @@ describe('land --pin: fail closed and merge methods', () => { fx.write(d => { d.prs['25'].baseRefName = 'main'; }); const r = land(fx, '25', pin); expect(r.err).toBe(''); - expect(fx.read().mergeArgs).toEqual(['25', '--merge', '--match-head-commit', pin, '--subject', 'PR 25 (#25)']); + expect(fx.read().mergeArgs).toEqual(merged('25', pin, '--merge')); }, 90_000); test('land reads the policy after fetching the base: a required check main added since the last fetch is enforced', () => { @@ -1064,7 +1094,7 @@ describe('land --pin --repair: the one way through a backstop freeze under merge expect(r.err).toBe(''); expect(r.status).toBe(EXIT.ok); expect(r.out).toMatch(/^FREEZE: warn only: train backstop froze main \(backstop red on main [0-9a-f]{12}: .*\); the base policy declares release_gate/m); - expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin, '--subject', 'PR 7 (#7)']); + expect(fx.read().mergeArgs).toEqual(merged('7', pin)); expect(freezeOf(fx)).toMatchObject({ train: 'backstop', repair: null, cleared_at: null }); }, 90_000); @@ -1099,7 +1129,7 @@ describe('land --pin --repair: the one way through a backstop freeze under merge expect(r.err).toBe(''); expect(r.status).toBe(EXIT.ok); expect(r.out).toContain(`REPAIR: #7@${pin7.slice(0, 12)} admitted under the land lock`); - expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin7, '--subject', 'PR 7 (#7)']); + expect(fx.read().mergeArgs).toEqual(merged('7', pin7)); expect(fx.read().lockAtMerge).toMatchObject({ pr: '7', journal: 'land-pin:' + pin7 }); expect(freezeOf(fx)).toMatchObject({ train: 'backstop', repair: { pr: '7', head: pin7, train: null }, cleared_at: null, cleared_by: null }); expect(landNotes(fx)).toEqual([expect.objectContaining({ pr: '7', pin: pin7, merge_sha: remote(fx, 'main') })]); @@ -1107,7 +1137,7 @@ describe('land --pin --repair: the one way through a backstop freeze under merge expect(second.err).toContain('(QUEUE_TRAIN_FROZEN)'); expect(second.err).toContain(`repair #7@${pin7.slice(0, 12)}`); expect(land(fx, '8', pin8).err).toContain('(QUEUE_TRAIN_FROZEN)'); - expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin7, '--subject', 'PR 7 (#7)']); + expect(fx.read().mergeArgs).toEqual(merged('7', pin7)); }, 120_000); test('a recorded repair that never merged at its pin gives way to the next --repair; a repair train holding the freeze does not', () => { diff --git a/test/ship-queue-land.test.ts b/test/ship-queue-land.test.ts index 13f816660e5..1643148ebe2 100644 --- a/test/ship-queue-land.test.ts +++ b/test/ship-queue-land.test.ts @@ -626,7 +626,8 @@ describe('land: one pass, base, lock and history', () => { const r = land(fx, ['--pr', '13']); expect(r.err).toBe(''); expect(r.out).toContain('LANDED: '); - expect(JSON.parse(fs.readFileSync(fx.data, 'utf8')).mergeArgs).toContain('--merge'); + expect(JSON.parse(fs.readFileSync(fx.data, 'utf8')).mergeArgs).toEqual(['--merge', '--match-head-commit', expect.any(String), '--subject', 'PR 13 title (#13)', '--body', '']); + expect(r.out).toContain('SUBJECT: PR 13 title (#13)'); }, 90_000); // Value: protects=a merge-only land interrupted after GitHub merged resumes to LANDED, though a true merge puts the pin inside diff --git a/test/ship-receipt-depth.test.ts b/test/ship-receipt-depth.test.ts index 749167fb606..05056a28025 100644 --- a/test/ship-receipt-depth.test.ts +++ b/test/ship-receipt-depth.test.ts @@ -15,7 +15,7 @@ import { extractReceipt, renderReceiptBlock } from '../lib/ship-receipt'; import { bindShippedReceipt, receiptDepthAtHead, receiptDepthVerdict, reviewLoopExceptionLine } from '../lib/ship-receipt-depth'; import { bunIsolationArgs } from '../lib/bun-isolation'; import { runScriptSync } from '../lib/script-invocation'; -import { BUMP_NEVER_KEY_VERSION, POLICY_KEY_INTRODUCED, TRAIN_GATES_KEY_VERSION } from '../lib/ship-policy'; +import { BUMP_NEVER_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION, POLICY_KEY_INTRODUCED, TRAIN_GATES_KEY_VERSION } from '../lib/ship-policy'; import { cmpVersion, parseVersion } from '../lib/version-source'; import { cleanup, commit, makeFixtureRepo, ROOT, runBin, type FixtureRepo } from './helpers/pregate-fixture'; @@ -88,7 +88,7 @@ describe('write records the review depth at the checked-out head', () => { { cwd: repo.work, encoding: 'utf8', timeout: 180_000, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, ...repo.env } }); expect(write.status, write.stderr).toBe(EXIT.ok); expect(receiptIn(body).gstack_version).toBe('1.0.0.0'); - const newestKey = [...Object.values(POLICY_KEY_INTRODUCED), BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION].reduce((a, b) => (cmpVersion(parseVersion(b)!, parseVersion(a)!) > 0 ? b : a)); + const newestKey = [...Object.values(POLICY_KEY_INTRODUCED), BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION].reduce((a, b) => (cmpVersion(parseVersion(b)!, parseVersion(a)!) > 0 ? b : a)); const reader = spawnSync(process.execPath, [...bunIsolationArgs(), '-e', `console.log((await import(${JSON.stringify(path.join(installed, 'lib', 'ship-policy.ts'))})).runningGstackVersion())`], { cwd: repo.work, encoding: 'utf8', timeout: 60_000 }); expect(reader.stdout.trim(), reader.stderr).toBe(newestKey); diff --git a/test/ship-workflow-clarity.test.ts b/test/ship-workflow-clarity.test.ts index b8847b6e65e..f637c61b00b 100644 --- a/test/ship-workflow-clarity.test.ts +++ b/test/ship-workflow-clarity.test.ts @@ -223,7 +223,7 @@ test('Step 14.5 runs the doc caps before the verification gate and records the a expectTokens(docs, ['`DOCS_CAP: none declared`', '"status":"updated|current"', '"status":"blocked"', '"exception":{"accepted_by"', '`DOCS_AUDIT_BLOCKED`', 'An unattended run has no owner to accept: it stops here.'], 'ship documentation section'); const compose = between(prTemplate, 'Handoff record first', '**Existing open PR/MR**'); expectTokens(compose, ['--docs @.gstack/tmp/docs-audit.json', '`DOCS_AUDIT_BLOCKED`'], 'ship pr-body receipt write'); - expectTokens(compact(between(prTemplate, '## Documentation', '## Test plan')), ['`Documentation exception: accepted by <accepted_by> <date> via <via>: <reason>`'], 'ship pr-body Documentation'); + expectTokens(compact(between(prTemplate, '## Documentation', '## Tests')), ['`Documentation exception: accepted by <accepted_by> <date> via <via>: <reason>`'], 'ship pr-body Documentation'); }); test('Step 9.4 applies the cap before any edit, names its scratch files under .gstack/tmp/, logs Step 11 late defers, and hands reviewers the range from pass 2 (PR 1 review notes)', () => { diff --git a/test/size-ledger/ship/gst-2737-plain-pr-bodies.json b/test/size-ledger/ship/gst-2737-plain-pr-bodies.json new file mode 100644 index 00000000000..4f029c61295 --- /dev/null +++ b/test/size-ledger/ship/gst-2737-plain-pr-bodies.json @@ -0,0 +1,4 @@ +{ + "bytes": 1153, + "why": "GST-2737: /ship writes a folded PR body with a three-line opening (pr-body template and gstack-post fold)" +} diff --git a/test/squash-message.test.ts b/test/squash-message.test.ts new file mode 100644 index 00000000000..9a8b58781ba --- /dev/null +++ b/test/squash-message.test.ts @@ -0,0 +1,115 @@ +/** + * lib/squash-message.ts: every gstack merge lands as one commit titled "<PR title> (#n)" whose body is the PR body's + * opening lines plus the branch's trailers (docs/writing-prs.md#the-commit-on-main). Real git repositories in a temp + * directory; no network. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { branchTrailers, landMessage, landMethod, mergeArgs, openingLines, sectionText } from '../lib/squash-message'; + +const dirs: string[] = []; +afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); + +/** A repository with one base commit on main; `commit` adds a file as the named author with the given message. */ +function repo() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-squash-msg-')); + dirs.push(root); + const git = (args: string[], who = 'Ada <ada@example.com>') => { + const [name, email] = [who.replace(/ <.*/, ''), /<(.*)>/.exec(who)![1]!]; + const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 30_000, env: { ...process.env, GIT_AUTHOR_NAME: name, GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_NAME: name, GIT_COMMITTER_EMAIL: email } }); + if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); + return r.stdout.trim(); + }; + git(['init', '-q', '-b', 'main']); + const commit = (file: string, message: string, who?: string) => { fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); fs.writeFileSync(path.join(root, file), file + '\n'); git(['add', '-A'], who); git(['commit', '-q', '-m', message], who); return git(['rev-parse', 'HEAD']); }; + const base = commit('README.md', 'base'); + return { root, git, commit, base }; +} + +const OPENING = 'X is faster now: [the cache](https://example.com/c) keeps parsed files.\n\nWhy: big repositories waited a minute.\n\nNothing to do.\n'; +const BODY = OPENING + '\n## Tests\n\n- 12 pass\n'; +const SQUASH = { history: 'squash-ok' as const, land: null }; + +describe('the commit message', () => { + // Value: protects=main's log reads as plain changes with credit kept; fails_when=the subject loses the number, the body pastes the + // whole PR, a fold leaks in, links keep their URLs, or a trailer is lost or doubled; why_new=R76 as amended 2026-11-15 + test('subject is the title with (#n); body is the opening lines, then each trailer once and every other author', () => { + const r = repo(); + r.git(['checkout', '-q', '-b', 'pr']); + r.commit('src/a.ts', 'speed up the parser\n\nRemoved-test: test/old.test.ts\nCo-authored-by: Carol <carol@example.com>'); + const pin = r.commit('src/b.ts', 'tidy\n\nCo-authored-by: Carol <carol@example.com>', 'Bob <bob@example.com>'); + const m = landMessage(r.root, { pr: '5', title: 'Make X faster', prBody: BODY, mergeBase: r.base, pin, tip: r.base, policy: SQUASH }); + if ('error' in m) throw new Error(m.error); + expect(m.subject).toBe('Make X faster (#5)'); + expect(m.body).toBe('X is faster now: the cache keeps parsed files.\n\nWhy: big repositories waited a minute.\n\nNothing to do.\n\nRemoved-test: test/old.test.ts\nCo-authored-by: Carol <carol@example.com>\nCo-authored-by: Bob <bob@example.com>'); + expect([m.method, m.skippedParent]).toEqual(['squash', null]); + expect(mergeArgs('5', pin, m)).toEqual(['pr', 'merge', '5', '--squash', '--match-head-commit', pin, '--subject', 'Make X faster (#5)', '--body', m.body]); + }); + + test('an empty or receipt-only opening gives the trailers alone; a long line wraps at 72; at most three lines are kept', () => { + const r = repo(); + r.git(['checkout', '-q', '-b', 'pr']); + const pin = r.commit('src/a.ts', 'a\n\nCo-authored-by: Carol <carol@example.com>'); + const receiptOnly = '\`\`\`gstack-ship-receipt\n{ "schema_version": 1 }\n\`\`\`\n\n## What changed\n\nx\n'; + for (const prBody of ['', receiptOnly]) { + const m = landMessage(r.root, { pr: '5', title: 'T', prBody, mergeBase: r.base, pin, tip: r.base, policy: SQUASH }); + expect('error' in m ? m.error : m.body).toBe('Co-authored-by: Carol <carol@example.com>'); + } + const long = 'word '.repeat(30).trim(); + expect(openingLines(long).split('\n').every(l => l.length <= 72)).toBe(true); + expect(openingLines('one\n\ntwo\n\nthree\n\nfour\n')).toBe('one\n\ntwo\n\nthree'); + }); + + // Value: protects=a secret never reaches main's history through a commit message; fails_when=the scan is skipped or + // runs on other bytes than the ones sent; why_new=gate answer "the squash message goes through the redaction scan" + test('a key in the title, opening or --body-file refuses; a phone-shaped number drops the opening and keeps the trailers', () => { + const r = repo(); + r.git(['checkout', '-q', '-b', 'pr']); + const pin = r.commit('src/a.ts', 'a\n\nCo-authored-by: Carol <carol@example.com>'); + const key = 'AKIA' + '1234567890ABCDEF'; + const at = (o: { title?: string; prBody?: string; override?: string }) => landMessage(r.root, { pr: '5', title: o.title ?? 'T', prBody: o.prBody ?? BODY, override: o.override, mergeBase: r.base, pin, tip: r.base, policy: SQUASH }); + for (const o of [{ title: 'T ' + key }, { prBody: 'Uses ' + key + '.\n' }, { override: 'Uses ' + key }]) expect(at(o)).toMatchObject({ error: expect.stringContaining('nothing merged') }); + expect(at({ prBody: 'Call +14155552671 for help.\n' })).toMatchObject({ body: 'Co-authored-by: Carol <carol@example.com>' }); + expect(at({ override: 'The plain line I chose.' })).toMatchObject({ body: 'The plain line I chose.\n\nCo-authored-by: Carol <carol@example.com>' }); + expect(at({ title: ' ' })).toMatchObject({ error: expect.stringContaining('no title') }); + }); + + // Value: protects=a stacked PR's commit does not repeat the credit lines of its parent, which already landed; + // fails_when=landedStackParent is not consulted; why_new=gate answer Addition B + test('commits of a stacked parent that already landed are left out', () => { + const r = repo(); + r.git(['checkout', '-q', '-b', 'stack']); + const parent = r.commit('src/parent.ts', 'parent\n\nCo-authored-by: Dan <dan@example.com>'); + const pin = r.commit('src/child.ts', 'child\n\nCo-authored-by: Erin <erin@example.com>'); + r.git(['checkout', '-q', 'main']); + r.git(['checkout', '-q', parent, '--', 'src/parent.ts']); + r.git(['commit', '-q', '-m', 'Parent PR (#4)']); + const tip = r.git(['rev-parse', 'HEAD']); + const m = landMessage(r.root, { pr: '6', title: 'Child', prBody: '', mergeBase: r.base, pin, tip, policy: SQUASH }); + expect(m).toMatchObject({ skippedParent: parent, body: 'Co-authored-by: Erin <erin@example.com>' }); + expect(branchTrailers(r.root, r.base, pin)).toEqual(['Co-authored-by: Dan <dan@example.com>', 'Co-authored-by: Erin <erin@example.com>']); + }); +}); + +describe('the merge method', () => { + // Value: protects=repositories that must keep merge commits keep them, with the same subject and body; + // fails_when=merge-only or a merge_commit_paths match squashes; why_new=G1 and I1 + test('merge-only and a land.merge_commit_paths match merge; no-rewrite and a miss squash', () => { + const r = repo(); + r.git(['checkout', '-q', '-b', 'pr']); + const pin = r.commit('evals/results/run-1.json', 'results'); + expect(landMethod(r.root, { history: 'merge-only', land: null }, r.base, pin)).toEqual({ method: 'merge', why: 'history: merge-only' }); + expect(landMethod(r.root, { history: 'no-rewrite', land: null }, r.base, pin)).toEqual({ method: 'squash', why: 'history: no-rewrite' }); + expect(landMethod(r.root, { history: 'squash-ok', land: { merge_commit_paths: ['evals/**'] } }, r.base, pin)).toEqual({ method: 'merge', why: 'land.merge_commit_paths matches evals/results/run-1.json' }); + expect(landMethod(r.root, { history: 'squash-ok', land: { merge_commit_paths: ['docs/**'] } }, r.base, pin)).toEqual({ method: 'squash', why: 'no land.merge_commit_paths match' }); + }); + + test("a release PR's commit body is its Release notes section", () => { + const body = 'v1.2.0.0 ships 2 changes.\n\n<details><summary>Release notes</summary>\n\n- One thing (#1)\n- Another (#2)\n\n</details>\n\n<!-- gstack:agent-notes -->\n<details><summary>Agent notes</summary>\n\nx\n\n</details>\n'; + expect(sectionText(body, 'Release notes')).toBe('- One thing (#1)\n- Another (#2)'); + expect(sectionText(body, 'Missing')).toBe(''); + }); +}); From 169eb9c8a59571b54e5205dd4a351a6f271941ea Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 21:22:10 +0800 Subject: [PATCH 34/62] Approval page re-reviews two-reviewer scope changes and checks quotes only against this repository (#4441) /autoplan's approval page now re-reviews a scope change both reviewers raise, asks a plan with no Owner's words to confirm its direction, and checks owner quotes only against this repository's approvals record. This keeps the rule that only the owner's own words set a plan's direction, and there is nothing for the reader to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/specialist-batched#1 reader=specialist-batched Review-Finding: p1/specialist-batched#2 reader=specialist-batched --- .../fix-gate-gaps-after-day-one-gate.md | 1 + lib/autoplan-gate-items.ts | 29 +++++--- lib/autoplan-gate.ts | 5 +- lib/bin-context.ts | 10 +-- test/autoplan-answer-invalidation.test.ts | 4 +- test/autoplan-day-one-gate.test.ts | 72 ++++++++++++++++++- test/autoplan-gate-artifacts.test.ts | 2 +- test/autoplan-run-recovery.test.ts | 2 +- test/autoplan-shadow-driver.test.ts | 26 +++---- test/autoplan-shadow.test.ts | 12 ++-- 10 files changed, 124 insertions(+), 39 deletions(-) create mode 100644 changelog.d/fix-gate-gaps-after-day-one-gate.md diff --git a/changelog.d/fix-gate-gaps-after-day-one-gate.md b/changelog.d/fix-gate-gaps-after-day-one-gate.md new file mode 100644 index 00000000000..3a1d3ebe238 --- /dev/null +++ b/changelog.d/fix-gate-gaps-after-day-one-gate.md @@ -0,0 +1 @@ +- **/autoplan's approval page closes three gaps left by the last change.** When both reviewers challenge the plan and one calls it a build-order change while the other calls it a scope change, the page now treats it as a scope change, so taking it sends the plan back for review instead of settling it without one. A plan with no Owner's words section now gets the "confirm the direction is yours" question when both reviewers challenge it and the page recommends keeping the plan, as it already did for a challenge from one reviewer. And a quote is checked only against this repository's approvals record, so another repository's record for a branch with the same name can no longer verify it. diff --git a/lib/autoplan-gate-items.ts b/lib/autoplan-gate-items.ts index ce7d7a5b013..66c038575ee 100644 --- a/lib/autoplan-gate-items.ts +++ b/lib/autoplan-gate-items.ts @@ -15,6 +15,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { spawnSync } from 'node:child_process'; import { branchKey, captainApprovalsDir } from './approval-record'; +import { readVersionedSlugCache, sanitizeSlug } from './bin-context'; import { cutDrops, parseCuts, parseDayOne, parseOwnerWords, wordKey, type DayOneTable, type OwnerQuote, type OwnerWordsSection } from './autoplan-owner-text'; import { SETTLEABLE_CHANGES } from './autoplan-reconcile'; import { readDecisions, readJournal, type RunState } from './autoplan-state'; @@ -28,19 +29,24 @@ export interface GateOwnerWords { status: OwnerWordsSection['status']; quotes: A export interface OwnerContext { words: OwnerWordsSection; verified: Set<number>; dayOne: DayOneTable; cuts: string[]; app: boolean; lean: boolean } /** - * The owner's words in every approvals record already on disk for the branch checked out at `cwd` (lib/approval-record.ts - * layout: <state root>/projects/<slug>/approvals/<branch key>.jsonl and its mirrors). Read-only: the slug is not resolved, - * because resolving it writes the slug cache, and building a gate must not write outside the run. + * The owner's words in this repository's approvals record for the branch checked out at `cwd` (lib/approval-record.ts + * layout: <state root>/projects/<slug>/approvals/<branch key>.jsonl and <mirror>/<slug>/<branch key>.jsonl). Read-only: + * the slug comes from GSTACK_PROJECT_SLUG or the repository's slug cache entry gstack-slug already wrote (repository + * scope, which ignores project markers, as the writer resolves it), never a fresh resolution (that + * writes the cache, and building a gate must not write outside the run). No known slug reads no record, so a quote stays + * unverified rather than matching another repository's branch of the same name. */ export function ledgerWords(cwd: string, env: NodeJS.ProcessEnv = process.env): string[] { const head = spawnSync('git', ['symbolic-ref', '--short', '-q', 'HEAD'], { cwd, encoding: 'utf8', timeout: 10_000 }); const branch = head.status === 0 ? head.stdout.trim() : ''; if (!branch) return []; + const stateRoot = resolveStateRoot(env); + const pinned = sanitizeSlug((env.GSTACK_PROJECT_SLUG ?? '').trim()); + const slug = pinned && pinned !== '.' && pinned !== '..' ? pinned : readVersionedSlugCache(stateRoot, cwd, { scope: 'repository' }); + if (!slug) return []; const name = `${branchKey(branch)}.jsonl`; - const files: string[] = []; - const under = (root: string, sub: string[]) => { try { for (const d of fs.readdirSync(root)) files.push(path.join(root, d, ...sub, name)); } catch { /* no such root */ } }; - under(path.join(resolveStateRoot(env), 'projects'), ['approvals']); - for (const root of [env.GSTACK_APPROVALS_DIR, captainApprovalsDir(env)]) if (root) under(root, []); + const files = [path.join(stateRoot, 'projects', slug, 'approvals', name), + ...[env.GSTACK_APPROVALS_DIR, captainApprovalsDir(env)].flatMap(root => (root ? [path.join(root, slug, name)] : []))]; const words: string[] = []; for (const file of files) { let text: string; @@ -92,13 +98,18 @@ export function proposalCost(ctx: OwnerContext, phase: string, changes: string): /** A proposal behind a Critical or High row keeps the finding path's b: the draft stands and the finding becomes a blocking build task. */ export const blockingProposal = (rows: ChallengeRow[]): boolean => rows.some(r => r.severity === 'Critical' || r.severity === 'High'); +/** The heaviest `changes` any row names: scope, cost or direction before packaging or ordering, so a pair never settles a scope change. */ +export function heaviestChanges(rows: Array<{ changes?: string } | undefined>): string | undefined { + const named = rows.flatMap(r => (r?.changes ? [r.changes] : [])); + return ['scope', 'cost', 'direction'].find(c => named.includes(c)) ?? named[0]; +} + /** * One proposal from one or both voices (a paired twin) against agent-written plan text: a takes the change, b keeps the draft. * Its `changes` is the heaviest any row names (scope, cost, direction, then packaging or ordering), so a pair never settles a scope change. */ export function proposalItem(ctx: OwnerContext, phase: string, rows: ChallengeRow[], o: { carried?: boolean } = {}): NewItem { - const named: string[] = rows.flatMap(r => (r.changes ? [r.changes] : [])); - const changes = ['scope', 'cost', 'direction'].find(c => named.includes(c)) ?? named[0] ?? 'direction'; + const changes = heaviestChanges(rows) ?? 'direction'; const keep = blockingProposal(rows) ? "keep the plan's draft; carry it into the build as a blocking task (no plan change)" : "keep the plan's draft"; const fixes = [...new Set(rows.map(r => r.resolution).filter((r): r is string => !!r))]; const voices = rows.map(r => r.voice).join(' + '); diff --git a/lib/autoplan-gate.ts b/lib/autoplan-gate.ts index e2f4e33d29c..ebb42a4b313 100644 --- a/lib/autoplan-gate.ts +++ b/lib/autoplan-gate.ts @@ -27,7 +27,7 @@ import { applyCapChoices, pendingDeltas, releaseUndispatched, roundCap, roundOf import { evaluateCarry, gateEvidence, voidPendingCheck } from './autoplan-carry'; import { buildEli5, capyRelayLine } from './captain-brief'; import { FINDING_ORIGIN, openEarlier, previousReview, reviewRows, settledIds } from './autoplan-confirm'; -import { blockingProposal, confirmDirectionItem, dayOneItems, directionIsOwners, gateOwnerWords, ownerContext, ownerQuoteOf, proposalItem, type ChallengeRow, type NewItem } from './autoplan-gate-items'; +import { blockingProposal, confirmDirectionItem, dayOneItems, directionIsOwners, gateOwnerWords, heaviestChanges, ownerContext, ownerQuoteOf, proposalItem, type ChallengeRow, type NewItem } from './autoplan-gate-items'; import { phaseClose } from './autoplan-timing'; import { agentWords, ANSWERED_BY_RE, applyReply, autoDefault, decisionId, decisionRows, keepDirection, legacyRecHash, parseReply, pendingHint, recHash, replyShape, validateGateList, type GateChoice, type GateItem, type GateList, type GateOption, type ParsedReply } from './gate-list'; import type { DecisionRow, FindingRow } from './headless-artifacts'; @@ -235,7 +235,8 @@ export function buildGate(state: RunState, gateRev: number): GateList { const title = `${n.title} [${row.native_id} + ${row.outside_id}]`; if (reran && !n.changes && !o.changes) { push(agentDecision(`d${++d}`, title, phase, 'both voices recommend changing your stated direction'), ids); continue; } const def = challengeDefault(row, n, o); - push({ id: `uc${++uc}`, title, kind: 'approval', recommended: def.recommended, recommended_basis: def.basis, phase, item_class: 'challenge2', ...(n.changes ?? o.changes ? { changes: n.changes ?? o.changes } : {}), + if (!quoted && def.recommended === 'a') { kept.push(`uc${uc + 1}`); keptIds.push(n.id, o.id); } + push({ id: `uc${++uc}`, title, kind: 'approval', recommended: def.recommended, recommended_basis: def.basis, phase, item_class: 'challenge2', ...(heaviestChanges([n, o]) ? { changes: heaviestChanges([n, o]) } : {}), why: `both voices recommend changing your stated direction; blind spot: ${o.title}; cost if wrong: ${o.resolution ?? n.resolution ?? 'unstated'}`, options: [KEEP('keep your direction (the plan as reviewed)'), { key: 'b', text: def.text, changes_plan: true }] }, ids); continue; diff --git a/lib/bin-context.ts b/lib/bin-context.ts index b59ce3ad33d..85aa61a42ca 100644 --- a/lib/bin-context.ts +++ b/lib/bin-context.ts @@ -12,7 +12,7 @@ import { resolveStateRoot } from "./state-root"; import { legacyRemoteSlug, remoteSlug } from "./remote-identity"; /** Keep the slug inside the [a-zA-Z0-9._-] alphabet gstack-slug promises (`tr -cd`). */ -function sanitizeSlug(s: string): string { +export function sanitizeSlug(s: string): string { return s.replace(/[^a-zA-Z0-9._-]/g, ""); } @@ -386,10 +386,12 @@ function markerSlug(stateRoot: string, cwd: string, root: string): string { * no entry, the entry predates the versioned format, or its value is unusable * (empty, "." or ".." after sanitizing). Never spawns git: hot-path readers * (the AskUserQuestion preference hook) rely on gstack-slug, which every skill - * preamble runs, having already written the entry. + * preamble runs, having already written the entry. Scope "repository" skips the + * project marker's entry, as slugFromEnvironment's does, so approvals readers and + * writers agree on the slug. */ -export function readVersionedSlugCache(stateRoot: string, cwd: string): string | undefined { - const marker = projectMarkerRoot(cwd); +export function readVersionedSlugCache(stateRoot: string, cwd: string, opts: { scope?: "memory" | "repository" } = {}): string | undefined { + const marker = opts.scope === "repository" ? "" : projectMarkerRoot(cwd); const file = marker ? markerCacheFile(stateRoot, marker) : slugCacheReadOrder(stateRoot, cwd).find((f) => existsSync(f)); if (!file) return undefined; let raw: string; diff --git a/test/autoplan-answer-invalidation.test.ts b/test/autoplan-answer-invalidation.test.ts index 8b428b7682e..c6819ae5afe 100644 --- a/test/autoplan-answer-invalidation.test.ts +++ b/test/autoplan-answer-invalidation.test.ts @@ -64,7 +64,7 @@ describe('answer', () => { const out = gatedRun('shape'); const gate = JSON.parse(fs.readFileSync(path.join(out, 'gate.json'), 'utf8')); expect(gate.gate_rev).toBe(1); - expect(gate.items.map((i: any) => [i.id, i.kind, i.phase ?? null])).toEqual([['d1', 'auto', 'ceo'], ['uc1', 'approval', 'ceo'], ['d2', 'auto', 'ceo'], ['uc2', 'approval', 'eng'], ['d3', 'auto', 'eng'], ['d4', 'auto', 'eng'], ['p1', 'approval', null]]); + expect(gate.items.map((i: any) => [i.id, i.kind, i.phase ?? null])).toEqual([['d1', 'auto', 'ceo'], ['uc1', 'approval', 'ceo'], ['d2', 'auto', 'ceo'], ['uc2', 'approval', 'eng'], ['d3', 'auto', 'eng'], ['d4', 'auto', 'eng'], ['d5', 'auto', null], ['p1', 'approval', null]]); expect(gate.items.filter((i: any) => i.finding).map((i: any) => i.id)).toEqual(['d2', 'd3', 'd4']); expect(gate.items[0].why).toMatch(/voices disagree: severity: native High, outside Low/); }, 30_000); @@ -147,7 +147,7 @@ describe('answer', () => { expect(eng.outside.stdout).toContain('status=gate_pending'); expect(readRun(out).gate_rev).toBe(2); const rows = decisions(out); - expect(rows.filter((x: any) => x.gate_rev === 1)).toHaveLength(7); + expect(rows.filter((x: any) => x.gate_rev === 1)).toHaveLength(8); expect(rows.filter((x: any) => x.gate_rev === 2 && x.status === 'pending').length).toBeGreaterThan(0); const staleAgain = autoplan(['answer', '--by', 'human', '--out', out, '--gate-rev', '1', '--reply', 'all']); expect(staleAgain.status).toBe(3); diff --git a/test/autoplan-day-one-gate.test.ts b/test/autoplan-day-one-gate.test.ts index 8f711017f79..a14165fbf71 100644 --- a/test/autoplan-day-one-gate.test.ts +++ b/test/autoplan-day-one-gate.test.ts @@ -20,6 +20,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { applyGuidance, buildGate } from '../lib/autoplan-gate'; import { branchKey } from '../lib/approval-record'; +import { slugCacheReadOrder } from '../lib/bin-context'; import { proposalCost, proposalItem, ownerContext, recordedOwnerWords } from '../lib/autoplan-gate-items'; import { confirmBlock, openEarlier, settledIds } from '../lib/autoplan-confirm'; import { buildTasks } from '../lib/autoplan-export'; @@ -297,6 +298,35 @@ describe('owner_quote downgrade, the day-one page requirement and the cost line' }); }); +describe('two-voice challenges (known gaps after #4431)', () => { + const pair = (o: { native: 'ordering' | 'scope'; outside: 'ordering' | 'scope'; fix?: [string, string] }) => ({ + native: [row('ceo', 'native', { id: `${RUN}-ceo-r2-native-1`, severity: 'High', title: 'Ship the before-meeting card before the live lane', user_challenge: true, changes: o.native, resolution: o.fix?.[0] ?? 'build the card first' })], + outside: [row('ceo', 'outside', { id: `${RUN}-ceo-r2-outside-1`, severity: 'High', title: 'Ship the before-meeting card before the live lane', user_challenge: true, changes: o.outside, resolution: o.fix?.[1] ?? 'build the card first' })], + }) as unknown as ReturnType<typeof round2>; + + test('an ordering plus scope pair is a scope change, so taking it is re-reviewed, never settled', () => { + const list = buildGate(makeRun('pair-scope', { plan: planText({ owner: null }), round2: pair({ native: 'ordering', outside: 'scope' }), round1: false }), 1); + const item = byClass(list, 'challenge2')[0]!; + expect(item.changes).toBe('scope'); + expect(applyGuidance({ changes: item.changes, item: item.id })).toBe('edit the plan, then revise'); + }); + + test("with no Owner's words section, a two-voice challenge that keeps the plan's direction asks the owner to confirm it", () => { + const list = buildGate(makeRun('pair-keep', { plan: planText({ owner: null }), round2: pair({ native: 'scope', outside: 'scope', fix: ['build the card first', 'drop the live lane'] }), round1: false }), 1); + const item = byClass(list, 'challenge2')[0]!; + expect(item.recommended).toBe('a'); + const confirm = byClass(list, 'confirm_direction'); + expect(confirm.length).toBe(1); + expect(confirm[0]!.title).toContain(item.id); + }); + + test('a two-voice challenge that recommends the change adds no confirm item', () => { + const list = buildGate(makeRun('pair-change', { plan: planText({ owner: null }), round2: pair({ native: 'scope', outside: 'scope' }), round1: false }), 1); + expect(byClass(list, 'challenge2')[0]!.recommended).toBe('b'); + expect(byClass(list, 'confirm_direction')).toEqual([]); + }); +}); + describe('parsers, render and redaction', () => { test("Owner's words: ok, none and malformed, with the OWNER_WORDS line", () => { expect(parseOwnerWords(planText())).toEqual({ status: 'ok', quotes: [{ n: 1, who: 'The owner, day 0', text: 'I want to remember what I promised people after every meeting' }] }); @@ -349,12 +379,52 @@ describe('parsers, render and redaction', () => { const mirror = path.join(TMP, 'ledger-mirror', 'some-slug'); fs.mkdirSync(mirror, { recursive: true }); fs.writeFileSync(path.join(mirror, `${branchKey('day-one-ledger')}.jsonl`), JSON.stringify({ schema_version: 1, id: 'x', words: 'The owner said: I want to remember what I promised people after every meeting' }) + '\n'); - const env = { HOME: home, GSTACK_APPROVALS_DIR: path.dirname(mirror) }; + const env = { HOME: home, GSTACK_APPROVALS_DIR: path.dirname(mirror), GSTACK_PROJECT_SLUG: 'some-slug' }; const words = recordedOwnerWords(state, env); expect(ownerContext(state, words).verified).toEqual(new Set([1])); expect(fs.existsSync(home)).toBe(false); }); + test("another repo's approvals record on a branch of the same name never verifies a quote", () => { + const state = makeRun('ledger-other-repo', { plan: planText(), round2: round2(), round1: false }); + expect(spawnSync('git', ['init', '-q', '-b', 'main', path.dirname(state.plan_source)], { encoding: 'utf8', timeout: 30_000 }).status).toBe(0); + const root = path.join(TMP, 'ledger-other-mirror'); + fs.mkdirSync(path.join(root, 'other-repo'), { recursive: true }); + fs.writeFileSync(path.join(root, 'other-repo', `${branchKey('main')}.jsonl`), JSON.stringify({ schema_version: 1, id: 'y', words: 'I want to remember what I promised people after every meeting' }) + '\n'); + const env = { HOME: path.join(TMP, 'ledger-other-home'), GSTACK_APPROVALS_DIR: root, GSTACK_PROJECT_SLUG: 'this-repo' }; + expect(ownerContext(state, recordedOwnerWords(state, env)).verified).toEqual(new Set()); + expect(ownerContext(state, recordedOwnerWords(state, { ...env, GSTACK_PROJECT_SLUG: 'other-repo' })).verified).toEqual(new Set([1])); + }); + + test('without GSTACK_PROJECT_SLUG the repository slug cache entry finds the record, even under a project marker', () => { + const state = makeRun(path.join('ledger-marker', 'run'), { plan: planText(), round2: round2(), round1: false }); + const repo = path.dirname(state.plan_source); + expect(spawnSync('git', ['init', '-q', '-b', 'main', repo], { encoding: 'utf8', timeout: 30_000 }).status).toBe(0); + const stateRoot = path.join(TMP, 'ledger-marker-state'); + const cache = slugCacheReadOrder(stateRoot, repo)[0]; + fs.mkdirSync(path.dirname(cache), { recursive: true }); + fs.writeFileSync(cache, 'v2:this-repo'); + const record = path.join(stateRoot, 'projects', 'this-repo', 'approvals', `${branchKey('main')}.jsonl`); + fs.mkdirSync(path.dirname(record), { recursive: true }); + fs.writeFileSync(record, JSON.stringify({ schema_version: 1, id: 'z', words: 'I want to remember what I promised people after every meeting' }) + '\n'); + const env = { HOME: path.join(TMP, 'ledger-marker-home'), GSTACK_STATE_ROOT: stateRoot }; + expect(ownerContext(state, recordedOwnerWords(state, env)).verified).toEqual(new Set([1])); + fs.writeFileSync(path.join(TMP, 'ledger-marker', '.gstack-project'), ''); + expect(ownerContext(state, recordedOwnerWords(state, env)).verified).toEqual(new Set([1])); + }); + + test('with no GSTACK_PROJECT_SLUG and no slug cache entry, no record verifies a quote', () => { + const state = makeRun('ledger-no-slug', { plan: planText(), round2: round2(), round1: false }); + expect(spawnSync('git', ['init', '-q', '-b', 'main', path.dirname(state.plan_source)], { encoding: 'utf8', timeout: 30_000 }).status).toBe(0); + const stateRoot = path.join(TMP, 'ledger-no-slug-state'); + const record = path.join(stateRoot, 'projects', 'other-repo', 'approvals', `${branchKey('main')}.jsonl`); + fs.mkdirSync(path.dirname(record), { recursive: true }); + fs.writeFileSync(record, JSON.stringify({ schema_version: 1, id: 'w', words: 'I want to remember what I promised people after every meeting' }) + '\n'); + const env = { HOME: path.join(TMP, 'ledger-no-slug-home'), GSTACK_STATE_ROOT: stateRoot }; + expect(ownerContext(state, recordedOwnerWords(state, env)).verified).toEqual(new Set()); + expect(ownerContext(state, recordedOwnerWords(state, { ...env, GSTACK_PROJECT_SLUG: 'other-repo' })).verified).toEqual(new Set([1])); + }); + test('quoted owner words are redacted from public copies', () => { const state = makeRun('redact', { plan: planText(), round2: round2(), round1: false }); const words = ownerWords(state); diff --git a/test/autoplan-gate-artifacts.test.ts b/test/autoplan-gate-artifacts.test.ts index 9a8d5394a7c..7d1325219bb 100644 --- a/test/autoplan-gate-artifacts.test.ts +++ b/test/autoplan-gate-artifacts.test.ts @@ -133,7 +133,7 @@ describe('B6: PLAN_REALITY flag beside the approval item', () => { const gate = JSON.parse(fs.readFileSync(path.join(out, 'gate.json'), 'utf8')) as GateList; const p1 = gate.items.find(i => i.id === 'p1')!; expect(p1.flags).toEqual([expect.stringMatching(/^PLAN_REALITY "minimum effect" has no number, arm list or rule body \(plan\.md:6: .*minimum effect.*\) \(report only\)$/)]); - expect(renderGate(gate)).toMatch(/\n flagged: PLAN_REALITY "minimum effect"/); + expect([1, 2].map(p => renderGate(gate, p)).join('\n')).toMatch(/\n flagged: PLAN_REALITY "minimum effect"/); expect(readRun(out).status).toBe('gate_pending'); }); }); diff --git a/test/autoplan-run-recovery.test.ts b/test/autoplan-run-recovery.test.ts index 81a6eb2c2cb..de8a04fc659 100644 --- a/test/autoplan-run-recovery.test.ts +++ b/test/autoplan-run-recovery.test.ts @@ -106,7 +106,7 @@ describe('next/submit loop', () => { expect(v.status, v.stdout + v.stderr).toBe(0); expect(JSON.parse(v.stdout)).toMatchObject({ valid: true, status: 'gate_pending' }); const gate = JSON.parse(fs.readFileSync(path.join(out, 'gate.json'), 'utf8')); - expect(gate.items.map((i: any) => i.id)).toEqual(['uc1', 'd1', 'd2', 'uc2', 'd3', 'd4', 'p1']); + expect(gate.items.map((i: any) => i.id)).toEqual(['uc1', 'd1', 'd2', 'uc2', 'd3', 'd4', 'd5', 'p1']); expect(gate.items.filter((i: any) => i.finding).map((i: any) => i.title.split(':')[0])).toEqual(['Critical', 'High', 'Critical', 'High']); const decisions = fs.readFileSync(path.join(out, 'decisions.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l)); expect(decisions.every((d: any) => d.status === 'pending' && d.gate_rev === 1)).toBe(true); diff --git a/test/autoplan-shadow-driver.test.ts b/test/autoplan-shadow-driver.test.ts index 237f7fbadf6..1f608adb3f6 100644 --- a/test/autoplan-shadow-driver.test.ts +++ b/test/autoplan-shadow-driver.test.ts @@ -90,7 +90,7 @@ describe('submit records the shadow before GATE; the record stays private and ch test('one row per item with the frozen item, the rule pick, eligibility, class and hashes', () => { expect(shadowRows.map(r => [r.item, r.item_class, r.ceo_eligible, r.rule_pick, r.status, r.retrospective])).toEqual([ ['uc1', 'challenge2', true, 'a', 'recorded', false], ['d1', 'finding', false, null, 'recorded', false], ['d2', 'finding', false, null, 'recorded', false], - ['uc2', 'challenge2', false, 'a', 'recorded', false], ['d3', 'finding', false, null, 'recorded', false], ['d4', 'finding', false, null, 'recorded', false], ['p1', 'p1', true, 'a', 'recorded', false]]); + ['uc2', 'challenge2', false, 'a', 'recorded', false], ['d3', 'finding', false, null, 'recorded', false], ['d4', 'finding', false, null, 'recorded', false], ['d5', 'confirm_direction', false, 'a', 'recorded', false], ['p1', 'p1', true, 'a', 'recorded', false]]); expect(shadowRows[0].decision).toBe(`${readRun(out).run}-uc1`); expect(shadowRows[0].item_frozen.options.map((o: { key: string }) => o.key)).toEqual(['a', 'b']); expect(typeof shadowRows[0].audit).toBe('boolean'); @@ -158,12 +158,12 @@ describe('submit records the shadow before GATE; the record stays private and ch expect(r.stderr).toContain('(SHADOW_BEFORE_ANSWER)'); }); test('"Do it" relayed as tokens records owner_mode rec, owner_named false, the rec_hash and the agent role', () => { - ok(ap(['answer', '--out', out, '--gate-rev', '1', '--reply', 'uc1a d1a d2a uc2a d3a d4a p1b', '--by', 'agent:capy', '--owner-reply', 'Do it'], e), 'answer'); + ok(ap(['answer', '--out', out, '--gate-rev', '1', '--reply', 'uc1a d1a d2a uc2a d3a d4a d5a p1b', '--by', 'agent:capy', '--owner-reply', 'Do it'], e), 'answer'); const d = rows(path.join(out, 'decisions.jsonl')); const gateRec = shadowRows[0].rec_hash; expect(d.map(r => [r.label, r.owner_mode, r.owner_named, r.answered_role, r.rec_hash === gateRec, r.answered_by])).toEqual([ ['UC1', 'rec', false, 'agent', true, 'agent:capy'], ['D1', 'rec', false, 'agent', true, 'agent:capy'], ['D2', 'rec', false, 'agent', true, 'agent:capy'], - ['UC2', 'rec', false, 'agent', true, 'agent:capy'], ['D3', 'rec', false, 'agent', true, 'agent:capy'], ['D4', 'rec', false, 'agent', true, 'agent:capy'], ['P1', 'rec', false, 'agent', true, 'agent:capy']]); + ['UC2', 'rec', false, 'agent', true, 'agent:capy'], ['D3', 'rec', false, 'agent', true, 'agent:capy'], ['D4', 'rec', false, 'agent', true, 'agent:capy'], ['D5', 'rec', false, 'agent', true, 'agent:capy'], ['P1', 'rec', false, 'agent', true, 'agent:capy']]); }); test('the reader exports the answered revision with the owner provenance', () => { const r = exported(['--out', out], e); @@ -171,9 +171,9 @@ describe('submit records the shadow before GATE; the record stays private and ch const x = JSON.parse(r.stdout); expect(x.rows.map((row: any) => [row.item, row.status, row.shadow.pick, row.owner.chosen, row.owner.owner_mode, row.owner.rec_hash_at_answer === row.owner.rec_hash_at_record])).toEqual([ ['uc1', 'recorded', 'a', 'a', 'rec', true], ['d1', 'recorded', 'a', 'a', 'rec', true], ['d2', 'recorded', 'a', 'a', 'rec', true], - ['uc2', 'recorded', 'a', 'a', 'rec', true], ['d3', 'recorded', 'a', 'a', 'rec', true], ['d4', 'recorded', 'a', 'a', 'rec', true], ['p1', 'recorded', 'a', 'b', 'rec', true]]); - expect(x.counts.status).toEqual({ recorded: 7 }); - expect(x.counts.ceo_eligible).toEqual({ true: 2, false: 5 }); + ['uc2', 'recorded', 'a', 'a', 'rec', true], ['d3', 'recorded', 'a', 'a', 'rec', true], ['d4', 'recorded', 'a', 'a', 'rec', true], ['d5', 'recorded', 'a', 'a', 'rec', true], ['p1', 'recorded', 'a', 'b', 'rec', true]]); + expect(x.counts.status).toEqual({ recorded: 8 }); + expect(x.counts.ceo_eligible).toEqual({ true: 2, false: 6 }); }); }); @@ -207,7 +207,7 @@ describe('a failed shadow never blocks: the gate prints and answers; owner words const d = rows(path.join(out, 'decisions.jsonl')); expect(d.find(r => r.label === 'UC2')).toMatchObject({ owner_mode: 'unparsed', owner_named: false, owner_reply_parsed: false }); const x = JSON.parse(exported(['--out', out], e).stdout); - expect(x.rows.map((row: any) => [row.item, row.status, row.code])).toEqual([['uc1', 'failed', 'http'], ['d1', 'failed', 'http'], ['d2', 'failed', 'http'], ['uc2', 'failed', 'http'], ['d3', 'failed', 'http'], ['d4', 'failed', 'http'], ['p1', 'failed', 'http']]); + expect(x.rows.map((row: any) => [row.item, row.status, row.code])).toEqual([['uc1', 'failed', 'http'], ['d1', 'failed', 'http'], ['d2', 'failed', 'http'], ['uc2', 'failed', 'http'], ['d3', 'failed', 'http'], ['d4', 'failed', 'http'], ['d5', 'failed', 'http'], ['p1', 'failed', 'http']]); }); }); @@ -270,7 +270,7 @@ describe('a crash mid-call: the dispatched call settles unknown and answer recor }); test('the reader labels those rows retrospective', () => { const x = JSON.parse(exported(['--out', out], e).stdout); - expect(x.counts.status).toEqual({ retrospective: 7 }); + expect(x.counts.status).toEqual({ retrospective: 8 }); }); }); @@ -300,7 +300,7 @@ describe('every gate writer records the shadow before it prints GATE', async () ok(ap(['next', '--out', out], g.env), 'next eng'); const r = ok(ap(['close', '--out', out, '--phase', 'eng', '--deferred', 'out of time', '--by', 'human'], g.env), 'close'); expect(lineIndex(r.stdout, 'SHADOW: recorded')).toBeLessThan(lineIndex(r.stdout, 'GATE: gate_rev=1')); - expect(rows(record(out)).map(x => [x.item, x.item_class, x.status])).toEqual([['uc1', 'challenge2', 'malformed'], ['d1', 'finding', 'recorded'], ['d2', 'finding', 'recorded'], ['d3', 'cap_deferred', 'recorded'], ['p1', 'p1', 'recorded']]); + expect(rows(record(out)).map(x => [x.item, x.item_class, x.status])).toEqual([['uc1', 'challenge2', 'malformed'], ['d1', 'finding', 'recorded'], ['d2', 'finding', 'recorded'], ['d3', 'cap_deferred', 'recorded'], ['d4', 'confirm_direction', 'recorded'], ['p1', 'p1', 'recorded']]); ok(ap(['answer', '--out', out, '--gate-rev', '1', '--reply', 'rec', '--by', 'human', '--rec-hash', rows(record(out))[0].rec_hash], g.env), 'answer'); closeOut = out; }); @@ -399,7 +399,7 @@ describe('the reader over many runs', () => { fs.writeFileSync(list, [path.join(TMP, 'fail', 'run'), copy, copy].join('\n') + '\n'); const r = exported(['--runs', list], baseEnv({ GSTACK_CAPY: '' })); expect(r.status).toBe(0); - expect(JSON.parse(r.stdout).counts.status).toEqual({ failed: 14 }); + expect(JSON.parse(r.stdout).counts.status).toEqual({ failed: 16 }); }); test('missing, failed, malformed, retrospective and recorded rows; dedupe across a repeated entry; CEO_ONLY_NO_GATE', () => { const e = baseEnv({ GSTACK_CAPY: '' }); @@ -416,11 +416,11 @@ describe('the reader over many runs', () => { expect(r.status).toBe(0); expect(r.stderr).toContain('(CEO_ONLY_NO_GATE)'); const x = JSON.parse(r.stdout); - expect(x.counts.status).toEqual({ missing: 7, failed: 7, retrospective: 7, malformed: 1, recorded: 11 }); - expect(x.rows.length).toBe(33); + expect(x.counts.status).toEqual({ missing: 8, failed: 8, retrospective: 8, malformed: 1, recorded: 13 }); + expect(x.rows.length).toBe(38); expect(x.counts.item_class.cap_deferred).toBe(1); expect(x.rows.filter((row: any) => row.item_class === 'finding').every((row: any) => row.ceo_eligible === false)).toBe(true); const text = ap(['shadow', '--runs', list], e); - expect(text.stdout).toContain('SHADOW_EXPORT: rows=33 refused=1'); + expect(text.stdout).toContain('SHADOW_EXPORT: rows=38 refused=1'); }); }); diff --git a/test/autoplan-shadow.test.ts b/test/autoplan-shadow.test.ts index db4f550d1ec..9ff22d36212 100644 --- a/test/autoplan-shadow.test.ts +++ b/test/autoplan-shadow.test.ts @@ -120,7 +120,7 @@ describe('the reply contract: exactly one valid object per requested id', () => const P1 = valid.findIndex(v => v.id === 'p1'); const reply = (objs: unknown[]) => '```json\n' + JSON.stringify(objs) + '\n```'; test('the page carries each item as rendered, with its findings, and p1 lists every finding the others name', () => { - expect(page.items.map(i => i.item.id)).toEqual(['uc1', 'd1', 'd2', 'uc2', 'd3', 'd4', 'p1']); + expect(page.items.map(i => i.item.id)).toEqual(['uc1', 'd1', 'd2', 'uc2', 'd3', 'd4', 'd5', 'p1']); expect(page.items[0]!.frozen).toMatchObject({ item_class: 'challenge2', kind: 'approval', recommended: 'a' }); expect(page.items[0]!.findings.map(f => f.severity).every(Boolean)).toBe(true); expect(page.items[P1]!.findings.map(f => f.id).sort()).toEqual(page.items.filter((_, i) => i !== P1).flatMap(i => i.findings).map(f => f.id).sort()); @@ -133,7 +133,7 @@ describe('the reply contract: exactly one valid object per requested id', () => const p = buildPage({ ...readState(out), active_plan: planFile }, gateOf(out), decider()); expect(p.prompt).toContain('fill {{QUESTIONS}} and {{IDS}} in {{PLAN}}'); expect(p.prompt).toContain('"id": "uc1"'); - expect(p.prompt).toContain('uc1, d1, d2, uc2, d3, d4, p1'); + expect(p.prompt).toContain('uc1, d1, d2, uc2, d3, d4, d5, p1'); expect(p.prompt.split('{{').length).toBe(4); }); test('a good reply is clean', () => { @@ -208,7 +208,7 @@ describe('runShadow: retry, truncation, failures and the deadline', async () => expect(outcome.status).toBe('recorded'); expect(outcome.line).toMatch(/^SHADOW: recorded model=claude-opus-5-5 usd=0\.0140$/); expect(ids(out).map(r => [r.item, r.status, r.pick, r.rule_pick, r.prompt_sha256 === SHADOW_PROMPT_SHA256])).toEqual([['uc1', 'recorded', 'a', 'a', true], ['d1', 'recorded', 'a', null, true], ['d2', 'recorded', 'a', null, true], - ['uc2', 'recorded', 'a', 'a', true], ['d3', 'recorded', 'a', null, true], ['d4', 'recorded', 'a', null, true], ['p1', 'recorded', 'a', 'a', true]]); + ['uc2', 'recorded', 'a', 'a', true], ['d3', 'recorded', 'a', null, true], ['d4', 'recorded', 'a', null, true], ['d5', 'recorded', 'a', 'a', true], ['p1', 'recorded', 'a', 'a', true]]); expect(f.requests().map(r => r.body.max_tokens)).toEqual([4000]); expect(fs.existsSync(path.join(out, 'shadow', 'r1.prompt.md'))).toBe(true); expect(fs.readFileSync(path.join(out, 'shadow', 'shadow-r1-1.reply.txt'), 'utf8')).toContain('fake prediction'); @@ -247,9 +247,9 @@ describe('runShadow: retry, truncation, failures and the deadline', async () => expect(ids(fixed.out).every(r => r.status === 'recorded')).toBe(true); const still = await shadowed('bad-twice', [{ mode: 'bad_option' }, { mode: 'bad_option' }]); expect(still.f.requests().length).toBe(2); - expect(ids(still.out).map(r => r.status)).toEqual(['malformed', 'recorded', 'recorded', 'recorded', 'recorded', 'recorded', 'recorded']); + expect(ids(still.out).map(r => r.status)).toEqual(['malformed', 'recorded', 'recorded', 'recorded', 'recorded', 'recorded', 'recorded', 'recorded']); expect(ids(still.out)[0]).toMatchObject({ pick: null, audit: false, malformed: 'pick "z" is not an option of uc1' }); - expect(still.outcome.line).toContain('malformed=1/7'); + expect(still.outcome.line).toContain('malformed=1/8'); }); test('a truncated reply raises max_tokens once to 8,000 (no page retry); truncated twice fails truncated', async () => { const raised = await shadowed('truncated-once', [{ mode: 'truncated' }, { mode: 'valid' }]); @@ -274,7 +274,7 @@ describe('runShadow: retry, truncation, failures and the deadline', async () => const r = await shadowed('deadline-retry', [{ mode: 'missing', delay_ms: 2500 }, { mode: 'valid', delay_ms: 3400 }], undefined, 3500); expect(r.ms).toBeLessThan(5900); expect(r.outcome.status).toBe('recorded'); - expect(ids(r.out).map(x => x.status)).toEqual(['recorded', 'recorded', 'recorded', 'recorded', 'recorded', 'recorded', 'malformed']); + expect(ids(r.out).map(x => x.status)).toEqual(['recorded', 'recorded', 'recorded', 'recorded', 'recorded', 'recorded', 'recorded', 'malformed']); const slow = await shadowed('deadline-call', [{ mode: 'valid', delay_ms: 6000 }], undefined, 800); expect(slow.outcome.line).toBe('SHADOW: failed timeout'); expect(slow.ms).toBeLessThan(5000); From eff8b78dcef398ac11d0694f5e85ebd3a0a66940 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 21:45:28 +0800 Subject: [PATCH 35/62] v1.100.0.0 release (#4444) - /autoplan's approval page no longer hides a reviewer's product objection behind "keep your direction". (#4431) - Every skill that loads the shared preamble, on every host, now says to ask a question once and to check a file before handing it over. (#4383) - The Captain manuals now name the `Failed or skipped:` and `Also changed:` lines that READY and lane reports carry. (#4432) - gstack's shell locks hold again on Ubuntu 26.04, where `mkdir` reports success when another process won the race (GST-2247). (#4262) - `test/gstack-lock-race.test.ts` runs the old pattern and the helper against a PATH shim that behaves like uutils 0.8.0 `mkdir`, so it runs on any runner image: the old pattern lets two of four racers win, the helper admits exactly one in each of 60 races and never overlaps across take, hold and release loops, and parallel `gstack-config` writers keep every key. (#4262) - Windows Setup E2E now runs when `bin/gstack-lock.sh` changes. (#4433) - Claude Code's skill list now says when to use each gstack skill, so Opus loads /review and /plan-eng-review when a request fits. (#4387) - A pull request's merge head can no longer keep its `/ship` receipt without a full review. (#4365) - `/ship` now counts review rounds per pull request, and the head that merges always gets a full review. (#4360) - /ship's documentation audit no longer accepts a passing result when an earlier line from the same audit said "blocked". (#4434) - /ship's documentation audit no longer spends an attempt when the audit child writes text after its result. (#4285) - The README lists the two new guides, and the install doc counts its hooks right. (#4403) - docs/releases.md now says the stable release cut treats a failed commit status as red and a pending one as still going, as it has since #4257. (#4436) - /ship's `finish --docs-requested` now accepts a docs fix when the audit named the file with a line number. (#4437) - Document the `.gstack/approval-classes.json` schema, `gstack-approval-classes` CLI commands, and owner approval citation format in `docs/ship-policy.md#approval-classes`. (#4355) - `/eval-plan` now runs four result checks instead of leaving them to judgment. (#4384) - The /review coverage-audit eval no longer fails a run that really read the source file when zsh stops a command line at an `echo ====` separator. (#4364) - Sixteen in-repo documentation links reach their section again. (#4394) - gstack agents now open every status report with what failed, what they didn't verify and what else they changed. (#4273) - Two new short guides. (#4380) - A skill you wrote whose contract still lists `check_after_last_edit` keeps the rest of its contract. (#4439) - The ship policy guide now explains how to merge any pull request with `gstack-ship-queue land`, even in a repository with one maintainer. (#4377) - /ship's test step runs a large unit suite on Linux. (#4426) - Every skill that loads the shared preamble, on every host, now says never to print a whole environment, git config or process table. (#4382) - Pull requests from /ship now open with at most three plain lines, and every merge lands as one commit titled with the PR title. (#4438) - `gstack-pr-wait`, `gstack-ci-gate` and the release cut no longer call a commit green while a check on it failed. (#4257) - `gstack-runaway` now says what a thread's cold and empty wakes cost, not just how many there were (GST-2770). (#4385) - The optional Stop hook no longer checks for a test run after the last edit, and /verify asks for it in plain words instead. (#4428) - /ship's test step says when it ran out of time, and you can set its budget. (#4429) - The remote test command no longer puts every file on one command line. (#4429) - The stable release no longer waits on the nightly Windows tests (GST-2815). (#4400) - Ubicloud fan-outs can no longer overshoot the vCPU limit, and owners no longer delete each other's VMs. (#4430) - hono is pinned to 4.13.16, which fixes five advisories the weekly OSV scan found in 4.13.13 (gstack#4406). (#4408) - `package.json` overrides (#4408) - `test/dependency-security.test.ts`: the lockfile floor check now covers `hono >= 4.13.16`. (#4408) - The nightly Windows test run finishes again. (#4409) - A short write-up checklist in ETHOS.md. (#4381) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CHANGELOG.md | 75 +++++++++++++++++++ VERSION | 2 +- agents-digest/gstack-AGENTS.md | 2 +- ...-keeps-reviewer-product-challenges-open.md | 1 - .../ask-once-and-check-handoff-files.md | 1 - changelog.d/captain-docs-report-lines.md | 1 - ...ell-locks-hold-when-mkdir-lies-gst-2247.md | 5 -- ...y-windows-setup-e2e-watches-gstack-lock.md | 1 - ...aude-skill-descriptions-say-when-to-use.md | 1 - changelog.d/close-last-recheck-carry-paths.md | 1 - changelog.d/count-review-rounds-per-pr.md | 1 - ...ocs-audit-blocked-line-carries-gst-2349.md | 4 - ...dit-ignores-prose-after-result-gst-2349.md | 4 - changelog.d/docs-index-and-install-hooks.md | 1 - ...elease-cut-green-counts-commit-statuses.md | 1 - ...cs-requested-accepts-path-line-blockers.md | 1 - .../docs-ship-policy-approval-classes-4320.md | 1 - changelog.d/eval-plan-result-checks.md | 1 - .../fix-coverage-audit-zsh-separator.md | 1 - changelog.d/fix-docs-missing-anchors.md | 1 - .../fix-gate-gaps-after-day-one-gate.md | 1 - .../gstack-reports-lead-with-failures.md | 1 - .../guides-for-outside-fixes-and-playtests.md | 1 - ...keep-custom-contracts-with-removed-item.md | 1 - changelog.d/land-normal-merge.md | 1 - .../lanes-large-file-lists-on-linux.md | 1 - .../never-print-secrets-shared-rule.md | 1 - changelog.d/plain-pr-bodies.md | 4 - ...it-and-ci-gate-read-every-check-attempt.md | 1 - changelog.d/price-runaway-wakes.md | 1 - .../remove-test-after-edit-stop-hook-check.md | 1 - ...p-step-time-limit-and-remote-file-lists.md | 2 - .../stable-cut-ignores-windows-nightly.md | 1 - .../ubicloud-quota-booking-full-owner.md | 1 - .../update-hono-security-advisories.md | 7 -- .../windows-nightly-fits-its-time-limit.md | 1 - changelog.d/write-up-checklist.md | 1 - package.json | 2 +- 38 files changed, 78 insertions(+), 57 deletions(-) delete mode 100644 changelog.d/approval-page-keeps-reviewer-product-challenges-open.md delete mode 100644 changelog.d/ask-once-and-check-handoff-files.md delete mode 100644 changelog.d/captain-docs-report-lines.md delete mode 100644 changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md delete mode 100644 changelog.d/capy-windows-setup-e2e-watches-gstack-lock.md delete mode 100644 changelog.d/claude-skill-descriptions-say-when-to-use.md delete mode 100644 changelog.d/close-last-recheck-carry-paths.md delete mode 100644 changelog.d/count-review-rounds-per-pr.md delete mode 100644 changelog.d/docs-audit-blocked-line-carries-gst-2349.md delete mode 100644 changelog.d/docs-audit-ignores-prose-after-result-gst-2349.md delete mode 100644 changelog.d/docs-index-and-install-hooks.md delete mode 100644 changelog.d/docs-release-cut-green-counts-commit-statuses.md delete mode 100644 changelog.d/docs-requested-accepts-path-line-blockers.md delete mode 100644 changelog.d/docs-ship-policy-approval-classes-4320.md delete mode 100644 changelog.d/eval-plan-result-checks.md delete mode 100644 changelog.d/fix-coverage-audit-zsh-separator.md delete mode 100644 changelog.d/fix-docs-missing-anchors.md delete mode 100644 changelog.d/fix-gate-gaps-after-day-one-gate.md delete mode 100644 changelog.d/gstack-reports-lead-with-failures.md delete mode 100644 changelog.d/guides-for-outside-fixes-and-playtests.md delete mode 100644 changelog.d/keep-custom-contracts-with-removed-item.md delete mode 100644 changelog.d/land-normal-merge.md delete mode 100644 changelog.d/lanes-large-file-lists-on-linux.md delete mode 100644 changelog.d/never-print-secrets-shared-rule.md delete mode 100644 changelog.d/plain-pr-bodies.md delete mode 100644 changelog.d/pr-wait-and-ci-gate-read-every-check-attempt.md delete mode 100644 changelog.d/price-runaway-wakes.md delete mode 100644 changelog.d/remove-test-after-edit-stop-hook-check.md delete mode 100644 changelog.d/ship-step-time-limit-and-remote-file-lists.md delete mode 100644 changelog.d/stable-cut-ignores-windows-nightly.md delete mode 100644 changelog.d/ubicloud-quota-booking-full-owner.md delete mode 100644 changelog.d/update-hono-security-advisories.md delete mode 100644 changelog.d/windows-nightly-fits-its-time-limit.md delete mode 100644 changelog.d/write-up-checklist.md diff --git a/CHANGELOG.md b/CHANGELOG.md index debc49fc69c..19ce4d61563 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,80 @@ # Changelog +## [1.100.0.0] - 2026-11-17 + +- **/autoplan's approval page no longer hides a reviewer's product objection behind "keep your direction".** A plan can now quote its owner under `### Owner's words`, and only those quotes count as the plan's direction. When a reviewer recommends changing anything else the plan says (its scope, build order, direction, cost or packaging), at any severity and even from one reviewer, the approval page shows it as a lettered choice that recommends the reviewer's change, and the cost line says what taking it actually does. A plan with no Owner's words section keeps today's default and gets one question asking the owner to confirm the direction is theirs. A challenge raised in an earlier review round stays on the page until the owner answers it or a later round marks it fixed. App plans with a `### Day one` table (the owner's first actions, how often, the feature, the way in from the first screen, the first build that has it, and how it's checked) show it first on the approval page, turn each guessed row into a question for the owner, and letter every cut that drops a day-one row or a quoted owner line; an app plan without the table gets one item asking for it. Declining a reviewer's change on a High or Critical finding keeps the plan as written and carries the finding into the build as a blocking task. Quoted owner words, including ones a later revision removed, are redacted from public exports. + +- **Every skill that loads the shared preamble, on every host, now says to ask a question once and to check a file before handing it over.** The Ground Rules section in the shared preamble gains two lines: ask each question once, after checking what you can yourself, and until it is answered list it as one waiting line in later updates instead of asking again; and open every file you hand over and remove placeholders first (TODO, `<fill in>`, lorem ipsum, broken links and images). The ask-once rule used to live only in the Capy wrapper's "how we work" page, which now points at the shared rule. + +- **The Captain manuals now name the `Failed or skipped:` and `Also changed:` lines that READY and lane reports carry.** A controller asks for a missing one in a follow-up and never refuses or stales a READY over it, the same as a missing `Unverified:` (GST-1455). + +- **gstack's shell locks hold again on Ubuntu 26.04, where `mkdir` reports success when another process won the race (GST-2247).** Ubuntu 26.04, and GitHub's `ubuntu-latest` from 2026-11-09, ships Rust coreutils (uutils) 0.8.0 as `mkdir`. It exits 0 even when the directory already existed because a racing process just made it, so every `mkdir "$LOCK"` lock in gstack could admit two holders: two updates moving one checkout at once, or two `gstack-config set` calls where one dropped the other's key (a test with eight parallel writers under a uutils-style `mkdir` lost six of the eight keys). Every lock now goes through one helper, `gstack_lock_take` in `bin/gstack-lock.sh`: `mkdir` only makes the directory, and the holder is whoever creates the lock's pid or owner file with the shell's noclobber redirect, which bash, zsh and dash open `O_CREAT|O_EXCL`, so the kernel admits exactly one. No `flock` (macOS has none). This covers the session-start updater, `gstack-upgrade`, the Capy session pin switch, `gstack-ff-update` (inlined, pinned to the helper by a test, because it must run standalone), setup's dependency-migration and Chromium-install locks, `gstack-browser-ensure`, `gstack-config`, the install registry, the Claude render lock, the developer profile and its takeover lock, `gstack-memorable`, the settings.json hook, the brain-sync drain lock, the Codex model-probe lock and its breaker, the lease directory lock, freeze's state lock and /setup-gbrain's concurrent-run lock. The Claude Code wrapper's copied runtime (`CLAUDE_CODE_RUNTIME_FILES`) and `bin/gstack-render-claude.sh` now carry or source the helper themselves, so a copied runtime and every script that sources the render library still take the lock. Each caller keeps its own waiting, stale-lock recovery, timeout and release. If the owner file is created but can't be fully written (disk full, a quota or a file-size limit), the helper removes it and the directory again and returns 3, so a failed write never leaves a lock that nobody holds. A lock directory that already exists is still never taken, even with no owner file in it, so a lock left by a killed holder waits for the caller's existing stale rule, as before. +- `test/gstack-lock-race.test.ts` runs the old pattern and the helper against a PATH shim that behaves like uutils 0.8.0 `mkdir`, so it runs on any runner image: the old pattern lets two of four racers win, the helper admits exactly one in each of 60 races and never overlaps across take, hold and release loops, and parallel `gstack-config` writers keep every key. `test/mkdir-lock-guard.test.ts` fails when shipped shell, a template, a workflow, a Markdown bash fence or TypeScript that embeds shell decides anything on a non-`-p` `mkdir`'s exit status; it found 26 such sites before this change, 12 more than the first report listed. The /setup-gbrain lock test now expects `mkdir:` on stderr only when the parent cannot be created, because the helper never runs `mkdir` on a path that already exists; no other assertion, threshold or timeout changed. + +- **Windows Setup E2E now runs when `bin/gstack-lock.sh` changes.** `./setup` sources the lock helper on every install, but the workflow's path filter and its `windows-scope` list left it out, so a pull request that changed only the helper skipped the Windows install check. Both lists now name it. + +- **Claude Code's skill list now says when to use each gstack skill, so Opus loads /review and /plan-eng-review when a request fits.** gstack cut every Claude Code description to its first sentence, which says what a skill is but usually not when to load it. In a test with Opus 5.5 in Claude Code, "Review my changes before I land them" loaded /review 0 of 3 times (its line read "Use when you review this PR's diff."), and "plan this feature" loaded no gstack skill in 9 tries. Almost every Claude Code description now keeps a short when-to-use clause after its first sentence. The clause is the skill's own trigger phrases ("Use for: review my changes, look over my diff, review this pr."), or its "Use when" sentence when it has no trigger list; /design-consultation and /eval-plan keep only their first sentence. /review's line no longer assumes a PR exists (local changes and a branch count), /plan-eng-review says it plans a feature before you build it, and the `gstack` router's line says what it does instead of "Router for the gstack skill suite." The skill list Claude Code loads every session grows by about 840 tokens. The clause is added only to Claude Code's trimmed list, so `--catalog-mode=full` and the other hosts don't get it. + +- **A pull request's merge head can no longer keep its `/ship` receipt without a full review.** Three gaps let a receipt through on less than the full review R51 asks for. A head whose own added lines match the reviewed ones but whose removed lines changed with the base (the base took `SAVE_VERSION := 83` under a branch reviewed as `82` to `84`) used to carry after one scoped reader; it's now a product change, so carry refuses and `/ship` reviews the head in full. A receipt an older gstack carried through a scoped re-check no longer carries on through a later base merge or stamp, and `gstack-ship-queue` won't bind it (`QUEUE_RECEIPT_STALE`), until a fresh full review replaces it. And a `/ship` body post keeps the PR body's `gstack-receipt-runs` block, so `gstack-ship-receipt history` counts every run instead of only the last. The read-only review's `PR_ROUND_CAP` stop no longer offers a round grant it can't honor, and the `stamp-only-carry` no-stop class is gone: a refused carry already runs Steps 2-16 without a stop, so a receipt that still lists that class is invalid and its PR runs `/ship` again. See docs/review-policy.md#rounds-per-pull-request. + +- **`/ship` now counts review rounds per pull request, and the head that merges always gets a full review.** gstack's two-round review cap (R51) was counted inside each `/ship` run, so a PR shipped five times could be reviewed ten times. `/ship` Step 1 now reads the PR body's receipt history (`gstack-ship-receipt history`), prints `PR_REVIEW_HISTORY:` and `PR_REVIEW_ROUTE:`, and passes the earlier rounds to `gstack-review-plan` (`--prior-rounds`, and `--prior-full` for the full rounds the cap counts). A new head whose own lines changed gets a fresh full review, the PR's last before merge; a PR already at two full rounds gets one read-only full review with no fix round, whose blocker goes to the lane's Captain. A scoped re-check of only what changed is now advice only: `carry` prints `RECHECK: advisory` and refuses `--recheck`, because in the replay a diff-only re-check caught none of 8 real faults that full rounds had caught (docs/evals/pr-round-count-results.md). A run that stops before its receipt still counts (`gstack-ship-receipt stub`), and the lane or Captain can buy one more round with `gstack-approvals round-grant --kind extra-round`; gstack cannot grant itself one. See docs/review-policy.md#rounds-per-pull-request. + +- **/ship's documentation audit no longer accepts a passing result when an earlier line from the same audit said "blocked".** A blocked result line followed by an unfenced "current" JSON line for the same audit as the very last line was accepted as current, and a last "current" line whose only fault was its format could be repaired back to current. Now a last line that drops an earlier blocked status or blocker is never accepted. It gets the free one-way re-ask, whose reply must stay blocked and keep those blockers. This corrects the previous entry's claim. A later JSON line, fenced or not, and a re-ask reply can no longer turn a blocked audit into a passing one. A blocker written only in prose after a passing line still depends on the re-ask counting it, which the parser can't check (GST-2349). + +- **/ship's documentation audit no longer spends an attempt when the audit child writes text after its result.** Step 14.5 reads the child's last nonempty line. A child that ended with its JSON result and then restated the section in prose (founderstar #837 and harness-evals #393, both "docs current, no edits") had its result treated as unreadable content, which skipped the free format re-ask. Each rejection spent one of the two attempts, and after both, /ship stopped for an owner risk grant. Text after a JSON line that carries the audit id is now a format slip, provided every such line is free of content problems: `FORMAT_REPAIR:` re-asks once for the whole result line without spending an attempt. The re-ask only works one way. If any such line said blocked or listed a blocker, the reply must stay blocked and keep those blockers, so a later correction or a fenced "current" example can never turn a blocked audit into a passing one. A content problem on such a line (a missing status, "current" with edits) still spends an attempt. The re-ask and the retry note now tell the child to put the section inside the JSON as a string and write nothing after the line (GST-2349). + +- **The README lists the two new guides, and the install doc counts its hooks right.** The README's docs table links the guides for landing a fix in someone else's repository and for running a human playtest. `docs/install.md` no longer says setup registers "up to three hook families" before naming a fourth, and it now mentions the two hooks that stay off until you turn them on, skill routing and skill contracts. The manual uninstall steps in `docs/uninstall.md` now name those two hooks too. + +- **docs/releases.md now says the stable release cut treats a failed commit status as red and a pending one as still going, as it has since #4257.** The docs' definition of a green commit only mentioned check runs. + +- **/ship's `finish --docs-requested` now accepts a docs fix when the audit named the file with a line number.** An audit that wrote `changelog.d/engine-parity-decisions.md:8: wording` or `...md:8:12 wording` in its blockers or decisions was refused with "is not named in the audit result's blockers or decisions", even though `...md: line 8` worked. The path may now be followed by `:<line>` or `:<line>:<column>`. A different file whose name starts with the same path still doesn't match. + +- Document the `.gstack/approval-classes.json` schema, `gstack-approval-classes` CLI commands, and owner approval citation format in `docs/ship-policy.md#approval-classes`. + +- `/eval-plan` now runs four result checks instead of leaving them to judgment. `prereg --check` requires a `## Decisions` section (what each possible result changes, at least two different actions) and a `## Scoring` section (a judge from another model family than every arm, checked against at least 40 hand labels at kappa 0.6 or better, and paired results with a 95% interval and the smallest detectable difference stated before the run). The new `judge --check --labels` scores the judge against hand labels, and `results --check` holds back a judged result without passing labels, a zero from a counter never shown to find a planted case, and a failures column with no answer-only column beside it. Preregistrations frozen before 2026-11-15 keep their rules. + +- **The /review coverage-audit eval no longer fails a run that really read the source file when zsh stops a command line at an `echo ====` separator.** zsh treats an unquoted word that starts with `=` as a command lookup, so `cat -n src/billing.ts; echo ====; cat -n test/billing.test.ts` prints the source, then `(eval):1: === not found`, and runs nothing after it. The read check now credits the files printed before that error when the error is the last line of the output and everything before it matches the usual read rules; files after the separator still count only when they are read again (gate census 43575953190). + +Sixteen in-repo documentation links reach their section again. `docs/skills.md` linked 12 skills to `#anchors` with no section (13 links); those rows now open each skill's own `SKILL.md`. `docs/review-policy.md`'s three links to `#targeted-only-read-after-the-loop` lost their target when the heading gained `(GST-1598)`; the heading now carries that anchor. Contributed by @Davmunrey. + +- **/autoplan's approval page closes three gaps left by the last change.** When both reviewers challenge the plan and one calls it a build-order change while the other calls it a scope change, the page now treats it as a scope change, so taking it sends the plan back for review instead of settling it without one. A plan with no Owner's words section now gets the "confirm the direction is yours" question when both reviewers challenge it and the page recommends keeping the plan, as it already did for a challenge from one reviewer. And a quote is checked only against this repository's approvals record, so another repository's record for a branch with the same name can no longer verify it. + +- **gstack agents now open every status report with what failed, what they didn't verify and what else they changed.** The shared closing rule used to ask for "a few short lines". Now a report stays under 250 words and opens with three lines, `Failed or skipped:`, `Unverified:` and `Also changed:`, each naming every item or saying none. Lists longer than 10 get the top 10 and a count of the rest. Capy crews follow the same shape (factory.md point 10, the lane report and READY templates). On a 40-task dev split with Claude Opus 5.5, this wording raised the share of key facts disclosed in a report's first 250 words from 0.442 to 0.520 against the old closer, and in Capy lane reports from 0.552 to 0.604. Those are dev numbers, and the sealed held-out read is still to come (GST-1455). + +- **Two new short guides.** `docs/howto-land-a-fix-in-someone-elses-repo.md` covers reading the other project's rules, searching for the same fix first, running every guard their CI runs before you open, keeping the change small, and answering each review point in a new commit with the proof rerun. `docs/howto-run-human-playtests.md` covers asking about moments and where people would stop, and why a back-to-back pick between two builds measures the order they were played in, not the builds. + +- **A skill you wrote whose contract still lists `check_after_last_edit` keeps the rest of its contract.** This corrects the entry in this release that says such a contract is now invalid and none of its items are checked. The optional Stop hook now skips only that item and keeps checking the skill's other items. Until you delete the item, the hook prints a `SKILL_CONTRACT_SKIPPED` line naming the file and the item. A contract whose only items use the removed kind is still invalid, so the hook checks nothing for that skill. + +- **The ship policy guide now explains how to merge any pull request with `gstack-ship-queue land`, even in a repository with one maintainer.** It names the two policy keys land needs before it will run, lists what land already checks, gives a pinned `gh pr merge` fallback for repositories that can't use land yet, and covers four common traps. CONTRIBUTING.md links to it. + +- **/ship's test step runs a large unit suite on Linux.** A lane with thousands of unit files used to stop with `PREGATE: incomplete` and `E2BIG: argument list too long` before any test ran, because every file went into one command argument and Linux caps a single argument at 128 KiB. gstack now splits a big file list into runner processes of about 96 KB each, run one after another and counted as one run, so the result is the same as before: any failing chunk fails the lane. An `E2BIG` launch failure is now reported as its own cause (`arg-limit`) instead of telling you to install a missing tool. (#4424) + +- **Every skill that loads the shared preamble, on every host, now says never to print a whole environment, git config or process table.** The rule used to load only in the Capy wrapper, and its list missed `git config --list`, which can print a proxy's login header, process or container listings that show arguments or environment (`ps aux`, `ps -ef`, `ps -o args`, `docker top ... args`, `docker inspect`), where run tokens ride, and `set -x` or an `export $(...)` that expands to a bare `export`. A new Ground Rules section in the shared preamble lists these commands and the safe forms, which are to read one value by name (`git config --get <name>`), check a variable is set without printing it, and list processes by name or pid. It also says to wait on CI with one `gstack-pr-wait` call instead of a poll loop or `gh pr checks --watch`, which spends the shared GitHub GraphQL quota. The section is pinned, so no model loadout drops it. + +- **Pull requests from /ship now open with at most three plain lines, and every merge lands as one commit titled with the PR title.** /ship writes `## ` sections and `gstack-post` folds each into a collapsed section when it posts, so a reader sees what changed, why, and what they have to do, with the rest one click away and the Agent notes section last. `gstack-post fold --body-file F` shows the folded body without posting it. In a repository with `.gstack/plain-titles.json`, `gstack-post` and the Plain title check refuse a body that shows more than three lines (or 600 characters) before its first fold, or uses a listed in-house word above the Agent notes section (`PLAIN_BODY_REFUSED`); gstack now ships a default word list (outside voice, pregate, receipt, carry, stamp, train, lane, soak and more), which a policy extends or replaces with `replace_default_terms`, and `body_since` keeps PRs opened before that date to warnings. Every `gstack-ship-queue land` form now passes the subject `<title> (#n)` and a body of the PR's opening lines plus the branch's `Co-authored-by:` and other trailers, so GitHub no longer writes its commit list; `--dry-run` prints it and `--body-file` replaces the opening. Release PRs list one plain line per change with its PR. Two new policy settings: `history: no-rewrite` (squash landings, never a rebased or force-pushed branch) and `land.merge_commit_paths` (keep a merge commit for PRs that change those paths, such as eval results). See docs/writing-prs.md. + +- **`gstack-pr-wait`, `gstack-ci-gate` and the release cut no longer call a commit green while a check on it failed.** They read CI from GitHub's rollup or its default check-runs list, which hold only each check suite's latest attempt, so when a rerun attempt created no jobs the failed run before it disappeared, and a workflow run that failed before creating any job never appeared at all. That is the false green the merge queue had on gstack-evals#303 (#4235). All three now also read CI at the commit through the merge queue's own helper, which reads every attempt and every workflow run, and keep the worse answer per check. So `gstack-pr-wait --until green` blocks with `check failed: checks` and `check failed: sealed (run <id>, no jobs)`, the land gate says `VERDICT FAIL`, and the release cut skips the commit. The release cut now also counts a failed commit status as red, as the merge queue does. A rerun that passed still reads green, and an unreadable read is an error, never a pass (GST-2252). + +- **`gstack-runaway` now says what a thread's cold and empty wakes cost, not just how many there were (GST-2770).** Each wake it reads is marked cold when it started more than 5 minutes after the thread's last activity, so the prompt cache had lapsed, and is priced in warm model calls, with a cold call at 19.4 (measured on Opus 5.5: $2.42 against $0.125 per million counted tokens; a call after a tool that ran past 5 minutes is cold too). The RUNAWAY line adds `wakes`, `cold_wakes`, `empty_wakes`, `cold_extra_spend` and `empty_spend`, the empty-wake warning gives the empty wakes' share of spend, and `scan --wakes` prints one WAKE line per wake. A message sent to another thread now counts as action even when its state is "working", and more than 5 minutes idle inside a turn (not counting a tool's own run time) starts a new wake. On four coordinating threads over 4.7 days the meter's cold and empty shares came within 1.3 points of a hand count; before this, sends were counted as empty and the empty share read 4 to 12 points high. /runaway-stopper's fetch program now keeps each message's target and each call's run time. + +- **The optional Stop hook no longer checks for a test run after the last edit, and /verify asks for it in plain words instead.** With /verify loaded, Opus 5.5 and GPT-6.1 Sol already ran a test after their last edit in 96% and 89% of runs, and the hook's check added between -0.5 and +2 points, inside the noise on both models. The hook's other checks (report labels, specialist dispatches, the adversarial pass) are unchanged. If you wrote your own skill whose contract lists `check_after_last_edit`, that contract is now invalid. The hook then checks none of that skill's items and prints one line naming the file until you delete the item. /verify now says to run the full check after your last edit. It also no longer says it never edits CHANGELOG, because a changelog entry the repo expects with a change is part of the change; /ship still folds branch entries into the release entry. + +- **/ship's test step says when it ran out of time, and you can set its budget.** `gstack-ship-preflight` used to stop gstack-pregate after a fixed hour and print `PREGATE: unreadable (exit 143)`, which hid the cause. The whole step's budget is now `--step-timeout <s>` (default 3600 s), and a stop at that limit prints `PREGATE: time limit hit` with the way out: push and let CI's full run carry the tests, or give the step a larger budget. +- **The remote test command no longer puts every file on one command line.** On a small machine with a remote `test_backend`, the command pregate prints for gstack's Ubicloud runner used to carry every selected test file in one argument, which Linux refuses past 128 KiB (`E2BIG`). The files now go to the VM in a setup script, so the command stays short however many files are selected. docs/troubleshooting.md has a new `arg-limit` entry for this kind of failure. + +- **The stable release no longer waits on the nightly Windows tests (GST-2815).** The nightly Windows free suite never blocks a pull request, but the daily stable cut still treated its red or unfinished results as a reason to skip a commit, so stable stopped moving while one Windows shard kept timing out. The cut now sets that workflow's check runs aside, matched by workflow file, the same way it ignores its own job. Every other check, the required `free-tests` check and the release-gate evidence still block exactly as before. + +- **Ubicloud fan-outs can no longer overshoot the vCPU limit, and owners no longer delete each other's VMs.** `ubi-runner.sh up` now reads the project's vCPU usage and books its new VM under one lock per machine, so shards started together see each other's bookings instead of all passing on the same reading. A new `ubi-runner.sh room [-s SIZE]` command prints how many more VMs fit now, so a fan-out can size each batch to the room left. When usage can't be read and `UBI_QUOTA_VCPUS` is set, the create is refused (`UBI_QUOTA_UNREADABLE`) instead of going ahead. VM names now carry the whole owner id (up to 31 characters; longer is refused with `UBI_OWNER_TOO_LONG`) instead of its first 12, so two owners sharing a prefix no longer reap each other's expired VMs (#3748); a VM an older runner copy named under the old cut form is still reaped by the long owner on the machine whose VM record lists it, and `recover` accepts the longer owner ids. Merge checks and canaries set no `UBI_QUOTA_VCPUS` and behave as before. + +**hono is pinned to 4.13.16, which fixes five advisories the weekly OSV scan found in 4.13.13 (gstack#4406).** The 2026-11-16 scan (run 43825448246) flagged GHSA-3gg2-335m-rxc6 (CVSS 3.4, the `css` helper) and GHSA-46wx-v44x-9hh2, GHSA-4h7h-rv7c-7m2v, GHSA-4m76-xfj5-7975 and GHSA-h7mg-cq63-vhpq (CVSS 5.3 each: `csrf()`, `validator('form')`, `mount()` and RegExpRouter wildcard middleware). hono reaches gstack only through the dev and test toolchain (`@anthropic-ai/claude-agent-sdk` pulls in `@modelcontextprotocol/sdk`), gstack's own code never imports it or starts a hono server, and none of the affected helpers is used, so no advisory was reachable. Contributor checkouts get the patched version on their next `bun install`. + +- **`package.json` overrides**: `hono` moves from 4.13.13 to 4.13.16, the release that fixes all five. `bun.lock` holds the one copy. +- `test/dependency-security.test.ts`: the lockfile floor check now covers `hono >= 4.13.16`. It fails on main. + +- **The nightly Windows test run finishes again.** Since 2026-11-06 one of its six shards ran past the 15-minute job limit almost every night, because 95 newer test files had no recorded Windows duration and the planner packed them blind, so one shard got 26 minutes of work while another got 12. The Windows durations are refreshed to a recording that covers all 902 files, and the run now uses eight shards of about 12 minutes each, so the suite fits with room to grow. No test was dropped and the time limit is unchanged. + +- **A short write-up checklist in ETHOS.md.** Explain the Number now ends with three checks before a post or write-up goes out: its words match the page it links, every number, "green" and "ready" names its source and is read at the current head, and a fresh model reads it cold once. The READY template in `captain/templates/READY.md` points to the second check. Anything carried over from an earlier head goes under `Unverified:` until it is re-read. + ## [1.99.5.0] - 2026-11-15 - **CONTRIBUTING.md now says plainly how outside reports and PRs land.** It explains that AI agents working for the maintainer triage, rebuild and land outside patches with the author credited, which is why commits read as the maintainer's. It lists the three paths a PR can take (a docs-only PR for people can merge as it is after its links, commands and install steps are checked; a plainly correct fix of about 40 lines is taken even when small; everything else is rebuilt on main when it has proof, a real consequence and matters to most users), the 48-hour first-reply goal, and the narrowed open-PR limit, which never applies to anyone with a PR taken in the last 90 days. The stale wave process, which merged outside PRs on a collector branch, is gone. `crew/docs/captain.md`, the Captain's CREW template and `/captain` match. diff --git a/VERSION b/VERSION index 7a9079c44ee..f173507db10 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.99.5.0 +1.100.0.0 diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.md index 370b4f3097a..17c59a82d94 100644 --- a/agents-digest/gstack-AGENTS.md +++ b/agents-digest/gstack-AGENTS.md @@ -1,4 +1,4 @@ -# gstack digest v1.99.5.0 — regenerate/re-copy after upgrading gstack +# gstack digest v1.100.0.0 — regenerate/re-copy after upgrading gstack Behavioral rules from gstack (https://github.com/garrytan/gstack), compressed for agent hosts without a full skill install. The full skills add workflows, diff --git a/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md b/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md deleted file mode 100644 index 7486b88adbf..00000000000 --- a/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md +++ /dev/null @@ -1 +0,0 @@ -- **/autoplan's approval page no longer hides a reviewer's product objection behind "keep your direction".** A plan can now quote its owner under `### Owner's words`, and only those quotes count as the plan's direction. When a reviewer recommends changing anything else the plan says (its scope, build order, direction, cost or packaging), at any severity and even from one reviewer, the approval page shows it as a lettered choice that recommends the reviewer's change, and the cost line says what taking it actually does. A plan with no Owner's words section keeps today's default and gets one question asking the owner to confirm the direction is theirs. A challenge raised in an earlier review round stays on the page until the owner answers it or a later round marks it fixed. App plans with a `### Day one` table (the owner's first actions, how often, the feature, the way in from the first screen, the first build that has it, and how it's checked) show it first on the approval page, turn each guessed row into a question for the owner, and letter every cut that drops a day-one row or a quoted owner line; an app plan without the table gets one item asking for it. Declining a reviewer's change on a High or Critical finding keeps the plan as written and carries the finding into the build as a blocking task. Quoted owner words, including ones a later revision removed, are redacted from public exports. diff --git a/changelog.d/ask-once-and-check-handoff-files.md b/changelog.d/ask-once-and-check-handoff-files.md deleted file mode 100644 index dc76b9535fe..00000000000 --- a/changelog.d/ask-once-and-check-handoff-files.md +++ /dev/null @@ -1 +0,0 @@ -- **Every skill that loads the shared preamble, on every host, now says to ask a question once and to check a file before handing it over.** The Ground Rules section in the shared preamble gains two lines: ask each question once, after checking what you can yourself, and until it is answered list it as one waiting line in later updates instead of asking again; and open every file you hand over and remove placeholders first (TODO, `<fill in>`, lorem ipsum, broken links and images). The ask-once rule used to live only in the Capy wrapper's "how we work" page, which now points at the shared rule. diff --git a/changelog.d/captain-docs-report-lines.md b/changelog.d/captain-docs-report-lines.md deleted file mode 100644 index a580b24c2eb..00000000000 --- a/changelog.d/captain-docs-report-lines.md +++ /dev/null @@ -1 +0,0 @@ -- **The Captain manuals now name the `Failed or skipped:` and `Also changed:` lines that READY and lane reports carry.** A controller asks for a missing one in a follow-up and never refuses or stales a READY over it, the same as a missing `Unverified:` (GST-1455). diff --git a/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md b/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md deleted file mode 100644 index baa8e65604f..00000000000 --- a/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -important: blocker ---- -- **gstack's shell locks hold again on Ubuntu 26.04, where `mkdir` reports success when another process won the race (GST-2247).** Ubuntu 26.04, and GitHub's `ubuntu-latest` from 2026-11-09, ships Rust coreutils (uutils) 0.8.0 as `mkdir`. It exits 0 even when the directory already existed because a racing process just made it, so every `mkdir "$LOCK"` lock in gstack could admit two holders: two updates moving one checkout at once, or two `gstack-config set` calls where one dropped the other's key (a test with eight parallel writers under a uutils-style `mkdir` lost six of the eight keys). Every lock now goes through one helper, `gstack_lock_take` in `bin/gstack-lock.sh`: `mkdir` only makes the directory, and the holder is whoever creates the lock's pid or owner file with the shell's noclobber redirect, which bash, zsh and dash open `O_CREAT|O_EXCL`, so the kernel admits exactly one. No `flock` (macOS has none). This covers the session-start updater, `gstack-upgrade`, the Capy session pin switch, `gstack-ff-update` (inlined, pinned to the helper by a test, because it must run standalone), setup's dependency-migration and Chromium-install locks, `gstack-browser-ensure`, `gstack-config`, the install registry, the Claude render lock, the developer profile and its takeover lock, `gstack-memorable`, the settings.json hook, the brain-sync drain lock, the Codex model-probe lock and its breaker, the lease directory lock, freeze's state lock and /setup-gbrain's concurrent-run lock. The Claude Code wrapper's copied runtime (`CLAUDE_CODE_RUNTIME_FILES`) and `bin/gstack-render-claude.sh` now carry or source the helper themselves, so a copied runtime and every script that sources the render library still take the lock. Each caller keeps its own waiting, stale-lock recovery, timeout and release. If the owner file is created but can't be fully written (disk full, a quota or a file-size limit), the helper removes it and the directory again and returns 3, so a failed write never leaves a lock that nobody holds. A lock directory that already exists is still never taken, even with no owner file in it, so a lock left by a killed holder waits for the caller's existing stale rule, as before. -- `test/gstack-lock-race.test.ts` runs the old pattern and the helper against a PATH shim that behaves like uutils 0.8.0 `mkdir`, so it runs on any runner image: the old pattern lets two of four racers win, the helper admits exactly one in each of 60 races and never overlaps across take, hold and release loops, and parallel `gstack-config` writers keep every key. `test/mkdir-lock-guard.test.ts` fails when shipped shell, a template, a workflow, a Markdown bash fence or TypeScript that embeds shell decides anything on a non-`-p` `mkdir`'s exit status; it found 26 such sites before this change, 12 more than the first report listed. The /setup-gbrain lock test now expects `mkdir:` on stderr only when the parent cannot be created, because the helper never runs `mkdir` on a path that already exists; no other assertion, threshold or timeout changed. diff --git a/changelog.d/capy-windows-setup-e2e-watches-gstack-lock.md b/changelog.d/capy-windows-setup-e2e-watches-gstack-lock.md deleted file mode 100644 index 4ef32983dd1..00000000000 --- a/changelog.d/capy-windows-setup-e2e-watches-gstack-lock.md +++ /dev/null @@ -1 +0,0 @@ -- **Windows Setup E2E now runs when `bin/gstack-lock.sh` changes.** `./setup` sources the lock helper on every install, but the workflow's path filter and its `windows-scope` list left it out, so a pull request that changed only the helper skipped the Windows install check. Both lists now name it. diff --git a/changelog.d/claude-skill-descriptions-say-when-to-use.md b/changelog.d/claude-skill-descriptions-say-when-to-use.md deleted file mode 100644 index fdef5b07e92..00000000000 --- a/changelog.d/claude-skill-descriptions-say-when-to-use.md +++ /dev/null @@ -1 +0,0 @@ -- **Claude Code's skill list now says when to use each gstack skill, so Opus loads /review and /plan-eng-review when a request fits.** gstack cut every Claude Code description to its first sentence, which says what a skill is but usually not when to load it. In a test with Opus 5.5 in Claude Code, "Review my changes before I land them" loaded /review 0 of 3 times (its line read "Use when you review this PR's diff."), and "plan this feature" loaded no gstack skill in 9 tries. Almost every Claude Code description now keeps a short when-to-use clause after its first sentence. The clause is the skill's own trigger phrases ("Use for: review my changes, look over my diff, review this pr."), or its "Use when" sentence when it has no trigger list; /design-consultation and /eval-plan keep only their first sentence. /review's line no longer assumes a PR exists (local changes and a branch count), /plan-eng-review says it plans a feature before you build it, and the `gstack` router's line says what it does instead of "Router for the gstack skill suite." The skill list Claude Code loads every session grows by about 840 tokens. The clause is added only to Claude Code's trimmed list, so `--catalog-mode=full` and the other hosts don't get it. diff --git a/changelog.d/close-last-recheck-carry-paths.md b/changelog.d/close-last-recheck-carry-paths.md deleted file mode 100644 index ad0af674a14..00000000000 --- a/changelog.d/close-last-recheck-carry-paths.md +++ /dev/null @@ -1 +0,0 @@ -- **A pull request's merge head can no longer keep its `/ship` receipt without a full review.** Three gaps let a receipt through on less than the full review R51 asks for. A head whose own added lines match the reviewed ones but whose removed lines changed with the base (the base took `SAVE_VERSION := 83` under a branch reviewed as `82` to `84`) used to carry after one scoped reader; it's now a product change, so carry refuses and `/ship` reviews the head in full. A receipt an older gstack carried through a scoped re-check no longer carries on through a later base merge or stamp, and `gstack-ship-queue` won't bind it (`QUEUE_RECEIPT_STALE`), until a fresh full review replaces it. And a `/ship` body post keeps the PR body's `gstack-receipt-runs` block, so `gstack-ship-receipt history` counts every run instead of only the last. The read-only review's `PR_ROUND_CAP` stop no longer offers a round grant it can't honor, and the `stamp-only-carry` no-stop class is gone: a refused carry already runs Steps 2-16 without a stop, so a receipt that still lists that class is invalid and its PR runs `/ship` again. See docs/review-policy.md#rounds-per-pull-request. diff --git a/changelog.d/count-review-rounds-per-pr.md b/changelog.d/count-review-rounds-per-pr.md deleted file mode 100644 index 5fb3fa1c847..00000000000 --- a/changelog.d/count-review-rounds-per-pr.md +++ /dev/null @@ -1 +0,0 @@ -- **`/ship` now counts review rounds per pull request, and the head that merges always gets a full review.** gstack's two-round review cap (R51) was counted inside each `/ship` run, so a PR shipped five times could be reviewed ten times. `/ship` Step 1 now reads the PR body's receipt history (`gstack-ship-receipt history`), prints `PR_REVIEW_HISTORY:` and `PR_REVIEW_ROUTE:`, and passes the earlier rounds to `gstack-review-plan` (`--prior-rounds`, and `--prior-full` for the full rounds the cap counts). A new head whose own lines changed gets a fresh full review, the PR's last before merge; a PR already at two full rounds gets one read-only full review with no fix round, whose blocker goes to the lane's Captain. A scoped re-check of only what changed is now advice only: `carry` prints `RECHECK: advisory` and refuses `--recheck`, because in the replay a diff-only re-check caught none of 8 real faults that full rounds had caught (docs/evals/pr-round-count-results.md). A run that stops before its receipt still counts (`gstack-ship-receipt stub`), and the lane or Captain can buy one more round with `gstack-approvals round-grant --kind extra-round`; gstack cannot grant itself one. See docs/review-policy.md#rounds-per-pull-request. diff --git a/changelog.d/docs-audit-blocked-line-carries-gst-2349.md b/changelog.d/docs-audit-blocked-line-carries-gst-2349.md deleted file mode 100644 index b5190db44e3..00000000000 --- a/changelog.d/docs-audit-blocked-line-carries-gst-2349.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: blocker ---- -- **/ship's documentation audit no longer accepts a passing result when an earlier line from the same audit said "blocked".** A blocked result line followed by an unfenced "current" JSON line for the same audit as the very last line was accepted as current, and a last "current" line whose only fault was its format could be repaired back to current. Now a last line that drops an earlier blocked status or blocker is never accepted. It gets the free one-way re-ask, whose reply must stay blocked and keep those blockers. This corrects the previous entry's claim. A later JSON line, fenced or not, and a re-ask reply can no longer turn a blocked audit into a passing one. A blocker written only in prose after a passing line still depends on the re-ask counting it, which the parser can't check (GST-2349). diff --git a/changelog.d/docs-audit-ignores-prose-after-result-gst-2349.md b/changelog.d/docs-audit-ignores-prose-after-result-gst-2349.md deleted file mode 100644 index e5ec338b046..00000000000 --- a/changelog.d/docs-audit-ignores-prose-after-result-gst-2349.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: blocker ---- -- **/ship's documentation audit no longer spends an attempt when the audit child writes text after its result.** Step 14.5 reads the child's last nonempty line. A child that ended with its JSON result and then restated the section in prose (founderstar #837 and harness-evals #393, both "docs current, no edits") had its result treated as unreadable content, which skipped the free format re-ask. Each rejection spent one of the two attempts, and after both, /ship stopped for an owner risk grant. Text after a JSON line that carries the audit id is now a format slip, provided every such line is free of content problems: `FORMAT_REPAIR:` re-asks once for the whole result line without spending an attempt. The re-ask only works one way. If any such line said blocked or listed a blocker, the reply must stay blocked and keep those blockers, so a later correction or a fenced "current" example can never turn a blocked audit into a passing one. A content problem on such a line (a missing status, "current" with edits) still spends an attempt. The re-ask and the retry note now tell the child to put the section inside the JSON as a string and write nothing after the line (GST-2349). diff --git a/changelog.d/docs-index-and-install-hooks.md b/changelog.d/docs-index-and-install-hooks.md deleted file mode 100644 index 94daa40d66b..00000000000 --- a/changelog.d/docs-index-and-install-hooks.md +++ /dev/null @@ -1 +0,0 @@ -- **The README lists the two new guides, and the install doc counts its hooks right.** The README's docs table links the guides for landing a fix in someone else's repository and for running a human playtest. `docs/install.md` no longer says setup registers "up to three hook families" before naming a fourth, and it now mentions the two hooks that stay off until you turn them on, skill routing and skill contracts. The manual uninstall steps in `docs/uninstall.md` now name those two hooks too. diff --git a/changelog.d/docs-release-cut-green-counts-commit-statuses.md b/changelog.d/docs-release-cut-green-counts-commit-statuses.md deleted file mode 100644 index 847426185df..00000000000 --- a/changelog.d/docs-release-cut-green-counts-commit-statuses.md +++ /dev/null @@ -1 +0,0 @@ -- **docs/releases.md now says the stable release cut treats a failed commit status as red and a pending one as still going, as it has since #4257.** The docs' definition of a green commit only mentioned check runs. diff --git a/changelog.d/docs-requested-accepts-path-line-blockers.md b/changelog.d/docs-requested-accepts-path-line-blockers.md deleted file mode 100644 index cdee4b9d86d..00000000000 --- a/changelog.d/docs-requested-accepts-path-line-blockers.md +++ /dev/null @@ -1 +0,0 @@ -- **/ship's `finish --docs-requested` now accepts a docs fix when the audit named the file with a line number.** An audit that wrote `changelog.d/engine-parity-decisions.md:8: wording` or `...md:8:12 wording` in its blockers or decisions was refused with "is not named in the audit result's blockers or decisions", even though `...md: line 8` worked. The path may now be followed by `:<line>` or `:<line>:<column>`. A different file whose name starts with the same path still doesn't match. diff --git a/changelog.d/docs-ship-policy-approval-classes-4320.md b/changelog.d/docs-ship-policy-approval-classes-4320.md deleted file mode 100644 index c6e94573c79..00000000000 --- a/changelog.d/docs-ship-policy-approval-classes-4320.md +++ /dev/null @@ -1 +0,0 @@ -- Document the `.gstack/approval-classes.json` schema, `gstack-approval-classes` CLI commands, and owner approval citation format in `docs/ship-policy.md#approval-classes`. diff --git a/changelog.d/eval-plan-result-checks.md b/changelog.d/eval-plan-result-checks.md deleted file mode 100644 index 8613ccc0a10..00000000000 --- a/changelog.d/eval-plan-result-checks.md +++ /dev/null @@ -1 +0,0 @@ -- `/eval-plan` now runs four result checks instead of leaving them to judgment. `prereg --check` requires a `## Decisions` section (what each possible result changes, at least two different actions) and a `## Scoring` section (a judge from another model family than every arm, checked against at least 40 hand labels at kappa 0.6 or better, and paired results with a 95% interval and the smallest detectable difference stated before the run). The new `judge --check --labels` scores the judge against hand labels, and `results --check` holds back a judged result without passing labels, a zero from a counter never shown to find a planted case, and a failures column with no answer-only column beside it. Preregistrations frozen before 2026-11-15 keep their rules. diff --git a/changelog.d/fix-coverage-audit-zsh-separator.md b/changelog.d/fix-coverage-audit-zsh-separator.md deleted file mode 100644 index d01c3736ab5..00000000000 --- a/changelog.d/fix-coverage-audit-zsh-separator.md +++ /dev/null @@ -1 +0,0 @@ -- **The /review coverage-audit eval no longer fails a run that really read the source file when zsh stops a command line at an `echo ====` separator.** zsh treats an unquoted word that starts with `=` as a command lookup, so `cat -n src/billing.ts; echo ====; cat -n test/billing.test.ts` prints the source, then `(eval):1: === not found`, and runs nothing after it. The read check now credits the files printed before that error when the error is the last line of the output and everything before it matches the usual read rules; files after the separator still count only when they are read again (gate census 43575953190). diff --git a/changelog.d/fix-docs-missing-anchors.md b/changelog.d/fix-docs-missing-anchors.md deleted file mode 100644 index 27823e38e78..00000000000 --- a/changelog.d/fix-docs-missing-anchors.md +++ /dev/null @@ -1 +0,0 @@ -Sixteen in-repo documentation links reach their section again. `docs/skills.md` linked 12 skills to `#anchors` with no section (13 links); those rows now open each skill's own `SKILL.md`. `docs/review-policy.md`'s three links to `#targeted-only-read-after-the-loop` lost their target when the heading gained `(GST-1598)`; the heading now carries that anchor. Contributed by @Davmunrey. diff --git a/changelog.d/fix-gate-gaps-after-day-one-gate.md b/changelog.d/fix-gate-gaps-after-day-one-gate.md deleted file mode 100644 index 3a1d3ebe238..00000000000 --- a/changelog.d/fix-gate-gaps-after-day-one-gate.md +++ /dev/null @@ -1 +0,0 @@ -- **/autoplan's approval page closes three gaps left by the last change.** When both reviewers challenge the plan and one calls it a build-order change while the other calls it a scope change, the page now treats it as a scope change, so taking it sends the plan back for review instead of settling it without one. A plan with no Owner's words section now gets the "confirm the direction is yours" question when both reviewers challenge it and the page recommends keeping the plan, as it already did for a challenge from one reviewer. And a quote is checked only against this repository's approvals record, so another repository's record for a branch with the same name can no longer verify it. diff --git a/changelog.d/gstack-reports-lead-with-failures.md b/changelog.d/gstack-reports-lead-with-failures.md deleted file mode 100644 index dd0dda6ec2f..00000000000 --- a/changelog.d/gstack-reports-lead-with-failures.md +++ /dev/null @@ -1 +0,0 @@ -- **gstack agents now open every status report with what failed, what they didn't verify and what else they changed.** The shared closing rule used to ask for "a few short lines". Now a report stays under 250 words and opens with three lines, `Failed or skipped:`, `Unverified:` and `Also changed:`, each naming every item or saying none. Lists longer than 10 get the top 10 and a count of the rest. Capy crews follow the same shape (factory.md point 10, the lane report and READY templates). On a 40-task dev split with Claude Opus 5.5, this wording raised the share of key facts disclosed in a report's first 250 words from 0.442 to 0.520 against the old closer, and in Capy lane reports from 0.552 to 0.604. Those are dev numbers, and the sealed held-out read is still to come (GST-1455). diff --git a/changelog.d/guides-for-outside-fixes-and-playtests.md b/changelog.d/guides-for-outside-fixes-and-playtests.md deleted file mode 100644 index 6baed792a91..00000000000 --- a/changelog.d/guides-for-outside-fixes-and-playtests.md +++ /dev/null @@ -1 +0,0 @@ -- **Two new short guides.** `docs/howto-land-a-fix-in-someone-elses-repo.md` covers reading the other project's rules, searching for the same fix first, running every guard their CI runs before you open, keeping the change small, and answering each review point in a new commit with the proof rerun. `docs/howto-run-human-playtests.md` covers asking about moments and where people would stop, and why a back-to-back pick between two builds measures the order they were played in, not the builds. diff --git a/changelog.d/keep-custom-contracts-with-removed-item.md b/changelog.d/keep-custom-contracts-with-removed-item.md deleted file mode 100644 index a8789f00190..00000000000 --- a/changelog.d/keep-custom-contracts-with-removed-item.md +++ /dev/null @@ -1 +0,0 @@ -- **A skill you wrote whose contract still lists `check_after_last_edit` keeps the rest of its contract.** This corrects the entry in this release that says such a contract is now invalid and none of its items are checked. The optional Stop hook now skips only that item and keeps checking the skill's other items. Until you delete the item, the hook prints a `SKILL_CONTRACT_SKIPPED` line naming the file and the item. A contract whose only items use the removed kind is still invalid, so the hook checks nothing for that skill. diff --git a/changelog.d/land-normal-merge.md b/changelog.d/land-normal-merge.md deleted file mode 100644 index b76774f3abe..00000000000 --- a/changelog.d/land-normal-merge.md +++ /dev/null @@ -1 +0,0 @@ -- **The ship policy guide now explains how to merge any pull request with `gstack-ship-queue land`, even in a repository with one maintainer.** It names the two policy keys land needs before it will run, lists what land already checks, gives a pinned `gh pr merge` fallback for repositories that can't use land yet, and covers four common traps. CONTRIBUTING.md links to it. diff --git a/changelog.d/lanes-large-file-lists-on-linux.md b/changelog.d/lanes-large-file-lists-on-linux.md deleted file mode 100644 index 68f8401de9e..00000000000 --- a/changelog.d/lanes-large-file-lists-on-linux.md +++ /dev/null @@ -1 +0,0 @@ -- **/ship's test step runs a large unit suite on Linux.** A lane with thousands of unit files used to stop with `PREGATE: incomplete` and `E2BIG: argument list too long` before any test ran, because every file went into one command argument and Linux caps a single argument at 128 KiB. gstack now splits a big file list into runner processes of about 96 KB each, run one after another and counted as one run, so the result is the same as before: any failing chunk fails the lane. An `E2BIG` launch failure is now reported as its own cause (`arg-limit`) instead of telling you to install a missing tool. (#4424) diff --git a/changelog.d/never-print-secrets-shared-rule.md b/changelog.d/never-print-secrets-shared-rule.md deleted file mode 100644 index 0288caa4853..00000000000 --- a/changelog.d/never-print-secrets-shared-rule.md +++ /dev/null @@ -1 +0,0 @@ -- **Every skill that loads the shared preamble, on every host, now says never to print a whole environment, git config or process table.** The rule used to load only in the Capy wrapper, and its list missed `git config --list`, which can print a proxy's login header, process or container listings that show arguments or environment (`ps aux`, `ps -ef`, `ps -o args`, `docker top ... args`, `docker inspect`), where run tokens ride, and `set -x` or an `export $(...)` that expands to a bare `export`. A new Ground Rules section in the shared preamble lists these commands and the safe forms, which are to read one value by name (`git config --get <name>`), check a variable is set without printing it, and list processes by name or pid. It also says to wait on CI with one `gstack-pr-wait` call instead of a poll loop or `gh pr checks --watch`, which spends the shared GitHub GraphQL quota. The section is pinned, so no model loadout drops it. diff --git a/changelog.d/plain-pr-bodies.md b/changelog.d/plain-pr-bodies.md deleted file mode 100644 index a73331f9f50..00000000000 --- a/changelog.d/plain-pr-bodies.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -bump: minor ---- -- **Pull requests from /ship now open with at most three plain lines, and every merge lands as one commit titled with the PR title.** /ship writes `## ` sections and `gstack-post` folds each into a collapsed section when it posts, so a reader sees what changed, why, and what they have to do, with the rest one click away and the Agent notes section last. `gstack-post fold --body-file F` shows the folded body without posting it. In a repository with `.gstack/plain-titles.json`, `gstack-post` and the Plain title check refuse a body that shows more than three lines (or 600 characters) before its first fold, or uses a listed in-house word above the Agent notes section (`PLAIN_BODY_REFUSED`); gstack now ships a default word list (outside voice, pregate, receipt, carry, stamp, train, lane, soak and more), which a policy extends or replaces with `replace_default_terms`, and `body_since` keeps PRs opened before that date to warnings. Every `gstack-ship-queue land` form now passes the subject `<title> (#n)` and a body of the PR's opening lines plus the branch's `Co-authored-by:` and other trailers, so GitHub no longer writes its commit list; `--dry-run` prints it and `--body-file` replaces the opening. Release PRs list one plain line per change with its PR. Two new policy settings: `history: no-rewrite` (squash landings, never a rebased or force-pushed branch) and `land.merge_commit_paths` (keep a merge commit for PRs that change those paths, such as eval results). See docs/writing-prs.md. diff --git a/changelog.d/pr-wait-and-ci-gate-read-every-check-attempt.md b/changelog.d/pr-wait-and-ci-gate-read-every-check-attempt.md deleted file mode 100644 index 1cdff6feae7..00000000000 --- a/changelog.d/pr-wait-and-ci-gate-read-every-check-attempt.md +++ /dev/null @@ -1 +0,0 @@ -- **`gstack-pr-wait`, `gstack-ci-gate` and the release cut no longer call a commit green while a check on it failed.** They read CI from GitHub's rollup or its default check-runs list, which hold only each check suite's latest attempt, so when a rerun attempt created no jobs the failed run before it disappeared, and a workflow run that failed before creating any job never appeared at all. That is the false green the merge queue had on gstack-evals#303 (#4235). All three now also read CI at the commit through the merge queue's own helper, which reads every attempt and every workflow run, and keep the worse answer per check. So `gstack-pr-wait --until green` blocks with `check failed: checks` and `check failed: sealed (run <id>, no jobs)`, the land gate says `VERDICT FAIL`, and the release cut skips the commit. The release cut now also counts a failed commit status as red, as the merge queue does. A rerun that passed still reads green, and an unreadable read is an error, never a pass (GST-2252). diff --git a/changelog.d/price-runaway-wakes.md b/changelog.d/price-runaway-wakes.md deleted file mode 100644 index d1df30a8566..00000000000 --- a/changelog.d/price-runaway-wakes.md +++ /dev/null @@ -1 +0,0 @@ -- **`gstack-runaway` now says what a thread's cold and empty wakes cost, not just how many there were (GST-2770).** Each wake it reads is marked cold when it started more than 5 minutes after the thread's last activity, so the prompt cache had lapsed, and is priced in warm model calls, with a cold call at 19.4 (measured on Opus 5.5: $2.42 against $0.125 per million counted tokens; a call after a tool that ran past 5 minutes is cold too). The RUNAWAY line adds `wakes`, `cold_wakes`, `empty_wakes`, `cold_extra_spend` and `empty_spend`, the empty-wake warning gives the empty wakes' share of spend, and `scan --wakes` prints one WAKE line per wake. A message sent to another thread now counts as action even when its state is "working", and more than 5 minutes idle inside a turn (not counting a tool's own run time) starts a new wake. On four coordinating threads over 4.7 days the meter's cold and empty shares came within 1.3 points of a hand count; before this, sends were counted as empty and the empty share read 4 to 12 points high. /runaway-stopper's fetch program now keeps each message's target and each call's run time. diff --git a/changelog.d/remove-test-after-edit-stop-hook-check.md b/changelog.d/remove-test-after-edit-stop-hook-check.md deleted file mode 100644 index 8fa40aaa7fc..00000000000 --- a/changelog.d/remove-test-after-edit-stop-hook-check.md +++ /dev/null @@ -1 +0,0 @@ -- **The optional Stop hook no longer checks for a test run after the last edit, and /verify asks for it in plain words instead.** With /verify loaded, Opus 5.5 and GPT-6.1 Sol already ran a test after their last edit in 96% and 89% of runs, and the hook's check added between -0.5 and +2 points, inside the noise on both models. The hook's other checks (report labels, specialist dispatches, the adversarial pass) are unchanged. If you wrote your own skill whose contract lists `check_after_last_edit`, that contract is now invalid. The hook then checks none of that skill's items and prints one line naming the file until you delete the item. /verify now says to run the full check after your last edit. It also no longer says it never edits CHANGELOG, because a changelog entry the repo expects with a change is part of the change; /ship still folds branch entries into the release entry. diff --git a/changelog.d/ship-step-time-limit-and-remote-file-lists.md b/changelog.d/ship-step-time-limit-and-remote-file-lists.md deleted file mode 100644 index 243013fcbe4..00000000000 --- a/changelog.d/ship-step-time-limit-and-remote-file-lists.md +++ /dev/null @@ -1,2 +0,0 @@ -- **/ship's test step says when it ran out of time, and you can set its budget.** `gstack-ship-preflight` used to stop gstack-pregate after a fixed hour and print `PREGATE: unreadable (exit 143)`, which hid the cause. The whole step's budget is now `--step-timeout <s>` (default 3600 s), and a stop at that limit prints `PREGATE: time limit hit` with the way out: push and let CI's full run carry the tests, or give the step a larger budget. -- **The remote test command no longer puts every file on one command line.** On a small machine with a remote `test_backend`, the command pregate prints for gstack's Ubicloud runner used to carry every selected test file in one argument, which Linux refuses past 128 KiB (`E2BIG`). The files now go to the VM in a setup script, so the command stays short however many files are selected. docs/troubleshooting.md has a new `arg-limit` entry for this kind of failure. diff --git a/changelog.d/stable-cut-ignores-windows-nightly.md b/changelog.d/stable-cut-ignores-windows-nightly.md deleted file mode 100644 index e932e4ee0fa..00000000000 --- a/changelog.d/stable-cut-ignores-windows-nightly.md +++ /dev/null @@ -1 +0,0 @@ -- **The stable release no longer waits on the nightly Windows tests (GST-2815).** The nightly Windows free suite never blocks a pull request, but the daily stable cut still treated its red or unfinished results as a reason to skip a commit, so stable stopped moving while one Windows shard kept timing out. The cut now sets that workflow's check runs aside, matched by workflow file, the same way it ignores its own job. Every other check, the required `free-tests` check and the release-gate evidence still block exactly as before. diff --git a/changelog.d/ubicloud-quota-booking-full-owner.md b/changelog.d/ubicloud-quota-booking-full-owner.md deleted file mode 100644 index c38a1128652..00000000000 --- a/changelog.d/ubicloud-quota-booking-full-owner.md +++ /dev/null @@ -1 +0,0 @@ -- **Ubicloud fan-outs can no longer overshoot the vCPU limit, and owners no longer delete each other's VMs.** `ubi-runner.sh up` now reads the project's vCPU usage and books its new VM under one lock per machine, so shards started together see each other's bookings instead of all passing on the same reading. A new `ubi-runner.sh room [-s SIZE]` command prints how many more VMs fit now, so a fan-out can size each batch to the room left. When usage can't be read and `UBI_QUOTA_VCPUS` is set, the create is refused (`UBI_QUOTA_UNREADABLE`) instead of going ahead. VM names now carry the whole owner id (up to 31 characters; longer is refused with `UBI_OWNER_TOO_LONG`) instead of its first 12, so two owners sharing a prefix no longer reap each other's expired VMs (#3748); a VM an older runner copy named under the old cut form is still reaped by the long owner on the machine whose VM record lists it, and `recover` accepts the longer owner ids. Merge checks and canaries set no `UBI_QUOTA_VCPUS` and behave as before. diff --git a/changelog.d/update-hono-security-advisories.md b/changelog.d/update-hono-security-advisories.md deleted file mode 100644 index a360fb10973..00000000000 --- a/changelog.d/update-hono-security-advisories.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -important: security ---- -**hono is pinned to 4.13.16, which fixes five advisories the weekly OSV scan found in 4.13.13 (gstack#4406).** The 2026-11-16 scan (run 43825448246) flagged GHSA-3gg2-335m-rxc6 (CVSS 3.4, the `css` helper) and GHSA-46wx-v44x-9hh2, GHSA-4h7h-rv7c-7m2v, GHSA-4m76-xfj5-7975 and GHSA-h7mg-cq63-vhpq (CVSS 5.3 each: `csrf()`, `validator('form')`, `mount()` and RegExpRouter wildcard middleware). hono reaches gstack only through the dev and test toolchain (`@anthropic-ai/claude-agent-sdk` pulls in `@modelcontextprotocol/sdk`), gstack's own code never imports it or starts a hono server, and none of the affected helpers is used, so no advisory was reachable. Contributor checkouts get the patched version on their next `bun install`. - -- **`package.json` overrides**: `hono` moves from 4.13.13 to 4.13.16, the release that fixes all five. `bun.lock` holds the one copy. -- `test/dependency-security.test.ts`: the lockfile floor check now covers `hono >= 4.13.16`. It fails on main. diff --git a/changelog.d/windows-nightly-fits-its-time-limit.md b/changelog.d/windows-nightly-fits-its-time-limit.md deleted file mode 100644 index d5409538366..00000000000 --- a/changelog.d/windows-nightly-fits-its-time-limit.md +++ /dev/null @@ -1 +0,0 @@ -- **The nightly Windows test run finishes again.** Since 2026-11-06 one of its six shards ran past the 15-minute job limit almost every night, because 95 newer test files had no recorded Windows duration and the planner packed them blind, so one shard got 26 minutes of work while another got 12. The Windows durations are refreshed to a recording that covers all 902 files, and the run now uses eight shards of about 12 minutes each, so the suite fits with room to grow. No test was dropped and the time limit is unchanged. diff --git a/changelog.d/write-up-checklist.md b/changelog.d/write-up-checklist.md deleted file mode 100644 index 230ebf5b039..00000000000 --- a/changelog.d/write-up-checklist.md +++ /dev/null @@ -1 +0,0 @@ -- **A short write-up checklist in ETHOS.md.** Explain the Number now ends with three checks before a post or write-up goes out: its words match the page it links, every number, "green" and "ready" names its source and is read at the current head, and a fresh model reads it cold once. The READY template in `captain/templates/READY.md` points to the second check. Anything carried over from an earlier head goes under `Unverified:` until it is re-read. diff --git a/package.json b/package.json index 306cd7ddae3..2bd4a94b6b1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gstack", - "version": "1.99.5", + "version": "1.100.0", "description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.", "license": "MIT", "type": "module", From b79843c5d7021c870dc31d7bd9c3eadbfdf95bf2 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 22:10:23 +0800 Subject: [PATCH 36/62] Keep a pull request's review count intact when a posted description brings its own run history (GST-2707) (#4440) When `/ship` posts a pull request's description, the count of earlier review rounds now always comes from the PR's real history. Before this fix, a description that brought extra history blocks of its own could make gstack count one round where there were three. Why: the per-PR round cap (R51) depends on that count, and it's the last gap before crews can stop counting rounds by hand. Nothing to do as a reader. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=red-team Review-Finding: p1/specialist-batched#2 reader=testing --- changelog.d/strip-incoming-receipt-runs.md | 1 + docs/review-policy.md | 4 ++- lib/gstack-post.ts | 27 ++++++++++++----- test/pr-review-history.test.ts | 35 ++++++++++++++++++++++ 4 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 changelog.d/strip-incoming-receipt-runs.md diff --git a/changelog.d/strip-incoming-receipt-runs.md b/changelog.d/strip-incoming-receipt-runs.md new file mode 100644 index 00000000000..05324cf8e76 --- /dev/null +++ b/changelog.d/strip-incoming-receipt-runs.md @@ -0,0 +1 @@ +- **A PR's review-round count can no longer be overwritten by the body `/ship` posts.** When `/ship` posted a PR body whose Agent notes held their own `gstack-receipt-runs` blocks, gstack removed only the first one, so a second block placed before the receipt became the history `gstack-ship-receipt history` counted (one round where there were three). A post now drops every runs block it brings and keeps exactly one. That one is the live body's history, placed right after the posted receipt, or none when the PR had no earlier runs. A post whose notes hold no receipt yet keeps the live started stubs in place of the runs block it brings. See docs/review-policy.md#rounds-per-pull-request. diff --git a/docs/review-policy.md b/docs/review-policy.md index 79ceb2c37d2..f38b993b115 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -159,7 +159,9 @@ caught on another crew's PRs. run still reviews its head in full; what's lost is the cap on earlier runs, so check the PR body by hand when that line shows. A `/ship` body post keeps the live `gstack-receipt-runs` block (`lib/gstack-post.ts`), so - earlier runs and started stubs stay countable. + earlier runs and started stubs stay countable. Any runs block the posted + body brings in its own Agent notes is dropped first, so only the live + history is counted. 2. **Runs that stop count too.** After each Step 9 pass, `gstack-ship-receipt stub --pr <n> --run <id> --review-loop <summary>` writes a `status: started` entry, so a run that stops before its receipt still counts. The run's receipt diff --git a/lib/gstack-post.ts b/lib/gstack-post.ts index 4259790410b..fd56b04da16 100644 --- a/lib/gstack-post.ts +++ b/lib/gstack-post.ts @@ -36,7 +36,7 @@ import { CI_RUN_WORD_BEFORE } from "./redact-patterns"; import { agentNotesLines, splitAgentNotes } from "./agent-notes"; import { checkTitle, loadPlainTitlePolicy, PLAIN_TITLE_POLICY_PATH, type PlainTitlePolicy } from "./plain-title"; import { bodyFindingLine, checkBodyShape, foldSections, unfoldSections } from "./pr-body-shape"; -import { RECEIPT_FENCE, RUNS_FENCE, extractReceipt, placeReceipt, renderReceiptBlock, validateReceipt } from "./ship-receipt"; +import { RECEIPT_FENCE, RUNS_FENCE, RUNS_RE, extractReceipt, placeReceipt, renderReceiptBlock, validateReceipt } from "./ship-receipt"; import type { ShipReceipt } from "./headless-artifacts"; import { canonicalRemote } from "./remote-identity"; import { parseChangelog } from "./changelog-check"; @@ -300,20 +300,33 @@ export function mergeBodySections(current: string, incoming: string): { body: st const RUNS_BLOCK_RE = new RegExp("^```" + RUNS_FENCE + "[ \\t]*\\r?\\n[\\s\\S]*?\\r?\\n```[ \\t]*(?:\\r?\\n|$)", "m"); +/** Every runs block the history reader (lib/ship-receipt.ts receiptRuns) would recognize, not only one at a line start. */ +const READER_RUNS_RE = new RegExp(RUNS_RE.source, "g"); + /** - * A /ship body post (an Agent notes section holding a receipt) keeps the live body's run history (GST-2706): the merge - * replaces the notes, so the runs block placeReceipt would write on the live body (earlier runs, started stubs and the - * replaced receipt) goes back right after the posted receipt, and gstack-ship-receipt history still counts every run. + * A post that brings its own Agent notes section keeps the live body's run history and none of the file's (GST-2706, + * GST-2707): the merge replaces the notes, so every runs block the file's notes hold is removed, since the history + * reader takes the first one it finds, and a block placed before the receipt would stand in for the real history. The + * runs block placeReceipt would write on the live body (earlier runs, started stubs and the replaced receipt) then goes + * back, once, right after the posted receipt; with no live history there is none, and gstack-ship-receipt history + * counts the posted receipt alone. Notes with no receipt (a body between a Step 9 stub and the receipt write) get the + * live body's runs block in place of the first block they bring, so their stubs are kept and never replaced. */ function keepRuns(current: string, next: Section[], m: ReturnType<typeof mergeSplit>): ReturnType<typeof mergeSplit> { + if (!next.some(n => n.key === NOTES_KEY)) return m; const posted = next.some(n => n.key === NOTES_KEY && extractReceipt(n.text).found) ? extractReceipt(m.body).receipt : undefined; const notesAt = (body: string) => splitAgentNotes(body).notes === null ? 0 : splitAgentNotes(body).readable.length; const placed = posted ? placeReceipt(current, posted) : ""; const runs = RUNS_BLOCK_RE.exec(placed.slice(notesAt(placed)))?.[0]; const at = notesAt(m.body); - const notes = m.body.slice(at).replace(RUNS_BLOCK_RE, ""); - const end = runs && /```gstack-ship-receipt[ \t]*\r?\n[\s\S]*?\r?\n```[ \t]*(?:\r?\n|$)/.exec(notes); - return end ? { ...m, body: m.body.slice(0, at) + notes.slice(0, end.index + end[0].length) + "\n" + runs + notes.slice(end.index + end[0].length) } : m; + if (!posted) { + const live = RUNS_RE.exec(current.slice(notesAt(current)))?.[0] ?? ""; + let first = true; + return { ...m, body: m.body.slice(0, at) + m.body.slice(at).replace(READER_RUNS_RE, () => first ? (first = false, live) : "") }; + } + const notes = m.body.slice(at).replace(READER_RUNS_RE, ""); + const end = runs ? /```gstack-ship-receipt[ \t]*\r?\n[\s\S]*?\r?\n```[ \t]*(?:\r?\n|$)/.exec(notes) : null; + return { ...m, body: m.body.slice(0, at) + (end ? notes.slice(0, end.index + end[0].length) + "\n" + runs + notes.slice(end.index + end[0].length) : notes) }; } function mergeSplit(now: Section[], next: Section[], incoming: string): { body: string; replaced: string[]; kept: string[]; added: string[]; dropped: string[] } { diff --git a/test/pr-review-history.test.ts b/test/pr-review-history.test.ts index 7035d75bffe..3f5e839182e 100644 --- a/test/pr-review-history.test.ts +++ b/test/pr-review-history.test.ts @@ -85,6 +85,41 @@ describe('prReviewHistory', () => { expect(prReviewHistory(mergeBodySections(posted, composed).body)).toEqual(prReviewHistory(posted)); }); + // Value: protects=the PR's review count from a posted body whose notes carry their own runs blocks: the reader takes the + // first block it finds, so one placed before the receipt would replace the real history (Sol audit of #4365, GST-2707); + // fails_when=keepRuns removes only the first incoming block, or returns the file's history when the live body has none; + // seam=none (mergeBodySections); no_claim=the gh round trip + test('a /ship body post drops every runs block it brings and keeps only the live history (GST-2707)', () => { + const fake = (c: string) => '```gstack-receipt-runs\n' + JSON.stringify({ head: sha(c), run: `fake-${c}`, review_loop: loop({ passes: 0, rounds: 0 }) }) + '\n```\n'; + const composed = placeReceipt('## Summary\nnew prose\n', receipt(sha('c'), { passes: 1, rounds: 1 }, { run: 'r2' })); + const injected = composed.replace('```gstack-ship-receipt', fake('d') + '\n' + fake('e') + '\n```gstack-ship-receipt'); + expect(receiptRuns(injected).map(r => r.run)).toEqual(['fake-d']); + let live = placeReceipt('## Summary\nprose\n', receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' })); + live = placeRunEntry(live, { head: sha('b'), run: 'r3', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); + const posted = mergeBodySections(live, injected).body; + expect(prReviewHistory(posted)).toMatchObject({ full: 3, runs: 2, stubs: 1, last_full: sha('c') }); + expect(receiptRuns(posted).map(r => r.run)).toEqual(['r3', 'r1']); + expect(posted.match(/```gstack-receipt-runs/g)).toHaveLength(1); + expect(prReviewHistory(mergeBodySections(posted, injected).body)).toEqual(prReviewHistory(posted)); + const fresh = mergeBodySections('## Summary\nprose\n', injected).body; + expect(fresh).not.toContain('gstack-receipt-runs'); + expect(prReviewHistory(fresh)).toMatchObject({ full: 1, runs: 1, stubs: 0 }); + }); + + // Value: protects=a PR's started stubs when a post's Agent notes carry no receipt yet (the body between a Step 9 stub and + // the receipt write); fails_when=keepRuns drops the live runs block, or lets a block the file brings stand in for it; + // seam=none (mergeBodySections); no_claim=the gh round trip + test('a post whose notes hold no receipt keeps the live stubs and none of its own runs blocks (GST-2707)', () => { + const live = placeRunEntry('## Summary\nprose\n', { head: sha('b'), run: 'r3', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); + expect(mergeBodySections(live, live).body).toBe(live); + const fake = '```gstack-receipt-runs\n' + JSON.stringify({ head: sha('d'), run: 'fake-d', review_loop: loop({ passes: 0, rounds: 0 }) }) + '\n```\n'; + const injected = live.replace('```gstack-receipt-runs', fake + '\n```gstack-receipt-runs'); + expect(receiptRuns(injected).map(r => r.run)).toEqual(['fake-d']); + const posted = mergeBodySections(live, injected).body; + expect(receiptRuns(posted).map(r => r.run)).toEqual(['r3']); + expect(prReviewHistory(posted)).toEqual(prReviewHistory(live)); + }); + test('a stub lands in a body with no receipt yet, inside the Agent notes section', () => { const body = placeRunEntry('## Summary\nprose\n', { head: sha('a'), run: 'r1', status: 'started', review_loop: loop({ passes: 1, rounds: 1 }) }); expect(body.startsWith('## Summary\nprose\n')).toBe(true); From f000b6e0e32a7f4ec968bd607a6c9dbb23cef68f Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 22:37:34 +0800 Subject: [PATCH 37/62] Stop giving bug reports a special rule in gstack's router (GST-2873) (#4442) gstack's router no longer gives bug reports a special check-the-cause, fix-it-test-first rule, and its description no longer lists debugging, so the model fixes a bug the way it would without gstack. This keeps gstack to the parts that measurably help, and on 26 hard real bugs the rule gave no clear gain. Nothing to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team --- SKILL.md | 8 +- SKILL.md.tmpl | 8 +- changelog.d/remove-router-bug-fix-route.md | 1 + docs/TESTING_INTERNALS.md | 27 ++-- docs/skills.md | 2 +- gstack/llms.txt | 2 +- lib/harness-register.ts | 2 +- scripts/free-test-durations-windows.json | 1 - scripts/free-test-durations.json | 1 - .../preamble/generate-test-failure-triage.ts | 7 -- test/codex-host.test.ts | 4 +- test/eng-finding-retry-budget.test.ts | 2 +- test/failure-routing-arm.test.ts | 102 ---------------- test/harness-register.test.ts | 2 +- test/helpers/e2e-hosts.ts | 3 +- test/helpers/failure-routing-fixture.ts | 115 ------------------ test/helpers/touchfiles-data.ts | 6 - test/skill-e2e-failure-routing.test.ts | 79 ------------ test/skill-validation.test.ts | 21 +--- 19 files changed, 25 insertions(+), 368 deletions(-) create mode 100644 changelog.d/remove-router-bug-fix-route.md delete mode 100644 test/failure-routing-arm.test.ts delete mode 100644 test/helpers/failure-routing-fixture.ts delete mode 100644 test/skill-e2e-failure-routing.test.ts diff --git a/SKILL.md b/SKILL.md index 8f2d4aa713e..f35707eb35b 100644 --- a/SKILL.md +++ b/SKILL.md @@ -2,7 +2,7 @@ name: gstack preamble-tier: 1 version: 1.2.0 -description: "Picks the gstack skill that fits a request: planning, review, QA, shipping, debugging, docs, security or design. Use for: gstack, which gstack skill, route this with gstack. (gstack)" +description: "Picks the gstack skill that fits a request: planning, review, QA, shipping, docs, security or design. Use for: gstack, which gstack skill, route this with gstack. (gstack)" allowed-tools: - Bash - Read @@ -206,7 +206,6 @@ quality gates that produce better results than answering inline. - User asks to review design of a plan → invoke `/plan-design-review` - User asks about developer experience of a plan, API/CLI/SDK design → invoke `/plan-devex-review` - User wants all reviews done automatically, "review everything" → invoke `/autoplan` -- User reports a bug, error, failing test or broken behavior, "why is this broken", "this doesn't work", "wtf", "something's wrong" → check the cause by **Failures** below, then fix it test-first - User asks to test the site, find bugs, QA, "does this work", "check the deploy" → invoke `/qa` - User asks to just report bugs without fixing → invoke `/qa-only` - User asks to review code, check the diff, pre-landing review, "look at my changes" → invoke `/review` @@ -267,11 +266,6 @@ Generic “second opinion”, “outside review”, or “cross-model review” - Voice trigger "quality check", "test the app", "run QA" → invoke `/qa` - Voice trigger "bug report", "just check for bugs" → invoke `/qa-only` -**Failures: check the cause, then fix it test-first.** A failing test, error or stack trace shows where a failure surfaces, not its root cause. - -- **Cause supplied** (the user names a specific cause and a narrow fix): make one read-only check of the evidence it rests on, such as the named file, test or log. If that confirms the cause, make the fix and run the focused test that covers it. If it does not, leave the suggested fix alone: reproduce the failure with a focused failing test, trace it to the root cause, fix that and rerun the test. -- **Cause unknown:** make one read-only triage pass over the supplied evidence and the directly implicated test and code. Do not reproduce, test hypotheses or search wider. If that pass establishes the root cause and a narrow fix, make the fix and run the focused test that covers it. If the cause or scope is still unclear, write or run a focused test that fails on the bug before any edit, trace the failure to its root cause, fix that and rerun the test. If the intended behavior is unclear, ask the user. - **Route only to skills in your available-skills list.** A rule above whose skill is not listed there is turned off on this install; skip it, never try to invoke it. diff --git a/SKILL.md.tmpl b/SKILL.md.tmpl index 745251a6e36..e4115f016ab 100644 --- a/SKILL.md.tmpl +++ b/SKILL.md.tmpl @@ -4,7 +4,7 @@ preamble-tier: 1 version: 1.2.0 description: | Picks the gstack skill that fits a request: planning, review, QA, shipping, - debugging, docs, security or design. Routes QA by + docs, security or design. Routes QA by intent and browser interaction to /browse. Use when you invoke gstack without a specific skill, or ask "which gstack skill fits this?". (gstack) allowed-tools: @@ -75,7 +75,6 @@ quality gates that produce better results than answering inline. - User asks to review design of a plan → invoke `/plan-design-review` - User asks about developer experience of a plan, API/CLI/SDK design → invoke `/plan-devex-review` - User wants all reviews done automatically, "review everything" → invoke `/autoplan` -- User reports a bug, error, failing test or broken behavior, "why is this broken", "this doesn't work", "wtf", "something's wrong" → check the cause by **Failures** below, then fix it test-first - User asks to test the site, find bugs, QA, "does this work", "check the deploy" → invoke `/qa` - User asks to just report bugs without fixing → invoke `/qa-only` - User asks to review code, check the diff, pre-landing review, "look at my changes" → invoke `/review` @@ -115,11 +114,6 @@ quality gates that produce better results than answering inline. - User asks to tune question sensitivity, "stop asking me that" → invoke `/plan-tune` - User asks for code quality dashboard, "health check" → invoke `/health`{{VOICE_TRIGGER_ROUTING}} -**Failures: check the cause, then fix it test-first.** A failing test, error or stack trace shows where a failure surfaces, not its root cause. - -- **Cause supplied** (the user names a specific cause and a narrow fix): make one read-only check of the evidence it rests on, such as the named file, test or log. If that confirms the cause, make the fix and run the focused test that covers it. If it does not, leave the suggested fix alone: reproduce the failure with a focused failing test, trace it to the root cause, fix that and rerun the test. -- **Cause unknown:** make one read-only triage pass over the supplied evidence and the directly implicated test and code. Do not reproduce, test hypotheses or search wider. If that pass establishes the root cause and a narrow fix, make the fix and run the focused test that covers it. If the cause or scope is still unclear, write or run a focused test that fails on the bug before any edit, trace the failure to its root cause, fix that and rerun the test. If the intended behavior is unclear, ask the user. - **Route only to skills in your available-skills list.** A rule above whose skill is not listed there is turned off on this install; skip it, never try to invoke it. diff --git a/changelog.d/remove-router-bug-fix-route.md b/changelog.d/remove-router-bug-fix-route.md new file mode 100644 index 00000000000..148547c8c75 --- /dev/null +++ b/changelog.d/remove-router-bug-fix-route.md @@ -0,0 +1 @@ +- **gstack's router no longer gives bug reports a special rule, so the model fixes a bug the way it would without gstack.** The rule said to check the cause once and write a failing test first when the cause was unclear. On 26 real gbrain bugs that plain Opus 5.5 had failed once, gstack with the rule fixed 3 and plain Opus fixed 2: +3.8 points, with a 95% interval of -11.5 to +19.2, so no clear gain. The router's description no longer lists debugging either, so a bug report doesn't load it. Planning, review, /verify, /qa and /ship are unchanged, and the bug line gstack offers for your CLAUDE.md is unchanged too. The two paid evals of the removed rule are retired with it. diff --git a/docs/TESTING_INTERNALS.md b/docs/TESTING_INTERNALS.md index 806b6640e62..317cfd7fda1 100644 --- a/docs/TESTING_INTERNALS.md +++ b/docs/TESTING_INTERNALS.md @@ -2012,25 +2012,19 @@ appears only when it is part of the lesson, and datasets or tools are opened only with a stated reason. The rules and their honesty bars are in [ETHOS.md, Explain the Number](../ETHOS.md#8-explain-the-number). -**Safety-rule and router evals: a descriptive third arm.** The W1 safety-rule +**Safety-rule evals: a descriptive third arm.** The W1 safety-rule evals compare `GSTACK_SAFETY_ARM=rule` (the shipped rule) with `removed` (the -rule paragraph deleted), and the router failure-routing evals compare -`GSTACK_ROUTER_ARM=current` with `before` (the base branch's router). Both -variables also take `none` (GST-470): the same fixture, tools and user request, -with no skill excerpt, rule text, step file or installed skill. Any other value -throws, so a typo cannot run one arm under another's label. The `rule`, -`removed`, `current` and `before` prompts are byte for byte what they were -before `none` existed (`test/safety-none-arm.test.ts`, -`test/failure-routing-arm.test.ts`). To run the three arms as a comparison, run -the same case once per arm, each as its CI panel: +rule paragraph deleted). The variable also takes `none` (GST-470): the same +fixture, tools and user request, with no skill excerpt, rule text, step file or +installed skill. Any other value throws, so a typo cannot run one arm under +another's label. The `rule` and `removed` prompts are byte for byte what they +were before `none` existed (`test/safety-none-arm.test.ts`). To run the three +arms as a comparison, run the same case once per arm, each as its CI panel: ```bash for arm in rule removed none; do GSTACK_SAFETY_ARM=$arm bun run scripts/test-paid-shards.ts --tier gate --case safety-ship-stale-evidence done -for arm in current before none; do - GSTACK_ROUTER_ARM=$arm bun run scripts/test-paid-shards.ts --tier gate --case router-failure-verified-cause -done ``` The arm variable is part of the shard-reuse environment, so one arm's result is @@ -2046,11 +2040,8 @@ ran, the session ended normally) still assert. This departs from "the same panel" above because these contracts are gstack's own rules: a plain model was never asked to keep them, so a failing `none` trial is the measurement, not a regression, and a red verdict would block the gate on behavior nobody -specified. The router's `none` arm has no repro-first metric, -since it never sees the router's rules; it records plain metrics instead: -whether the suite is green, whether an edit came before the first read, and -how many read-only calls came before the first edit. The first paid comparison -with these arms gets its own preregistration. +specified. The first paid comparison with these arms gets its own +preregistration. **Cases without a `none` arm.** `safety-pair-agent-block` and `safety-ios-demo-ui-only` refuse `GSTACK_SAFETY_ARM=none` with the reason diff --git a/docs/skills.md b/docs/skills.md index 468f6cfcdd9..dd53ccf96c8 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -660,7 +660,7 @@ I want the model imagining the production incident before it happens. `/investigate` was cut on 2026-11-07 (GST-1717) after a preregistered eval found no gain. On 18 real bug-fix tasks that plain Opus 5.5 solves about half the time, 20 trials each, Opus told to use /investigate passed 50.0% of trials against 47.2% with no skill: +2.8 points (95% CI -5.8 to +11.4), below the 10-point lift the run could detect. A passing fix cost about 43% more with the skill. The evidence is GEVA-380's R3c result, [gstack-evals c90ab277, wiki/board/2026-11-07-geva-380-r3c-results.md](https://github.com/garrytan/gstack-evals/blob/c90ab277/wiki/board/2026-11-07-geva-380-r3c-results.md). -The skill no longer installs, and `./setup` removes an existing gstack-owned `investigate` / `gstack-investigate` entry on every host, along with the opt-in /investigate gate's hooks. For a bug, fix it directly: check the cause once, and when it is still unclear, write a focused test that fails on the bug before any edit, then fix the root cause and rerun the test. `/verify` runs the repo's checks while you build, and `/qa` tests a running site, API or CLI and fixes what it finds. +The skill no longer installs, and `./setup` removes an existing gstack-owned `investigate` / `gstack-investigate` entry on every host, along with the opt-in /investigate gate's hooks. For a bug, just ask the model to fix it. gstack's router also stopped giving bug reports a fix-it-test-first rule on 2026-11-17 (GST-2873), because a test on 26 hard real bugs found no clear gain from it: +3.8 points, with a 95% interval of -11.5 to +19.2. The optional routing block gstack offers for your CLAUDE.md still has its own bugs line (check the cause once, or write a failing test first when it is unclear); this change leaves it as it is. `/verify` runs the repo's checks while you build, and `/qa` tests a running site, API or CLI and fixes what it finds. --- diff --git a/gstack/llms.txt b/gstack/llms.txt index c85ccfbbb81..515f2c3b824 100644 --- a/gstack/llms.txt +++ b/gstack/llms.txt @@ -33,7 +33,7 @@ Conventions: - [/document-release](document-release/SKILL.md): Release documentation audit. - [/eval-plan](eval-plan/SKILL.md): Preregister a paid eval (bars, arms, decoys, stop rules), dry-run it at zero cost, then run a three-item priced pilot whose spend table gates approval. - [/freeze](freeze/SKILL.md): Restrict file edits to a specific directory for the session. -- [/gstack](SKILL.md): Picks the gstack skill that fits a request: planning, review, QA, shipping, debugging, docs, security or design. +- [/gstack](SKILL.md): Picks the gstack skill that fits a request: planning, review, QA, shipping, docs, security or design. - [/gstack-upgrade](gstack-upgrade/SKILL.md): Upgrade gstack to the latest version. - [/guard](guard/SKILL.md): Full safety mode: destructive command warnings + directory-scoped edits. - [/health](health/SKILL.md): Code quality dashboard. diff --git a/lib/harness-register.ts b/lib/harness-register.ts index 22ff1d09383..8016909ab5d 100644 --- a/lib/harness-register.ts +++ b/lib/harness-register.ts @@ -36,7 +36,7 @@ export const BLOCK_BEGIN = '<!-- gstack:begin harness-routing -->'; export const BLOCK_END = '<!-- gstack:end harness-routing -->'; /** Where a Dot keeps its own skills (feder-cr/dots nanobot/dots/skills.py DOT_SKILLS_DIR). */ export const DOT_SKILLS_DIR = '/home/dot/skills'; -export const ROUTER_DESCRIPTION = 'Use to review a diff or PR, debug a bug or failing test, QA test a site, plan or review architecture, ship a PR, audit security or write release docs. Load first for any coding task: lists every gstack skill and where to read it.'; +export const ROUTER_DESCRIPTION = 'Use to review a diff or PR, QA test a site, plan or review architecture, ship a PR, audit security or write release docs. Load first for any coding task: lists every gstack skill and where to read it.'; /** OpenClaw hybrid mode: these task skills are listed as skills of their own; the router carries the rest. */ export const HYBRID_SKILLS = ['review', 'qa', 'ship', 'plan-eng-review']; /** diff --git a/scripts/free-test-durations-windows.json b/scripts/free-test-durations-windows.json index 07cb2fde996..2ee89cd3cd5 100644 --- a/scripts/free-test-durations-windows.json +++ b/scripts/free-test-durations-windows.json @@ -439,7 +439,6 @@ "test/exit-propagation.test.ts": 489, "test/extension-pty-inject-invariant.test.ts": 52, "test/external-host-carve.test.ts": 7522, - "test/failure-routing-arm.test.ts": 2290, "test/flake-ledger.test.ts": 127, "test/free-home-guard.test.ts": 71, "test/free-seed-ratchet.test.ts": 550, diff --git a/scripts/free-test-durations.json b/scripts/free-test-durations.json index 9c66ddc4604..120d563c021 100644 --- a/scripts/free-test-durations.json +++ b/scripts/free-test-durations.json @@ -704,7 +704,6 @@ "test/extension-pty-inject-invariant.test.ts": 15, "test/external-host-carve.test.ts": 2750, "test/factory-scorecard.test.ts": 369, - "test/failure-routing-arm.test.ts": 217, "test/flake-ledger.test.ts": 30, "test/flaky-run.test.ts": 688, "test/founder-resources-optout.test.ts": 190, diff --git a/scripts/resolvers/preamble/generate-test-failure-triage.ts b/scripts/resolvers/preamble/generate-test-failure-triage.ts index 9db6f7d137e..1047becb074 100644 --- a/scripts/resolvers/preamble/generate-test-failure-triage.ts +++ b/scripts/resolvers/preamble/generate-test-failure-triage.ts @@ -1,13 +1,6 @@ import { FREE_TEXT_WRITE_RULE, freeTextFileBash, freeTextFileUse } from '../free-text-file'; -export function generateFailureRouting(): string { - return `**Failures: check the cause, then fix it test-first.** A failing test, error or stack trace shows where a failure surfaces, not its root cause. - -- **Cause supplied** (the user names a specific cause and a narrow fix): make one read-only check of the evidence it rests on, such as the named file, test or log. If that confirms the cause, make the fix and run the focused test that covers it. If it does not, leave the suggested fix alone: reproduce the failure with a focused failing test, trace it to the root cause, fix that and rerun the test. -- **Cause unknown:** make one read-only triage pass over the supplied evidence and the directly implicated test and code. Do not reproduce, test hypotheses or search wider. If that pass establishes the root cause and a narrow fix, make the fix and run the focused test that covers it. If the cause or scope is still unclear, write or run a focused test that fails on the bug before any edit, trace the failure to its root cause, fix that and rerun the test. If the intended behavior is unclear, ask the user.`; -} - export function generateTestFailureTriage(): string { return `## Test Failure Ownership Triage diff --git a/test/codex-host.test.ts b/test/codex-host.test.ts index 0976a72e6ee..b1ab0b89d0e 100644 --- a/test/codex-host.test.ts +++ b/test/codex-host.test.ts @@ -128,13 +128,13 @@ describe('per-case host metadata', () => { for (const id of Object.keys(E2E_HOSTS)) expect(Object.hasOwn(E2E_TOUCHFILES, id), id).toBe(true); }); - test('classifies 52 adapter-only, 29 Claude-specific, 26 rework and 1 host-neutral case', () => { + test('classifies 52 adapter-only, 27 Claude-specific, 26 rework and 1 host-neutral case', () => { const counts: Record<string, number> = {}; for (const support of Object.values(E2E_HOSTS)) counts[support] = (counts[support] ?? 0) + 1; expect(counts.both).toBe(52); expect(counts.rework).toBe(26); expect(counts['host-neutral']).toBe(1); - expect(['pty', 'sdk', 'subagents', 'skill-tool', 'hermetic', 'self-host'].reduce((sum, reason) => sum + (counts[reason] ?? 0), 0)).toBe(29); + expect(['pty', 'sdk', 'subagents', 'skill-tool', 'hermetic', 'self-host'].reduce((sum, reason) => sum + (counts[reason] ?? 0), 0)).toBe(27); }); }); diff --git a/test/eng-finding-retry-budget.test.ts b/test/eng-finding-retry-budget.test.ts index 774fd19418f..521e9fc4964 100644 --- a/test/eng-finding-retry-budget.test.ts +++ b/test/eng-finding-retry-budget.test.ts @@ -142,7 +142,7 @@ test('live periodic census fits the declared CI wall including setup', () => { test('registered allocation is deterministic and preserves every discovered file', () => { const files = collectPaidTestFiles(); - expect(files).toHaveLength(108); // - skill-e2e-investigate-owned-completion, -owned-termination and codex-e2e-sol-scope (/investigate retired, GST-1717); - skill-e2e-plan-eng-plan-mode, -plan-eng-finding-floor and -plan-eng-artifact-full (standalone /plan-eng-review retired, GST-1698); - skill-llm-eval (last standalone judges removed, GST-1403); + skill-e2e-autoplan-ceo-only (GST-537); + skill-e2e-planning-wave (GSTA-228); + skill-e2e-model-panel (GSTA-173); + skill-e2e-write-skill (GSTA-133); + skill-e2e-ship-frozen-scope (frozen review scope, GSTA-113 PR 2); + skill-e2e-failure-routing (#3157/#3158); + skill-e2e-dx-error-contract (#3226); + skill-e2e-gate-integrity (HONEST_WORK_GATE_INTEGRITY W8); + skill-e2e-autoplan-schema-canary, -guard-pty and -long-session (Oct 7 wave, CEO-13, ENG-18, CEO-15); + skill-e2e-ship-measure-seeded-flake (v1.91.32.0); W5a: 15 carve wrappers became one case-sharded file; + codex-e2e-multiblock-live and skill-e2e-design-model-smoke (v1.91.30.0); + expect(files).toHaveLength(107); // - skill-e2e-failure-routing (router bug-fix route removed, GST-2873); - skill-e2e-investigate-owned-completion, -owned-termination and codex-e2e-sol-scope (/investigate retired, GST-1717); - skill-e2e-plan-eng-plan-mode, -plan-eng-finding-floor and -plan-eng-artifact-full (standalone /plan-eng-review retired, GST-1698); - skill-llm-eval (last standalone judges removed, GST-1403); + skill-e2e-autoplan-ceo-only (GST-537); + skill-e2e-planning-wave (GSTA-228); + skill-e2e-model-panel (GSTA-173); + skill-e2e-write-skill (GSTA-133); + skill-e2e-ship-frozen-scope (frozen review scope, GSTA-113 PR 2); + skill-e2e-failure-routing (#3157/#3158); + skill-e2e-dx-error-contract (#3226); + skill-e2e-gate-integrity (HONEST_WORK_GATE_INTEGRITY W8); + skill-e2e-autoplan-schema-canary, -guard-pty and -long-session (Oct 7 wave, CEO-13, ENG-18, CEO-15); + skill-e2e-ship-measure-seeded-flake (v1.91.32.0); W5a: 15 carve wrappers became one case-sharded file; + codex-e2e-multiblock-live and skill-e2e-design-model-smoke (v1.91.30.0); expect(files).toContain('test/skill-e2e-ship-skip.test.ts'); const m = livePlan(files); expect(livePlan([...files].reverse())).toEqual(m); diff --git a/test/failure-routing-arm.test.ts b/test/failure-routing-arm.test.ts deleted file mode 100644 index 9d72401693c..00000000000 --- a/test/failure-routing-arm.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * GST-470: the router failure-routing eval's arms. GSTACK_ROUTER_ARM is - * current (the default), before or none, and anything else throws. The none arm - * builds a repository with no installed skills and a prompt that is the user's - * request alone. The current and before arms' prompts and repositories are byte - * for byte what main built (the reference copies below, from - * test/skill-e2e-failure-routing.test.ts at 0cd2b4a). - */ -import { afterAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { FIXTURES, makeRepo, plainMetrics, routerArm, routerPrompt, type Fixture } from './helpers/failure-routing-fixture'; -import { extractSkillHead, sliceBetween } from './helpers/skill-fixture'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const BASE = 'HEAD'; -const dirs: string[] = []; -afterAll(() => { for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true }); }); - -function mainRouterSection(arm: 'before' | 'current'): string { - const skill = arm === 'before' - ? spawnSync('git', ['show', `${BASE}:SKILL.md`], { cwd: ROOT, encoding: 'utf8', timeout: 10_000 }).stdout - : fs.readFileSync(path.join(ROOT, 'SKILL.md'), 'utf8'); - return sliceBetween(skill, '## Route first', 'Best-effort, record') + sliceBetween(skill, '**Routing rules', 'If the user opts out'); -} - -function mainPrompt(fixture: Fixture, arm: 'before' | 'current'): string { - return `The user invoked the gstack router skill (/gstack) in this repository. The router's instructions:\n\n${mainRouterSection(arm)}\n\nThe user's request: "${fixture.request}"`; -} - -function mainMakeRepo(fixture: Fixture): string { - const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'failure-routing-')); - fs.writeFileSync(path.join(repo, 'package.json'), JSON.stringify({ name: 'fixture', type: 'module', scripts: { test: 'bun test' } }, null, 2)); - for (const [file, body] of Object.entries(fixture.files)) { - fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true }); - fs.writeFileSync(path.join(repo, file), body); - } - for (const skill of ['qa', 'review', 'ship']) { - fs.mkdirSync(path.join(repo, '.claude', 'skills', skill), { recursive: true }); - fs.writeFileSync(path.join(repo, '.claude', 'skills', skill, 'SKILL.md'), extractSkillHead(path.join(ROOT, skill, 'SKILL.md'))); - } - const git = (...args: string[]) => spawnSync('git', ['-c', 'user.email=test@example.invalid', '-c', 'user.name=Test', ...args], { cwd: repo, timeout: 10_000 }); - git('init', '-q', '-b', 'main'); - git('add', '.'); - git('commit', '-qm', 'initial'); - return repo; -} - -/** Every file under dir except .git, path → contents, plus the committed file list. */ -function tree(dir: string): { files: Record<string, string>; committed: string } { - dirs.push(dir); - const files: Record<string, string> = {}; - for (const rel of fs.readdirSync(dir, { recursive: true, encoding: 'utf8' }).sort()) { - if (rel === '.git' || rel.startsWith('.git' + path.sep)) continue; - const abs = path.join(dir, rel); - if (fs.statSync(abs).isFile()) files[rel] = fs.readFileSync(abs, 'utf8'); - } - const committed = spawnSync('git', ['ls-files'], { cwd: dir, encoding: 'utf8', timeout: 10_000 }).stdout; - return { files, committed }; -} - -describe('router arms (GST-470)', () => { - test('GSTACK_ROUTER_ARM: unset is current; before, current and none parse; anything else throws', () => { - expect(routerArm({})).toBe('current'); - for (const arm of ['before', 'current', 'none'] as const) expect(routerArm({ GSTACK_ROUTER_ARM: arm })).toBe(arm); - for (const bad of ['nonee', 'Current', 'after', '']) { - expect(() => routerArm({ GSTACK_ROUTER_ARM: bad })).toThrow('must be before, current or none, got ' + bad); - } - }); - - test('none: the repository has no installed skills and the prompt is the request alone', () => { - for (const fixture of FIXTURES) { - const repo = tree(makeRepo(fixture, 'none')); - const reference = tree(mainMakeRepo(fixture)); - expect(Object.keys(repo.files).some(f => f.startsWith('.claude'))).toBe(false); - const withoutSkills = Object.fromEntries(Object.entries(reference.files).filter(([f]) => !f.startsWith('.claude'))); - expect(repo.files).toEqual(withoutSkills); - const prompt = routerPrompt(fixture, 'none'); - expect(prompt).toBe(fixture.request); - for (const word of ['## Route first', '**Routing rules', 'gstack', 'router', 'skill', '/investigate']) expect(prompt).not.toContain(word); - } - }); - - test('current and before: prompts and repositories are byte-identical to main', () => { - for (const fixture of FIXTURES) { - for (const arm of ['current', 'before'] as const) expect(routerPrompt(fixture, arm, BASE)).toBe(mainPrompt(fixture, arm)); - for (const arm of ['current', 'before'] as const) expect(tree(makeRepo(fixture, arm))).toEqual(tree(mainMakeRepo(fixture))); - } - }); - - test('plain metrics count read-only calls before the first edit', () => { - const call = (tool: string, input: Record<string, unknown> = {}) => ({ tool, input, output: '' }); - expect(plainMetrics([])).toMatchObject({ editedBeforeRead: false, readsBeforeEdit: 0 }); - expect(plainMetrics([call('Read'), call('Grep'), call('Edit'), call('Read')])).toMatchObject({ editedBeforeRead: false, readsBeforeEdit: 2 }); - expect(plainMetrics([call('Edit'), call('Read')])).toMatchObject({ editedBeforeRead: true, readsBeforeEdit: 0 }); - expect(plainMetrics([call('Bash', { command: "sed -i 's/ /-/' src/slug.js" }), call('Read')])).toMatchObject({ editedBeforeRead: true, readsBeforeEdit: 0 }); - expect(plainMetrics([call('Bash', { command: 'bun test' }), call('Skill', { skill: 'qa' }), call('Write')])) - .toMatchObject({ editedBeforeRead: false, readsBeforeEdit: 1, sequence: 'Bash → Skill(qa) → Write' }); - }); -}); diff --git a/test/harness-register.test.ts b/test/harness-register.test.ts index 213910a09a1..927db544a72 100644 --- a/test/harness-register.test.ts +++ b/test/harness-register.test.ts @@ -234,7 +234,7 @@ describe('GSTA-135: registered skills get used', () => { test('router lines lead with each skill\'s trigger, within 160 chars; the router description leads with task verbs', () => { expect(ROUTER_DESCRIPTION.length).toBeLessThanOrEqual(ROUTER_DESCRIPTION_MAX); - for (const verb of ['review', 'debug', 'test', 'plan', 'ship']) expect(ROUTER_DESCRIPTION.slice(0, 200), verb).toContain(verb); + for (const verb of ['review', 'test', 'plan', 'ship']) expect(ROUTER_DESCRIPTION.slice(0, 200), verb).toContain(verb); const d = tmp(); for (const [target, mode] of [['openclaw', 'router'], ['dots', 'router']] as const) { const r = register(opts(d, target, { mode, skillsDir: path.join(d, target) })); diff --git a/test/helpers/e2e-hosts.ts b/test/helpers/e2e-hosts.ts index 4ebe9f491ef..12e7d9dfd2f 100644 --- a/test/helpers/e2e-hosts.ts +++ b/test/helpers/e2e-hosts.ts @@ -98,8 +98,7 @@ const CLAUDE_ONLY: Readonly<Record<ClaudeOnlyReason, readonly string[]>> = { 'shared-libs-review-prior-coverage', 'shared-libs-review-revalidation', 'ship-frozen-scope-convergence', 'ship-local-hook-preservation', 'ship-managed-hook-refresh', 'ship-skipped-queued-finding', 'ship-unmanaged-hook-consent'], subagents: ['docsync-spawned', 'review-army-perf-n-plus-one'], - 'skill-tool': ['router-failure-triage-resolves', - 'router-failure-verified-cause', 'skillify-approval-reject', 'skillify-happy-path', 'skillify-provenance-refusal'], + 'skill-tool': ['skillify-approval-reject', 'skillify-happy-path', 'skillify-provenance-refusal'], hermetic: ['hermetic-canary', 'hermetic-sentinel'], 'self-host': ['safety-codex-consult-embed'], rework: ['qa-functional-cli-fix', 'qa-functional-cli-report', 'qa-functional-webhook-fix', 'qa-functional-webhook-report', diff --git a/test/helpers/failure-routing-fixture.ts b/test/helpers/failure-routing-fixture.ts deleted file mode 100644 index a97018923e4..00000000000 --- a/test/helpers/failure-routing-fixture.ts +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Router failure-routing fixtures and scoring (#3157, #3158), shared by - * test/skill-e2e-failure-routing.test.ts and its free arm test (GST-470). - * GSTACK_ROUTER_ARM picks what the candidate sees: `current` (the default) the - * rendered router section of SKILL.md, `before` the base branch's router, and - * `none` the user's request alone in a repository with no installed skills. - * Any other value throws, so a typo cannot run one arm under another's label. - */ -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import type { SkillTestResult } from './session-runner'; -import { extractSkillHead, sliceBetween } from './skill-fixture'; - -const ROOT = path.resolve(import.meta.dir, '..', '..'); - -export type RouterArm = 'before' | 'current' | 'none'; - -export function routerArm(env: NodeJS.ProcessEnv = process.env): RouterArm { - const arm = env.GSTACK_ROUTER_ARM ?? 'current'; - if (arm !== 'before' && arm !== 'current' && arm !== 'none') throw new Error(`GSTACK_ROUTER_ARM must be before, current or none, got ${arm}`); - return arm; -} - -const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']); -const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'Bash']); -const SHELL_WRITE = /\b(?:sed|perl)\b[^|;&]*\s-[a-z]*i|(?<![=0-9&>])>>?\s*(?!&|\/dev\/null)\S|\btee\b|\b(?:mv|cp|rm)\s|\bgit\s+(?:apply|checkout|restore)\b/; - -export function isEdit(call: { tool: string; input: any }): boolean { - return EDIT_TOOLS.has(call.tool) || (call.tool === 'Bash' && SHELL_WRITE.test(String(call.input?.command ?? ''))); -} - -export interface Fixture { - name: string; - files: Record<string, string>; - request: string; -} - -export const FIXTURES: Fixture[] = [ - { - name: 'router-failure-verified-cause', - files: { - 'src/slug.js': "export function slugify(title) {\n return title.trim().toLowerCase().replace(/ /, '-');\n}\n", - 'test/slug.test.js': "import { expect, test } from 'bun:test';\nimport { slugify } from '../src/slug.js';\n\ntest('slugify joins every word with a hyphen', () => {\n expect(slugify('Hello Big World')).toBe('hello-big-world');\n});\n", - }, - request: "test/slug.test.js fails: slugify('Hello Big World') returns 'hello-big world'. The cause is the regex in src/slug.js: / / has no g flag, so only the first space is replaced. Fix it by making it / /g.", - }, - { - name: 'router-failure-triage-resolves', - files: { - 'src/initials.js': "export function initials(fullName) {\n const [first, last] = fullName.split(',');\n return (first[0] + last[0]).toUpperCase();\n}\n", - 'test/initials.test.js': "import { expect, test } from 'bun:test';\nimport { initials } from '../src/initials.js';\n\ntest('initials of a first and last name', () => {\n expect(initials('Ada Lovelace')).toBe('AL');\n});\n", - }, - request: "bun test fails on test/initials.test.js with: TypeError: undefined is not an object (evaluating 'last[0]') at initials (src/initials.js:3). Can you fix it?", - }, -]; - -export function routerSection(arm: Exclude<RouterArm, 'none'>, base = process.env.EVALS_BASE || 'origin/main'): string { - const skill = arm === 'before' - ? spawnSync('git', ['show', `${base}:SKILL.md`], { cwd: ROOT, encoding: 'utf8', timeout: 10_000 }).stdout - : fs.readFileSync(path.join(ROOT, 'SKILL.md'), 'utf8'); - return sliceBetween(skill, '## Route first', 'Best-effort, record') + sliceBetween(skill, '**Routing rules', 'If the user opts out'); -} - -/** The candidate's prompt: the router section and the request, or under `none` the request alone. */ -export function routerPrompt(fixture: Fixture, arm: RouterArm, base?: string): string { - if (arm === 'none') return fixture.request; - return `The user invoked the gstack router skill (/gstack) in this repository. The router's instructions:\n\n${routerSection(arm, base)}\n\nThe user's request: "${fixture.request}"`; -} - -/** The fixture repository; under `none` it has no installed skills. */ -export function makeRepo(fixture: Fixture, arm: RouterArm): string { - const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'failure-routing-')); - fs.writeFileSync(path.join(repo, 'package.json'), JSON.stringify({ name: 'fixture', type: 'module', scripts: { test: 'bun test' } }, null, 2)); - for (const [file, body] of Object.entries(fixture.files)) { - fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true }); - fs.writeFileSync(path.join(repo, file), body); - } - for (const skill of arm === 'none' ? [] : ['qa', 'review', 'ship']) { - fs.mkdirSync(path.join(repo, '.claude', 'skills', skill), { recursive: true }); - fs.writeFileSync(path.join(repo, '.claude', 'skills', skill, 'SKILL.md'), extractSkillHead(path.join(ROOT, skill, 'SKILL.md'))); - } - const git = (...args: string[]) => spawnSync('git', ['-c', 'user.email=test@example.invalid', '-c', 'user.name=Test', ...args], { cwd: repo, timeout: 10_000 }); - git('init', '-q', '-b', 'main'); - git('add', '.'); - git('commit', '-qm', 'initial'); - return repo; -} - -export function routing(result: SkillTestResult) { - const calls = result.toolCalls; - const firstEditAt = calls.findIndex(isEdit); - const before = firstEditAt >= 0 ? calls.slice(0, firstEditAt) : calls; - return { - skillRouted: calls.some(c => c.tool === 'Skill'), - readsBeforeRoute: before.filter(c => READ_TOOLS.has(c.tool) && !isEdit(c)).length, - sequence: calls.map(c => c.tool === 'Skill' ? `Skill(${c.input?.skill})` : c.tool).join(' → '), - }; -} - -/** - * The no-gstack arm's plain metrics: no skill exists to route to, so they say - * only whether the agent read before it edited. - */ -export function plainMetrics(calls: SkillTestResult['toolCalls']) { - const firstEditAt = calls.findIndex(isEdit); - const firstReadAt = calls.findIndex(c => READ_TOOLS.has(c.tool) && !isEdit(c)); - const before = firstEditAt >= 0 ? calls.slice(0, firstEditAt) : calls; - return { - editedBeforeRead: firstEditAt >= 0 && (firstReadAt < 0 || firstEditAt < firstReadAt), - readsBeforeEdit: before.filter(c => READ_TOOLS.has(c.tool) && !isEdit(c)).length, - sequence: calls.map(c => c.tool === 'Skill' ? `Skill(${c.input?.skill})` : c.tool).join(' → '), - }; -} diff --git a/test/helpers/touchfiles-data.ts b/test/helpers/touchfiles-data.ts index 4d1cc3c4b8d..efee9c93d0f 100644 --- a/test/helpers/touchfiles-data.ts +++ b/test/helpers/touchfiles-data.ts @@ -1166,8 +1166,6 @@ export const E2E_TOUCHFILES: Record<string, string[]> = { "scripts/resolvers/preamble/generate-preamble-bash.ts", "scripts/resolvers/preamble/generate-completion-status.ts" ], - 'router-failure-verified-cause': ['SKILL.md.tmpl', 'SKILL.md', 'scripts/resolvers/preamble/generate-test-failure-triage.ts', 'lib/bun-isolation.ts', 'test/skill-e2e-failure-routing.test.ts', 'test/helpers/failure-routing-fixture.ts', 'test/helpers/none-arm.ts'], - 'router-failure-triage-resolves': ['SKILL.md.tmpl', 'SKILL.md', 'scripts/resolvers/preamble/generate-test-failure-triage.ts', 'lib/bun-isolation.ts', 'test/skill-e2e-failure-routing.test.ts', 'test/helpers/failure-routing-fixture.ts', 'test/helpers/none-arm.ts'], }; /** @@ -1573,8 +1571,6 @@ export const E2E_TIERS: Record<string, 'gate' | 'periodic' | 'marathon'> = { 'overlay-harness-claude-dedicated-tools-vs-bash-sonnet': 'periodic', 'overlay-harness-claude-dedicated-tools-vs-bash-opus-5-5': 'periodic', 'journey-negatives': 'periodic', - 'router-failure-verified-cause': 'gate', - 'router-failure-triage-resolves': 'gate', }; /** @@ -1891,8 +1887,6 @@ export const E2E_KINDS: Record<string, 'rule' | 'behavior' | 'judge'> = { 'overlay-harness-claude-dedicated-tools-vs-bash-sonnet': 'rule', 'overlay-harness-claude-dedicated-tools-vs-bash-opus-5-5': 'rule', 'journey-negatives': 'rule', - 'router-failure-verified-cause': 'rule', - 'router-failure-triage-resolves': 'rule', }; /** diff --git a/test/skill-e2e-failure-routing.test.ts b/test/skill-e2e-failure-routing.test.ts deleted file mode 100644 index 0e83ff452d0..00000000000 --- a/test/skill-e2e-failure-routing.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Router failure routing (#3157, #3158). The gstack router checks a reported - * failure's cause before it fixes it: a user-supplied cause that one read-only - * check confirms is fixed directly, and an unknown cause gets one bounded - * triage pass. Anything still unverified gets a focused failing test first. - * - * Two fixtures, one per issue (verified cause, triage that resolves it): each - * must fix the bug directly, without routing to a skill, and leave the suite - * green after one to four read-only calls. The two /investigate fallback cases - * retired with that skill (GST-1717). The agent sees the rendered router section, sliced from - * SKILL.md; GSTACK_ROUTER_ARM=before slices the base branch's router instead. - * GSTACK_ROUTER_ARM=none is the descriptive no-gstack arm: the request alone, - * no installed skills, scored on plain metrics (suite green, edits before the - * first read, read-only calls before the first edit) recorded as observations. - * Fixtures and scoring live in test/helpers/failure-routing-fixture.ts. - */ -import { afterAll, expect } from 'bun:test'; -import * as fs from 'node:fs'; -import { spawnSync } from 'node:child_process'; -import { runSkillTest } from './helpers/session-runner'; -import { - runId, describeIfSelected, testConcurrentIfSelected, logCost, recordE2E, - createEvalCollector, finalizeEvalCollector, -} from './helpers/e2e-helpers'; -import { CAPTURE_MS } from './helpers/eval-budgets'; -import { bunIsolationArgs } from '../lib/bun-isolation'; -import { FIXTURES, makeRepo, plainMetrics, routerArm, routerPrompt, routing } from './helpers/failure-routing-fixture'; -import { recordObservation } from './helpers/none-arm'; - -const collector = createEvalCollector('e2e-failure-routing'); -const ARM = routerArm(); -const SCORE_GRACE_MS = 10_000; - -describeIfSelected('Router failure routing (#3157, #3158)', FIXTURES.map(f => f.name), () => { - const dirs: string[] = []; - afterAll(() => { - for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true }); - finalizeEvalCollector(collector); - }); - - for (const fixture of FIXTURES) { - testConcurrentIfSelected(fixture.name, async () => { - const repo = makeRepo(fixture, ARM); - dirs.push(repo); - const result = await runSkillTest({ - prompt: routerPrompt(fixture, ARM), - workingDirectory: repo, - maxTurns: 6, - tools: ['Skill', 'Read', 'Grep', 'Glob', 'Edit', 'Bash'], - allowedTools: ['Skill', 'Read', 'Grep', 'Glob', 'Edit', 'Bash'], - timeout: CAPTURE_MS - SCORE_GRACE_MS, - testName: fixture.name, - runId, - }); - logCost(`router ${fixture.name} (${ARM})`, result); - const suite = spawnSync(process.execPath, [...bunIsolationArgs(), 'test'], { cwd: repo, encoding: 'utf8', timeout: 60_000 }); - const green = suite.status === 0; - if (ARM === 'none') { - const p = plainMetrics(result.toolCalls); - const plain = `arm=none reads_before_edit=${p.readsBeforeEdit} edited_before_read=${p.editedBeforeRead} green=${green} tools: ${p.sequence}`; - recordE2E(collector, fixture.name, 'Router failure routing', result, { passed: true, output: plain }); - recordObservation(fixture.name, green, `suite green after the run: ${plain}`); - recordObservation(fixture.name, !p.editedBeforeRead, `no edit before the first read-only call: ${plain}`); - recordObservation(fixture.name, p.readsBeforeEdit >= 1, `at least one read-only call before the first edit: ${plain}`); - return; - } - const r = routing(result); - const summary = `arm=${ARM} route=${r.skillRouted ? 'skill' : 'direct'} reads=${r.readsBeforeRoute} green=${green} tools: ${r.sequence}`; - const bounded = r.readsBeforeRoute >= 1 && r.readsBeforeRoute <= 4; - const passed = bounded && !r.skillRouted && green; - recordE2E(collector, fixture.name, 'Router failure routing', result, { passed, output: summary }); - - expect(r.skillRouted, summary).toBe(false); - expect(green, `suite still red after the direct fix: ${summary}\n${suite.stdout}${suite.stderr}`).toBe(true); - expect(r.readsBeforeRoute, `no read-only check before routing: ${summary}`).toBeGreaterThanOrEqual(1); - expect(r.readsBeforeRoute, `triage was not bounded: ${summary}`).toBeLessThanOrEqual(4); - }, CAPTURE_MS); - } -}); diff --git a/test/skill-validation.test.ts b/test/skill-validation.test.ts index ea2b5a996ad..e265081efd5 100644 --- a/test/skill-validation.test.ts +++ b/test/skill-validation.test.ts @@ -7,7 +7,6 @@ import * as os from 'os'; import * as path from 'path'; import { usePrivateStateRoot } from './helpers/private-state-root'; import { expectMentions } from './helpers/prompt-structure'; -import { generateFailureRouting } from '../scripts/resolvers/preamble/generate-test-failure-triage'; import { readShippedSkillRouting } from './helpers/shipped-skill-routing'; import { readSkillStartup } from './helpers/skill-startup'; import { RETIRED_SKILLS } from '../scripts/discover-skills'; @@ -2031,25 +2030,15 @@ describe('Test failure triage in ship skill', () => { }); }); -describe('Failure routing: verified cause → fix, unknown cause → bounded triage (#3157, #3158)', () => { - const rule = generateFailureRouting(); - const unknownCause = rule.slice(rule.indexOf('**Cause unknown:** ') + '**Cause unknown:** '.length); - - test('the router sends bug reports through the failure rule and names no retired skill (GST-1717)', () => { +describe('Bug reports: the router has no bug-fix route, other surfaces keep their bounded triage (GST-2873)', () => { + test('the router routes no bug report and carries no failure rule, so bug fixes run plain', () => { const router = fs.readFileSync(path.join(ROOT, 'SKILL.md'), 'utf-8'); - expect(router).toContain(rule); - const bugRule = router.split('\n').find(line => line.startsWith('- User reports a bug')); - expect(bugRule).toContain('**Failures**'); - expect(bugRule).toContain('then fix it test-first'); + expect(router.split('\n').some(line => line.startsWith('- User reports a bug'))).toBe(false); + expect(router).not.toContain('**Failures'); + expect(router).not.toContain('**Cause supplied**'); expect(router).not.toContain('/investigate'); }); - test('the rule keeps the root-cause bar on both paths, with a focused failing test when the cause is unclear', () => { - expect(rule).toMatch(/\*\*Cause supplied\*\*[^\n]*one read-only check[^\n]*If it does not, leave the suggested fix alone: reproduce the failure with a focused failing test, trace it to the root cause/); - expect(unknownCause).toMatch(/^make one read-only triage pass[^\n]*Do not reproduce, test hypotheses or search wider[^\n]*still unclear, write or run a focused test that fails on the bug before any edit, trace the failure to its root cause/); - expect(rule).not.toContain('/investigate'); - }); - test('the routing gstack offers for CLAUDE.md, and this repo\'s own, fix bugs directly behind a cause check or a failing test', () => { const bugRule = readShippedSkillRouting().section.split('\n').find(line => line.startsWith('- Bugs/errors')); expect(bugRule).toMatch(/→ fix them directly: one read-only check of the cause, or a focused failing test first when the cause is unclear/); From b49ed6a0d960653220c7850dced71afac4d94411 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 22:45:34 +0800 Subject: [PATCH 38/62] Ubicloud pack no longer fails while git rewrites a ref, and the HOLD SCOPE eval stops requiring the mode name (#4447) Packing a checkout for a Ubicloud run no longer fails when git running beside it is rewriting a ref, and the /plan-ceo-review HOLD SCOPE eval no longer fails a review whose follow-up question doesn't repeat the mode name. Why: both made tests fail at random. The pack race failed Free Tests twice on 2026-11-17, and the HOLD check failed the weekly eval census on main. Nothing to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../ubicloud-pack-skips-refs-being-rewritten.md | 2 ++ scripts/ubicloud/ubi-runner.sh | 6 +++++- test/ceo-hold-posture-review.test.ts | 10 ++++++++++ test/helpers/ceo-hold-posture-review.ts | 5 +++-- test/ubicloud-runner.test.ts | 13 +++++++++++++ 5 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 changelog.d/ubicloud-pack-skips-refs-being-rewritten.md diff --git a/changelog.d/ubicloud-pack-skips-refs-being-rewritten.md b/changelog.d/ubicloud-pack-skips-refs-being-rewritten.md new file mode 100644 index 00000000000..3066cce587c --- /dev/null +++ b/changelog.d/ubicloud-pack-skips-refs-being-rewritten.md @@ -0,0 +1,2 @@ +- **Packing a checkout for a Ubicloud run no longer fails when git beside it is rewriting a ref.** `ubi-runner.sh pack` asked git's upload-pack for every ref, and upload-pack advertises a ref it cannot read (a loose ref file caught mid-write or mid-delete) with a null id, so the snapshot failed with "not our ref 0000…". Pack now reads the refs once with `git for-each-ref`, which skips an unreadable ref, and fetches those exact objects. Seen twice in Free Tests on 2026-11-17 (runs 44063454800 and 44050883970); an empty loose ref file reproduces it every time. +- **The /plan-ceo-review HOLD SCOPE eval no longer fails a review because its follow-up question didn't repeat the mode name.** The check required the decision's "Project/branch/task" line to say "HOLD SCOPE", which the skill never asks for; the decision is already tied to the HOLD answer by session and order. A line naming another mode, or past or hypothetical work, still fails. diff --git a/scripts/ubicloud/ubi-runner.sh b/scripts/ubicloud/ubi-runner.sh index 371c1ab6629..32662d5d42b 100755 --- a/scripts/ubicloud/ubi-runner.sh +++ b/scripts/ubicloud/ubi-runner.sh @@ -1703,7 +1703,11 @@ cmd_pack() { trap "rm -rf $(printf %q "$tmp")" EXIT # No template hooks from a global init.templateDir, and no auto-gc under the tar. git -c gc.auto=0 init -q --bare --template= "$tmp/.git" - git -C "$tmp/.git" -c gc.auto=0 fetch -q --no-tags --update-shallow "$src" '+refs/*:refs/*' \ + # Fetch the object ids one for-each-ref read, not upload-pack's own ref list: a ref that git running beside pack is + # deleting is advertised with a null id that no fetch can want, while for-each-ref skips it as broken. + git -C "$src" for-each-ref --format='+%(objectname):%(refname)' refs/ \ + | git -C "$tmp/.git" -c gc.auto=0 fetch -q --no-tags --update-shallow --stdin \ + --upload-pack='git -c uploadpack.allowAnySHA1InWant=true upload-pack' "$src" \ || die "pack: could not snapshot the refs of $src" if [ -z "$branch" ]; then branch="detached-${head:0:12}" diff --git a/test/ceo-hold-posture-review.test.ts b/test/ceo-hold-posture-review.test.ts index 11accf0cb9e..763372a017c 100644 --- a/test/ceo-hold-posture-review.test.ts +++ b/test/ceo-hold-posture-review.test.ts @@ -284,3 +284,13 @@ test('a decision whose grounding line names no plan file stays bound by the owne unread.publicTools=unread.publicTools.filter(e=>e.toolUseId!==sourceId); expect(()=>buildCeoHoldPostureReview(unread)).toThrow('complete original source Read/ACK'); }); + +test('a decision whose grounding line does not restate the mode stays bound by its HOLD answer (census 43815320847 HOLD D4)',()=>{ + const line='Project/branch/task: main branch, PLAN.md saved project views; the repo contains only PLAN.md and CLAUDE.md.'; + const f=input();revise(f,q=>{q.question=q.question.replace(/Project\/branch\/task:[^\n]*/,line);}); + expect(buildCeoHoldPostureReview(f)!.plan).toBe(f.source.content); + for(const other of ['SELECTIVE EXPANSION','SCOPE REDUCTION','previous']){ + const g=input();revise(g,q=>{q.question=q.question.replace(/Project\/branch\/task:[^\n]*/,line.replace('main branch,',`main branch, ${other} review,`));}); + expect(()=>buildCeoHoldPostureReview(g)).toThrow('decision is not current HOLD work'); + } +}); diff --git a/test/helpers/ceo-hold-posture-review.ts b/test/helpers/ceo-hold-posture-review.ts index d7b97646b4c..3904a0690fd 100644 --- a/test/helpers/ceo-hold-posture-review.ts +++ b/test/helpers/ceo-hold-posture-review.ts @@ -68,8 +68,9 @@ export function buildCeoHoldPostureReview(input: CeoHoldPostureReviewInput): Pla if (plans.length > 1 || (plans.length === 1 && plans[0] !== name && plans[0] !== source.path)) fail('native source context differs from original plan'); } const decisionContext = /Project\/branch\/task:([^\n]*)/i.exec(decision.questions[0]!.question)?.[1] ?? ''; - if (!/\bHOLD SCOPE\b/.test(decisionContext) || - /\b(?:SCOPE EXPANSION|SELECTIVE EXPANSION|SCOPE REDUCTION|historical|previous|example|hypothetical|withdrawn)\b/i.test(decisionContext)) + // The decision is bound to the HOLD answer by session and chronology above; the skill never asks its grounding + // line to restate the mode, so only a context naming another mode or past or hypothetical work disqualifies it. + if (/\b(?:SCOPE EXPANSION|SELECTIVE EXPANSION|SCOPE REDUCTION|historical|previous|example|hypothetical|withdrawn)\b/i.test(decisionContext)) fail('decision is not current HOLD work'); const sourceLines = source.content.split('\n').length; const loaded = events.some(request => { diff --git a/test/ubicloud-runner.test.ts b/test/ubicloud-runner.test.ts index 4ce8d5d2c04..fbc8d635fe0 100644 --- a/test/ubicloud-runner.test.ts +++ b/test/ubicloud-runner.test.ts @@ -520,6 +520,19 @@ test('pack ships a linked worktree with a self-contained .git on the checked-out } finally { rmSync(d, { recursive: true, force: true }); } }, 90_000); + // Value: protects=pack snapshots a checkout while git beside it is mid-way through writing or deleting a ref (two Free Tests reds on 2026-11-17, runs 44063454800 and 44050883970, from the churn test above); fails_when=pack asks upload-pack for every ref, which advertises a ref it cannot read with a null id, and the fetch then fails "not our ref 0000…"; why_new=the churn test hits that window about once in 600 fetches, an empty loose ref file is the same state held still; seam=none + test('pack skips a ref git cannot read (an empty loose ref file) and still ships every readable ref', () => { + const d = mkdtempSync(join(tmpdir(), 'ubi-pack-broken-ref-')); + try { + const sh = (cmd: string, cwd: string) => { const r = Bun.spawnSync(['bash', '-c', cmd], { cwd, timeout: 30_000, env: { ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' } }); expect(r.exitCode, `${cmd}\n${r.stderr.toString()}`).toBe(0); return r.stdout.toString(); }; + sh('git init -q -b main src && cd src && echo a > a && git add a && git commit -qm one && git tag -a v1 -m v1 && git branch side && : > .git/refs/heads/broken', d); + sh(`mkdir vm && bash ${JSON.stringify(join(DIR, 'ubi-runner.sh'))} pack src | tar -xzf - -C vm`, d); + const head = sh('git rev-parse HEAD', join(d, 'src')).trim(); + expect(sh('git for-each-ref --format="%(refname) %(objectname)" refs/heads && git rev-parse v1^{commit}', join(d, 'vm')).split('\n').filter(Boolean)) + .toEqual([`refs/heads/main ${head}`, `refs/heads/side ${head}`, head]); + } finally { rmSync(d, { recursive: true, force: true }); } + }, 60_000); + // Value: protects=pack never lets macOS tar add AppleDouble ._* entries (files with extended attributes), which the VM's tree check would count as untracked files and fail the run with UBI_VM_TREE_MISMATCH; fails_when=a tar call in pack runs without COPYFILE_DISABLE=1; why_new=only Apple's tar reads the variable, so no Linux run can see the ._* entries themselves; seam=PATH (a tar shim records its environment, then runs the real tar); no_claim=Apple tar's metadata behavior itself (checked by hand on a Mac) test('pack runs every tar with COPYFILE_DISABLE=1, for a checkout and for a plain directory', () => { const d = mkdtempSync(join(tmpdir(), 'ubi-pack-copyfile-')); From e0c4136dc2999840720091ee772666127099e13d Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Tue, 17 Nov 2026 23:35:50 +0800 Subject: [PATCH 39/62] office-hours explains why it recommends a mode (#4450) /office-hours now backs its mode recommendation with the user's own words and says what another mode would skip, instead of restating the mode's name. Why: the weekly eval census (run 43815320847) scored this question's reasoning 2 of 5, because the recommendation repeated the option label as its reason. Nothing to do as a reader; this changes one sentence of skill prose. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- changelog.d/office-hours-explains-mode-pick.md | 1 + office-hours/SKILL.md | 2 +- office-hours/SKILL.md.tmpl | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 changelog.d/office-hours-explains-mode-pick.md diff --git a/changelog.d/office-hours-explains-mode-pick.md b/changelog.d/office-hours-explains-mode-pick.md new file mode 100644 index 00000000000..457395c18b0 --- /dev/null +++ b/changelog.d/office-hours-explains-mode-pick.md @@ -0,0 +1 @@ +- **/office-hours explains why it recommends a mode.** The first question (what's your goal?) now recommends a mode by quoting your own words and saying what another mode would skip, instead of restating the mode's name. diff --git a/office-hours/SKILL.md b/office-hours/SKILL.md index aaeb8c89d47..e92e0ee4688 100644 --- a/office-hours/SKILL.md +++ b/office-hours/SKILL.md @@ -314,7 +314,7 @@ matches a past learning, display: This makes the compounding visible. The user should see that gstack is getting smarter on their codebase over time. -5. **Ask: what's your goal with this?** This is a real question, not a formality. The answer determines everything about how the session runs. Unless the user already chose a mode, ask it even when the request suggests one, recommending that mode. Read the chosen mode's section before its first question. +5. **Ask: what's your goal with this?** It decides how the session runs. Unless the user already chose a mode, ask it even when the request suggests one; recommend that mode by quoting the user's words and naming what another mode would skip. Read the chosen mode's section before its first question. Via AskUserQuestion, ask: diff --git a/office-hours/SKILL.md.tmpl b/office-hours/SKILL.md.tmpl index de7f761c045..02e36cc837b 100644 --- a/office-hours/SKILL.md.tmpl +++ b/office-hours/SKILL.md.tmpl @@ -94,7 +94,7 @@ Understand the project and the area the user wants to change. {{LEARNINGS_SEARCH}} -5. **Ask: what's your goal with this?** This is a real question, not a formality. The answer determines everything about how the session runs. Unless the user already chose a mode, ask it even when the request suggests one, recommending that mode. Read the chosen mode's section before its first question. +5. **Ask: what's your goal with this?** It decides how the session runs. Unless the user already chose a mode, ask it even when the request suggests one; recommend that mode by quoting the user's words and naming what another mode would skip. Read the chosen mode's section before its first question. Via AskUserQuestion, ask: From 9c6e0a0f859f54074c2945b6c27203ccd1e1e2dc Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 00:37:56 +0800 Subject: [PATCH 40/62] Token-capped /ship hands its child Claude Code session its prompt (#4448) (#4452) A `/ship` with a token cap on Claude Code no longer stops at its first handoff: the child `claude -p` session now gets its prompt. Why: `--allowedTools` takes every argument after it, so the prompt was read as one more tool name and the child exited at once. The launch now puts `--` before the prompt. Nothing to do. Thanks to @exGeni for the report and diagnosis. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../ship-handoff-child-gets-its-prompt.md | 4 +++ lib/ship-handoff.ts | 2 +- test/ship-budget.test.ts | 28 +++++++++++++++++-- 3 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 changelog.d/ship-handoff-child-gets-its-prompt.md diff --git a/changelog.d/ship-handoff-child-gets-its-prompt.md b/changelog.d/ship-handoff-child-gets-its-prompt.md new file mode 100644 index 00000000000..f2a6e3a0c55 --- /dev/null +++ b/changelog.d/ship-handoff-child-gets-its-prompt.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +- **A `/ship` with a token cap on Claude Code no longer stops at its first handoff.** When the budget handed steps to a fresh child, `gstack-ship-budget launch` started `claude -p` with `--allowedTools <list>` right before the prompt. Claude Code reads every argument after that option as one more tool name, so the child got no prompt, exited with "Input must be provided either through stdin or as a prompt argument", and the run stopped. The launch now ends the options with `--` before the prompt, which Claude Code 2.1.292 and 2.1.326 both read as the prompt. Thanks to @exGeni for the report and diagnosis (#4448). diff --git a/lib/ship-handoff.ts b/lib/ship-handoff.ts index e19cdb1905e..786d187dc96 100644 --- a/lib/ship-handoff.ts +++ b/lib/ship-handoff.ts @@ -304,7 +304,7 @@ export function cmdLaunch(argv: string[], ctx: Ctx): Outcome { const log = path.join(path.dirname(block.return_file), `child-${session}.log`); joinMeter(block.parent_ledger, session, ctx.env); const out = fs.openSync(log, 'a', 0o600); - const child = spawn(claude.command, [...claude.argsPrefix, '-p', '--session-id', session, ...CHILD_PERMISSION_ARGS, prompt], { cwd: ctx.cwd, env: ctx.env, detached: true, stdio: ['ignore', out, out] }); + const child = spawn(claude.command, [...claude.argsPrefix, '-p', '--session-id', session, ...CHILD_PERMISSION_ARGS, '--', prompt], { cwd: ctx.cwd, env: ctx.env, detached: true, stdio: ['ignore', out, out] }); child.unref(); fs.closeSync(out); return { stdout: [`CHILD: session=${session} pid=${child.pid} log=${log} return=${block.return_file}`], exit: 0 }; diff --git a/test/ship-budget.test.ts b/test/ship-budget.test.ts index 5043da5a123..af8871f951e 100644 --- a/test/ship-budget.test.ts +++ b/test/ship-budget.test.ts @@ -301,6 +301,27 @@ describe('delegation', () => { }); describe('Claude Code child launch', () => { + /** + * The argv rules of `claude --help` (2.1.292 pinned in CI, 2.1.326): a `<values...>` option takes + * every following argument up to the next one that starts with '-', and '--' ends the options. + */ + function parseLikeClaudeCli(argv: string[]): { options: Record<string, string[]>; prompts: string[] } { + const variadic = new Set(['--allowedTools', '--allowed-tools', '--disallowedTools', '--disallowed-tools', '--add-dir', '--tools']); + const valued = new Set(['--session-id', '--permission-mode', '--model', '--settings', '--output-format']); + const options: Record<string, string[]> = {}; + const prompts: string[] = []; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]!; + if (arg === '--') { prompts.push(...argv.slice(i + 1)); break; } + if (variadic.has(arg)) { + const values = options[arg] ??= []; + while (i + 1 < argv.length && !argv[i + 1]!.startsWith('-')) values.push(argv[++i]!); + } else if (valued.has(arg)) options[arg] = [argv[++i]!]; + else if (!arg.startsWith('-')) prompts.push(arg); + } + return { options, prompts }; + } + test('launch runs the child in the background with explicit permission flags and the return file named', async () => { const h = fresh(); const s = started(h, ['--token-cap', '80M', '--meter', 'estimate']); @@ -314,9 +335,12 @@ describe('Claude Code child launch', () => { const session = h.field(r.out, 'CHILD', 'session'); expect(h.field(r.out, 'CHILD', 'return')).toBe(ho.out.match(/^RETURN_FILE: (\S+)$/m)![1]!); for (let i = 0; i < 50 && !fs.existsSync(argsFile); i++) await Bun.sleep(100); - const args = fs.readFileSync(argsFile, 'utf8').split('\n'); + const args = fs.readFileSync(argsFile, 'utf8').split('\n').slice(0, -1); expect(args.slice(0, 7)).toEqual(['-p', '--session-id', session, '--permission-mode', 'acceptEdits', '--allowedTools', 'Bash,Read,Edit,Write,Grep,Glob']); - expect(args[7]).toContain(`verify-handoff --in ${file} --session ${session}`); + const parsed = parseLikeClaudeCli(args); + expect(parsed.options['--allowedTools']).toEqual(['Bash,Read,Edit,Write,Grep,Glob']); + expect(parsed.prompts).toHaveLength(1); + expect(parsed.prompts[0]).toContain(`verify-handoff --in ${file} --session ${session}`); }); }); From 0ee5914628eb0373876bfc9c511a48178a6700fa Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 00:44:06 +0800 Subject: [PATCH 41/62] Run each driven /ship phase as one command, count its calls, and stop it at 100 minutes (GST-2984) (#4451) A driven /ship now runs each ship/DRIVER.md phase as one command, shows how many calls the run made, and stops itself with a printed line at 100 minutes. Why: measured /ship runs made 121 to 308 calls where the driver plans 9 to 12, and 10 of 12 ran past the 100-minute stop while those limits were only prose. Nothing to do: older ship records without `calls=` still validate and print. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/outside-voice#1 reader=outside-voice --- bin/gstack-ship-phase | 60 +++++ bin/gstack-ship-receipt | 14 +- capy/skill/gstack/SKILL.md | 2 +- changelog.d/capy-run-each-driven-ship.md | 1 + docs/ship-budget.md | 51 +++- lib/capy-review-pass.js | 2 +- lib/capy-ship-phase.js | 69 +++++ lib/headless-artifacts.ts | 4 +- lib/ship-budget-cli.ts | 18 +- lib/ship-budget.ts | 4 +- lib/ship-call-log.ts | 7 + lib/ship-clock.ts | 86 ++++++ lib/ship-phase.ts | 123 +++++++++ lib/ship-receipt.ts | 3 +- ship/DRIVER.md | 34 +-- ship/DRIVER.md.tmpl | 34 +-- test/exercised-map.test.ts | 1 + test/review-pass.test.ts | 13 + test/ship-phase.test.ts | 330 +++++++++++++++++++++++ 19 files changed, 807 insertions(+), 49 deletions(-) create mode 100755 bin/gstack-ship-phase create mode 100644 changelog.d/capy-run-each-driven-ship.md create mode 100644 lib/capy-ship-phase.js create mode 100644 lib/ship-clock.ts create mode 100644 lib/ship-phase.ts create mode 100644 test/ship-phase.test.ts diff --git a/bin/gstack-ship-phase b/bin/gstack-ship-phase new file mode 100755 index 00000000000..802e55fe4c6 --- /dev/null +++ b/bin/gstack-ship-phase @@ -0,0 +1,60 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * gstack-ship-phase — one ship/DRIVER.md phase as one call (G2). + * + * gstack-ship-phase run --dir <run dir> --phase <n> [--record <rec>] [--wait-s <s>] -- '<command>' ['<command>' ...] + * Runs the phase's commands in order, each in the background (output in <run dir>/phases/<n>/<k>.log), and prints + * only result lines: RAN: <k>/<N> exit=<c> with each command's CODE: lines, then PHASE: <n> done. A command still + * running after --wait-s (default 200) keeps running and the run prints WAITING: and NEXT: rerun; rerun the same + * command to resume. A failed command prints STOP: (exit 3); fix it and rerun the same command: finished commands + * stay done (the journal keys each by the sha256 of its text). With --record, a stopped run or one past 100 + * minutes prints STOP: and runs nothing (exit 3); past 100 minutes it also writes <ledger dir>/stop.json. + * gstack-ship-phase program + * Prints the checked-in Capy phase program (lib/capy-ship-phase.js): PROGRAM: v<n> sha256=<h> bytes=<n>, then its + * text as one JSON string. Load it the way capy/skill/gstack/SKILL.md loads the review pass program. + * + * Exit: 0 done or waiting · 3 stop · 2 usage. Logic: lib/ship-phase.ts, lib/ship-clock.ts. + */ +import { createHash } from 'node:crypto'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { runPhase } from '../lib/ship-phase'; +import { logShipCall } from '../lib/ship-call-log'; + +logShipCall('gstack-ship-phase'); + +const PROGRAM_VERSION = 1; +const [command, ...rest] = process.argv.slice(2); +const usage = (why: string) => { process.stderr.write(`gstack-ship-phase: ${why} (usage; see gstack-ship-phase --help)\n`); process.exit(2); }; + +if (!command || command === '--help' || command === '-h') { + const lines = (await Bun.file(import.meta.path).text()).split('\n'); + (command ? console.log : console.error)(lines.slice(2, lines.indexOf(' */')).map(l => l.replace(/^ \* ?/, '')).join('\n')); + process.exit(command ? 0 : 2); +} +if (command === 'program') { + const text = fs.readFileSync(path.join(import.meta.dir, '..', 'lib', 'capy-ship-phase.js'), 'utf8'); + const sha = createHash('sha256').update(text).digest('hex'); + process.stdout.write(`PROGRAM: v${PROGRAM_VERSION} sha256=${sha} bytes=${Buffer.byteLength(text)}\n${JSON.stringify(text)}\n`); + process.exit(0); +} +if (command !== 'run') usage(`unknown command '${command}'`); +const sep = rest.indexOf('--'); +const opts = sep < 0 ? rest : rest.slice(0, sep); +const commands = sep < 0 ? [] : rest.slice(sep + 1); +const flag = (name: string) => { const i = opts.indexOf(`--${name}`); return i >= 0 ? opts[i + 1] : undefined; }; +const known = new Set(['--dir', '--phase', '--record', '--wait-s']); +for (let i = 0; i < opts.length; i += 2) if (!known.has(opts[i]!) || opts[i + 1] === undefined) usage(`run: unexpected '${opts[i]}'`); +const dir = flag('dir'), phase = flag('phase'), waitRaw = flag('wait-s'); +if (!dir) usage('run needs --dir <run dir>'); +if (!phase || !/^[A-Za-z0-9._-]+$/.test(phase)) usage('run needs --phase <n> (letters, digits, dot, underscore or dash)'); +if (!commands.length || commands.some(c => !c.trim())) usage("run needs the phase's commands after --, one argument each"); +if (waitRaw !== undefined && !/^\d+$/.test(waitRaw)) usage(`--wait-s '${waitRaw}' is not a whole number of seconds`); +try { + const out = await runPhase({ dir: dir!, phase: phase!, commands, record: flag('record'), waitS: waitRaw === undefined ? undefined : Number(waitRaw), cwd: process.cwd(), env: process.env }); + if (out.stdout.length) process.stdout.write(out.stdout.join('\n') + '\n'); + process.exit(out.exit); +} catch (e: any) { + process.stderr.write(`gstack-ship-phase: ${e?.message ?? e}\n`); + process.exit(e?.exit === 3 ? 3 : 2); +} diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 6d8b048e083..607dd3d00d1 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -3,7 +3,7 @@ * gstack-ship-receipt — the handoff record, identifiers first (plan C5). * * gstack-ship-receipt write [--pr <n>] [--head <sha>] [--base <ref>] [--version <X>] [--gated-tree <sha>] - * [--predecessor <sha>] [--gate <json|@file>] [--ci <json|@file>] [--spend-usd <n>] + * [--predecessor <sha>] [--gate <json|@file>] [--ci <json|@file>] [--spend-usd <n>] [--calls <n> | --budget-record <rec>] * [--session-kind <k>] [--artifacts-consumed <n>/<m>] [--run <id>] [--thread <id>] * [--receipt <tree-receipt.json>] [--policy <label>] [--preregistration <text>] [--history <text>] * [--pregate <pregate.json>] [--issues <json|@file>] [--approval <line>]... [--approval-run <dir>]... @@ -66,6 +66,7 @@ import { historyLine, placeRunEntry, prReviewHistory, reviewRoute, runStub } fro import { grantAt, readReviewRoundGrants } from '../lib/review-round-grant'; import { readMechanicalLines } from '../lib/ship-mechanical'; import { isRegistryUnavailable, loadRegistryFromBase } from '../lib/regen'; +import { runCalls } from '../lib/ship-clock'; const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt) @@ -108,6 +109,7 @@ const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block instead); any over (or absent) file exits 1 (DOCS_AUDIT_BLOCKED) write flags: --pr --head --base --version --gated-tree --predecessor --gate <json|@file> --ci <json|@file> --spend-usd + --calls <n> | --budget-record <rec> (calls=: the run's calls from the call log since gstack-ship-budget start; lib/ship-clock.ts) --session-kind --artifacts-consumed <n>/<m> --run --thread --receipt <tree-receipt.json> --policy --preregistration --history --queue-mode --pregate <pregate.json> (C8: refused unless current, green and every requires-remote obligation carries a receipt: PREGATE_STALE / PREGATE_LANE_FAILED / PREGATE_INCOMPLETE / PREGATE_REMOTE_UNCLEARED) --issues <json|@file> @@ -232,6 +234,15 @@ function ciCarried(base: string): ShipReceipt['ci_carried'] { try { const list = JSON.parse(r.stdout); return Array.isArray(list) && list.length ? list : undefined; } catch { return undefined; } } +/** calls= (G2): --calls <n>, or the run's count from the call log through its budget record; absent when neither is given or the log holds no row. */ +function callsArg(rest: string[]): number | undefined { + const raw = flag(rest, '--calls'); + if (raw !== undefined) { if (!/^\d+$/.test(raw)) throw new Error(`--calls '${raw}' is not a whole number`); return Number(raw); } + const record = flag(rest, '--budget-record'); + if (record === undefined) return undefined; + try { return runCalls(record, process.env) ?? undefined; } catch (e: any) { throw new Error(`--budget-record ${record}: ${e.message}`); } +} + function cmdWrite(rest: string[], json: boolean): number { const repoRoot = git(['rev-parse', '--show-toplevel']) ?? process.cwd(); const checkedOut = git(['rev-parse', 'HEAD'], repoRoot); @@ -350,6 +361,7 @@ function cmdWrite(rest: string[], json: boolean): number { tree: tree?.tree, gate_reuse: tree ? `${tree.gate_reuse} (${tree.gate_reuse_reason})` : undefined, gate: jsonArg(flag(rest, '--gate')), ci: jsonArg(flag(rest, '--ci')), ci_carried: carried, spend_usd: flag(rest, '--spend-usd') !== undefined ? (Number.isFinite(Number(flag(rest, '--spend-usd'))) ? Number(flag(rest, '--spend-usd')) : flag(rest, '--spend-usd')) : undefined, + calls: callsArg(rest), session_kind: sessionKind, artifacts_consumed: flag(rest, '--artifacts-consumed'), run: flag(rest, '--run'), thread: flag(rest, '--thread'), policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'), ...pregate, issues: issuesFile ? receiptIssuesFrom(issuesFile) : undefined, approval: approval.kind === 'ok' ? approval.approval : undefined, diff --git a/capy/skill/gstack/SKILL.md b/capy/skill/gstack/SKILL.md index fae0748875b..9c6fcb69725 100644 --- a/capy/skill/gstack/SKILL.md +++ b/capy/skill/gstack/SKILL.md @@ -46,7 +46,7 @@ Capy checklist for `/autoplan`: drive `gstack-autoplan`, never a hand adaptation Token caps on /ship: pass a brief's cap as `--token-cap <n>`. /ship reads `cost.tokens` and `cost.credits` from `tools.thread.get({ thread_id: "<your own jam id>" })` (its own jam; a subagent reading root `"this"` starts `--subagent --reading-from this --meter-scope tree`) inside the same execute program as the `gstack-ship-budget` command that takes them as `--reading <n> --credits <c>`, never alone. `ship/DRIVER.md` starts `--mode observe`: each program ends with `note`, and only a note past the cap stops (`docs/ship-budget.md`). -/ship on Capy is about a dozen calls, each an execute program (`ship/DRIVER.md`). Each review pass and Step 11 is one call to the checked-in pass program (fill only `input`): `const t0 = await now(); const p = (await tools.capy.bash({ command: ". '<launch file>' && gstack-review-dispatch program", description: "Pass" })).output.split("\n"); return p[0] + "\n" + (await new (Object.getPrototypeOf(async () => {}).constructor)("tools", "sleep", "now", "input", JSON.parse(p[1]))(tools, sleep, now, { startedAt: t0, launch: "<launch file>", cwd: "<repo>", base: "<base>", out: "<run dir>/p<n>", pass: "<run>-p<n>", laneModel: "<your model id>", planFlags: [], logStart: ["review"], jam: "<jam id>", record: "<rec>", step: "9.2" }));` It plans, logs `logStart` (`reservation` mode from `RESERVATION_ID:`), sends each brief on `machine: "shared"`, then polls: one `tools.subagent.list` per ~20 s tick, returning 200 s after the program's first line, where a reader is settled only at status `done` or `failed` or with a `summary` (a just-created `idle` reader has not run); it starts readers under `rejected` with `tools.subagent.start` as slots free and stops on one stuck 20 minutes. It ends on `NEXT:` (`poll`: rerun) or `STOP:`. `models` maps roles to models (`outside-voice`: another family, pinned in `voice-models.json`); Step 11 swaps `logStart` for `stage: "voices"`; a full repeat pass, `diffBase: "<RANGE_BASE>"`. Steps 7, 8 and 14.5 (`step: "14.5"`) use `extras`, JSON `{name, prompt_file, first, model}` (prompts verbatim from their sections, Step 7 `first`); they cannot block, so omit `model`: the pass prints `AUDIT_MODEL:`. Waits: never let 5 minutes pass between calls. While readers run, never end the turn on `wait`; rerun the loader. Else re-issue `wait` with `duration_seconds: 200` and operation ids. At Step 22 report the `CALLS:` line of `gstack-ship-budget calls --record <rec>`. A small waiting child saves nothing. +/ship on Capy is about a dozen calls, each an execute program (`ship/DRIVER.md`). Each review pass and Step 11 is one call to the checked-in pass program (fill only `input`): `const t0 = await now(); const p = (await tools.capy.bash({ command: ". '<launch file>' && gstack-review-dispatch program", description: "Pass" })).output.split("\n"); return p[0] + "\n" + (await new (Object.getPrototypeOf(async () => {}).constructor)("tools", "sleep", "now", "input", JSON.parse(p[1]))(tools, sleep, now, { startedAt: t0, launch: "<launch file>", cwd: "<repo>", base: "<base>", out: "<run dir>/p<n>", pass: "<run>-p<n>", laneModel: "<your model id>", planFlags: [], logStart: ["review"], jam: "<jam id>", record: "<rec>", step: "9.2" }));` It plans, logs `logStart` (`reservation` mode from `RESERVATION_ID:`), sends each brief on `machine: "shared"`, then polls: one `tools.subagent.list` per ~20 s tick, returning 200 s after the program's first line, where a reader is settled only at status `done` or `failed` or with a `summary` (a just-created `idle` reader has not run); it starts readers under `rejected` with `tools.subagent.start` as slots free and stops on one stuck 20 minutes. It ends on `NEXT:` (`poll`: rerun) or `STOP:`. `models` maps roles to models (`outside-voice`: another family, pinned in `voice-models.json`); Step 11 swaps `logStart` for `stage: "voices"`; a full repeat pass, `diffBase: "<RANGE_BASE>"`. Steps 7, 8 and 14.5 (`step: "14.5"`) use `extras`, JSON `{name, prompt_file, first, model}` (prompts verbatim from their sections, Step 7 `first`); they cannot block, so omit `model`: the pass prints `AUDIT_MODEL:`. Every other phase is one call to `gstack-ship-phase program`, loaded the same way, with `input` `{ startedAt, launch, cwd, dir: "<run dir>", phase: <n>, commands: ["<bin> …"], record, jam, step: "<last step>" }` (Phase 2's `gstack-ship-budget start` takes `--reading "$GSTACK_SHIP_READING" --credits "$GSTACK_SHIP_CREDITS"`; `pass: { … }` runs that pass after the commands); on `NEXT: rerun`, call it again unchanged. Waits under about 80 minutes: never let 5 minutes pass between calls. While readers run, never end the turn on `wait`; rerun the loader. Else re-issue `wait` with `duration_seconds: 200` and operation ids. A wait expected past 80 minutes (full CI) ends the turn on one `wait` on its operations; never poll every 10-15 minutes. `STOP: past 100 minutes`: report its `stop.json` and end. At Step 22 report the `CALLS:` line of `gstack-ship-budget calls --record <rec>`. A small waiting child saves nothing. ## Plan, approve, ship diff --git a/changelog.d/capy-run-each-driven-ship.md b/changelog.d/capy-run-each-driven-ship.md new file mode 100644 index 00000000000..66c3a5fa401 --- /dev/null +++ b/changelog.d/capy-run-each-driven-ship.md @@ -0,0 +1 @@ +- **A driven /ship now runs each phase as one command, counts its calls, and stops itself at 100 minutes.** `gstack-ship-phase run` runs a ship/DRIVER.md phase's commands in order, prints only their result lines, returns after 200 s while slow work keeps running, and on a rerun skips what already finished; on Capy, `gstack-ship-phase program` serves a checked-in program that also runs the review pass or the closing budget note in the same call. `gstack-ship-budget note` records the calls since the previous note, and `gstack-ship-receipt write --budget-record <rec>` puts the run's total in the receipt, so `SHIP_RECEIPT:` shows `calls=` (older receipts without it still validate and carry). Past 100 minutes, the note or the phase runner prints `STOP: past 100 minutes` and writes the head, review passes and next act to `stop.json`; `gstack-ship-budget resume` restarts the clock. The driver also prices waits by length. It keeps a 200 s keep-alive under about 80 minutes, uses one wait for anything longer, and never polls every 10-15 minutes. Measured conductors made 121 to 308 calls against the driver's 9 to 12 and 10 of 12 ran past the 100-minute line while these limits were prose. diff --git a/docs/ship-budget.md b/docs/ship-budget.md index 4df69e43c1c..5bd755e7648 100644 --- a/docs/ship-budget.md +++ b/docs/ship-budget.md @@ -31,9 +31,10 @@ delegated, so a run spends no call on the meter: each program the driver runs en gstack-ship-budget note --run <id> --step <last step> [--label <what ran>] --reading <tokens> --credits <credits> \ [--dispatched-at <tokens before the readers> --dispatched-credits <credits before> --readers <n>] -which prints `NOTE: <step>[:<label>] used=<n> credits=<c> [readers=<n> readers_tokens=<n> readers_credits=<c>]` -and the `BUDGET:` line. The cap is one hard stop: a note (or a check) whose `used + unknown` is past -`--token-cap` prints the stop block and exits 3, and nothing else stops the run. No review-log marker +which prints `NOTE: <step>[:<label>] used=<n> credits=<c> [readers=<n> readers_tokens=<n> readers_credits=<c>] [calls=<n>]` +and the `BUDGET:` line. `calls=` is the calls since the previous note, counted from the call log +(below), so `BUDGET_TIMELINE:` shows where a run's calls went. The cap is the one stop on spend: a note (or a check) whose `used + unknown` is past +`--token-cap` prints the stop block and exits 3. The other stop is the clock ([The 100-minute stop](#the-100-minute-stop)). No review-log marker is written, so `gstack-review-log --start` takes no `--reservation`, and `close` audits no unreserved dispatch. `close` prints `BUDGET_TIMELINE:`, one entry per note. The admission mode below is what `ship/SKILL.md` runs; it is unchanged. @@ -67,7 +68,8 @@ that did not note, then a loader 200 s or more later) and never below 0 are not in it. **Credits.** Every command that takes `--reading` also takes `--credits <cost.credits>` from the -same `thread.get`. Tokens count a cached read the same as a fresh one; credits are what the run +same `thread.get`; when Capy reports only `cost.dollars`, the checked-in phase and pass programs pass +`cost.dollars` x 1,000 instead. Tokens count a cached read the same as a fresh one; credits are what the run costs, including the full-context re-bill after a gap over five minutes (about 40x a cached call, handoffs/GSTA-167/cache-probe.md). The first credits reading is the baseline; the `BUDGET:`, `BUDGET_FINAL:` and record-block lines print `credits=<used>` once one exists, and a reading below @@ -75,6 +77,47 @@ the last is refused like a token reading ([BUDGET_READING_REJECTED](troubleshoot A successor thread's readings open a new epoch for credits as well as tokens ([Successor handoff](#successor-handoff)). +### The 100-minute stop + +ship/DRIVER.md stops a run past 100 minutes. Measured conductors ran past it in 10 of 12 runs while it was a +line of prose (handoffs/ship-conductor-cost-2026-11-16), so it is now code (`lib/ship-clock.ts`). In observe mode +the first `note`, or `gstack-ship-phase run --record`, past 100 minutes from the ledger's start prints + + STOP: past 100 minutes (<m> min since <start>) head=<sha12> rounds=<n> calls=<n> next=<next act> state=<ledger dir>/stop.json + RECOVER: hand <stop.json> to the next session; it runs gstack-ship-budget resume --record <rec> (the clock restarts), then reruns the phase that stopped + GSTACK_RESULT: skill=ship status=incomplete run=<ledger dir> + +and exits 3. `stop.json` holds the head, the review passes noted so far (`rounds`: Step 9 notes that dispatched +readers), the next act (the last line under the record's Next steps heading) and the run's calls, so the stop is a +clean handoff. Until `resume` the ledger stays stopped: every `note` and every `gstack-ship-phase run --record` +prints the stop again and runs nothing. `resume` prints `CLOCK: restarted at <iso>` and the next 100 minutes count +from there. Admission mode (`ship/SKILL.md`) has no clock. + +### The phase runner + +`gstack-ship-phase run --dir <run dir> --phase <n> [--record <rec>] [--wait-s 200] -- '<command>'...` runs one +driver phase's commands in order, each in the background with its output in `<run dir>/phases/<n>/<k>.log`, and +prints only result lines (`CODE: …` lines and `gstack-<bin>: …` refusals): `RAN: <k>/<N> exit=<c>` per command, +then `PHASE: <n> done`. A command still running after `--wait-s` keeps running; the run prints `WAITING:` and +`NEXT: rerun`, and the same command resumes the wait. A failed command prints `STOP:` (exit 3); after the fix, the +same command starts at it, because the journal (`phases/<n>/journal.json`) keeps each finished command by the +sha256 of its text. A command a restart killed runs again; a changed list stops a replaced command that still runs, then reruns from its first changed command. + +On Capy one call runs a whole phase: `gstack-ship-phase program` prints the checked-in program +`lib/capy-ship-phase.js`, loaded like the review pass program. It reads this jam's counter into +`$GSTACK_SHIP_READING` and `$GSTACK_SHIP_CREDITS` for the commands, runs `gstack-ship-phase run`, then either the +review pass program (`input.pass`) or the closing `note` with a fresh reading, then the next phase's section parts. + +**Waits priced by length.** A warm keep-alive at a conductor's average 231k-token context costs about $0.05 and a +cold re-cache about $1.16, so they break even at about 80 minutes of waiting (estimated). Keep the 200 s keep-alive +for expected waits under about 80 minutes; end the turn on one wait for longer ones (full CI, a long preflight); +never poll every 10 to 15 minutes, which pays a full re-cache each time. + +**calls= in the receipt.** `gstack-ship-receipt write --budget-record <rec>` (or `--calls <n>`) puts the run's +calls, start to write, in the receipt; `SHIP_RECEIPT:` prints `calls=<n>`. The count is the call log's +(`total_est` over the run): calls that ran a gstack command plus the keep-alive estimate, so quick calls that run +no gstack command are not in it. Receipts written before it have no `calls` and still validate, print and carry. + ## Quickstart **Capy.** Read your own jam's counter inside the execute program that runs the command, never as a diff --git a/lib/capy-review-pass.js b/lib/capy-review-pass.js index 38fed86e66a..14be511f593 100644 --- a/lib/capy-review-pass.js +++ b/lib/capy-review-pass.js @@ -88,7 +88,7 @@ const mark = async (reader, state, extra) => { const reading = async () => { if (!input.record || !input.jam) return null; const t = await tools.thread.get({ thread_id: input.jam }); - return { tokens: t.cost.tokens, credits: t.cost.credits }; + return { tokens: t.cost.tokens, credits: t.cost.credits ?? Math.round(Number(String(t.cost.dollars).replace(/[^0-9.]/g, '')) * 100000) / 100 }; }; const briefText = async (r) => { let text = ''; diff --git a/lib/capy-ship-phase.js b/lib/capy-ship-phase.js new file mode 100644 index 00000000000..9f6a12d9d52 --- /dev/null +++ b/lib/capy-ship-phase.js @@ -0,0 +1,69 @@ +// gstack /ship phase program for Capy (lib/capy-ship-phase.js, G2). The body of an async function (tools, sleep, now, input), +// served verbatim by `gstack-ship-phase program` and loaded the way capy/skill/gstack/SKILL.md loads the review pass program; +// never retyped. One call runs one ship/DRIVER.md phase end to end: +// 1. `gstack-ship-phase run` with input.commands, in order and resumable (lib/ship-phase.ts). With input.jam, this jam's +// cost.tokens and cost.credits (cost.dollars x 1,000 when the host reports only dollars) go to the commands as +// $GSTACK_SHIP_READING and $GSTACK_SHIP_CREDITS (gstack-ship-budget start). +// A command still running at 200 s returns NEXT: rerun: call the same program again with the same input. +// 2. With input.pass, the review pass program (gstack-review-dispatch program) on that pass's input: its dispatches, polls +// and closing note. Otherwise, with input.record and input.step, the closing `gstack-ship-budget note` with a fresh reading. +// 3. The next phase's section parts (`gstack-ship-parts next`) once Phase 2 started <dir>/parts. +// It returns result lines only, at most 32 KB; any STOP: line ends the phase (STOP: past 100 minutes included). +const T0 = input.startedAt ?? (await now()); +const RETURN_BYTES = 32000; +const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'"; +const lines = []; +const sh = async (cmd, env) => { + const pre = (input.launch ? '. ' + q(input.launch) + ' && ' : '') + (input.cwd ? 'cd ' + q(input.cwd) + ' && ' : '') + (env || ''); + const r = await tools.capy.bash({ command: pre + cmd, description: 'Ship phase ' + input.phase, timeout: 300 }); + return { code: r.exit_code, out: (r.output || '').trimEnd() }; +}; +const finish = () => { + const text = lines.join('\n'); + if (text.length <= RETURN_BYTES) return text; + const last = '\n(return capped at 32 KB; each command\'s log is under <dir>/phases)\n' + lines[lines.length - 1]; + return lines.slice(0, -1).join('\n').slice(0, Math.max(0, RETURN_BYTES - last.length)) + last; +}; +const push = (out) => { for (const l of out.split('\n')) if (l.trim()) lines.push(l); }; +const stopped = () => lines.some((l) => l.startsWith('STOP:')); +const reading = async () => { + const t = await tools.thread.get({ thread_id: input.jam }); + return { tokens: t.cost.tokens, credits: t.cost.credits ?? Math.round(Number(String(t.cost.dollars).replace(/[^0-9.]/g, '')) * 100000) / 100 }; +}; +if (!input.dir || input.phase === undefined || input.phase === null) return 'STOP: input.dir and input.phase are required; nothing ran'; +const commands = input.commands || []; +if (!Array.isArray(commands) || !commands.every((c) => typeof c === 'string' && c.trim())) return 'STOP: input.commands must be a list of shell command strings; nothing ran'; +if (commands.length) { + const r0 = input.jam ? await reading() : null; + const env = r0 ? 'GSTACK_SHIP_READING=' + r0.tokens + ' GSTACK_SHIP_CREDITS=' + r0.credits + ' ' : ''; + const run = await sh('gstack-ship-phase run --dir ' + q(input.dir) + ' --phase ' + q(input.phase) + (input.record ? ' --record ' + q(input.record) : '') + + ' --wait-s ' + Math.max(1, Math.round((T0 + (input.budgetMs || 200000) - (await now())) / 1000)) + ' -- ' + commands.map(q).join(' '), env); + push(run.out); + if (run.code !== 0 && !stopped()) lines.push('STOP: gstack-ship-phase run exited ' + run.code + '; nothing after it ran'); + if (run.code !== 0 || (lines.length && lines[lines.length - 1].startsWith('NEXT: rerun'))) return finish(); +} +if (input.pass) { + const p = await sh('gstack-review-dispatch program'); + const nl = p.out.indexOf('\n'); + if (p.code !== 0 || !p.out.startsWith('PROGRAM: ') || nl < 0) { lines.push('STOP: gstack-review-dispatch program exited ' + p.code + ': ' + p.out.slice(0, 300)); return finish(); } + lines.push(p.out.slice(0, nl)); + const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; + const passInput = Object.assign({ startedAt: T0, launch: input.launch, cwd: input.cwd, record: input.record, jam: input.jam }, input.pass); + push(String(await new AsyncFunction('tools', 'sleep', 'now', 'input', JSON.parse(p.out.slice(nl + 1).split('\n')[0]))(tools, sleep, now, passInput))); + return finish(); +} +if (input.record && input.step) { + if (!input.jam) { lines.push('STOP: the closing note needs input.jam (this jam\'s id) for its reading; the phase\'s commands ran'); return finish(); } + const r1 = await reading(); + const n = await sh('gstack-ship-budget note --record ' + q(input.record) + ' --step ' + q(input.step) + (input.label ? ' --label ' + q(input.label) : '') + + ' --reading ' + r1.tokens + ' --credits ' + r1.credits); + push(n.out); + if (n.code !== 0) { if (!stopped()) lines.push('STOP: gstack-ship-budget note exited ' + n.code + ' (its lines above say why)'); return finish(); } +} +const s = await sh('test -f ' + q(String(input.dir).replace(/\/+$/, '') + '/parts/state.json') + ' && echo started || true'); +if (s.out.startsWith('started') && /^\d+$/.test(String(input.phase))) { + const room = RETURN_BYTES - lines.join('\n').length - 200; + const p = await sh('gstack-ship-parts next --run ' + q(input.dir) + ' --phase ' + (Number(input.phase) + 1) + ' --room ' + Math.max(0, room)); + push(p.out); +} +return finish(); diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 927970c9a90..983ceb4ac33 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -102,6 +102,8 @@ export interface PregateFile { export interface ShipReceipt { schema_version: 1; head: string; base: string; pr?: number; version?: string; gated_tree?: string; gate?: Record<string, unknown>; ci?: Record<string, unknown>; spend_usd?: number | string; predecessor?: string; + /** The run's calls from the call log (lib/ship-clock.ts callsSince: gstack-command calls plus keep-alives), so a 200-call run shows at the receipt; absent on older receipts. */ + calls?: number; /** GSTA-258: the lanes CI carried at this head's tree, one entry per run (gstack-evidence carried). */ ci_carried?: Array<{ lane: string; run: number; attempt: number; tree: string; exception?: BoundLaneException }>; session_kind?: string; artifacts_consumed?: string; run?: string; @@ -263,7 +265,7 @@ export const ARTIFACT_SCHEMAS = { type: 'object', required: ['schema_version', 'head', 'base'], properties: { schema_version: { const: 1 }, pr: { type: 'integer' }, head: str, version: str, base: str, gated_tree: str, - gate: { type: 'object' }, ci: { type: 'object' }, spend_usd: { type: ['number', 'string'] }, predecessor: str, + gate: { type: 'object' }, ci: { type: 'object' }, spend_usd: { type: ['number', 'string'] }, calls: { type: 'integer', minimum: 0 }, predecessor: str, ci_carried: { type: 'array', items: { type: 'object', required: ['lane', 'run', 'attempt', 'tree'], properties: { lane: str, run: { type: 'integer', minimum: 1 }, attempt: { type: 'integer', minimum: 1 }, tree: str, exception: { type: 'object', required: ['head', 'files', 'by', 'reason', 'at', 'approval', 'preflight'], properties: { head: str, files: strList, by: str, reason: str, at: str, approval: str, preflight: { type: 'object', required: ['label', 'tests_ran'], properties: { label: str, tests_ran: { type: 'integer', minimum: 1 } } } } } } } }, diff --git a/lib/ship-budget-cli.ts b/lib/ship-budget-cli.ts index 6e4f605e0e5..c17221c1f6a 100644 --- a/lib/ship-budget-cli.ts +++ b/lib/ship-budget-cli.ts @@ -21,6 +21,7 @@ import { } from './ship-budget'; import { callLogFile, countLoggedCalls, loggedCallsLine, readCallLog } from './ship-call-log'; import { callsLine, countCalls } from './ship-calls'; +import { callsSince, timeStop } from './ship-clock'; import { claudeConfigDir, loadMeterState, newMeterState, nonceSessions, readClaudeUsage, saveMeterState, sessionJournals } from './claude-usage'; export type Opts = Record<string, string | true>; @@ -380,14 +381,15 @@ export function cmdClose(argv: string[], ctx: Ctx): Outcome { }); } -const noteText = (n: Note) => `${n.step}${n.label ? `:${n.label}` : ''} used=${n.used}${n.credits === undefined ? '' : ` credits=${n.credits}`}` +const noteText = (n: Note) => `${n.step}${n.label ? `:${n.label}` : ''} used=${n.used}${n.credits === undefined ? '' : ` credits=${n.credits}`}${n.calls === undefined ? '' : ` calls=${n.calls}`}` + (n.readers ? ` readers=${n.readers.n} readers_tokens=${n.readers.tokens}${n.readers.credits === undefined ? '' : ` readers_credits=${n.readers.credits}`}` : ''); /** * note: record one program's readings (tokens and credits) and, when --dispatched-at * brackets them, the readers it dispatched; stop only once used + unknown pass the cap. * It reserves, admits and delegates nothing: ship/DRIVER.md's observe runs end every - * program with it instead of a check at each boundary. + * program with it instead of a check at each boundary. It records the calls since the previous + * note (lib/ship-clock.ts), and in observe mode past 100 minutes it prints STOP: past 100 minutes. */ export function cmdNote(argv: string[], ctx: Ctx): Outcome { const o = parseArgs(argv, ['run', 'record', 'step', 'label', 'reading', 'credits', 'dispatched-at', 'dispatched-credits', 'readers']); @@ -406,9 +408,14 @@ export function cmdNote(argv: string[], ctx: Ctx): Outcome { const credits = creditsUsed(l); const readers = dispatched && l.meter.last !== null ? { n: dispatched.readers ?? 1, tokens: l.meter.last - dispatched.at, ...(before !== undefined && l.credits ? { credits: Math.round((l.credits.last - before) * 100) / 100 } : {}) } : undefined; - const n: Note = { step, ...(label ? { label } : {}), at: new Date().toISOString(), used: tally(l).used, ...(credits === null ? {} : { credits }), ...(readers ? { readers } : {}) }; + const at = new Date().toISOString(); + const prev = l.notes?.at(-1)?.at; + const calls = callsSince(ctx.env, prev ?? l.created_at, at, prev === undefined); + const n: Note = { step, ...(label ? { label } : {}), at, used: tally(l).used, ...(credits === null ? {} : { credits }), ...(readers ? { readers } : {}), ...(calls === null ? {} : { calls }) }; (l.notes ??= []).push(n); - return observed(l, step, label ?? step, null, `NOTE: ${noteText(n)}`); + const out = observed(l, step, label ?? step, null, `NOTE: ${noteText(n)}`); + const stop = out.exit === 0 ? timeStop(l, ctx.cwd, step, ctx.env) : null; + return stop ? { stdout: [out.stdout[0]!, ...stop], exit: 3 } : out; }); } @@ -480,8 +487,9 @@ export function cmdResume(argv: string[], ctx: Ctx): Outcome { } const was = l.stopped; delete l.stopped; + if (was?.reason === 'past_100_minutes') l.clock_from = new Date().toISOString(); pointMarker(l.marker, l); - return [`BUDGET_RUN: id=${l.run} ledger=${l.file}`, `RESUMED: from=${was ? `Step ${was.step} (${was.reason})` : 'running'}`, budgetLine(l, { call: null, next: was?.next ?? '-', projected: 0, verdict: 'continue' })]; + return [`BUDGET_RUN: id=${l.run} ledger=${l.file}`, `RESUMED: from=${was ? `Step ${was.step} (${was.reason})` : 'running'}`, ...(was?.reason === 'past_100_minutes' ? [`CLOCK: restarted at ${l.clock_from} (the 100-minute limit counts from here)`] : []), budgetLine(l, { call: null, next: was?.next ?? '-', projected: 0, verdict: 'continue' })]; }); return { stdout: [...lines, ...out], exit: 0 }; } diff --git a/lib/ship-budget.ts b/lib/ship-budget.ts index b9b7c4bd514..a05c5900d5a 100644 --- a/lib/ship-budget.ts +++ b/lib/ship-budget.ts @@ -70,7 +70,7 @@ export interface Reservation { starts?: Array<{ token: string; at: string }>; } /** One observation: the run's totals at a program's end, and the readers it dispatched when it measured them. */ -export interface Note { step: string; label?: string; at: string; used: number; credits?: number; readers?: { n: number; tokens: number; credits?: number } } +export interface Note { step: string; label?: string; at: string; used: number; credits?: number; readers?: { n: number; tokens: number; credits?: number }; calls?: number } export interface Sample { id: string; kind: 'step' | 'dispatch'; epoch: number; prior: number; projected: number; actual: number } export interface Handoff { n: number; sha: string; file: string; from: string; to: string; sub_cap: number; reservation: string; reading_at: number | null; @@ -102,6 +102,8 @@ export interface Ledger { /** tree: the reading is the root thread's counter (a subagent cannot read its own jam id), so every cost line carries TREE_METER. */ meter_scope?: 'tree'; stopped?: { at: string; reason: string; step: string; next: string }; closed_at?: string; + /** Where the 100-minute clock starts (lib/ship-clock.ts): created_at, or the resume after a time stop. */ + clock_from?: string; } /** A refusal: exit 2 for usage and validation (stderr), exit 3 for a stop. */ diff --git a/lib/ship-call-log.ts b/lib/ship-call-log.ts index d8cbdb34d8f..673dee5e02a 100644 --- a/lib/ship-call-log.ts +++ b/lib/ship-call-log.ts @@ -25,6 +25,12 @@ export interface LoggedCalls { } const NESTED = 'GSTACK_SHIP_CALL_NESTED'; +let pending: { bin: string; sub: string; started: number } | null = null; + +/** This process's own row as it will be written at exit (null when it writes none), for a count taken before it exits (lib/ship-clock.ts). */ +export function pendingRow(): CallRow | null { + return pending && { v: 1, bin: pending.bin, sub: pending.sub, start: new Date(pending.started).toISOString(), ms: Date.now() - pending.started, exit: 0 }; +} const ROTATE_BYTES = 8 * 1024 * 1024; const JOIN_MS = 5_000; const POLL_S = 200; @@ -41,6 +47,7 @@ export function logShipCall(bin: string, argv: string[] = process.argv.slice(2)) const started = Date.now(); const flag = (name: string) => { const i = argv.indexOf(`--${name}`); return i >= 0 ? argv[i + 1] : undefined; }; const num = (name: string) => { const v = Number(flag(name)); return flag(name) !== undefined && Number.isFinite(v) ? v : undefined; }; + pending = { bin, sub: argv[0] && !argv[0].startsWith('-') ? argv[0] : '', started }; process.on('exit', code => { try { const row: CallRow = { v: 1, bin, sub: argv[0] && !argv[0].startsWith('-') ? argv[0] : '', start: new Date(started).toISOString(), ms: Date.now() - started, exit: code }; diff --git a/lib/ship-clock.ts b/lib/ship-clock.ts new file mode 100644 index 00000000000..7a75899554f --- /dev/null +++ b/lib/ship-clock.ts @@ -0,0 +1,86 @@ +/** + * ship-clock — a driven /ship's 100-minute stop and its call count, in code instead of prose (ship/DRIVER.md). + * Measured conductors made 121-308 calls against the driver's 9 to 12, and 10 of 12 ran past its 100-minute stop + * (handoffs/ship-conductor-cost-2026-11-16), so the limits now print. An observe-mode run measures its time from + * the ledger's start, or from the resume that followed a time stop; the first `gstack-ship-budget note` or + * `gstack-ship-phase run` past 100 minutes stops the run and writes its state (head, review passes, next act) to + * <ledger dir>/stop.json, so the next session starts from that file and the record, not from memory. + * Calls come from the call log (lib/ship-call-log.ts): the calls that ran a gstack command plus its keep-alive + * estimate; quick calls that run no gstack command are not in it. + */ +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { ledgerFileFor, readLedger, type Ledger } from './ship-budget'; +import { callLogFile, countLoggedCalls, pendingRow, readCallLog } from './ship-call-log'; + +export const TIME_LIMIT_MIN = 100; +export const STOP_FILE = 'stop.json'; + +export const clockFrom = (l: Pick<Ledger, 'created_at' | 'clock_from'>) => l.clock_from ?? l.created_at; +export const elapsedMin = (l: Pick<Ledger, 'created_at' | 'clock_from'>, now = Date.now()) => (now - Date.parse(clockFrom(l))) / 60_000; + +/** + * Calls whose rows start after `since` (and at or before `until`): the log's calls plus its keep-alive estimate. + * Counting rows by start keeps two back-to-back windows from sharing a row. At the run's start (`fromRunStart`) a row + * still running at `since` counts too: the call that ran `gstack-ship-budget start` began before the ledger existed. + * This process's own row, written only at its exit, counts as if written. Null when the window holds none. + */ +export function callsSince(env: NodeJS.ProcessEnv, since: string, until?: string, fromRunStart = false): number | null { + const from = Date.parse(since), to = until ? Date.parse(until) : Infinity; + const self = pendingRow(); + const rows = [...readCallLog(callLogFile(env)), ...(self ? [self] : [])].filter(r => { const s = Date.parse(r.start); return s <= to && (s > from || (fromRunStart && s + Math.max(0, r.ms) >= from)); }); + if (!rows.length) return null; + const c = countLoggedCalls(rows); + return c.calls + c.keepaliveEst; +} + +/** A run's calls from its budget record, start to now (gstack-ship-receipt write --budget-record); null when the log holds none. */ +export function runCalls(record: string, env: NodeJS.ProcessEnv): number | null { + return callsSince(env, readLedger(ledgerFileFor({ record }, env)).created_at, undefined, true); +} + +const HEADING = /^\s*(?:[-*]\s*)?(?:#+\s*)?(?:\*\*)?(Release|Decisions|Reviews|Checks|Documentation|Next steps)(?:\*\*)?:?(?:\*\*)?(?:\s|$)/; + +/** The record's next act: the last line under its Next steps heading (one of the six lib/ship-handoff.ts names), else null. */ +export function nextAct(record: string | undefined): string | null { + if (!record) return null; + let text: string; + try { text = fs.readFileSync(record, 'utf8'); } catch { return null; } + const lines = text.split('\n'); + const at = lines.findIndex(l => HEADING.exec(l)?.[1] === 'Next steps'); + if (at < 0) return null; + const end = lines.findIndex((l, i) => i > at && (HEADING.test(l) || l.startsWith('```'))); + const body = lines.slice(at + 1, end < 0 ? lines.length : end).map(l => l.replace(/^\s*[-*]\s*/, '').trim()) + .filter(l => l && !l.startsWith('<!--')); + return body.at(-1) ?? null; +} + +const oneLine = (s: string) => s.replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, 300); + +/** + * The time stop: null while an observe-mode run is within 100 minutes (or already stopped or closed); past them it + * marks the ledger stopped, writes stop.json and returns the STOP block. The caller persists the ledger (mutateLedger). + */ +export function timeStop(l: Ledger, cwd: string, step: string, env: NodeJS.ProcessEnv, now = Date.now(), fallbackNext = `resume, then continue after Step ${step}`): string[] | null { + if (l.mode !== 'observe' || l.stopped || l.closed_at) return null; + const min = elapsedMin(l, now); + if (!(min > TIME_LIMIT_MIN)) return null; + const at = new Date(now).toISOString(); + const g = spawnSync('git', ['rev-parse', 'HEAD'], { cwd, encoding: 'utf8', timeout: 15_000 }); + const head = g.status === 0 ? g.stdout.trim() : 'unknown'; + const rounds = (l.notes ?? []).filter(n => n.step === '9' && n.readers).length; + const next = nextAct(l.record) ?? fallbackNext; + const calls = callsSince(env, l.created_at, at, true); + const file = path.join(l.dir, STOP_FILE); + const state = { schema_version: 1, kind: 'gstack-ship-stop', reason: 'past_100_minutes', run: l.run, record: l.record ?? null, at, + clock_from: clockFrom(l), elapsed_min: Math.floor(min), step, head, rounds, next, calls }; + fs.mkdirSync(l.dir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(file, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 }); + l.stopped = { at, reason: 'past_100_minutes', step, next }; + return [ + `STOP: past 100 minutes (${Math.floor(min)} min since ${clockFrom(l)}) head=${head.slice(0, 12)} rounds=${rounds} calls=${calls ?? 'unknown'} next=${oneLine(next)} state=${file}`, + `RECOVER: hand ${file} to the next session; it runs gstack-ship-budget resume --record ${l.record ?? '<record>'} (the clock restarts), then reruns the phase that stopped`, + `GSTACK_RESULT: skill=ship status=incomplete run=${l.dir}`, + ]; +} diff --git a/lib/ship-phase.ts b/lib/ship-phase.ts new file mode 100644 index 00000000000..c04fa829b12 --- /dev/null +++ b/lib/ship-phase.ts @@ -0,0 +1,123 @@ +/** + * ship-phase — one ship/DRIVER.md phase as one command (G2, handoffs/ship-conductor-cost-2026-11-16): measured + * conductors made 121-308 calls where the driver plans 9 to 12, so a phase's bins now run from one command. + * `run` executes the phase's commands in order, each in the background with its output in <dir>/phases/<phase>/, + * and prints only their result lines. A command still running when --wait-s ends (200 s) keeps running and the run + * prints `NEXT: rerun`: the same command resumes the wait. The journal keeps each finished command by the sha256 of + * its text, so a rerun after a failure or a restart starts at the first command that has not passed, and a command + * a restart killed runs again. With --record, a stopped run, or one past 100 minutes (lib/ship-clock.ts), refuses to + * start the phase and prints the STOP block. + */ +import { spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { ledgerFileFor, mutateLedger, parseRecordBlock } from './ship-budget'; +import { bashCommandInvocation } from './script-invocation'; +import { timeStop } from './ship-clock'; + +export interface PhaseEntry { sha: string; cmd: string; state: 'running' | 'done' | 'failed'; pid?: number; started: string; ended?: string; exit?: number; log: string; lines?: string[] } +export interface Journal { schema_version: 1; phase: string; entries: PhaseEntry[] } +export interface PhaseOut { stdout: string[]; exit: number } + +export const WAIT_S_DEFAULT = 200; +const MAX_LINES = 60; +const RESULT_RE = /^(?:[A-Z][A-Z0-9_]*(?:\([^)]*\))?|gstack-[a-z0-9-]+(?: [a-z0-9-]+)?): /; +const sha256 = (s: string) => createHash('sha256').update(s).digest('hex'); + +/** The lines of a command's output that a parent acts on: `CODE: …` result lines and `gstack-<bin>: …` refusals. */ +export function resultLines(text: string): string[] { + const hits = text.split('\n').map(l => l.trimEnd()).filter(l => RESULT_RE.test(l)).map(l => (l.length > 2000 ? l.slice(0, 2000) + ' …' : l)); + return hits.length > MAX_LINES ? [...hits.slice(0, MAX_LINES - 1), `(${hits.length - MAX_LINES + 1} more result lines in the log)`, hits[hits.length - 1]!] : hits; +} + +const alive = (pid: number | undefined) => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch { return false; } }; + +function readJournal(file: string, phase: string): Journal { + try { const j = JSON.parse(fs.readFileSync(file, 'utf8')); if (j?.schema_version === 1 && Array.isArray(j.entries)) return j; } catch { /* a new or unreadable journal starts over */ } + return { schema_version: 1, phase, entries: [] }; +} +function writeJournal(file: string, j: Journal): void { + fs.writeFileSync(`${file}.tmp`, JSON.stringify(j, null, 2) + '\n', { mode: 0o600 }); + fs.renameSync(`${file}.tmp`, file); +} + +/** Start one command detached: its output goes to the log and its exit status to <log>.exit when it ends, even after this process returns. */ +function start(cmd: string, log: string, cwd: string, env: NodeJS.ProcessEnv): number | undefined { + try { fs.rmSync(`${log}.exit`, { force: true }); } catch { /* absent */ } + const inv = bashCommandInvocation('( eval "$GSTACK_SHIP_PHASE_CMD" ) >"$GSTACK_SHIP_PHASE_LOG" 2>&1 </dev/null; echo $? >"$GSTACK_SHIP_PHASE_LOG.exit.tmp"; mv "$GSTACK_SHIP_PHASE_LOG.exit.tmp" "$GSTACK_SHIP_PHASE_LOG.exit"'); + if (!inv.ok) { fs.writeFileSync(log, `gstack-ship-phase: ${inv.error}\n`); fs.writeFileSync(`${log}.exit`, '127\n'); return undefined; } + const child = spawn(inv.cmd, inv.argv, { cwd, env: { ...env, GSTACK_SHIP_PHASE_CMD: cmd, GSTACK_SHIP_PHASE_LOG: log }, detached: true, stdio: 'ignore' }); + child.unref(); + return child.pid; +} + +/** The run's stop check before a phase starts: a stopped run, or one past 100 minutes; null to go on (no record, or no ledger yet). */ +function preflight(record: string | undefined, phase: string, cwd: string, env: NodeJS.ProcessEnv): string[] | null { + if (!record || !parseRecordBlock(record)?.ledger) return null; + return mutateLedger(ledgerFileFor({ record }, env), env, l => { + if (l.stopped) return [`STOP: run ${l.run} stopped (${l.stopped.reason}) at Step ${l.stopped.step}; nothing ran; resume first: gstack-ship-budget resume --record ${l.record}`, `GSTACK_RESULT: skill=ship status=incomplete run=${l.dir}`]; + return timeStop(l, cwd, `Phase ${phase}`, env, Date.now(), `resume, then rerun Phase ${phase}`); + }); +} + +export interface RunOpts { dir: string; phase: string; commands: string[]; record?: string; waitS?: number; cwd: string; env: NodeJS.ProcessEnv; pollMs?: number } + +/** run: the phase's commands in order, resumable from the journal; see the header. */ +export async function runPhase(o: RunOpts): Promise<PhaseOut> { + const t0 = Date.now(); + const deadline = t0 + (o.waitS ?? WAIT_S_DEFAULT) * 1000; + const stopped = preflight(o.record, o.phase, o.cwd, o.env); + if (stopped) return { stdout: stopped, exit: 3 }; + const dir = path.join(path.resolve(o.dir), 'phases', o.phase); + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + const file = path.join(dir, 'journal.json'); + const j = readJournal(file, o.phase); + const out: string[] = []; + const n = o.commands.length; + const firstChanged = j.entries.findIndex((e, i) => i >= n || e.sha !== sha256(o.commands[i]!)); + if (firstChanged >= 0) { + const live = j.entries.slice(firstChanged).filter(e => e.state === 'running' && alive(e.pid)); + for (const e of live) { + out.push(`REPLACED: ${j.entries.indexOf(e) + 1}/${n} pid=${e.pid} ran a command this list no longer names; stopping it (log=${e.log})`); + try { process.kill(-e.pid!, 'SIGTERM'); } catch { /* already gone */ } + } + for (let t = 0; t < 50 && live.some(e => alive(e.pid)); t++) await Bun.sleep(100); + const stuck = live.filter(e => alive(e.pid)); + if (stuck.length) return { stdout: [...out, `STOP: phase ${o.phase}: replaced command pid ${stuck.map(e => e.pid).join(',')} is still running and shares its log and exit file with the new list; stop it (kill -- -<pid>), then rerun the same command`], exit: 3 }; + j.entries.length = firstChanged; + } + for (let i = 0; i < n; i++) { + const cmd = o.commands[i]!; + const k = `${i + 1}/${n}`; + let e = j.entries[i]; + if (e?.state === 'done') { out.push(`RAN: ${k} exit=0 (done earlier)`, ...(e.lines ?? [])); continue; } + if (!e || e.state === 'failed' || (e.state === 'running' && !alive(e.pid) && !fs.existsSync(`${e.log}.exit`))) { + const log = path.join(dir, `${i + 1}.log`); + e = j.entries[i] = { sha: sha256(cmd), cmd, state: 'running', started: new Date().toISOString(), log }; + e.pid = start(cmd, log, o.cwd, o.env); + writeJournal(file, j); + } + while (!fs.existsSync(`${e.log}.exit`)) { + if (Date.now() >= deadline) { + const ran = Math.round((Date.now() - Date.parse(e.started)) / 1000); + out.push(`WAITING: ${k} pid=${e.pid ?? 'unknown'} running=${ran}s log=${e.log}`, `NEXT: rerun (the same gstack-ship-phase command resumes the wait; commands before ${i + 1} stay done)`); + return { stdout: out, exit: 0 }; + } + if (!alive(e.pid) && !fs.existsSync(`${e.log}.exit`)) { await Bun.sleep(200); if (!fs.existsSync(`${e.log}.exit`)) break; } + await Bun.sleep(o.pollMs ?? 500); + } + const raw = fs.existsSync(`${e.log}.exit`) ? fs.readFileSync(`${e.log}.exit`, 'utf8').trim() : ''; + const code = /^\d+$/.test(raw) ? Number(raw) : -1; + const text = fs.existsSync(e.log) ? fs.readFileSync(e.log, 'utf8') : ''; + e.exit = code; e.ended = new Date().toISOString(); e.lines = resultLines(text); e.state = code === 0 ? 'done' : 'failed'; + writeJournal(file, j); + out.push(`RAN: ${k} exit=${code < 0 ? 'lost' : code}${code === 0 ? '' : ` log=${e.log}`}`, ...e.lines); + if (code === 0) continue; + if (!e.lines.length) out.push(...text.trimEnd().split('\n').slice(-5).map(l => ` | ${l.slice(0, 500)}`)); + out.push(`STOP: phase ${o.phase} command ${k} exited ${code < 0 ? 'without a status (killed?)' : code}; fix the cause, then rerun the same command (commands before ${i + 1} stay done)`); + return { stdout: out, exit: 3 }; + } + out.push(`PHASE: ${o.phase} done commands=${n} elapsed_s=${Math.round((Date.now() - t0) / 1000)} journal=${file}`); + return { stdout: out, exit: 0 }; +} diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index be73f6cdaba..a65895b27db 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -21,7 +21,7 @@ import { stampOnlyLine, type BranchSide } from './stamp-only'; export const RECEIPT_FENCE = 'gstack-ship-receipt'; const KEY_ORDER: Array<keyof ShipReceipt | 'docs'> = [ - 'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', + 'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', 'calls', 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history', 'head_tree', 'product_patch_id', 'gstack_version', 'review_depth', 'pregate', 'requires_remote', 'issues', 'approval', 'docs', 'review_loop', 'review_loop_exception', 'review_round_grants', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'carry', 'base_red', 'flaky_exception', 'no_stop', @@ -200,6 +200,7 @@ export function receiptSummaryLine(r: ShipReceipt): string { if (r.predecessor) parts.push(`predecessor=${r.predecessor.slice(0, 12)}`); if (r.session_kind) parts.push(`session_kind=${r.session_kind}`); if (r.artifacts_consumed) parts.push(`artifacts_consumed=${r.artifacts_consumed}`); + if (typeof r.calls === 'number') parts.push(`calls=${r.calls}`); if (r.review_depth && typeof r.review_depth.depth === 'string') parts.push(`depth=${r.review_depth.depth}`); if (r.approval) parts.push(`approval=${approvalSummary(r.approval)}`); const loop = parseReviewLoop(r.review_loop); diff --git a/ship/DRIVER.md b/ship/DRIVER.md index e50f772b885..e43f0066039 100644 --- a/ship/DRIVER.md +++ b/ship/DRIVER.md @@ -7,16 +7,16 @@ Read this, not `ship/SKILL.md`, when a parent agent runs /ship the `GSTACK_LAUNCH` assignments your installer printed (`. <its GSTACK_LAUNCH_FILE>`), never `export $(...)`, `env`, `printenv` or a bare `set` in a tool fence. -**Rules.** Each phase below is one call: one program (Capy: execute; else a script) -that runs the bins, reads, dispatches and waits, returning only result lines and reader -outputs verbatim. The model keeps only lead judgment, fixes, CHANGELOG, PR prose, +**Rules.** Each phase below is one call: `gstack-ship-phase run --dir <run dir> --phase <n> --record <rec> -- <cmds>` +runs its bins, reads, dispatches and waits, returning only result lines and reader +outputs verbatim. The model keeps only judgment, fixes, CHANGELOG, PR prose, gates, the report. `STOP:` (exit 3) means nothing after it ran; `NEXT:` names the next act. Read a section only when a phase or the list below sends you, never up front. A STOP or decision this file does not cover: read `ship/SKILL.md` at that step, finish there, come back. Unattended, take a question's recommended option (log it); gate dispositions and approvals stay pending and end the run, except `gstack-no-stop`. Keep a record (`--record`): write its six headings at Phase 1, fill each per phase: **Checks** (Phases 2-4: lanes, pregate, evals, `Coverage:`, the plan checks, `Exploratory QA:`, `Scope Check:`), **Decisions** (any -phase: each answered or auto-taken question, verbatim), **Reviews** (Phases 3-5: the plan line, +phase: questions and answers, verbatim), **Reviews** (Phases 3-5: the plan line, start tokens, `Pre-Landing Review:`, `Gate edits:`, the reviewed tree), **Release** (Phases 5-7: version, CHANGELOG, commits), **Documentation** (Step 14.5) and **Next steps** (every phase: the next act). @@ -27,18 +27,18 @@ file, unchanged; its findings reach `merged.jsonl` only via `collect`; `judge` r 14.5 once; findings go to the PR body. **Calls.** One pass with no fixes is 9 calls: Phases 1-8 and the report; at most 12 with a STOP's -section read or fix-check, plus a keep-alive per 200 s waited. +section read or fix-check, plus a keep-alive per 200 s waited under ~80 min (longer: end the turn on one wait; no 10-15 min polls). -**Budget: observe.** `gstack-ship-budget start --mode observe` records, never admits: each program ends -with `gstack-ship-budget note --step <last step> --reading R --credits C --record <rec>`, R and C read in that program +**Budget: observe.** `gstack-ship-budget start --mode observe` only records: each program ends +with `gstack-ship-budget note --step <last step> --reading R --credits C --record <rec>`, R and C read in it (Capy: `cost.tokens`, `cost.credits`). No check per step, no reservation, no meter-only -call, no handoff; under `--token-cap` a note past the cap prints `verdict=stop`, the one stop check. -A dispatching program takes `BEFORE` (R and C) as readers start and passes -`--dispatched-at <R> --dispatched-credits <C> --readers <n>` with the reading after the last settles. +call, no handoff; under `--token-cap` a note past the cap prints `verdict=stop`, the one stop check on spend. +A dispatching program passes `--dispatched-at <R> --dispatched-credits <C> --readers <n>` (`BEFORE`). **Waits.** No call waits past 200 s: a program returns what still runs 200 s after its first line; the next call resumes the poll. Lanes, pregate, `finish` run in background; after a restart, rerun the same command. Never end the turn while -readers run (each wakes it). A small waiting child saves nothing. Past 100 minutes, stop. Returns: +readers run. A small waiting child saves nothing. Past 100 minutes the run stops: +`STOP: past 100 minutes`, state in `stop.json`. Returns: ≤32 KB per program; split longer reads at headings, each byte once, before first use: phase programs end with `gstack-ship-parts next --run <run dir> --phase <n+1> --room <32000 - its output>`; on `NEXT: parts` run it alone. @@ -63,8 +63,8 @@ Install check, this file. `gstack-ship-preflight --base <base> --run <run dir name> --lane <label>=<test command>...`. `CARRY: carried` ends the run on its `GSTACK_RESULT:` line. `ship_lanes_from`: push early (`sections/tests.md#ci-carry`). A lane passes on `tests_ran: N` with exit 0; `0` is ZERO-RUN (failed); `unknown` is `count unavailable`. In-branch failures stop; after a repair rerun `--tests-only`. -`requires-remote` needs `gstack-pregate clear` before Step 18. When prompts, templates, judges or eval -harness changed, start the eval selector and pre-merge command (detached past 30 min); else +`requires-remote` needs `gstack-pregate clear` before Step 18. Changed prompts, templates, judges or eval +harness: start the eval selector and pre-merge command (detached past 30 min); else record `evals: none affected`. Step 6.5 runs only if `gstack-greptile-early detect` finds Greptile. Then `gstack-ship-preflight --audit --base <base> --out <run dir>` writes the diff once (`CONTEXT:`) and the TODOS.md items on touched paths (`TODOS:`); prints the coverage map, @@ -92,7 +92,7 @@ pass with `fixCheck: {fix_list, hunks, tests, callers}`; `done` or `voices`: tha Judge the voices; missing outside coverage is `unavailable`, never clean; queued fixes rerun Phases 3-4. Then `gstack-review-dispatch verify` (`VERIFY: clean`) and `gstack-review-read`: the final Step 9 and Step 11 native rows (or `CURRENT` freshness -after a planned skip) agree on `wtree`, `start_wtree`, `end_wtree`; save that tree and base `<b>`. Then +after a planned skip) agree on their trees; save that tree and base `<b>`. Then `gstack-ship-release version --base <base> [--bump micro|patch] --why '<line>'`; MINOR, MAJOR, `BUMP_ANSWER_REQUIRED`: approvals; `VERSION: skipped|kept`: no write. @@ -106,7 +106,7 @@ One re-audit at most. ## 7. Release: Steps 15, 16, 17 -Commit in bisectable chunks; `gstack-ship-release finish --base <base> --reviewed-tree <t> --reviewed-base <b> +Commit bisectably; `gstack-ship-release finish --base <base> --reviewed-tree <t> --reviewed-base <b> --docs-post <post> --lane ... [--build <cmd>] --trailer '<t>' [--plan <line>]`: `PLAN:`, `ROUTE:`, `DOCS:`, `EVIDENCE:` (FRESH; STALE or MISSING reruns once), `PREGATE:`; print them, the last `Gate edits:` and each `tests_ran`. Then `gstack-ship-release push --branch <branch> [--gate-open <n>]`: `REDACT_PREPUSH:`, `SEALED:`, `GUARDS:`, `PUSH:` @@ -116,9 +116,9 @@ repo gates run beside CI. Unattended, push defers the pre-push offer; else its S ## 8. Publish: Steps 18, 19, 19-C, 20, 21, 22 - Step 18: the open-PR lookup; a plain `v<NEW_VERSION> ` title (`gstack-plain-title check`). `UNATTENDED_SHIP:` with no open PR at HEAD takes Step 18-H. -- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint <top> --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run <dir> && gstack-ship-receipt write --pr <n> --base <base> --gate @<f> --pregate <f> --issues @<f> --review-loop @<f> --docs @<f> [--review-exclude <d>] [--review-targeted @<f>] --body <body>`; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report. +- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint <top> --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run <dir> && gstack-ship-receipt write --pr <n> --base <base> --gate @<f> --pregate <f> --issues @<f> --review-loop @<f> --docs @<f> --budget-record <rec> [--review-exclude <d>] [--review-targeted @<f>] --body <body>`; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report. - Step 20: a metrics row via `gstack-review-log`. -- Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:` (tokens, credits), any `METER:` line), then `gstack-ship-receipt result --pr <n>`: `GSTACK_RESULT: skill=ship status=complete head=<sha> run=<dir>`. Under a merge queue, `gstack-ship-queue ready --pr <n> [--screen|--no-screen]` at the pushed head; paste its output. +- Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:`, any `METER:` line), then `gstack-ship-receipt result --pr <n>`: `GSTACK_RESULT: skill=ship status=complete head=<sha> run=<dir>`. Under a merge queue, `gstack-ship-queue ready --pr <n> [--screen|--no-screen]` at the pushed head; paste its output. ## Where each STOP sends you (paths under `<root>/ship/`) diff --git a/ship/DRIVER.md.tmpl b/ship/DRIVER.md.tmpl index 72a39e0c7ee..1dd4beef528 100644 --- a/ship/DRIVER.md.tmpl +++ b/ship/DRIVER.md.tmpl @@ -5,16 +5,16 @@ Read this, not `ship/SKILL.md`, when a parent agent runs /ship the `GSTACK_LAUNCH` assignments your installer printed (`. <its GSTACK_LAUNCH_FILE>`), never `export $(...)`, `env`, `printenv` or a bare `set` in a tool fence. -**Rules.** Each phase below is one call: one program (Capy: execute; else a script) -that runs the bins, reads, dispatches and waits, returning only result lines and reader -outputs verbatim. The model keeps only lead judgment, fixes, CHANGELOG, PR prose, +**Rules.** Each phase below is one call: `gstack-ship-phase run --dir <run dir> --phase <n> --record <rec> -- <cmds>` +runs its bins, reads, dispatches and waits, returning only result lines and reader +outputs verbatim. The model keeps only judgment, fixes, CHANGELOG, PR prose, gates, the report. `STOP:` (exit 3) means nothing after it ran; `NEXT:` names the next act. Read a section only when a phase or the list below sends you, never up front. A STOP or decision this file does not cover: read `ship/SKILL.md` at that step, finish there, come back. Unattended, take a question's recommended option (log it); gate dispositions and approvals stay pending and end the run, except `gstack-no-stop`. Keep a record (`--record`): write its six headings at Phase 1, fill each per phase: **Checks** (Phases 2-4: lanes, pregate, evals, `Coverage:`, the plan checks, `Exploratory QA:`, `Scope Check:`), **Decisions** (any -phase: each answered or auto-taken question, verbatim), **Reviews** (Phases 3-5: the plan line, +phase: questions and answers, verbatim), **Reviews** (Phases 3-5: the plan line, start tokens, `Pre-Landing Review:`, `Gate edits:`, the reviewed tree), **Release** (Phases 5-7: version, CHANGELOG, commits), **Documentation** (Step 14.5) and **Next steps** (every phase: the next act). @@ -25,18 +25,18 @@ file, unchanged; its findings reach `merged.jsonl` only via `collect`; `judge` r 14.5 once; findings go to the PR body. **Calls.** One pass with no fixes is 9 calls: Phases 1-8 and the report; at most 12 with a STOP's -section read or fix-check, plus a keep-alive per 200 s waited. +section read or fix-check, plus a keep-alive per 200 s waited under ~80 min (longer: end the turn on one wait; no 10-15 min polls). -**Budget: observe.** `gstack-ship-budget start --mode observe` records, never admits: each program ends -with `gstack-ship-budget note --step <last step> --reading R --credits C --record <rec>`, R and C read in that program +**Budget: observe.** `gstack-ship-budget start --mode observe` only records: each program ends +with `gstack-ship-budget note --step <last step> --reading R --credits C --record <rec>`, R and C read in it (Capy: `cost.tokens`, `cost.credits`). No check per step, no reservation, no meter-only -call, no handoff; under `--token-cap` a note past the cap prints `verdict=stop`, the one stop check. -A dispatching program takes `BEFORE` (R and C) as readers start and passes -`--dispatched-at <R> --dispatched-credits <C> --readers <n>` with the reading after the last settles. +call, no handoff; under `--token-cap` a note past the cap prints `verdict=stop`, the one stop check on spend. +A dispatching program passes `--dispatched-at <R> --dispatched-credits <C> --readers <n>` (`BEFORE`). **Waits.** No call waits past 200 s: a program returns what still runs 200 s after its first line; the next call resumes the poll. Lanes, pregate, `finish` run in background; after a restart, rerun the same command. Never end the turn while -readers run (each wakes it). A small waiting child saves nothing. Past 100 minutes, stop. Returns: +readers run. A small waiting child saves nothing. Past 100 minutes the run stops: +`STOP: past 100 minutes`, state in `stop.json`. Returns: ≤32 KB per program; split longer reads at headings, each byte once, before first use: phase programs end with `gstack-ship-parts next --run <run dir> --phase <n+1> --room <32000 - its output>`; on `NEXT: parts` run it alone. @@ -61,8 +61,8 @@ Install check, this file. `gstack-ship-preflight --base <base> --run <run dir name> --lane <label>=<test command>...`. `CARRY: carried` ends the run on its `GSTACK_RESULT:` line. `ship_lanes_from`: push early (`sections/tests.md#ci-carry`). A lane passes on `tests_ran: N` with exit 0; `0` is ZERO-RUN (failed); `unknown` is `count unavailable`. In-branch failures stop; after a repair rerun `--tests-only`. -`requires-remote` needs `gstack-pregate clear` before Step 18. When prompts, templates, judges or eval -harness changed, start the eval selector and pre-merge command (detached past 30 min); else +`requires-remote` needs `gstack-pregate clear` before Step 18. Changed prompts, templates, judges or eval +harness: start the eval selector and pre-merge command (detached past 30 min); else record `evals: none affected`. Step 6.5 runs only if `gstack-greptile-early detect` finds Greptile. Then `gstack-ship-preflight --audit --base <base> --out <run dir>` writes the diff once (`CONTEXT:`) and the TODOS.md items on touched paths (`TODOS:`); prints the coverage map, @@ -90,7 +90,7 @@ pass with `fixCheck: {fix_list, hunks, tests, callers}`; `done` or `voices`: tha Judge the voices; missing outside coverage is `unavailable`, never clean; queued fixes rerun Phases 3-4. Then `gstack-review-dispatch verify` (`VERIFY: clean`) and `gstack-review-read`: the final Step 9 and Step 11 native rows (or `CURRENT` freshness -after a planned skip) agree on `wtree`, `start_wtree`, `end_wtree`; save that tree and base `<b>`. Then +after a planned skip) agree on their trees; save that tree and base `<b>`. Then `gstack-ship-release version --base <base> [--bump micro|patch] --why '<line>'`; MINOR, MAJOR, `BUMP_ANSWER_REQUIRED`: approvals; `VERSION: skipped|kept`: no write. @@ -104,7 +104,7 @@ One re-audit at most. ## 7. Release: Steps 15, 16, 17 -Commit in bisectable chunks; `gstack-ship-release finish --base <base> --reviewed-tree <t> --reviewed-base <b> +Commit bisectably; `gstack-ship-release finish --base <base> --reviewed-tree <t> --reviewed-base <b> --docs-post <post> --lane ... [--build <cmd>] --trailer '<t>' [--plan <line>]`: `PLAN:`, `ROUTE:`, `DOCS:`, `EVIDENCE:` (FRESH; STALE or MISSING reruns once), `PREGATE:`; print them, the last `Gate edits:` and each `tests_ran`. Then `gstack-ship-release push --branch <branch> [--gate-open <n>]`: `REDACT_PREPUSH:`, `SEALED:`, `GUARDS:`, `PUSH:` @@ -114,9 +114,9 @@ repo gates run beside CI. Unattended, push defers the pre-push offer; else its S ## 8. Publish: Steps 18, 19, 19-C, 20, 21, 22 - Step 18: the open-PR lookup; a plain `v<NEW_VERSION> ` title (`gstack-plain-title check`). `UNATTENDED_SHIP:` with no open PR at HEAD takes Step 18-H. -- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint <top> --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run <dir> && gstack-ship-receipt write --pr <n> --base <base> --gate @<f> --pregate <f> --issues @<f> --review-loop @<f> --docs @<f> [--review-exclude <d>] [--review-targeted @<f>] --body <body>`; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report. +- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint <top> --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run <dir> && gstack-ship-receipt write --pr <n> --base <base> --gate @<f> --pregate <f> --issues @<f> --review-loop @<f> --docs @<f> --budget-record <rec> [--review-exclude <d>] [--review-targeted @<f>] --body <body>`; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report. - Step 20: a metrics row via `gstack-review-log`. -- Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:` (tokens, credits), any `METER:` line), then `gstack-ship-receipt result --pr <n>`: `GSTACK_RESULT: skill=ship status=complete head=<sha> run=<dir>`. Under a merge queue, `gstack-ship-queue ready --pr <n> [--screen|--no-screen]` at the pushed head; paste its output. +- Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:`, any `METER:` line), then `gstack-ship-receipt result --pr <n>`: `GSTACK_RESULT: skill=ship status=complete head=<sha> run=<dir>`. Under a merge queue, `gstack-ship-queue ready --pr <n> [--screen|--no-screen]` at the pushed head; paste its output. ## Where each STOP sends you (paths under `<root>/ship/`) diff --git a/test/exercised-map.test.ts b/test/exercised-map.test.ts index 8704fc1df91..57772a3429d 100644 --- a/test/exercised-map.test.ts +++ b/test/exercised-map.test.ts @@ -330,6 +330,7 @@ describe('parity with the measured prototype', () => { 'lib/eval-plan-checks.ts': 'lib/eval-plan.ts and bin/gstack-eval-plan import it (the result checks), so it reaches every consumer of the eval planner', 'lib/ship-receipt-docs.ts': 'bin/gstack-ship-receipt imports it (the docs audit record and doc caps), so it reaches every consumer of the receipt binary', 'lib/ship-receipt-prose.ts': 'bin/gstack-ship-receipt imports it (read --check-prose), so it reaches every consumer of the receipt binary', + 'lib/ship-clock.ts': 'G2: bin/gstack-ship-receipt (write --budget-record), lib/ship-budget-cli.ts (note, resume) and lib/ship-phase.ts import it, so it reaches every consumer of the receipt and budget binaries', 'lib/default-base.ts': 'GST-511/GST-774: lib/ship-policy.ts (resolveBaseBranch), lib/gate-diff/git.ts, lib/pregate/context.ts, lib/ship-receipt-depth.ts and the review-plan, gate-diff, pregate, docs-candidate and diff-scope bins import or run it, so it reaches every consumer of those readers', }; diff --git a/test/review-pass.test.ts b/test/review-pass.test.ts index fbda28eb5d5..1e3eae6bbae 100644 --- a/test/review-pass.test.ts +++ b/test/review-pass.test.ts @@ -841,6 +841,19 @@ describe('Capy pass program (fake host, real bins)', () => { expect(res).not.toContain('NEXT: judge'); }, 240_000); + // Value: protects=a host whose thread.get reports cost.dollars and no cost.credits still notes the pass with a credits reading (1,000 credits a dollar); fails_when=the pass passes --credits undefined and its note refuses it; + // why_new=Capy's thread.get returned only cost.dollars on 2026-11-17; seam=tools.thread.get stub; no_claim=Capy's own pricing + test('a host that reports only cost.dollars still notes the pass in credits', async () => { + const { dir, env } = repo(); + const rec = path.join(dir, '.state/rec.md'); + fs.mkdirSync(path.dirname(rec), { recursive: true }); + expect(spawnSync('bash', ['-c', 'gstack-ship-budget start --record "$1" --mode observe --reading 1000 --credits 1', '_', rec], { cwd: dir, env, encoding: 'utf8', timeout: 60_000 }).status).toBe(0); + const h = host(dir, env); + h.tools.thread.get = async () => ({ cost: { tokens: 2000, dollars: '$0.05' } }) as never; + const res = await runPass(h, { base: 'main', out: path.join(dir, '.state/run/p1'), pass: 'x15d', planFlags: ['--depth-floor', 'full'], record: rec, jam: 'jam_test', step: '9' }); + expect(res).toMatch(/NOTE: \S+ used=\d+ credits=49 /); + }, 240_000); + test('Step 14.5 runs as an audit-only pass: its docs reader alone, verbatim, with no reviewer plan', async () => { const { dir, env } = repo(); const out = path.join(dir, '.state/run/docs'); diff --git a/test/ship-phase.test.ts b/test/ship-phase.test.ts new file mode 100644 index 00000000000..499f998b114 --- /dev/null +++ b/test/ship-phase.test.ts @@ -0,0 +1,330 @@ +/** + * G2 (handoffs/fold-subagents-2026-11-17, handoffs/ship-conductor-cost-2026-11-16): ship/DRIVER.md's limits in tools. + * Measured conductors made 121-308 calls against the driver's 9 to 12 and 10 of 12 ran past its 100-minute stop, so + * a phase now runs as one gstack-ship-phase command (resumable from its journal), every note records its calls, the + * receipt carries calls=, and the first note or phase past 100 minutes prints STOP: past 100 minutes with the run's + * state on disk. All checks here are free: real bins on fixture repositories, and the Capy phase program on a fake host + * whose shell is real. + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { extractReceipt, orderReceipt, placeReceipt, receiptSummaryLine, validateReceipt } from '../lib/ship-receipt'; +import { resultLines } from '../lib/ship-phase'; +import { cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const BIN_DIR = path.join(ROOT, 'bin'); +const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ship-phase-'))); +const repos: FixtureRepo[] = []; +afterAll(() => { fs.rmSync(tmp, { recursive: true, force: true }); while (repos.length) cleanup(repos.pop()!); }); + +interface Box { root: string; repo: string; state: string; record: string; env: NodeJS.ProcessEnv } +let n = 0; +/** A git fixture with a feature branch, a state root and an invocation record whose Next steps names the next act. */ +function box(): Box { + const root = path.join(tmp, `box-${++n}`); + const repo = path.join(root, 'repo'); + fs.mkdirSync(path.join(repo, 'src'), { recursive: true }); + const env = { ...process.env, GSTACK_STATE_ROOT: path.join(root, 'state'), GSTACK_CAPY: '1', GSTACK_SHIP_CALL_NESTED: '', GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@example.com', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@example.com' }; + const git = (...a: string[]) => { const r = spawnSync('git', a, { cwd: repo, env, encoding: 'utf8', timeout: 30_000 }); if (r.status !== 0) throw new Error(r.stderr); return r.stdout.trim(); }; + git('init', '-q', '-b', 'main'); + fs.writeFileSync(path.join(repo, 'src', 'a.ts'), 'export const a = 1;\n'); + fs.writeFileSync(path.join(repo, 'package.json'), '{"name":"fixture","scripts":{"test":"true"}}\n'); + git('add', '-A'); git('commit', '-qm', 'init'); + git('checkout', '-qb', 'feat'); + fs.writeFileSync(path.join(repo, 'src', 'b.ts'), 'export const b = 2;\n'); + git('add', '-A'); git('commit', '-qm', 'feat: b'); + git('update-ref', 'refs/remotes/origin/main', 'main'); + const record = path.join(root, 'record.md'); + fs.writeFileSync(record, '# /ship record\n\n## Checks\n## Decisions\n## Reviews\n## Release\n## Documentation\n## Next steps\n- Phase 3: audits and review\n'); + return { root, repo, state: path.join(root, 'state'), record, env }; +} +const bin = (b: Box, name: string, args: string[], extra: NodeJS.ProcessEnv = {}) => + spawnSync(path.join(BIN_DIR, name), args, { cwd: b.repo, env: { ...b.env, ...extra }, encoding: 'utf8', timeout: 60_000 }); +const phase = (b: Box, args: string[], cmds: string[], extra: NodeJS.ProcessEnv = {}) => + bin(b, 'gstack-ship-phase', ['run', '--dir', path.join(b.root, 'run'), ...args, '--', ...cmds], extra); +const ledgerOf = (b: Box) => /ledger=(\S+)/.exec(fs.readFileSync(b.record, 'utf8'))![1]!; +const backdate = (b: Box, minutes: number) => { + const l = JSON.parse(fs.readFileSync(ledgerOf(b), 'utf8')); + l.created_at = new Date(Date.now() - minutes * 60_000).toISOString(); + fs.writeFileSync(ledgerOf(b), JSON.stringify(l, null, 2)); +}; +const start = (b: Box, mode: 'observe' | 'admit' = 'observe') => { + const r = bin(b, 'gstack-ship-budget', ['start', '--record', b.record, ...(mode === 'observe' ? ['--mode', 'observe'] : []), '--reading', '1000', '--credits', '1']); + expect(r.status, r.stdout + r.stderr).toBe(0); +}; + +describe('gstack-ship-phase run', () => { + // Value: protects=a phase is one command that prints only result lines and resumes from its journal: a rerun after a failure starts at the failed command, finished ones stay done, and a changed list reruns from the first change; fails_when=the runner reruns finished commands (a second budget start, a second preflight), prints whole logs into the parent, or keeps a stale result after the command text changed; + // why_new=G2: the one-call-per-phase rule was prose and conductors made 121-308 calls; seam=none; no_claim=how many calls a model makes + test('result lines only, a failed command stops the phase, and the same command resumes at it', () => { + const b = box(); + const count = path.join(b.root, 'count'); + const first = `echo noise; echo x >> ${count}; echo 'FIRST: ran'`; + const second = `test -f ${b.root}/fixed || { echo 'BAD: not fixed yet'; echo detail; exit 1; }; echo 'SECOND: ok'`; + const failed = phase(b, ['--phase', '7'], [first, second]); + expect(failed.status).toBe(3); + const out = failed.stdout.trim().split('\n'); + expect(out[0]).toBe('RAN: 1/2 exit=0'); + expect(out).toContain('FIRST: ran'); + expect(out).toContain('BAD: not fixed yet'); + expect(failed.stdout).not.toContain('noise'); + expect(failed.stdout).not.toContain('detail'); + expect(out.at(-1)).toBe('STOP: phase 7 command 2/2 exited 1; fix the cause, then rerun the same command (commands before 2 stay done)'); + fs.writeFileSync(path.join(b.root, 'fixed'), ''); + const again = phase(b, ['--phase', '7'], [first, second]); + expect(again.status, again.stdout + again.stderr).toBe(0); + expect(again.stdout).toContain('RAN: 1/2 exit=0 (done earlier)\nFIRST: ran\nRAN: 2/2 exit=0\nSECOND: ok\nPHASE: 7 done commands=2'); + expect(fs.readFileSync(count, 'utf8')).toBe('x\n'); + const changed = phase(b, ['--phase', '7'], [first + ' # v2', second]); + expect(changed.status).toBe(0); + expect(changed.stdout).toStartWith('RAN: 1/2 exit=0\nFIRST: ran\nRAN: 2/2 exit=0\n'); + expect(fs.readFileSync(count, 'utf8')).toBe('x\nx\n'); + }, 60_000); + + // Value: protects=no phase call waits past its 200 s budget: a long command keeps running after the call returns NEXT: rerun, and the rerun attaches to the same process instead of starting it again; fails_when=the runner blocks until slow work ends (a cold cache re-bill per long wait), kills the command when it returns, or starts it a second time on the rerun; + // why_new=G2 waits; seam=none; no_claim=the host's own timeout + test('a command past --wait-s keeps running, the call returns NEXT: rerun, and the rerun waits on the same process', async () => { + const b = box(); + const count = path.join(b.root, 'starts'); + const slow = `echo s >> ${count}; sleep 3; echo 'SLOW: done'`; + const first = phase(b, ['--phase', '2', '--wait-s', '1'], [slow]); + expect(first.status).toBe(0); + expect(first.stdout).toMatch(/^WAITING: 1\/1 pid=\d+ running=\d+s log=\S+\/phases\/2\/1\.log\nNEXT: rerun /); + const done = phase(b, ['--phase', '2', '--wait-s', '30'], [slow]); + expect(done.status, done.stdout + done.stderr).toBe(0); + expect(done.stdout).toStartWith('RAN: 1/1 exit=0\nSLOW: done\nPHASE: 2 done'); + expect(fs.readFileSync(count, 'utf8')).toBe('s\n'); + }, 60_000); + + // Value: protects=a changed command list never credits the replaced command's exit status to its replacement: the replaced process is stopped before the new command starts on the same log; fails_when=the old process keeps running and writes exit 0 into the file the new command is judged by (a false pass); + // why_new=/ship outside-voice review of #4451 reproduced the false pass; seam=none; no_claim=a process that ignores SIGTERM (it stops the phase instead) + test.skipIf(process.platform === 'win32')('a replaced command still running is stopped, so its exit never settles the new command', () => { + const b = box(); + const first = phase(b, ['--phase', '5', '--wait-s', '1'], [`sleep 2; echo 'OLD: ok'`]); + expect(first.stdout).toContain('NEXT: rerun'); + const changed = phase(b, ['--phase', '5', '--wait-s', '30'], [`sleep 4; echo 'NEW: failed'; exit 1`]); + expect(changed.stdout).toMatch(/^REPLACED: 1\/1 pid=\d+ ran a command this list no longer names; stopping it/); + expect(changed.status, changed.stdout + changed.stderr).toBe(3); + expect(changed.stdout).toContain('RAN: 1/1 exit=1'); + expect(changed.stdout).toContain('NEW: failed'); + expect(changed.stdout).not.toContain('OLD: ok'); + }, 60_000); + + test('result lines keep CODE: lines and gstack refusals, and drop everything else', () => { + expect(resultLines('noise\nBUDGET: used=1\n INDENTED: no\ngstack-ship-receipt write: refused (X)\nGSTACK_RESULT: skill=ship\nlower: no\n')) + .toEqual(['BUDGET: used=1', 'gstack-ship-receipt write: refused (X)', 'GSTACK_RESULT: skill=ship']); + }); + + test('usage errors exit 2 and run nothing', () => { + const b = box(); + expect(bin(b, 'gstack-ship-phase', ['run', '--phase', '2', '--', 'true']).status).toBe(2); + expect(bin(b, 'gstack-ship-phase', ['run', '--dir', b.root, '--phase', '2']).status).toBe(2); + expect(bin(b, 'gstack-ship-phase', ['run', '--dir', b.root, '--phase', '../x', '--', 'true']).status).toBe(2); + expect(bin(b, 'gstack-ship-phase', ['nope']).status).toBe(2); + expect(fs.existsSync(path.join(b.root, 'phases'))).toBe(false); + }); +}); + +const PROGRAM = fs.readFileSync(path.join(ROOT, 'lib/capy-ship-phase.js'), 'utf8'); +const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (...a: string[]) => (...v: unknown[]) => Promise<string>; +/** A fake Capy host whose shell is real: bash runs in the fixture with bin/ on PATH; the jam's counter grows 1,000 tokens a read. */ +function host(b: Box, intercept: (cmd: string) => { exit_code: number; output: string } | null = () => null) { + let tokens = 1000; + const bashes: string[] = []; + const tools = { + capy: { bash: async ({ command, timeout }: { command: string; timeout?: number }) => { + bashes.push(command); + const hit = intercept(command); + if (hit) return hit; + const r = spawnSync('bash', ['-c', command], { cwd: b.repo, env: { ...b.env, PATH: `${BIN_DIR}${path.delimiter}${process.env.PATH}` }, encoding: 'utf8', timeout: (timeout ?? 120) * 1000 }); + return { exit_code: r.status ?? 1, output: r.stdout + r.stderr }; + } }, + thread: { get: async () => { tokens += 1000; return { cost: { tokens, credits: tokens / 1000 } }; } }, + }; + return { tools, bashes, run: (input: Record<string, unknown>) => new AsyncFunction('tools', 'sleep', 'now', 'input', PROGRAM)(tools, async () => {}, async () => Date.now(), input) }; +} + +describe('the Capy phase program', () => { + // Value: protects=the checked-in phase program drives a real DRIVER phase on a fixture in one call: the budget start takes this jam's reading through $GSTACK_SHIP_READING, preflight --audit runs, only result lines return, and the closing note records the phase's calls; the same call again reruns nothing; fails_when=the program loses the reading, returns whole logs, skips the note, or a rerun repeats the budget start or the preflight; + // why_new=G2 item 1 (a no-cost check that the runner drives a real phase); seam=tools.capy.bash and tools.thread.get (real shell, counter stub); no_claim=Capy's own execute limits + test('Phase 2 on a fixture: budget start and preflight --audit through gstack-ship-phase, then the note, in one program', async () => { + const b = box(); + const h = host(b); + const run = path.join(b.root, 'run'); + const input = { dir: run, phase: 2, record: b.record, jam: 'jam_test', step: '6', label: 'preflight', cwd: b.repo, commands: [ + `gstack-ship-budget start --record ${b.record} --mode observe --reading "$GSTACK_SHIP_READING" --credits "$GSTACK_SHIP_CREDITS"`, + `gstack-ship-preflight --audit --base main --out ${run}`] }; + const first = (await h.run(input)).split('\n'); + expect(first[0]).toBe('RAN: 1/2 exit=0'); + expect(first).toContain('RAN: 2/2 exit=0'); + expect(first.some(l => l.startsWith('CONTEXT: diff='))).toBe(true); + expect(first.some(l => l.startsWith('READER: coverage='))).toBe(true); + expect(first.some(l => l.startsWith('PHASE: 2 done commands=2'))).toBe(true); + expect(first.find(l => l.startsWith('NOTE: 6:preflight '))).toMatch(/^NOTE: 6:preflight used=1000 credits=1 calls=\d+$/); + expect(first.every(l => !l.startsWith(' ') && !l.includes('diff --git'))).toBe(true); + const ledger = JSON.parse(fs.readFileSync(ledgerOf(b), 'utf8')); + expect(ledger.meter.baseline).toBe(2000); + const again = await h.run(input); + expect(again).toContain('RAN: 1/2 exit=0 (done earlier)'); + expect(again).toContain('RAN: 2/2 exit=0 (done earlier)'); + }); + + // Value: protects=a host whose thread.get reports cost.dollars and no cost.credits still gives the budget a credits reading (1,000 credits a dollar); fails_when=the program passes --credits undefined and the start or closing note refuses it; + // why_new=Capy's thread.get returned only cost.dollars on 2026-11-17, so every phase note failed parseCredits; seam=tools.thread.get stub; no_claim=Capy's own pricing + test('a host that reports only cost.dollars still gets a credits reading', async () => { + const b = box(); + const h = host(b); + let tokens = 1000; + h.tools.thread.get = async () => { tokens += 1000; return { cost: { tokens, dollars: `$${(tokens / 1000).toFixed(2)}` } } as never; }; + const run = path.join(b.root, 'run'); + const out = await h.run({ dir: run, phase: 2, record: b.record, jam: 'jam_test', step: '6', cwd: b.repo, commands: [ + `gstack-ship-budget start --record ${b.record} --mode observe --reading "$GSTACK_SHIP_READING" --credits "$GSTACK_SHIP_CREDITS"`] }); + expect(out).not.toContain('STOP:'); + expect(out.split('\n').find(l => l.startsWith('NOTE: 6 '))).toMatch(/^NOTE: 6 used=1000 credits=1000 calls=\d+$/); + }); + + // Value: protects=a review phase is the same one call: after its commands, the program hands the review pass program its pass input with the launch, checkout, record and jam, and returns that program's lines; a phase whose commands stop never dispatches; fails_when=the phase program dispatches after a failed command, or drops the record or jam the pass notes with; + // why_new=G2 (dispatches inside the phase call); seam=gstack-review-dispatch program, replaced by a stub that echoes its input; no_claim=the pass program's own behavior (test/review-pass.test.ts) + test('with input.pass it runs the review pass program on that input, and never after a failed command', async () => { + const b = box(); + const stub = 'return "PASS_INPUT: " + JSON.stringify({ pass: input.pass, out: input.out, record: input.record, jam: input.jam, cwd: input.cwd });'; + const h = host(b, cmd => (cmd.endsWith('gstack-review-dispatch program') ? { exit_code: 0, output: `PROGRAM: v9 sha256=x bytes=1\n${JSON.stringify(stub)}\n` } : null)); + const out = await h.run({ dir: path.join(b.root, 'run'), phase: 3, record: b.record, jam: 'jam_test', cwd: b.repo, commands: ['echo "AUDIT: ok"'], pass: { pass: 'r-p1', out: path.join(b.root, 'run', 'p1') } }); + expect(out).toContain('AUDIT: ok'); + expect(out).toContain('PROGRAM: v9 sha256=x bytes=1'); + expect(out).toContain(`PASS_INPUT: {"pass":"r-p1","out":"${path.join(b.root, 'run', 'p1')}","record":"${b.record}","jam":"jam_test","cwd":"${b.repo}"}`); + const failed = await h.run({ dir: path.join(b.root, 'run2'), phase: 3, cwd: b.repo, commands: ['echo "BAD: no"; exit 1'], pass: { pass: 'r-p2' } }); + expect(failed).toContain('STOP: phase 3 command 1/1 exited 1'); + expect(failed).not.toContain('PASS_INPUT'); + }); +}); + +describe('the 100-minute stop', () => { + // Value: protects=the 100-minute stop is a printed STOP with the run's state on disk (head, review passes, next act), the run refuses to start another phase until a resume restarts the clock, and an admit-mode run (ship/SKILL.md) never stops on time; fails_when=a note past 100 minutes continues (10 of 12 measured runs ran past the prose stop), stop.json lacks the head or the next act, a stopped run still starts a phase, or resume leaves the clock where every later note stops again; + // why_new=G2 item 3; seam=the ledger's created_at, backdated instead of waiting 100 minutes; no_claim=what the next session does with the state + test('a note past 100 minutes prints STOP: past 100 minutes, writes stop.json, blocks the next phase until resume restarts the clock', () => { + const b = box(); + start(b); + const early = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '2', '--reading', '2000', '--credits', '2']); + expect(early.status, early.stdout + early.stderr).toBe(0); + backdate(b, 101); + const late = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '6', '--reading', '3000', '--credits', '3']); + expect(late.status).toBe(3); + const lines = late.stdout.trim().split('\n'); + expect(lines[0]).toMatch(/^NOTE: 6 used=2000 credits=2/); + const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: b.repo, encoding: 'utf8', timeout: 30_000 }).stdout.trim(); + const dir = path.dirname(ledgerOf(b)); + expect(lines[1]).toMatch(new RegExp(`^STOP: past 100 minutes \\(10[01] min since \\S+\\) head=${head.slice(0, 12)} rounds=0 calls=\\d+ next=Phase 3: audits and review state=${dir}/stop\\.json$`)); + expect(lines.at(-1)).toBe(`GSTACK_RESULT: skill=ship status=incomplete run=${dir}`); + const state = JSON.parse(fs.readFileSync(path.join(dir, 'stop.json'), 'utf8')); + expect(state).toMatchObject({ kind: 'gstack-ship-stop', reason: 'past_100_minutes', head, rounds: 0, next: 'Phase 3: audits and review', step: '6', record: b.record }); + const marker = path.join(b.root, 'phase-ran'); + const blocked = phase(b, ['--phase', '3', '--record', b.record], [`touch ${marker}`]); + expect(blocked.status).toBe(3); + expect(blocked.stdout).toContain('STOP: run '); + expect(blocked.stdout).toContain('stopped (past_100_minutes) at Step 6; nothing ran; resume first: gstack-ship-budget resume --record'); + expect(fs.existsSync(marker)).toBe(false); + const resumed = bin(b, 'gstack-ship-budget', ['resume', '--record', b.record, '--reading', '3000', '--credits', '3']); + expect(resumed.status, resumed.stdout + resumed.stderr).toBe(0); + expect(resumed.stdout).toContain('RESUMED: from=Step 6 (past_100_minutes)'); + expect(resumed.stdout).toMatch(/^CLOCK: restarted at \S+ \(the 100-minute limit counts from here\)$/m); + const ran = phase(b, ['--phase', '3', '--record', b.record], [`touch ${marker}`]); + expect(ran.status, ran.stdout).toBe(0); + expect(bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '9', '--reading', '4000', '--credits', '4']).status).toBe(0); + }); + + test('a phase that starts past 100 minutes stops before its first command; an admit-mode run never stops on time', () => { + const b = box(); + start(b); + backdate(b, 120); + const marker = path.join(b.root, 'phase-ran'); + const late = phase(b, ['--phase', '5', '--record', b.record], [`touch ${marker}`]); + expect(late.status).toBe(3); + expect(late.stdout).toMatch(/^STOP: past 100 minutes \(1[12]\d min since /); + expect(late.stdout).toContain('next=Phase 3: audits and review'); + expect(fs.existsSync(marker)).toBe(false); + const admit = box(); + start(admit, 'admit'); + backdate(admit, 300); + const note = bin(admit, 'gstack-ship-budget', ['note', '--record', admit.record, '--step', '6', '--reading', '2000', '--credits', '2']); + expect(note.stdout).not.toContain('past 100 minutes'); + }); +}); + +describe('calls per phase and calls= in the receipt', () => { + // Value: protects=every note records the calls since the previous one and the receipt carries the run's total, so a 200-call run shows at the receipt; receipts written before calls= still validate, print and carry; fails_when=note drops calls, two notes count the same call, the summary line omits calls=, the schema refuses an older receipt or accepts a negative count, or carry loses calls; + // why_new=G2 item 2; seam=none; no_claim=calls that run no gstack command (the call log cannot see them) + test('notes record calls per phase and close prints them in the timeline', () => { + const b = box(); + phase(b, ['--phase', '2', '--record', b.record], [`${BIN_DIR}/gstack-ship-budget start --record ${b.record} --mode observe --reading 1000 --credits 1`]); + const n1 = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '2', '--reading', '2000', '--credits', '2']); + expect(n1.stdout).toMatch(/^NOTE: 2 used=1000 credits=1 calls=1$/m); + const n2 = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '6', '--reading', '3000', '--credits', '3']); + expect(n2.stdout).toMatch(/^NOTE: 6 used=2000 credits=2 calls=1$/m); + const close = bin(b, 'gstack-ship-budget', ['close', '--record', b.record, '--reading', '3500', '--credits', '3.5']); + expect(close.stdout).toMatch(/^BUDGET_TIMELINE: 2 used=1000 credits=1 calls=1; 6 used=2000 credits=2 calls=1$/m); + }); + + test('receipt write takes --calls or the run total from --budget-record', () => { + const repo = makeFixtureRepo({ prefix: 'ship-phase-write-' }); + repos.push(repo); + const env = { GSTACK_STATE_ROOT: path.join(repo.root, 'state'), GSTACK_CAPY: '1', GSTACK_SHIP_CALL_NESTED: '' }; + const record = path.join(repo.root, 'record.md'); + fs.writeFileSync(record, '# record\n'); + expect(runBin(repo, 'gstack-ship-budget', ['start', '--record', record, '--mode', 'observe', '--reading', '1000', '--credits', '1'], env).status).toBe(0); + expect(runBin(repo, 'gstack-ship-budget', ['note', '--record', record, '--step', '2', '--reading', '2000', '--credits', '2'], env).status).toBe(0); + const write = (extra: string[]) => runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '9', '--base', 'main', '--session-kind', 'unattended', ...extra], env); + const counted = write(['--budget-record', record]); + expect(counted.status, counted.err).toBe(0); + expect(counted.err).toMatch(/^SHIP_RECEIPT: pr=9 .* calls=[1-9]\d*( |$)/m); + expect(extractReceipt(counted.out).receipt!.calls).toBeGreaterThanOrEqual(1); + const given = write(['--calls', '214']); + expect(given.err).toMatch(/ calls=214( |$)/m); + expect(write(['--calls', 'many']).status).toBe(2); + expect(write([]).err).not.toContain('calls='); + }, 60_000); + + test('the receipt field: optional, a whole number, printed as calls=, kept by placement and carry', () => { + const old = { schema_version: 1, pr: 5, head: 'a'.repeat(40), base: 'main' }; + expect(validateReceipt(old)).toEqual([]); + expect(receiptSummaryLine(old as any)).not.toContain('calls='); + const withCalls = orderReceipt({ ...old, spend_usd: 1.5, session_kind: 'unattended', calls: 214 } as any); + expect(Object.keys(withCalls)).toEqual(['schema_version', 'pr', 'head', 'base', 'spend_usd', 'calls', 'session_kind']); + expect(validateReceipt(withCalls)).toEqual([]); + expect(receiptSummaryLine(withCalls)).toBe(`SHIP_RECEIPT: pr=5 head=${'a'.repeat(12)} version=- base=main session_kind=unattended calls=214`); + for (const bad of [-1, 1.5, '12']) expect(validateReceipt({ ...old, calls: bad }).length).toBeGreaterThan(0); + expect(extractReceipt(placeReceipt('## Summary\n\nProse.\n', withCalls)).receipt!.calls).toBe(214); + }); + + test('carry moves a receipt with calls= and one without it to a test-only head', () => { + for (const calls of [undefined, 37]) { + const repo = makeFixtureRepo({ prefix: 'ship-phase-carry-' }); + repos.push(repo); + fs.mkdirSync(path.join(repo.work, 'src'), { recursive: true }); + fs.mkdirSync(path.join(repo.work, 'test'), { recursive: true }); + fs.writeFileSync(path.join(repo.work, 'src', 'app.ts'), 'export const a = 1;\n'); + fs.writeFileSync(path.join(repo.work, 'test', 'app.test.ts'), 'test a\n'); + repo.git('add', '.'); repo.git('commit', '-qm', 'seed'); repo.git('push', '-q', 'origin', 'main'); + repo.git('checkout', '-qb', 'feat'); + fs.writeFileSync(path.join(repo.work, 'src', 'app.ts'), 'export const a = 2;\n'); + repo.git('commit', '-qam', 'feat: a=2'); + const reviewed = repo.git('rev-parse', 'HEAD'); + fs.writeFileSync(path.join(repo.work, 'test', 'app.test.ts'), 'test a=2\n'); + repo.git('commit', '-qam', 'test: fix expectation'); + const head = repo.git('rev-parse', 'HEAD'); + const body = path.join(repo.root, 'body.md'); + fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 5, head: reviewed, base: 'main', ...(calls === undefined ? {} : { calls }) } as any)); + const carried = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body], { GSTACK_STATE_ROOT: path.join(repo.root, 'state'), GSTACK_SESSION_KIND: 'unattended' }); + expect(carried.status, carried.out + carried.err).toBe(0); + const after = extractReceipt(fs.readFileSync(body, 'utf8')); + expect(after.errors).toEqual([]); + expect(after.receipt!.head).toBe(head); + expect(after.receipt!.calls).toBe(calls); + expect(carried.err.includes(`calls=${calls}`)).toBe(calls !== undefined); + } + }, 60_000); +}); From f2d96dcba1e8caf7b710c7d088d53a61640b13b6 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 01:07:29 +0800 Subject: [PATCH 42/62] CI uploads test results with Trunk's uploader v2.1.8 (GST-2999) (#4453) Free-tests CI now uploads test results to Trunk with analytics-uploader v2.1.8 and analytics-cli 0.17.0, up from v2.1.6 and 0.16.2. Why: Trunk warned that uploader v2.1.6 may pick up analytics-cli 1.0.0 when it ships and then fail to upload; v2.1.8 never resolves a CLI above 0.x. Nothing to do. Co-authored-by: Tyler Beebe <tsb252@gmail.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .github/workflows/free-tests.yml | 4 ++-- changelog.d/trunk-uploader-v2.1.8.md | 1 + test/free-tests-workflow-wiring.test.ts | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) create mode 100644 changelog.d/trunk-uploader-v2.1.8.md diff --git a/.github/workflows/free-tests.yml b/.github/workflows/free-tests.yml index 02a4f06d56c..db8462f9f6c 100644 --- a/.github/workflows/free-tests.yml +++ b/.github/workflows/free-tests.yml @@ -816,13 +816,13 @@ jobs: if: env.TRUNK_ORG_API_TOKEN != '' timeout-minutes: 5 continue-on-error: true - uses: trunk-io/analytics-uploader@a86313c7029d22e6ea2d5c346060a224d90053dc # v2.1.6 + uses: trunk-io/analytics-uploader@9886de74a788c450c793109577a4d97bfb3e799f # v2.1.8 with: junit-paths: ${{ runner.temp }}/free-junit/**/*.xml org-slug: garry-tan token: ${{ env.TRUNK_ORG_API_TOKEN }} test-collection-id: 7yDVXXE3 - cli-version: 0.16.2 + cli-version: 0.17.0 use-cache: 'false' quarantine: 'false' use-uncloned-repo: 'true' diff --git a/changelog.d/trunk-uploader-v2.1.8.md b/changelog.d/trunk-uploader-v2.1.8.md new file mode 100644 index 00000000000..80c5438458d --- /dev/null +++ b/changelog.d/trunk-uploader-v2.1.8.md @@ -0,0 +1 @@ +- CI now uploads free-suite test results to Trunk with analytics-uploader v2.1.8 and analytics-cli 0.17.0, up from v2.1.6 and 0.16.2. diff --git a/test/free-tests-workflow-wiring.test.ts b/test/free-tests-workflow-wiring.test.ts index 6d4dcaba625..59d970f7cfe 100644 --- a/test/free-tests-workflow-wiring.test.ts +++ b/test/free-tests-workflow-wiring.test.ts @@ -99,14 +99,14 @@ describe('free-tests workflow wiring', () => { } expect(download.uses).toMatch(/^actions\/download-artifact@[0-9a-f]{40}$/); expect(download.with).toEqual({ pattern: 'free-junit-*', path: '${{ runner.temp }}/free-junit' }); - expect(upload.uses).toBe('trunk-io/analytics-uploader@a86313c7029d22e6ea2d5c346060a224d90053dc'); + expect(upload.uses).toBe('trunk-io/analytics-uploader@9886de74a788c450c793109577a4d97bfb3e799f'); expect(upload['timeout-minutes']).toBe(5); expect(upload.with).toEqual({ 'junit-paths': '${{ runner.temp }}/free-junit/**/*.xml', 'org-slug': 'garry-tan', token: '${{ env.TRUNK_ORG_API_TOKEN }}', 'test-collection-id': '7yDVXXE3', - 'cli-version': '0.16.2', + 'cli-version': '0.17.0', 'use-cache': 'false', quarantine: 'false', 'use-uncloned-repo': 'true', From b1c32824fd8c075172863c76e57e5ca4cec6bcae Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 01:13:42 +0800 Subject: [PATCH 43/62] Keep skill_prefix after updates, retire the ClawHub install route, and stop misreading cross-repo issue refs (GST-2967) (#4454) Three small fixes: `skill_prefix=true` now survives updates when gbrain is installed, the OpenClaw docs stop sending people to stale ClawHub skills, and `gstack-issue-links` no longer reads other repositories' issue numbers as gstack issues. Why: each one misleads users or /ship today (wrong skill names after every update, April 2026 skill builds, wrong `Refs #N` lines in PR bodies). Nothing to do as a reader. Thanks @fliaron (#4413) and @exGeni (#4421) for the detailed reports. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- README.md | 4 +- bin/gstack-config | 4 +- bin/gstack-issue-links | 9 +-- bin/gstack-render-claude.sh | 6 +- ...-prefix-renders-clawhub-docs-issue-refs.md | 3 + docs/OPENCLAW.md | 17 +++-- docs/OPENCLAW_PUBLISHING.md | 5 ++ docs/hosts.md | 23 +++---- docs/pregate.md | 3 + lib/issue-links.ts | 32 ++++++++-- setup | 3 + test/ship-issue-intent.test.ts | 32 +++++++++- test/user-render-out-dir-install.test.ts | 64 +++++++++++++++++++ 13 files changed, 166 insertions(+), 39 deletions(-) create mode 100644 changelog.d/fix-skill-prefix-renders-clawhub-docs-issue-refs.md diff --git a/README.md b/README.md index 9935ca7cdcd..59a4f1e74eb 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ installs and passes the conformance tests but has no certification run yet; | Hermes | experimental | `--host hermes` (every skill in `$HERMES_HOME/skills/gstack`; automatic when setup runs inside Hermes) | ask for the task, or `/gstack-review` | advisory, not blocked | — | `./setup --host hermes` | | GBrain (mod) | instruction-only | `--host gbrain` (brain-aware variants ship from the GBrain repo) | — | advisory, not blocked | — | — | -Per-host notes (agent harnesses, Copilot, Antigravity, Gemini CLI, OpenClaw and ClawHub, the Codex behavioral profile and model tiers, outside-review providers, the design binary's models) are in [docs/hosts.md](docs/hosts.md). Any rules-reading agent (Zed, Amp, Jules) can use the 2KB [agents digest](agents-digest/gstack-AGENTS.md) with no install. Adding a host: [docs/ADDING_A_HOST.md](docs/ADDING_A_HOST.md). +Per-host notes (agent harnesses, Copilot, Antigravity, Gemini CLI, OpenClaw native skills, the Codex behavioral profile and model tiers, outside-review providers, the design binary's models) are in [docs/hosts.md](docs/hosts.md). Any rules-reading agent (Zed, Amp, Jules) can use the 2KB [agents digest](agents-digest/gstack-AGENTS.md) with no install. Adding a host: [docs/ADDING_A_HOST.md](docs/ADDING_A_HOST.md). ## See it work @@ -262,7 +262,7 @@ On Windows without Developer Mode (MSYS2 / Git Bash), `setup` falls back to file | [gstack + Capy: the software factory](capy/README.md) | What we built with Capy Captains and gstack, how the pieces fit, the measured before/after, tips, and how Garry uses it | | [Why gstack](docs/why-gstack.md) | The story, the productivity numbers and their caveats, Karpathy's failure modes, parallel sprints | | [Install details](docs/install.md) | Setup timing, requirements in detail, team mode, the hooks setup registers, agent harness registration | -| [Other agents](docs/hosts.md) | Agent harnesses (OpenClaw, Hermes, dots, QM, Muse Code, Grok, any other), OpenClaw and ClawHub, per-host notes, the Codex profile and model tiers, outside-review providers, the design binary's models | +| [Other agents](docs/hosts.md) | Agent harnesses (OpenClaw, Hermes, dots, QM, Muse Code, Grok, any other), OpenClaw native skills, per-host notes, the Codex profile and model tiers, outside-review providers, the design binary's models | | [QA without a webpage](docs/qa-without-a-webpage.md) | `/qa` and `/qa-only` on CLIs, APIs, jobs, workers and webhooks | | [Standalone binaries](docs/standalone-binaries.md) | The standalone `gstack-*` CLIs (egress auditor, context bill, model benchmark, the review and evidence ledgers, the iOS QA daemon), and the CSO evaluation producer contract | | [Privacy & Telemetry](docs/privacy.md) | What is sent, what never is, the update check, outside reviews, egress receipts | diff --git a/bin/gstack-config b/bin/gstack-config index 89c4a815023..239c1ee1bd8 100755 --- a/bin/gstack-config +++ b/bin/gstack-config @@ -1280,7 +1280,9 @@ $_gstack_legacy_root" gstack_claude_overlay "$INSTALL_DIR" "$0" RENDER_TMP="$RENDER_DIR.tmp.$$" rm -rf "$RENDER_TMP" - if ( cd "$INSTALL_DIR" && bun run gen:skill-docs:user --host claude --out-dir "$RENDER_TMP" --link-root "$RENDER_DIR" --model "$_GSTACK_OVERLAY" ${_PLAN_MODE_ARG:+"$_PLAN_MODE_ARG"} ${_LOADOUT_ARG:+"$_LOADOUT_ARG"} >/dev/null 2>&1 ); then + _skill_prefix="$("$0" get skill_prefix 2>/dev/null || echo false)" + if ( cd "$INSTALL_DIR" && bun run gen:skill-docs:user --host claude --out-dir "$RENDER_TMP" --link-root "$RENDER_DIR" --model "$_GSTACK_OVERLAY" ${_PLAN_MODE_ARG:+"$_PLAN_MODE_ARG"} ${_LOADOUT_ARG:+"$_LOADOUT_ARG"} >/dev/null 2>&1 \ + && "$INSTALL_DIR/bin/gstack-patch-names" "$RENDER_TMP" "$_skill_prefix" >/dev/null ); then gstack_render_lock "$RENDER_DIR" _swap_in_render "$RENDER_DIR" "$RENDER_TMP" gstack_render_unlock "$RENDER_DIR" diff --git a/bin/gstack-issue-links b/bin/gstack-issue-links index 50241179e34..764f45b9782 100755 --- a/bin/gstack-issue-links +++ b/bin/gstack-issue-links @@ -25,7 +25,7 @@ import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; -import { lineSources, mentionsIn, promotionCandidates, receiptIssues, relatedPrs, renderIssueLines, resolveLinks, selectFlakes, type ClosingPr, type FlakeLink, type IssueMention, type IssueRow } from '../lib/issue-links'; +import { lineSources, mentionsIn, ownRepoMentions, promotionCandidates, receiptIssues, relatedPrs, renderIssueLines, resolveLinks, selectFlakes, type ClosingPr, type FlakeLink, type IssueMention, type IssueRow } from '../lib/issue-links'; import { resultLine, resultLineWithDocs } from '../lib/result-codes'; import { resolveBaseBranch } from '../lib/ship-policy'; @@ -143,19 +143,20 @@ function main(argv: string[]): number { const log = git(['log', '--format=%H%n%B%x00', `origin/${base}..HEAD`], repoRoot) ?? git(['log', '--format=%H%n%B%x00', `${base}..HEAD`], repoRoot); if (log === undefined) { process.stderr.write(`gstack-issue-links: cannot read commits ${base}..HEAD (fetch origin/${base} first)\n`); return EXIT.usage; } - const mentions: IssueMention[] = []; + const named: IssueMention[] = []; for (const entry of log.split('\0')) { const nl = entry.indexOf('\n'); if (nl < 0) continue; - mentions.push(...mentionsIn(entry.slice(nl + 1), `commit ${entry.slice(0, nl).trim().slice(0, 12)}`)); + named.push(...mentionsIn(entry.slice(nl + 1), `commit ${entry.slice(0, nl).trim().slice(0, 12)}`)); } const readable = (issue: number): boolean => { const r = spawnSync(path.join(binDir, 'gstack-issue-guard'), ['issue', String(issue)], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 16 * 1024 * 1024 }); return r.status === 0 && r.stdout.length > 0; }; const gh = ghLookups(repoRoot); - const needRepo = runs.length > 0 || explicit.length > 0 || (autoLinks && mentions.some(m => m.intent === 'fixes')); + const needRepo = runs.length > 0 || explicit.length > 0 || named.some(m => m.repo?.includes('/')) || (autoLinks && named.some(m => m.intent === 'fixes')); const repo = flags(argv, '--repo')[0] ?? (needRepo ? gh.json<{ nameWithOwner?: string }>('repository', ['repo', 'view', '--json', 'nameWithOwner'])?.nameWithOwner : undefined); + const mentions = ownRepoMentions(named, repo); const flakes: FlakeLink[] = []; const rejectedFlakes: Array<{ issue: number; run: string; reason: string }> = []; diff --git a/bin/gstack-render-claude.sh b/bin/gstack-render-claude.sh index f626461cc8f..3353f074a22 100644 --- a/bin/gstack-render-claude.sh +++ b/bin/gstack-render-claude.sh @@ -129,14 +129,18 @@ gstack_claude_render_action() { fi } +_GSTACK_RENDER_BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + # gstack_claude_render_plain SOURCE_DIR RENDER_DIR — render the pinned overlay -# without brain blocks into a temp dir and swap it in only on success. +# without brain blocks into a temp dir, apply the saved skill_prefix to its +# name: fields (#4413), and swap it in only on success. gstack_claude_render_plain() { local src="$1" RENDER_DIR="$2" RENDER_TMP out rc=0 RENDER_TMP="$RENDER_DIR.tmp.$$" rm -rf "$RENDER_TMP" _gstack_render_say "Rendering Claude skills with the $_GSTACK_OVERLAY overlay${_PLAN_MODE_ARG:+ and no plan-mode preamble}${_LOADOUT_ARG:+ and the ${_LOADOUT_ARG#--loadout=} loadout} into $RENDER_DIR (source checkout stays clean)..." out="$(cd "$src" && _gstack_render_bun run gen:skill-docs --host claude --out-dir "$RENDER_TMP" --link-root "$RENDER_DIR" --model "$_GSTACK_OVERLAY" ${_DISABLED_CSV:+"--disabled-skills=$_DISABLED_CSV"} ${_PLAN_MODE_ARG:+"$_PLAN_MODE_ARG"} ${_LOADOUT_ARG:+"$_LOADOUT_ARG"} 2>&1)" || rc=$? + [ "$rc" -ne 0 ] || out="$("$_GSTACK_RENDER_BIN/gstack-patch-names" "$RENDER_TMP" "$("$_GSTACK_RENDER_BIN/gstack-config" get skill_prefix 2>/dev/null || echo false)" 2>&1)" || rc=$? if [ "$rc" -ne 0 ]; then rm -rf "$RENDER_TMP" printf '%s\n' "$out" | tail -3 diff --git a/changelog.d/fix-skill-prefix-renders-clawhub-docs-issue-refs.md b/changelog.d/fix-skill-prefix-renders-clawhub-docs-issue-refs.md new file mode 100644 index 00000000000..a8206dad065 --- /dev/null +++ b/changelog.d/fix-skill-prefix-renders-clawhub-docs-issue-refs.md @@ -0,0 +1,3 @@ +- **`skill_prefix=true` now survives updates when gbrain is installed.** Every Claude re-render (the brain-aware render in `./setup`, `gstack-config gbrain-refresh`, and the pinned-overlay render) applies your saved prefix before it goes live, so skills stay `/gstack-retro`, `/gstack-review` and so on instead of reverting to short names after each update (#4413). Thanks @fliaron for the report. +- The OpenClaw docs no longer send you to ClawHub, which held only April 2026 builds of office-hours, ceo-review and retro and no longer has gstack skills (the docs also said four skills while listing three). `docs/hosts.md` and `docs/OPENCLAW.md` now point to native registration (`./setup --host openclaw`), which already serves the current version of each, and tell you to remove the ClawHub copies if you installed them (#4421). Thanks @exGeni for the report. +- **`gstack-issue-links` no longer reads other repositories' issues as gstack's.** A parenthesis that cites several repositories, such as `(founderstar #837, harness-evals #393)`, now gives each its own cross-repo reference instead of `Refs #837` and `Refs #393` on this repository, and `owner/repo#N` naming the current repository counts as its own issue, so `Fixes garrytan/gstack#N` closes it. diff --git a/docs/OPENCLAW.md b/docs/OPENCLAW.md index 0ec78bc3a49..48d49834027 100644 --- a/docs/OPENCLAW.md +++ b/docs/OPENCLAW.md @@ -101,15 +101,14 @@ The orchestrator persists the plan link to its own memory store (brain repo, knowledge base, or whatever is configured in AGENTS.md). When the user is ready to build, spawn a FULL session that references the saved plan. -### Native methodology skills -Published to ClawHub. Install with `clawhub install`: -- `gstack-openclaw-office-hours` — Product interrogation (6 forcing questions) -- `gstack-openclaw-ceo-review` — Strategic challenge (10-section review, 4 modes) -- `gstack-openclaw-retro` — Operational retrospective (weekly review) +### Methodology skills in the OpenClaw agent +To run /office-hours, /plan-ceo-review or /retro in the OpenClaw agent itself, +use native registration (see [Installation](#installation)): its `gstack` router +skill serves the current version of each. -Source lives in `openclaw/skills/` in the gstack repo. These are hand-crafted -adaptations of the gstack methodology for OpenClaw's conversational context. -No gstack infrastructure (no browser, no telemetry, no preamble). +gstack no longer publishes skills on ClawHub. If you installed the April 2026 +`gstack-openclaw-office-hours`, `gstack-openclaw-ceo-review` or +`gstack-openclaw-retro` from there, remove them. ## Spawned session detection @@ -175,7 +174,7 @@ For OpenClaw users: tell your OpenClaw agent "install gstack for openclaw." The agent should: 1. Install gstack-lite CLAUDE.md into its coding session templates -2. Install the 4 native methodology skills +2. Register gstack's native skills with `./setup --host openclaw` (below) 3. Add dispatch routing to AGENTS.md 4. Verify with a test spawn diff --git a/docs/OPENCLAW_PUBLISHING.md b/docs/OPENCLAW_PUBLISHING.md index 8defe424e22..ea3571a45da 100644 --- a/docs/OPENCLAW_PUBLISHING.md +++ b/docs/OPENCLAW_PUBLISHING.md @@ -2,6 +2,11 @@ Moved verbatim from CLAUDE.md (token-load reduction). +**Status:** gstack's user docs no longer send anyone to ClawHub (#4421). Native +registration (`./setup --host openclaw`) gives OpenClaw's agent the current +/office-hours, /plan-ceo-review and /retro, and the gstack skills were removed +from ClawHub on 2026-11-17. + ## Workflow Native OpenClaw skills live in `openclaw/skills/gstack-openclaw-*/SKILL.md`. These are diff --git a/docs/hosts.md b/docs/hosts.md index e0a55a6cd92..1138610aeb2 100644 --- a/docs/hosts.md +++ b/docs/hosts.md @@ -117,22 +117,17 @@ when Claude Code has gstack installed. Paste this to your OpenClaw agent: See [docs/OPENCLAW.md](OPENCLAW.md) for advanced dispatch routing and the gstack-lite/gstack-full prompt templates. -## Native OpenClaw Skills (via ClawHub) +## /office-hours, /plan-ceo-review and /retro in OpenClaw -Four methodology skills that work directly in your OpenClaw agent, no Claude Code -session needed. Install from ClawHub: +Your OpenClaw agent can run these directly in chat, with no Claude Code session. +They come with native registration: `./setup --host openclaw` registers gstack's +`gstack` router skill, which lists them with every other workflow and serves +the current version of each ([install, verify and remove](#agent-harnesses)). -``` -clawhub install gstack-openclaw-office-hours gstack-openclaw-ceo-review gstack-openclaw-retro -``` - -| Skill | What it does | -|-------|-------------| -| `gstack-openclaw-office-hours` | Product interrogation with 6 forcing questions | -| `gstack-openclaw-ceo-review` | Strategic challenge with 4 scope modes | -| `gstack-openclaw-retro` | Weekly engineering retrospective | - -These are conversational skills. Your OpenClaw agent runs them directly via chat. +Earlier docs sent you to ClawHub for `gstack-openclaw-office-hours`, +`gstack-openclaw-ceo-review` and `gstack-openclaw-retro`. Those were April 2026 +builds, and gstack no longer publishes skills on ClawHub. If you installed them, +remove them, so your agent doesn't load an old copy next to the current one. ## Which agents a checkout renders for diff --git a/docs/pregate.md b/docs/pregate.md index 6a51c6acebd..4f72ae55b41 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -2278,6 +2278,9 @@ cross-repo `owner/repo#N` are `Refs`. A parenthesised named reference, token that is not a closure, reference, filler or version word, is a cross-repo `Refs name#N`, never a same-repo Refs line or a promotion candidate; `(see #12)`, `(closing #12)` and `(#301)` stay bare refs. +Several in one parenthesis, `(founderstar #837, harness-evals #393)`, are each +their own name's reference. `owner/repo#N` naming this repository is its own +issue, so a `Fixes garrytan/gstack#N` trailer closes it. Same-repo references are printed as promotion candidates (`reference #N ← <commit line> (promote: fix #N)` on stderr, `candidates` in `--json`): the owner's `fix #N` reply reruns with diff --git a/lib/issue-links.ts b/lib/issue-links.ts index f167f9bf454..1fd791d5f40 100644 --- a/lib/issue-links.ts +++ b/lib/issue-links.ts @@ -14,6 +14,10 @@ * reference, filler or version word (`closing`, `cf.`, `e.g.`, `v1.2` * name nothing), is a cross-repo reference to `name`: rendered as * `Refs name#N`, never a same-repo Refs line or a promotion candidate. + * Several in one parenthesis, `(founderstar #837, harness-evals #393)`, + * are each their own name's reference. + * - `owner/repo#N` naming this repository (ownRepoMentions) is this + * repository's own issue, so `Fixes garrytan/gstack#N` closes it. * - A closure issue that cannot be read through gstack-issue-guard is * downgraded to `Refs #N` with ISSUE_UNREADABLE (never Fixes). * - Same-repo references are promotion candidates: the owner's `fix #N` @@ -41,12 +45,14 @@ export interface IssueRow { number: number; title?: string; body?: string; autho /** One `closedByPullRequestsReferences` node of an issue this PR fixes. */ export interface ClosingPr { number: number; state?: string; headRefName?: string; author?: { login?: string } | null; repository?: { nameWithOwner?: string } } -const CLOSURE = /^\s*(?:fix(?:es|ed)?|close[sd]?|resolve[sd]?)\s*:?\s+(?:#|GH-)(\d+)\s*$/i; +const CLOSURE = /^\s*(?:fix(?:es|ed)?|close[sd]?|resolve[sd]?)\s*:?\s+(?:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#|#|GH-)(\d+)\s*$/i; const PARTIAL = /\b(?:partial(?:ly)?|part of|defer(?:red)?|follow-?up|related|refs?|see|context)\b/i; const CROSS = /\b([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#(\d+)\b/g; const BARE = /(?<![A-Za-z0-9_./-])#(\d+)\b/g; -/** `(name #N[, #M]…)`, `(name PR #N)`, `(name issue #N)`: the name, then every number. */ -const NAMED = /\(([A-Za-z][\w.-]*(?:\/[\w.-]+)?)\s+(?:(?:PR|issue)\s+)?(#\d+(?:,\s*#\d+)*)\)/gi; +/** One `name #N[, #M]…`, `name PR #N` or `name issue #N`: the name, then every number. */ +const NAMED_PART = /([A-Za-z][\w.-]*(?:\/[\w.-]+)?)\s+(?:(?:PR|issue)\s+)?(#\d+(?:,\s*#\d+)*)/gi; +/** A parenthesis holding one or more NAMED_PARTs separated by commas or semicolons. */ +const NAMED = new RegExp(`\\((?:${NAMED_PART.source})(?:[,;]\\s*(?:${NAMED_PART.source}))*\\)`, 'gi'); /** Words that open a reference in parentheses without naming a repository. */ const NOT_A_NAME = /^(?:fix(?:es|ed|ing)?|clos(?:e[sd]?|ing)|resolv(?:e[sd]?|ing)|address(?:es|ed|ing)?|implement(?:s|ed|ing)?|supersed(?:es|ed|ing)|replac(?:es|ed|ing)|track(?:s|ed|ing)?|block(?:s|ed|ing)?|dup|duplicates?|bugs?|upstream|refs?|see|related|partial(?:ly)?|part|context|follow-?up|defer(?:red)?|prs?|issues?|gh|via|from|after|since|with|in|by|for|also|cf\.?|e\.?g\.?|i\.?e\.?|and|or|per|of|to|on|at|as|is|was|the|an?|this|that|not|no|vs\.?|like|v\d[\w.-]*)$/i; @@ -58,12 +64,12 @@ export function mentionsIn(message: string, source = 'commit'): IssueMention[] { for (const raw of message.split('\n')) { const line = raw.replace(/\s+$/, ''); const trailer = CLOSURE.exec(line); - if (trailer && !PARTIAL.test(line)) { add({ issue: Number(trailer[1]), intent: 'fixes', source: `${source}: ${line.trim()}` }); continue; } - const rest = line.replace(NAMED, (whole, name: string, numbers: string) => { - if (NOT_A_NAME.test(name)) return whole; + if (trailer && !PARTIAL.test(line)) { add({ issue: Number(trailer[2]), intent: 'fixes', ...(trailer[1] ? { repo: trailer[1] } : {}), source: `${source}: ${line.trim()}` }); continue; } + const rest = line.replace(NAMED, whole => whole.replace(NAMED_PART, (part, name: string, numbers: string) => { + if (NOT_A_NAME.test(name)) return part; for (const n of numbers.matchAll(/#(\d+)/g)) add({ issue: Number(n[1]), intent: 'refs', repo: name, source: `${source}: ${line.trim()}` }); return ' '; - }); + })); for (const c of rest.matchAll(CROSS)) add({ issue: Number(c[2]), intent: 'refs', repo: c[1], source: `${source}: ${line.trim()}` }); const stripped = rest.replace(CROSS, ''); for (const b of stripped.matchAll(BARE)) add({ issue: Number(b[1]), intent: 'refs', source: `${source}: ${line.trim()}` }); @@ -71,6 +77,18 @@ export function mentionsIn(message: string, source = 'commit'): IssueMention[] { return out; } +/** Mentions whose `owner/repo` is `repo` (case-insensitive) become this repository's own; the rest are unchanged. */ +export function ownRepoMentions(mentions: IssueMention[], repo: string | undefined): IssueMention[] { + if (!repo) return mentions; + const out: IssueMention[] = []; + for (const m of mentions) { + const { repo: named, ...own } = m; + const next: IssueMention = named?.toLowerCase() === repo.toLowerCase() ? own : m; + if (!out.some(o => o.repo === next.repo && o.issue === next.issue && o.intent === next.intent)) out.push(next); + } + return out; +} + /** * Resolve the final link set. `readable(n)` is the gstack-issue-guard probe * for a closure candidate; a false answer downgrades it to Refs. diff --git a/setup b/setup index af032fd9416..c810f60c7d4 100755 --- a/setup +++ b/setup @@ -4548,6 +4548,9 @@ if [ -x "$DETECT_BIN" ]; then # main gen:skill-docs site had). Capture, show the tail, propagate. _GEN_USER_OUT=$(bun_cmd run gen:skill-docs:user --host claude --out-dir "$_GSTACK_RENDER_TMP" --link-root "$_GSTACK_RENDER_DIR" --model "$_GSTACK_OVERLAY" ${_DISABLED_CSV:+"--disabled-skills=$_DISABLED_CSV"} ${_PLAN_MODE_ARG:+"$_PLAN_MODE_ARG"} ${_LOADOUT_ARG:+"$_LOADOUT_ARG"} 2>&1) _GEN_USER_RC=$? + # The generator writes unprefixed name: fields; apply skill_prefix + # before the swap, as _render_install does (#4413). + [ "$_GEN_USER_RC" -ne 0 ] || "$SOURCE_GSTACK_DIR/bin/gstack-patch-names" "$_GSTACK_RENDER_TMP" "$SKILL_PREFIX" >/dev/null || _GEN_USER_RC=$? printf '%s\n' "$_GEN_USER_OUT" | tail -3 exit "$_GEN_USER_RC" ); then diff --git a/test/ship-issue-intent.test.ts b/test/ship-issue-intent.test.ts index 4f800f39016..f4a5e95ac31 100644 --- a/test/ship-issue-intent.test.ts +++ b/test/ship-issue-intent.test.ts @@ -9,7 +9,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { splitAgentNotes } from '../lib/agent-notes'; import { EXIT } from '../lib/headless-artifacts'; -import { lineSources, mentionsIn, promotionCandidates, relatedPrs, renderIssueLines, resolveLinks, selectFlakes, type ClosingPr, type IssueRow } from '../lib/issue-links'; +import { lineSources, mentionsIn, ownRepoMentions, promotionCandidates, relatedPrs, renderIssueLines, resolveLinks, selectFlakes, type ClosingPr, type IssueRow } from '../lib/issue-links'; import { cleanup, commit, ghShim, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; const repos: FixtureRepo[] = []; @@ -47,6 +47,27 @@ describe('issue intent (pure)', () => { expect(mentionsIn('same line (gbrain #7625) and #13 here').map(x => [x.repo ?? '', x.issue])).toEqual([['gbrain', 7625], ['', 13]]); }); + // Value: protects=several named references in one parenthesis, "(founderstar #837, harness-evals #393)", are each a cross-repo reference to their own + // name, never this repository's #837 and #393, while "(see #12, #13)", "mentions #12" and "Fixes #14" keep their meaning; owner/repo#N naming this + // repository is its own issue (a Fixes trailer closes it) and another repository's never closes here; fails_when=a list of named references falls + // through to the bare-#N rule (GST-2967: wrong Refs lines and fix-#N offers for issues the commit never meant), or this repository's full form stays a + // cross-repo Refs line; why_new=the named-reference test covers one name per parenthesis only; seam=none; no_claim=prose outside parentheses + test('a list of named references is cross-repo; this repository\'s owner/repo#N is its own issue (GST-2967)', () => { + const listed = mentionsIn('docs audit: stop halting on prose (founderstar #837, harness-evals #393)\n\nSee #12 (gbrain #7625; acme/tools issue #4).\n'); + expect(listed.map(x => [x.repo ?? '', x.issue, x.intent])).toEqual([['founderstar', 837, 'refs'], ['harness-evals', 393, 'refs'], ['gbrain', 7625, 'refs'], ['acme/tools', 4, 'refs'], ['', 12, 'refs']]); + const links = resolveLinks(listed, [], () => true); + expect(links).toEqual({ fixes: [], refs: [12], flakes: [], cross: ['acme/tools#4', 'founderstar#837', 'gbrain#7625', 'harness-evals#393'], unreadable: [] }); + expect(promotionCandidates(listed, links).map(c => c.issue)).toEqual([12]); + expect(mentionsIn('retry (see #12, #13) and (closing #14; #15)').map(x => [x.repo ?? '', x.issue])).toEqual([['', 12], ['', 13], ['', 14], ['', 15]]); + expect(mentionsIn('mentions #12 only').map(x => [x.repo ?? '', x.issue])).toEqual([['', 12]]); + const own = ownRepoMentions(mentionsIn('Refs garrytan/gstack#40, same as #40, and owner/other#9\n\nFixes garrytan/gstack#41\nFixes owner/other#42\n'), 'garrytan/GStack'); + expect(own.map(x => [x.repo ?? '', x.issue, x.intent])).toEqual([['', 40, 'refs'], ['owner/other', 9, 'refs'], ['', 41, 'fixes'], ['owner/other', 42, 'fixes']]); + const ownLinks = resolveLinks(own, [], () => true); + expect(ownLinks).toEqual({ fixes: [41], refs: [40], flakes: [], cross: ['owner/other#42', 'owner/other#9'], unreadable: [] }); + expect(renderIssueLines(ownLinks)).toEqual(['Fixes #41', 'Refs #40', 'Refs owner/other#42', 'Refs owner/other#9']); + expect(ownRepoMentions(mentionsIn('Fixes garrytan/gstack#41'), undefined).map(x => [x.repo ?? '', x.issue])).toEqual([['garrytan/gstack', 41]]); + }); + test('resolution: explicit --issue is closure, unreadable closure becomes Refs, a flake issue is never a plain Ref', () => { const links = resolveLinks(mentionsIn('Fixes #14\nFixes #15\nsee #40 and #16'), [16], n => n !== 15, [{ issue: 40, run: '7' }]); expect(links).toEqual({ fixes: [14, 16], refs: [15], flakes: [{ issue: 40, run: '7' }], cross: [], unreadable: [15] }); @@ -77,6 +98,15 @@ describe('gstack-issue-links (bin)', () => { expect(JSON.parse(receipt.out).issues).toEqual({ fixes: [14, 16], refs: [12, 13, 15], flakes: [{ issue: 40, run: '123456' }] }); }); + + test('a named-reference list in a commit is cross-repo, and Fixes owner/repo#N for this repository closes it (GST-2967)', () => { + const repo = fixture(); + commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" }, 'docs audit: stop halting on prose (founderstar #837, harness-evals #393)\n\nFixes owner/repo#14\n'); + const env = ghShim(repo, { issues: { '14': { title: 't', body: 'b', comments: [] } } }); + const r = runBin(repo, 'gstack-issue-links', ['--base', 'main', '--no-auto-links'], env); + expect(r).toMatchObject({ status: EXIT.ok, out: 'Fixes #14\nRefs founderstar#837\nRefs harness-evals#393\n' }); + expect(r.err).toContain('closure #14 ← commit '); + }); test('no mentions prints ISSUE_LINKS: none with exit 0; a bare mention never closes; bad flags are usage', () => { const repo = fixture(); commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" }, 'tidy\n\nmentions #12 only\n'); diff --git a/test/user-render-out-dir-install.test.ts b/test/user-render-out-dir-install.test.ts index 3a73176cd89..ff4c5b6f8ed 100644 --- a/test/user-render-out-dir-install.test.ts +++ b/test/user-render-out-dir-install.test.ts @@ -144,6 +144,70 @@ describe(':user render targets the out-dir, never the checkout (#2569)', () => { }); }); +// Value: protects=with skill_prefix=true every rendered Claude skill keeps its gstack-<name> after a re-render, because each path that swaps a fresh +// render into a live render dir runs gstack-patch-names on it first; fails_when=a render path (setup's gbrain branch, gstack-config gbrain-refresh, +// gstack_claude_render_plain) swaps in the generator's unprefixed name: fields, the #4413 symptom; why_new=#2738 patched the render only from +// gstack-relink, which setup runs before these renders; seam=none; no_claim=the scan pins the call order, not each path's end-to-end behavior +describe('skill_prefix survives every Claude re-render (#4413)', () => { + const RENDER_HELPER = path.join(ROOT, 'bin', 'gstack-render-claude.sh'); + + test('every render swap is preceded by gstack-patch-names on the same temp dir', () => { + const sources: Array<[string, string]> = [ + ['setup', SETUP_SRC], + ['bin/gstack-config', CONFIG_SRC], + ['bin/gstack-render-claude.sh', fs.readFileSync(RENDER_HELPER, 'utf-8')], + ]; + let swaps = 0; + for (const [rel, src] of sources) { + const lines = src.split('\n'); + lines.forEach((line, i) => { + const m = /^\s*_swap_in_render "([^"]+)" "([^"]+)"/.exec(line); + if (!m) return; + swaps++; + const before = lines.slice(Math.max(0, i - 30), i).join('\n'); + expect(before, `${rel}:${i + 1} swaps ${m[2]} in without gstack-patch-names`).toContain(`gstack-patch-names" "${m[2]}"`); + }); + } + expect(swaps).toBe(4); + }); + + function renderPlain(prefix: string) { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-render-prefix-')); + try { + const state = path.join(tmp, 'state'); + fs.mkdirSync(state, { recursive: true }); + fs.writeFileSync(path.join(state, 'config.yaml'), `skill_prefix: ${prefix}\n`); + const render = path.join(tmp, 'render', 'claude'); + const script = [ + 'set -euo pipefail', + `. ${JSON.stringify(RENDER_HELPER)}`, + extractFn(SETUP_SRC, '_swap_in_render'), + 'bun_cmd() {', + ' local out="" prev=""', + ' for a in "$@"; do [ "$prev" = --out-dir ] && out="$a"; prev="$a"; done', + ' mkdir -p "$out/retro" "$out/gstack-upgrade"', + ` printf -- '---\\nname: gstack\\n---\\n' > "$out/SKILL.md"`, + ` printf -- '---\\nname: retro\\n---\\n' > "$out/retro/SKILL.md"`, + ` printf -- '---\\nname: gstack-upgrade\\n---\\n' > "$out/gstack-upgrade/SKILL.md"`, + '}', + '_GSTACK_OVERLAY=claude', + `gstack_claude_render_plain ${JSON.stringify(tmp)} ${JSON.stringify(render)}`, + ].join('\n'); + const r = runBashScript(script, { timeout: 30_000, env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: tmp, GSTACK_STATE_ROOT: state } }); + expect(r.status, r.stderr).toBe(0); + const name = (rel: string) => /^name: (.*)$/m.exec(fs.readFileSync(path.join(render, rel), 'utf-8'))?.[1]; + return { root: name('SKILL.md'), retro: name('retro/SKILL.md'), upgrade: name('gstack-upgrade/SKILL.md') }; + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + } + + test('gstack_claude_render_plain serves prefixed names with skill_prefix true and the generator names with it false', () => { + expect(renderPlain('true')).toEqual({ root: 'gstack', retro: 'gstack-retro', upgrade: 'gstack-upgrade' }); + expect(renderPlain('false')).toEqual({ root: 'gstack', retro: 'retro', upgrade: 'gstack-upgrade' }); + }); +}); + describe('link_claude_skill_dirs prefers rendered SKILL.md (behavior)', () => { test('a rendered variant is served; skills without one fall back to source', () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-render-pref-')); From a9da30363c91cd314a7c3fd9c9cfa22d55c91ef3 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 01:14:39 +0800 Subject: [PATCH 44/62] Release notes list every change with its pull request instead of "see CHANGELOG.md" (#4390) GitHub release pages now list every change a release ships, one plain line each, linked to the pull request that made it, instead of one headline per version or "see CHANGELOG.md". Why: the release page is where people read what changed, and recent releases went out saying only "see CHANGELOG.md". Nothing to do: the next release uses it; a release with no CHANGELOG entry stops with `NOTES_MISSING` instead of publishing a stub. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .github/workflows/weekly-release.yml | 1 + changelog.d/README.md | 2 +- .../release-notes-list-every-change.md | 1 + crew/docs/recommended-harness.md | 5 +- crew/scripts/release-cut.ts | 90 +------ crew/scripts/release-notes.ts | 224 ++++++++++++++++ crew/test/release-cadence.test.ts | 36 ++- crew/test/release-cut.test.ts | 252 ++++++++++++++++-- docs/releases.md | 53 +++- .../scripts/test-pr-profile.ts.json | 2 +- scripts/test-pr-profile.ts | 1 + test/weekly-release-workflow.test.ts | 2 +- 12 files changed, 551 insertions(+), 118 deletions(-) create mode 100644 changelog.d/release-notes-list-every-change.md create mode 100644 crew/scripts/release-notes.ts diff --git a/.github/workflows/weekly-release.yml b/.github/workflows/weekly-release.yml index 3c9ea8756a1..534e5862da6 100644 --- a/.github/workflows/weekly-release.yml +++ b/.github/workflows/weekly-release.yml @@ -55,6 +55,7 @@ on: paths: - '.github/workflows/weekly-release.yml' - 'crew/scripts/release-cut.ts' + - 'crew/scripts/release-notes.ts' - 'crew/scripts/release-cadence.ts' - 'lib/changelog-fragments.ts' diff --git a/changelog.d/README.md b/changelog.d/README.md index 177f3258df4..b74d7ab97a8 100644 --- a/changelog.d/README.md +++ b/changelog.d/README.md @@ -1,3 +1,3 @@ # CHANGELOG fragments -A PR adds its CHANGELOG entry here as `changelog.d/<branch-slug>.md`: the entry text only, with no `## [x]` heading, and `bump: minor` or `bump: major` front matter only when the change warrants more than a patch, and `important: security|regression|data-loss|blocker` only when it must reach stable within about a day (docs/releases.md#the-daily-check). It never edits VERSION, `package.json`'s version or a released CHANGELOG section. The merge step (`gstack-ship-queue land`, or `train land` in a stamped train) assigns the version (under `merge: direct`, the release PR from `gstack-release-stamp open` does), folds every fragment into one CHANGELOG section and deletes the files. This README is skipped. See docs/ship-policy.md#changelog-fragments. +A PR adds its CHANGELOG entry here as `changelog.d/<branch-slug>.md`: the entry text only, with no `## [x]` heading, and `bump: minor` or `bump: major` front matter only when the change warrants more than a patch, and `important: security|regression|data-loss|blocker` only when it must reach stable within about a day (docs/releases.md#the-daily-check). It never edits VERSION, `package.json`'s version or a released CHANGELOG section. The merge step (`gstack-ship-queue land`, or `train land` in a stamped train) assigns the version (under `merge: direct`, the release PR from `gstack-release-stamp open` does), folds every fragment into one CHANGELOG section and deletes the files. The entry's first sentence (or bold lead) becomes its line in the GitHub release notes, so write it for someone using gstack: docs/releases.md#release-notes. This README is skipped. See docs/ship-policy.md#changelog-fragments. diff --git a/changelog.d/release-notes-list-every-change.md b/changelog.d/release-notes-list-every-change.md new file mode 100644 index 00000000000..0f312b4733f --- /dev/null +++ b/changelog.d/release-notes-list-every-change.md @@ -0,0 +1 @@ +- **GitHub release notes now list every change in plain words, with a link to its pull request.** Releases v1.99.1.0 to v1.99.4.0 said only "see CHANGELOG.md", because the release cut took one headline per version and found none in entries written as bullets. Each release page now lists every change the release ships under What's new, Fixes and Changes for maintainers, one line each, with the pull request that made it, then the compare link. A release whose CHANGELOG has no entry for its version, or an entry with nothing in it, now stops with `NOTES_MISSING` instead of publishing an empty page, and notes too long for GitHub keep the changes that fit and say how many more are in the full changelog (docs/releases.md#release-notes). diff --git a/crew/docs/recommended-harness.md b/crew/docs/recommended-harness.md index c484e7282a1..210d65409c6 100644 --- a/crew/docs/recommended-harness.md +++ b/crew/docs/recommended-harness.md @@ -239,8 +239,9 @@ moves `stable` more than once in 72 hours otherwise, except for a verified security or regression fix (`--security` or `--regression`, with `--ref`): it takes the newest green commit on main's first-parent history (its required check succeeded, the backstop check succeeded, every check run completed and none failed, no active freeze), tags it `v<VERSION>`, publishes a -GitHub Release whose notes are one line per CHANGELOG version since the -previous release, and fast-forwards `stable`. New installs and team-mode installs +GitHub Release whose notes list every change in the CHANGELOG versions since +the previous release, one line each with the pull request that made it +([release notes](../../docs/releases.md#release-notes)), and fast-forwards `stable`. New installs and team-mode installs follow `stable`; `gstack-config set update_channel main` follows every merge. A hotfix is `--ref <sha on main>`, held by the same floor. Details, the floor's refusal codes and the "nothing green in the window" failure mode: diff --git a/crew/scripts/release-cut.ts b/crew/scripts/release-cut.ts index 54feb4d0d73..f78c3b57cc5 100755 --- a/crew/scripts/release-cut.ts +++ b/crew/scripts/release-cut.ts @@ -1,7 +1,7 @@ #!/usr/bin/env -S bun --no-env-file --config=/dev/null /** * release-cut: tag the newest green commit on main as v<VERSION>, publish a - * GitHub Release whose notes are that span's CHANGELOG headlines, and + * GitHub Release whose notes list that span's CHANGELOG changes (release-notes.ts), and * fast-forward refs/heads/stable to it (docs/releases.md). Run by * .github/workflows/weekly-release.yml ("Stable release") every day at 14:00 * UTC with --daily (the daily check, crew/scripts/release-cadence.ts: an important @@ -69,10 +69,12 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { spawnSync } from 'node:child_process'; import { FLOOR_HOURS, IMPORTANT_FLOOR_HOURS, SCHEDULED_GRACE_HOURS, decideDaily, importantChanges, type DailyDecision } from './release-cadence'; +import { KIND_LABEL, NOTES_CAP, changeSources, changelogEntries, compareVersions, releaseKind, releaseNotes } from './release-notes'; import { bucketClass } from '../../lib/ci-gate'; import { headCheckRows, type AsideRuns } from '../../lib/ci-head-checks'; export { FLOOR_HOURS, SCHEDULED_GRACE_HOURS }; +export { NOTES_CAP, changelogEntries, compareVersions, releaseKind, releaseNotes }; export type Gh = (args: string[]) => { status: number | null; stdout: string; stderr: string }; export type Git = (args: string[]) => { ok: boolean; out: string }; @@ -87,7 +89,6 @@ const NOTES_LOCAL = 'refs/notes/gstack-trains-release'; const RED = new Set(['failure', 'timed_out', 'cancelled', 'action_required', 'startup_failure', 'stale']); export const WINDOW_DAYS = 7; export const WINDOW_COMMITS = 200; -export const NOTES_CAP = 60_000; const HOUR = 3_600_000; export const runGh: Gh = (args) => { @@ -104,16 +105,6 @@ function parseJson<T>(r: { status: number | null; stdout: string }): T | null { try { return JSON.parse(r.stdout) as T; } catch { return null; } } -/** Four-part versions compare numerically, part by part. */ -export function compareVersions(a: string, b: string): number { - const pa = a.split('.').map(Number), pb = b.split('.').map(Number); - for (let i = 0; i < Math.max(pa.length, pb.length); i++) { - const d = (pa[i] ?? 0) - (pb[i] ?? 0); - if (d !== 0) return d; - } - return 0; -} - /** Green names what gated the commit: the backstop check's name, or `train <nonce>`. Pending means a check run on it is still going. */ export type Verdict = { green: true; via: string } | { green: false; why: string; pending: boolean }; interface CheckRun { id?: number; name: string; status: string; conclusion: string | null } @@ -231,68 +222,9 @@ export function readTrainNotes(git: Git, notesRef = NOTES_REF): TrainNotes { return notes; } -export interface ChangelogEntry { version: string; date: string; headline: string } - -/** Every "## [X.Y.Z.W] - date" entry of a CHANGELOG with its first prose line, markdown stripped. */ -export function changelogEntries(text: string): ChangelogEntry[] { - const out: ChangelogEntry[] = []; - const lines = text.split('\n'); - for (let i = 0; i < lines.length; i++) { - const m = /^## \[(\d+(?:\.\d+)+)\](?: - (\S+))?/.exec(lines[i]!); - if (!m) continue; - let headline = ''; - for (let j = i + 1; j < lines.length && !lines[j]!.startsWith('## '); j++) { - const l = lines[j]!.trim(); - if (!l || l.startsWith('#') || l.startsWith('|') || l.startsWith('-') || l.startsWith('```')) continue; - const bold = /^\*\*(.+?)\*\*/.exec(l); - headline = (bold ? bold[1]! : l.replace(/\*\*/g, '')).replace(/\s+/g, ' '); - break; - } - out.push({ version: m[1]!, date: m[2] ?? '', headline }); - } - return out; -} - -export interface NotesInput { repo: string; version: string; date: string; prevVersion: string | null; prevTag: string | null; entries: ChangelogEntry[]; hotfix: boolean; first?: boolean; exception?: Exception | null } - /** A verified floor exception (a security or a regression cut): the sanitized reason and what tied it to the released commits. */ export interface Exception { kind: 'security' | 'regression'; reason: string; evidence: string } -const KIND_LABEL = { security: 'Security', regression: 'Regression' } as const; - -export function releaseKind(hotfix: boolean, exception: Exception | null | undefined): 'security' | 'regression' | 'hotfix' | 'regular' { - return exception ? exception.kind : hotfix ? 'hotfix' : 'regular'; -} - -/** Release notes: one headline per version in (prev, version], capped at NOTES_CAP. */ -export function releaseNotes(n: NotesInput): string { - const span = n.entries.filter(e => compareVersions(e.version, n.version) <= 0 && (!n.prevVersion || compareVersions(e.version, n.prevVersion) > 0)) - .sort((a, b) => compareVersions(b.version, a.version)); - const plural = span.length === 1 ? '' : 's'; - const changelogUrl = 'https://github.com/' + n.repo + '/blob/v' + n.version + '/CHANGELOG.md'; - const compare = n.prevTag ? '[Compare](https://github.com/' + n.repo + '/compare/' + n.prevTag + '...v' + n.version + ') or read ' : 'Read '; - const head = [ - '## gstack v' + n.version + ' (' + releaseKind(n.hotfix, n.exception) + ' release)', - '', - ...(n.exception ? ['**' + KIND_LABEL[n.exception.kind] + ' release:** `' + n.exception.reason + '` (verified: ' + n.exception.evidence + '). Every version since the previous release ships with it.', ''] : []), - n.first || !n.prevVersion - ? 'First tagged release: the ' + span.length + ' version' + plural + (n.prevVersion ? ' since v' + n.prevVersion + ' (the week before it)' : '') + ', one line each; the [full changelog](' + changelogUrl + ') has every earlier one.' - : span.length + ' version' + plural + ' since v' + n.prevVersion + ', one line each. ' + compare + 'the [full changelog](' + changelogUrl + ').', - '', - 'New installs and team-mode installs follow the stable branch, which now points here; gstack-config set update_channel main follows every merge instead ([docs/releases.md](https://github.com/' + n.repo + '/blob/v' + n.version + '/docs/releases.md)).', - '', - ].join('\n'); - const bullets = span.map(e => '- **' + e.version + '**' + (e.date ? ' (' + e.date + ')' : '') + ': ' + (e.headline || 'see CHANGELOG.md')); - let body = head + bullets.join('\n') + '\n'; - if (body.length > NOTES_CAP) { - const kept: string[] = []; - let size = head.length; - for (const b of bullets) { if (size + b.length + 1 > NOTES_CAP - 200) break; kept.push(b); size += b.length + 1; } - body = head + kept.join('\n') + '\n- ...and ' + (bullets.length - kept.length) + ' more versions; see CHANGELOG.md\n'; - } - return body; -} - const iso = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z'); /** @@ -448,8 +380,8 @@ export interface Plan { tagExists: 'no' | 'same' | 'other'; stableAt: boolean; notes: string; skipped: string[]; exception: Exception | null; floor: Floor; ridingAlong: number; } -export type RefusalCode = 'NOTHING_NEW' | 'NO_GREEN_COMMIT' | 'NO_RELEASE_PR' | 'REFUSED' | 'REFUSED_FLOOR' | 'FLOOR_UNKNOWN' | 'REFUSED_SECURITY' | 'REFUSED_REGRESSION'; -/** `sha` names the candidate on NO_RELEASE_PR, which comes after the candidate was picked but before a plan exists. */ +export type RefusalCode = 'NOTHING_NEW' | 'NO_GREEN_COMMIT' | 'NO_RELEASE_PR' | 'NOTES_MISSING' | 'REFUSED' | 'REFUSED_FLOOR' | 'FLOOR_UNKNOWN' | 'REFUSED_SECURITY' | 'REFUSED_REGRESSION'; +/** `sha` names the candidate on NO_RELEASE_PR and NOTES_MISSING, which come after the candidate was picked but before a plan exists. */ export type PlanResult = { ok: true; plan: Plan } | { ok: false; code: RefusalCode; message: string; skipped?: string[]; next?: string; plan?: Plan; sha?: string }; export interface PlanOptions { @@ -567,9 +499,11 @@ export function planRelease(o: PlanOptions): PlanResult { } const changelog = git(['show', sha + ':CHANGELOG.md']); const date = git(['show', '-s', '--format=%cs', sha]).out; - const notes = releaseNotes({ repo, version, date, prevVersion, prevTag, entries: changelog.ok ? changelogEntries(changelog.out) : [], hotfix: Boolean(o.ref), first: !before, exception }); + const written = releaseNotes({ repo, version, date, prevVersion, prevTag, entries: changelog.ok ? changelogEntries(changelog.out) : [], hotfix: Boolean(o.ref), first: !before, exception, sources: changeSources(git, before, sha) }); + if (!written.ok) return { ok: false, code: 'NOTES_MISSING', sha, message: written.why }; + const notes = written.body; const floor = floorStatus({ git, gh, repo, prevStable, sha, exception: exception?.kind ?? null, scheduled: Boolean(o.scheduled), now: o.now?.() ?? Date.now(), floorHours: o.floorHours }); - const ridingAlong = Math.max(0, notes.split('\n').filter(l => l.startsWith('- **')).length - 1); + const ridingAlong = written.versions - 1; const plan: Plan = { sha, version, tag, date, hotfix: Boolean(o.ref), via, prevStable, prevVersion, prevTag, tagExists, stableAt: prevStable === sha, notes, skipped, exception, floor, ridingAlong }; if (floor.verdict === 'refused' || floor.verdict === 'unknown') return { ok: false, code: floor.verdict === 'refused' ? 'REFUSED_FLOOR' : 'FLOOR_UNKNOWN', message: floor.message!, next: floor.next, plan }; return { ok: true, plan }; @@ -621,7 +555,7 @@ export function describePlan(p: Plan, dryRun: boolean): string[] { 'CANDIDATE: ' + p.sha + ' (' + p.date + ')' + (p.hotfix ? ' [hotfix: --ref]' : '') + ' gated by ' + p.via, 'VERSION: ' + p.version + ' -> tag ' + p.tag + (p.tagExists === 'same' ? ' (exists at this commit)' : ''), 'STABLE: ' + (p.stableAt ? 'already at ' + p.sha.slice(0, 12) + ' (finishing an earlier cut)' : (p.prevStable ? p.prevStable.slice(0, 12) + ' (v' + (p.prevVersion ?? '?') + ')' : 'none yet') + ' -> ' + p.sha.slice(0, 12)), - 'NOTES: ' + p.notes.split('\n').filter(l => l.startsWith('- ')).length + ' version lines, ' + p.notes.length + ' chars', + 'NOTES: ' + p.notes.split('\n').filter(l => l.startsWith('- ')).length + ' change lines, ' + p.notes.length + ' chars', p.floor.line, ]; if (p.exception) lines.push(p.exception.kind.toUpperCase() + ': `' + p.exception.reason + '` (verified: ' + p.exception.evidence + ')', 'RIDING_ALONG: ' + p.ridingAlong + ' other version' + (p.ridingAlong === 1 ? '' : 's') + ' ship with the fix'); @@ -638,7 +572,7 @@ export function describePlan(p: Plan, dryRun: boolean): string[] { /** * The daily check (--daily, crew/scripts/release-cadence.ts): plan at the 24-hour important floor, then let * decideDaily pick the trigger, if any; NO_RELEASE_PR becomes a blocked decision only when a trigger - * is due. decision is null when the plan's refusal stands on its own (a freeze, nothing green, + * is due, and NOTES_MISSING stops only a cut decision (no version to cut today needs no notes). decision is null when the plan's refusal stands on its own (a freeze, nothing green, * FLOOR_UNKNOWN, a non-fast-forward, a version stamped on an unrelated commit); lines then say which * important changes are still waiting on the gate. A plan that cleared while the daily check itself * cannot date stable is held as FLOOR_UNKNOWN, so a null decision never reaches a cut. @@ -652,7 +586,7 @@ export function planDaily(o: PlanOptions & { fragmentsDir?: string }): { planned const noReleasePr = !planned.ok && planned.code === 'NO_RELEASE_PR'; const sha = planned.ok ? planned.plan.sha : planned.code === 'REFUSED_FLOOR' ? planned.plan?.sha - : noReleasePr ? planned.sha + : noReleasePr || (!planned.ok && planned.code === 'NOTES_MISSING') ? planned.sha : planned.code === 'NOTHING_NEW' ? prev ?? undefined : undefined; const moved = prev ? stableMovedAt(git, gh, repo, prev) : null; diff --git a/crew/scripts/release-notes.ts b/crew/scripts/release-notes.ts new file mode 100644 index 00000000000..02200583653 --- /dev/null +++ b/crew/scripts/release-notes.ts @@ -0,0 +1,224 @@ +/** + * Release notes for a cut (crew/scripts/release-cut.ts, docs/releases.md#release-notes): every change in the + * CHANGELOG versions a release ships, one line each, grouped under What's new, Fixes and Changes for + * maintainers, with a link to the pull request that made it. + * + * A change is a top-level bullet of a version's section, or a paragraph when it is not a bullet. Its line is + * the bullet's bold lead when that lead is a sentence, else its first sentence, with internal issue codes in + * parentheses dropped. Its pull request is read from git (changeSources), never from its words: the commit that + * added a version's heading folded the changelog.d fragments it deleted, in path order, so a folded version lists + * each of those fragments' changes, as the fragment read just before the fold, with the trailing "(#N)" of the + * squash commit that added that file there (wherever it sits, since a release can fold fragments that landed + * before the previous one, and never a later commit that reused the file name). Changes the version holds past + * its fragments' link the heading commit's pull request; a release commit (a "v<version> release" subject) + * links nothing. + * Its group comes from the heading it sits under ("### Fixed", "### Added", "### Tests" and the like, read + * inside its fragment when it has one), else from the files its pull request touched (only tests, CI and + * gstack's own release tooling: maintainers), else from its words (internal shipping machinery: maintainers; + * "no longer", "again", "fix": a fix; anything else is new). A release whose own version has no entry, or a version + * with no change, refuses the notes instead of publishing a stub or an older version's entry. Notes past NOTES_CAP + * keep the changes that fit and send the rest to the full changelog. + */ +import { parseFragment } from '../../lib/changelog-fragments'; +import type { Exception, Git } from './release-cut'; + +export const NOTES_CAP = 60_000; + +export interface Change { text: string; heading: string } +export interface ChangelogEntry { version: string; date: string; changes: Change[] } +/** A folded fragment: the pull request whose commit added its file (null when that commit names none), the files that commit touched, and its changes. */ +export interface FragmentSource { pr: number | null; files: string[]; changes: Change[] } +/** The commit that added a version's heading: its pull request (null for a release commit), its files, and the fragments it folded in path order. */ +export interface VersionSource { pr: number | null; files: string[]; fragments: FragmentSource[] } +export interface NotesSources { versions: Record<string, VersionSource> } +export interface NotesInput { repo: string; version: string; date: string; prevVersion: string | null; prevTag: string | null; entries: ChangelogEntry[]; hotfix: boolean; first?: boolean; exception?: Exception | null; sources?: NotesSources } +export type Notes = { ok: true; body: string; versions: number } | { ok: false; why: string }; +type Group = 'new' | 'fix' | 'maintainers'; + +const GROUPS: Array<[Group, string]> = [['new', "What's new"], ['fix', 'Fixes'], ['maintainers', 'Changes for maintainers']]; +export const KIND_LABEL = { security: 'Security', regression: 'Regression' } as const; +const HEADING_GROUP: Array<[RegExp, Group]> = [ + [/^(tests?|testing|ci|for contributors|contributors|internal|maintainers?|chores?|infrastructure)\b/i, 'maintainers'], + [/^(fixed|fixes|bug ?fixes|security)\b/i, 'fix'], + [/^(added|new|features?)\b/i, 'new'], +]; +const NEUTRAL_PATH = /^(changelog\.d\/|CHANGELOG\.md$|VERSION$|package\.json$|bun\.lock$)/; +const MAINTAINER_PATH = /^(test\/|crew\/|\.github\/|evals?\/|CONTRIBUTING\.md$|TODOS\.md$|docs\/TESTING)/; +const MAINTAINER_WORDS = /\b(test suite|flaky|CI|evals?|receipts?|pregate|ship-queue|merge trains?|carry|lander|release gate|backstop|fix-checks?|stamps?|review plan|review log)\b/i; +const FIX_WORDS = /\b(no longer|again|fix(es|ed)?|broken|regression|crash(es|ed)?|bug)\b|instead of (failing|refusing|crashing|stopping)/i; +const STAMP_SUBJECT = /^v\d+(\.\d+)+ release\b/; + +/** Four-part versions compare numerically, part by part. */ +export function compareVersions(a: string, b: string): number { + const pa = a.split('.').map(Number), pb = b.split('.').map(Number); + for (let i = 0; i < Math.max(pa.length, pb.length); i++) { + const d = (pa[i] ?? 0) - (pb[i] ?? 0); + if (d !== 0) return d; + } + return 0; +} + +/** The changes in a run of CHANGELOG lines: top-level bullets with their continuation lines, and plain paragraphs. */ +export function changesIn(lines: string[]): Change[] { + const changes: Change[] = []; + let heading = '', open: Change | null = null, blank = false, fence = false; + for (const raw of lines) { + const l = raw.trimEnd(); + if (/^\s*(```|~~~)/.test(l)) { fence = !fence; continue; } + if (fence) continue; + if (/^#{2,}\s/.test(l)) { heading = l.replace(/^#+\s*/, '').trim(); open = null; continue; } + if (!l.trim()) { blank = true; continue; } + const wasBlank = blank; + blank = false; + if (/^[-*] /.test(l)) { open = { text: l.slice(2).trim(), heading }; changes.push(open); continue; } + if (/^\s*\|/.test(l) || /^\s*<\/?(details|summary)/i.test(l)) { open = null; continue; } + if (open && (/^\s/.test(l) || !wasBlank)) { open.text += ' ' + l.trim(); continue; } + open = { text: l.trim(), heading }; + changes.push(open); + } + return changes; +} + +/** Every "## [X.Y.Z.W] - date" section of a CHANGELOG with its changes. */ +export function changelogEntries(text: string): ChangelogEntry[] { + const out: ChangelogEntry[] = []; + const lines = text.split('\n'); + for (let i = 0; i < lines.length; i++) { + const m = /^## \[(\d+(?:\.\d+)+)\](?: - (\S+))?/.exec(lines[i]!); + if (!m) continue; + let j = i + 1; + while (j < lines.length && !lines[j]!.startsWith('## [')) j++; + out.push({ version: m[1]!, date: m[2] ?? '', changes: changesIn(lines.slice(i + 1, j)) }); + i = j - 1; + } + return out; +} + +function firstSentence(text: string): string { + let code = false; + for (let i = 0; i < text.length; i++) { + const c = text[i]!; + if (c === '`') code = !code; + if (code || !'.!?'.includes(c)) continue; + const rest = text.slice(i + 1); + if (/^["')*]*$/.test(rest) || /^["')*]*\s+["'(\[*`]*[A-Z0-9/@`]/.test(rest)) return text.slice(0, i + 1) + (/^["')*]+/.exec(rest)?.[0] ?? ''); + } + return text; +} + +/** One line for a change: its bold lead when that is a sentence, else its first sentence, markdown bold and internal codes removed. */ +export function changeLine(text: string): string { + const bold = /^\*\*(.+?)\*\*/.exec(text); + const lead = bold && /[.!?]["')`]*$/.test(bold[1]!.trim()) ? bold[1]! : firstSentence(text); + return lead.replace(/\*\*/g, '') + .replace(/\s*\((?!CVE-|GHSA-)[A-Z][A-Z0-9]*-\d+(?:(?:,\s*|\s+and\s+)(?!CVE-|GHSA-)[A-Z][A-Z0-9]*-\d+)*\)/g, '') + .replace(/\b([Oo])utside voice/g, (_, o: string) => (o === 'O' ? 'S' : 's') + 'econd-model review') + .replace(/\s+/g, ' ').replace(/\s+([.,;:!?])/g, '$1').trim(); +} + +function prOf(subject: string): number | null { + const squash = /\(#(\d+)\)\s*$/.exec(subject); + const merge = /^Merge pull request #(\d+)/.exec(subject); + return squash ? Number(squash[1]) : merge ? Number(merge[1]) : null; +} + +/** + * The pull requests behind the versions whose headings were added in from..to along main's first-parent history: for + * each, the commit that added its "## [version]" heading and the changelog.d fragments that commit deleted, each read + * as it stood just before that commit, with the pull request of the commit that added that file. No from (a first + * release) reads nothing. + */ +export function changeSources(git: Git, from: string | null, to: string): NotesSources { + const out: NotesSources = { versions: {} }; + if (!from) return out; + const range = ['--first-parent', '--diff-merges=first-parent', '--no-renames', from + '..' + to]; + const log = git(['log', '--format=%x00%H%x09%s', '--name-status', ...range]); + if (!log.ok) return out; + const commits = new Map<string, { pr: number | null; stamp: boolean; files: string[]; folded: string[] }>(); + for (const block of log.out.split('\0').filter(b => b.trim())) { + const [head, ...rest] = block.split('\n'); + const [sha, subject = ''] = head!.split('\t'); + const status = rest.filter(l => l.trim()).map(l => l.split('\t')); + const folded = status.filter(([kind, file]) => kind === 'D' && /^changelog\.d\/[^/]+\.md$/.test(file!) && file !== 'changelog.d/README.md').map(([, file]) => file!).sort(); + commits.set(sha!, { pr: prOf(subject), stamp: STAMP_SUBJECT.test(subject), files: status.map(s => s.at(-1)!), folded }); + } + const fragment = (fold: string, file: string): FragmentSource | null => { + const added = git(['log', '-1', '--no-patch', '--first-parent', '--diff-merges=first-parent', '--diff-filter=A', '--format=%H%x09%s', fold + '^', '--', file]); + const [sha, subject = ''] = added.ok ? added.out.split('\t') : []; + const shown = git(['show', fold + '^:' + file]); + const parsed = shown.ok ? parseFragment(file, shown.out) : null; + if (!parsed || !('body' in parsed)) return null; + const files = sha ? git(['show', '--diff-merges=first-parent', '--no-renames', '--format=', '--name-only', sha]) : null; + return { pr: sha ? prOf(subject) : null, files: files?.ok ? files.out.split('\n').filter(Boolean) : [], changes: changesIn(parsed.body.split('\n')) }; + }; + const headings = git(['log', '--format=%x00%H', '-p', '--unified=0', ...range, '--', 'CHANGELOG.md']); + if (headings.ok) for (const block of headings.out.split('\0').filter(b => b.trim())) { + const sha = block.slice(0, 40); + const c = commits.get(sha); + if (!c) continue; + for (const m of block.matchAll(/^\+## \[(\d+(?:\.\d+)+)\]/gm)) { + out.versions[m[1]!] = { pr: c.stamp ? null : c.pr, files: c.files, fragments: c.folded.map(file => fragment(sha, file)).filter((f): f is FragmentSource => f !== null) }; + } + } + return out; +} + +function groupOf(line: string, heading: string, files: string[]): Group { + const byHeading = HEADING_GROUP.find(([re]) => re.test(heading)); + if (byHeading) return byHeading[1]; + const own = files.filter(f => !NEUTRAL_PATH.test(f)); + if (own.length && own.every(f => MAINTAINER_PATH.test(f))) return 'maintainers'; + if (MAINTAINER_WORDS.test(line)) return 'maintainers'; + return FIX_WORDS.test(line) ? 'fix' : 'new'; +} + +export function releaseKind(hotfix: boolean, exception: Exception | null | undefined): 'security' | 'regression' | 'hotfix' | 'regular' { + return exception ? exception.kind : hotfix ? 'hotfix' : 'regular'; +} + +/** The release notes for versions in (prevVersion, version], or why there are none to publish. */ +export function releaseNotes(n: NotesInput): Notes { + const span = n.entries.filter(e => compareVersions(e.version, n.version) <= 0 && (!n.prevVersion || compareVersions(e.version, n.prevVersion) > 0)) + .sort((a, b) => compareVersions(b.version, a.version)); + if (!span.length) return { ok: false, why: 'CHANGELOG.md at the release has no entry for v' + n.version + (n.prevVersion ? ' or any version since v' + n.prevVersion : '') }; + if (compareVersions(span[0]!.version, n.version) !== 0) return { ok: false, why: 'CHANGELOG.md at the release has no entry for v' + n.version + ', only for the older v' + span[0]!.version + '; write the entry before cutting the release' }; + const grouped: Record<Group, string[]> = { new: [], fix: [], maintainers: [] }; + const empty: string[] = []; + for (const e of span) { + const version = n.sources?.versions[e.version]; + const folded = version?.fragments ?? []; + const own = e.changes.slice(folded.reduce((count, f) => count + f.changes.length, 0)); + const items: Array<{ change: Change; from?: { pr: number | null; files: string[] } }> = [...folded.flatMap(f => f.changes.map(change => ({ change, from: f }))), ...own.map(change => ({ change, from: version }))]; + let lines = 0; + for (const { change, from } of items) { + const line = changeLine(change.text); + if (!line) continue; + const pr = from?.pr ? ' ([#' + from.pr + '](https://github.com/' + n.repo + '/pull/' + from.pr + '))' : ''; + grouped[groupOf(line, change.heading, from?.files ?? [])].push('- ' + line + pr); + lines++; + } + if (!lines) empty.push('v' + e.version); + } + if (empty.length) return { ok: false, why: 'no change to list in the CHANGELOG entry of ' + empty.join(', ') + '; write the entry before cutting the release' }; + const kind = releaseKind(n.hotfix, n.exception); + const changelogUrl = 'https://github.com/' + n.repo + '/blob/v' + n.version + '/CHANGELOG.md'; + const plural = span.length === 1 ? '' : 's'; + const render = (omitted: number) => [ + '## gstack v' + n.version + (kind === 'regular' ? '' : ' (' + kind + ' release)'), + '', + ...(n.exception ? ['**' + KIND_LABEL[n.exception.kind] + ' release:** `' + n.exception.reason + '` (verified: ' + n.exception.evidence + '). Every version since the previous release ships with it.', ''] : []), + ...(n.first || !n.prevVersion ? ['First tagged release: the ' + span.length + ' version' + plural + (n.prevVersion ? ' since v' + n.prevVersion : '') + '; the [full changelog](' + changelogUrl + ') has every earlier one.', ''] : []), + ...GROUPS.filter(([g]) => grouped[g].length).flatMap(([g, title]) => ['### ' + title, '', ...grouped[g], '']), + ...(omitted ? [omitted + (omitted === 1 ? ' more change is' : ' more changes are') + ' in the [full changelog](' + changelogUrl + ').', ''] : []), + (n.prevTag ? '[Compare ' + n.prevTag + '...v' + n.version + '](https://github.com/' + n.repo + '/compare/' + n.prevTag + '...v' + n.version + ') · ' : '') + '[Full changelog](' + changelogUrl + ')', + '', + ].join('\n'); + let omitted = 0, body = render(0); + for (const g of [...GROUPS].reverse().map(([g]) => g)) { + while (body.length > NOTES_CAP && grouped[g].length) { + grouped[g].pop(); + body = render(++omitted); + } + } + return { ok: true, body, versions: span.length }; +} diff --git a/crew/test/release-cadence.test.ts b/crew/test/release-cadence.test.ts index 6988b80ab0d..e05cb850df8 100644 --- a/crew/test/release-cadence.test.ts +++ b/crew/test/release-cadence.test.ts @@ -185,7 +185,7 @@ describe('planDaily', () => { expect(blocked.decision?.lines[0]).toStartWith('NO_RELEASE_PR: important change waiting, no release PR'); expect(blocked.planned.ok).toBe(false); - const stamped = r.commit('release 1.0.1', { VERSION: '1.0.1\n', 'changelog.d/fix.md': null }); + const stamped = r.commit('release 1.0.1', { VERSION: '1.0.1\n', 'CHANGELOG.md': '# Changelog\n\n## [1.0.1] - 2026-11-02\n\n- **The fix.**\n\n## [1.0.0] - 2026-11-01\n\n**First.**\n', 'changelog.d/fix.md': null }); r.refresh(); const cut = day(25); expect(cut.decision).toMatchObject({ action: 'cut', trigger: 'important' }); @@ -217,7 +217,7 @@ describe('planDaily', () => { // seam=gh faked (only the last release view fails), git real; no_claim=which gh errors are transient test('a plan that clears while the daily check cannot date stable is FLOOR_UNKNOWN, never a cuttable plan with no decision', () => { const r = repo(); - r.commit('release 1.0.1', { VERSION: '1.0.1\n' }); + r.commit('release 1.0.1', { VERSION: '1.0.1\n', 'CHANGELOG.md': '# Changelog\n\n## [1.0.1] - 2026-11-02\n\n- **The fix.**\n\n## [1.0.0] - 2026-11-01\n\n**First.**\n' }); r.refresh(); const g = gitIn(r.work); const green = fakeGh(); @@ -278,7 +278,7 @@ describe.skipIf(process.platform === 'win32')('release-cut --daily (the workflow expect(plainCut.status).toBe(1); expect(plainCut.stdout).toContain('::error title=release-cut NO_RELEASE_PR::'); - const stamped = r.commit('release 1.0.1', { VERSION: '1.0.1\n', 'changelog.d/fix.md': null, 'changelog.d/docs.md': null }); + const stamped = r.commit('release 1.0.1', { VERSION: '1.0.1\n', 'CHANGELOG.md': '# Changelog\n\n## [1.0.1] - 2026-11-02\n\n- **The fix.**\n\n## [1.0.0] - 2026-11-01\n\n**First.**\n', 'changelog.d/fix.md': null, 'changelog.d/docs.md': null }); r.refresh(); const due = run('--daily', '--dry-run'); expect(due.status, due.stdout + due.stderr).toBe(0); @@ -299,4 +299,34 @@ describe.skipIf(process.platform === 'win32')('release-cut --daily (the workflow expect(ref.status).toBe(2); expect(ref.stderr).toContain('--daily picks its own candidate'); }); + + // Value: protects=no version to cut today needs no notes: a stamped version whose CHANGELOG lacks its entry leaves a day with no due trigger green, + // and only a due cut refuses NOTES_MISSING; fails_when=the daily check goes red on a quiet day because the notes were built before the decision, or a + // due cut publishes without notes; why_new=planDaily dropped the candidate on NOTES_MISSING, so no decision ran; seam=gh shim on PATH, real bare origin; + // no_claim=GitHub's API or a real gh + test('a version with no CHANGELOG entry stays green on a day with no due trigger and refuses NOTES_MISSING only when a cut is due', () => { + const r = repo(30); + const shim = path.join(r.root, 'shim'); + fs.mkdirSync(shim); + fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\ncase "$*" in\n' + ciShimCases(GREEN) + ' "release view v1.0.0 "*) echo \'{}\' ;;\n *) exit 1 ;;\nesac\n', { mode: 0o755 }); + const env: Record<string, string | undefined> = { ...process.env, PATH: shim + path.delimiter + process.env.PATH, GITHUB_ACTIONS: 'true' }; + for (const k of ['GITHUB_EVENT_NAME', 'GITHUB_STEP_SUMMARY']) delete env[k]; + const run = () => spawnSync(process.execPath, [...bunIsolationArgs(), 'run', path.join(path.resolve(import.meta.dir, '..', '..'), 'crew', 'scripts', 'release-cut.ts'), '--repo', 'o/r', '--daily'], + { cwd: r.work, encoding: 'utf8', timeout: 60_000, env }); + + r.commit('release 1.0.1', { VERSION: '1.0.1\n' }); + r.refresh(); + const quiet = run(); + expect(quiet.status, quiet.stdout + quiet.stderr).toBe(0); + expect(quiet.stdout.split('\n')[0]).toStartWith('DAILY: no-op: nothing important since stable'); + expect(quiet.stdout).not.toContain('NOTES_MISSING'); + + r.commit('fix the tar path (#4101)', { 'changelog.d/fix.md': '---\nimportant: security\n---\n- tar\n' }); + r.refresh(); + const due = run(); + expect(due.status, due.stdout + due.stderr).toBe(1); + expect(due.stdout.split('\n')[0]).toStartWith('DAILY: cut (important: security in #4101'); + expect(due.stdout).toContain('NOTES_MISSING: CHANGELOG.md at the release has no entry for v1.0.1'); + expect(due.stdout).toContain('::error title=release-cut NOTES_MISSING::'); + }); }); diff --git a/crew/test/release-cut.test.ts b/crew/test/release-cut.test.ts index 98eb767861b..d809e48f94e 100644 --- a/crew/test/release-cut.test.ts +++ b/crew/test/release-cut.test.ts @@ -17,6 +17,7 @@ import { BACKSTOP_CHECK, CUT_WORKFLOW, FLOOR_HOURS, NEVER_GATING_WORKFLOWS, NOTES_CAP, NOTES_REF, REQUIRED_CHECK, SCHEDULED_GRACE_HOURS, changelogEntries, compareVersions, cutRelease, describePlan, floorStatus, gateVerdict, gitIn, planRelease, readTrainNotes, releaseNotes, sanitizeReason, stableMovedAt, verifyRegression, verifySecurity, type Gh, type Git, type TrainEvidence, } from '../scripts/release-cut'; +import { changeLine, changeSources, changesIn, type NotesSources } from '../scripts/release-notes'; const bases: string[] = []; // A cut made a moment ago clears the 72-hour floor at this clock. @@ -128,10 +129,11 @@ describe('release-cut: planning', () => { f.shas['1.0.3']!.slice(0, 12) + ': ' + BACKSTOP_CHECK + ' is still running', f.shas['1.0.2']!.slice(0, 12) + ': red check runs: windows-free-tests', ]); - expect(r.plan.notes).toContain('First tagged release: the 2 versions, one line each'); - expect(r.plan.notes).toContain('- **1.0.1** (2026-10-21): Second: the updater no longer skips.'); - expect(r.plan.notes).toContain('- **1.0.0**'); - expect(r.plan.notes).not.toContain('1.0.2'); + expect(r.plan.notes).toContain('First tagged release: the 2 versions;'); + expect(r.plan.notes).toContain('- Second: the updater no longer skips.'); + expect(r.plan.notes).toContain('- First one.'); + expect(r.plan.notes).not.toContain('Third fixes Windows.'); + expect(r.plan.notes).not.toContain('see CHANGELOG'); const lines = describePlan(r.plan, true); expect(lines.some(l => l.startsWith('DRY_RUN:'))).toBe(true); expect(lines).toContain(' git push --force-with-lease=refs/heads/stable: origin ' + f.shas['1.0.1'] + ':refs/heads/stable'); @@ -605,10 +607,10 @@ describe('release-cut: cutting, hotfixes and the forward-only stable', () => { expect(promo.plan.prevStable).toBe(f.shas['1.0.3']); expect(promo.plan.prevTag).toBe('v1.0.3'); expect(promo.plan.notes).toContain('## gstack v1.0.4 (hotfix release)'); - expect(promo.plan.notes).toContain('1 version since v1.0.3'); + expect(promo.plan.notes).not.toContain('First tagged release'); expect(promo.plan.notes).toContain('compare/v1.0.3...v1.0.4'); - expect(promo.plan.notes).toContain('- **1.0.4**'); - expect(promo.plan.notes).not.toContain('- **1.0.3**'); + expect(promo.plan.notes).toContain('- Hotfix: the lease never blocks.'); + expect(promo.plan.notes).not.toContain('Fourth trims the preamble.'); const cut2 = cutRelease(promo.plan, { repo: f.repo, git: f.git, gh: f.gh, notesDir: f.base }); expect(cut2.ok, cut2.lines.join('\n')).toBe(true); expect(git(f.origin, 'rev-parse', 'refs/heads/stable')).toBe(hot); @@ -643,7 +645,7 @@ describe('release-cut: cutting, hotfixes and the forward-only stable', () => { expect(again.plan.stableAt).toBe(true); expect(again.plan.tagExists).toBe('same'); expect(again.plan.prevVersion).toBeNull(); - expect(again.plan.notes).toContain('First tagged release: the 4 versions, one line each'); + expect(again.plan.notes).toContain('First tagged release: the 4 versions;'); expect(describePlan(again.plan, true)[2]).toBe('STABLE: already at ' + f.shas['1.0.3']!.slice(0, 12) + ' (finishing an earlier cut)'); } const done = cutRelease(resumed, { repo: f.repo, git: f.git, gh: f.gh, notesDir: f.base }); @@ -665,9 +667,9 @@ describe('release-cut: cutting, hotfixes and the forward-only stable', () => { if (!finish.ok) return; expect(finish.plan.sha).toBe(hot); expect(finish.plan.prevTag).toBe('v1.0.3'); - expect(finish.plan.notes).toContain('1 version since v1.0.3'); + expect(finish.plan.notes).toContain('- Hotfix: the lease never blocks.'); expect(finish.plan.notes).toContain('compare/v1.0.3...v1.0.4'); - expect(finish.plan.notes).not.toContain('- **1.0.3**'); + expect(finish.plan.notes).not.toContain('Fourth trims the preamble.'); const once = planRelease({ repo: f.repo, git: f.git, gh: f.gh }); expect(cutRelease(finish.plan, { repo: f.repo, git: f.git, gh: f.gh, notesDir: f.base }).ok).toBe(true); expect(once.ok).toBe(true); @@ -739,7 +741,7 @@ describe.skipIf(process.platform === 'win32')('release-cut: the workflow entry p const written = fs.readFileSync(summary, 'utf8'); expect(written).toContain('- CANDIDATE: ' + f.shas['1.0.3']); expect(written).toContain('<details><summary>Release notes</summary>'); - expect(written).toContain('- **1.0.3** (2026-10-23): Fourth trims the preamble.'); + expect(written).toContain('- Fourth trims the preamble.'); expect(execFileSync('git', ['ls-remote', f.origin, 'refs/heads/stable', 'refs/tags/v1.0.3'], { encoding: 'utf8', timeout: 30_000 }).trim()).toBe(''); expect(fs.readFileSync(path.join(f.base, 'gh.log'), 'utf8')).not.toContain('gh release'); @@ -818,7 +820,7 @@ describe('release-cut: the 72-hour floor', () => { if (!schedEarly.ok) { expect(schedEarly.code).toBe('REFUSED_FLOOR'); expect(schedEarly.message).toContain('a scheduled run needs 69 h (72 h less 3 h cron grace)'); } const schedOk = plan(FLOOR_HOURS - SCHEDULED_GRACE_HOURS, true); expect(schedOk.ok, JSON.stringify(schedOk)).toBe(true); - if (schedOk.ok) expect(schedOk.plan.notes).toContain('## gstack v1.0.4 (regular release)'); + if (schedOk.ok) expect(schedOk.plan.notes).toContain('## gstack v1.0.4\n'); const handInGrace = plan(70); expect(handInGrace.ok).toBe(false); if (!handInGrace.ok) expect(handInGrace.code).toBe('REFUSED_FLOOR'); @@ -1052,9 +1054,10 @@ describe('release-cut: the security exception', () => { if (!next.ok) return; expect(next.plan.exception).toBeNull(); expect(next.plan.prevTag).toBe('v1.0.4'); - expect(next.plan.notes).toContain('## gstack v1.0.6 (regular release)'); - expect(next.plan.notes).toContain('2 versions since v1.0.4'); - expect(next.plan.notes).not.toContain('- **1.0.4**'); + expect(next.plan.notes).toContain('## gstack v1.0.6\n'); + expect(next.plan.ridingAlong).toBe(1); + expect(next.plan.notes).toContain('compare/v1.0.4...v1.0.6'); + expect(next.plan.notes).not.toContain('Hardens tar extraction.'); expect(next.plan.notes).not.toContain('Security release'); }, 30_000); @@ -1274,20 +1277,217 @@ describe.skipIf(process.platform === 'win32')('release-cut: refusals at the work }); describe('release-cut: notes', () => { - test('changelog headlines are the bold first line of each entry; versions order numerically', () => { - const entries = changelogEntries('# Changelog\n\n## [1.91.221.0] - 2026-10-25\n\n**The updater no longer skips.** More.\n\n### Fixed\n- x\n\n## [1.91.99.0] - 2026-10-01\n\n| a | b |\n\n**Older.**\n'); - expect(entries).toEqual([{ version: '1.91.221.0', date: '2026-10-25', headline: 'The updater no longer skips.' }, { version: '1.91.99.0', date: '2026-10-01', headline: 'Older.' }]); - expect(changelogEntries('## [1.0.0] - 2026-01-01\n\nPlain lead with **some** bold.\n')[0]!.headline).toBe('Plain lead with some bold.'); + // A fixture CHANGELOG in the shapes main has held: fragment-era bullets with bold leads, a plain bullet, + // and an older per-version entry with "### Fixed" and "### Tests" headings and a paragraph lead. + const CHANGELOG = [ + '# Changelog', '', + '## [2.1.0.0] - 2026-11-14', '', + '- **/review now reads Rust files (GST-101).** It used to skip them.', '', + '- **The installer no longer deletes your config.** It kept a copy.', '', + '- **/ship\'s outside voice now reads the whole diff.** Before, it read half.', '', + '- `gstack-redact` now says its 16 MiB limit. Reported by @someone (#90).', '', + '## [2.0.1.0] - 2026-11-10', '', + 'Faster startup for every skill.', '', + '### Fixed', '- **`bin/x`**: the updater stops skipping a version. More text.', '', + '### Tests', '- The free suite is green again.', '', + '## [2.0.0.0] - 2026-11-01', '', + '**Already released.**', '', + ].join('\n'); + const sources: NotesSources = { + versions: { + '2.1.0.0': { pr: null, files: ['CHANGELOG.md', 'VERSION'], fragments: [ + { pr: 11, files: ['review/SKILL.md', 'changelog.d/rust.md'], changes: changesIn(['- **/review now reads Rust files (GST-101).** It used to skip them.']) }, + { pr: 12, files: ['bin/gstack-install', 'changelog.d/config.md'], changes: changesIn(['- **The installer no longer deletes your config.** It kept a copy.']) }, + { pr: 13, files: ['test/ship-review.test.ts', 'changelog.d/voice.md'], changes: changesIn(['### Changed', '', '- **/ship\'s outside voice now reads the whole diff.** Before, it read half.']) }, + ] }, + '2.0.1.0': { pr: 9, files: ['lib/startup.ts', 'VERSION', 'CHANGELOG.md'], fragments: [] }, + }, + }; + + // Value: protects=release bodies list each change in plain words with its PR, grouped, never a "see CHANGELOG.md" stub; fails_when=a bullet-only + // entry yields no line (the v1.99.x stubs), a change links the release commit's PR instead of its own, groups ignore headings or files, internal + // codes leak, or the compare link goes missing; why_new=the old notes printed one headline per version and fell back to "see CHANGELOG.md". + test('a fixture changelog becomes grouped lines with their PR links and the compare link at the bottom', () => { + const notes = releaseNotes({ repo: 'o/r', version: '2.1.0.0', date: '2026-11-14', prevVersion: '2.0.0.0', prevTag: 'v2.0.0.0', entries: changelogEntries(CHANGELOG), hotfix: false, sources }); + expect(notes.ok).toBe(true); + if (!notes.ok) return; + expect(notes.versions).toBe(2); + expect(notes.body).toBe([ + '## gstack v2.1.0.0', '', + "### What's new", '', + '- /review now reads Rust files. ([#11](https://github.com/o/r/pull/11))', + '- `gstack-redact` now says its 16 MiB limit.', + '- Faster startup for every skill. ([#9](https://github.com/o/r/pull/9))', '', + '### Fixes', '', + '- The installer no longer deletes your config. ([#12](https://github.com/o/r/pull/12))', + '- `bin/x`: the updater stops skipping a version. ([#9](https://github.com/o/r/pull/9))', '', + '### Changes for maintainers', '', + "- /ship's second-model review now reads the whole diff. ([#13](https://github.com/o/r/pull/13))", + '- The free suite is green again. ([#9](https://github.com/o/r/pull/9))', '', + '[Compare v2.0.0.0...v2.1.0.0](https://github.com/o/r/compare/v2.0.0.0...v2.1.0.0) · [Full changelog](https://github.com/o/r/blob/v2.1.0.0/CHANGELOG.md)', '', + ].join('\n')); + expect(notes.body).not.toContain('see CHANGELOG'); + expect(notes.body).not.toContain('Already released.'); expect(compareVersions('1.91.221.0', '1.91.99.0')).toBeGreaterThan(0); expect(compareVersions('1.91.9.0', '1.91.10.0')).toBeLessThan(0); }); - test('a span of a thousand versions stays under the notes cap and says how many were cut', () => { - const entries = Array.from({ length: 1000 }, (_, i) => ({ version: '1.91.' + (i + 1) + '.0', date: '2026-10-20', headline: 'Headline number ' + i + ' with enough words to take some room in the body.' })); - const notes = releaseNotes({ repo: 'o/r', version: '1.91.1000.0', date: '2026-10-26', prevVersion: '1.91.0.0', prevTag: null, entries, hotfix: false }); - expect(notes.length).toBeLessThanOrEqual(NOTES_CAP); - expect(notes).toMatch(/- \.\.\.and \d+ more versions; see CHANGELOG\.md/); - expect(notes).toContain('1000 versions since v1.91.0.0'); - expect(notes.split('\n')[0]).toBe('## gstack v1.91.1000.0 (regular release)'); + // Value: protects=a security fix's release line keeps its CVE or GHSA advisory id while internal issue codes still drop; fails_when=the issue-code + // stripper removes an advisory id; why_new=the stripper matched any CODE-123 in parentheses; seam=none; no_claim=GitHub's advisory formats beyond these two. + test('a change line keeps CVE and GHSA ids and drops internal issue codes', () => { + expect(changeLine('**Browse no longer follows symlinks out of the profile dir (CVE-2026-41234).** More.')).toBe('Browse no longer follows symlinks out of the profile dir (CVE-2026-41234).'); + expect(changeLine('**The tar path is safe again (GHSA-4x5v-abcd-1234, reported by a user).** More.')).toBe('The tar path is safe again (GHSA-4x5v-abcd-1234, reported by a user).'); + expect(changeLine('**/review now reads Rust files (GST-101).** More.')).toBe('/review now reads Rust files.'); + }); + + // Value: protects=a cut fails loudly instead of publishing a stub; fails_when=a version with an empty entry or a span with no entry still + // yields notes; why_new=the old notes always rendered, padding gaps with "see CHANGELOG.md". + test('a version with no change or a missing entry refuses instead of publishing a stub', () => { + const base = { repo: 'o/r', date: '2026-11-14', prevVersion: '2.0.0.0', prevTag: 'v2.0.0.0', hotfix: false }; + const hollow = releaseNotes({ ...base, version: '2.1.0.0', entries: changelogEntries('## [2.1.0.0] - 2026-11-14\n\n## [2.0.5.0] - 2026-11-12\n\n- One change.\n') }); + expect(hollow).toEqual({ ok: false, why: 'no change to list in the CHANGELOG entry of v2.1.0.0; write the entry before cutting the release' }); + const missing = releaseNotes({ ...base, version: '2.1.0.0', entries: changelogEntries('## [2.0.0.0] - 2026-11-01\n\n- Old.\n') }); + expect(missing).toEqual({ ok: false, why: 'CHANGELOG.md at the release has no entry for v2.1.0.0 or any version since v2.0.0.0' }); + }); + + // Value: protects=a release names the version it ships, never an older one's changes under its heading; fails_when=a span holding only an older + // entry than the release version still publishes; why_new=the span filter took any entry in (prev, version]; seam=none; no_claim=folded versions. + test('a release version with no entry of its own refuses even when an older version in the span has one', () => { + const notes = releaseNotes({ repo: 'o/r', version: '2.1.0.0', date: '2026-11-14', prevVersion: '2.0.0.0', prevTag: 'v2.0.0.0', hotfix: false, entries: changelogEntries('## [2.0.5.0] - 2026-11-12\n\n- One change.\n\n## [2.0.0.0] - 2026-11-01\n\n- Old.\n') }); + expect(notes).toEqual({ ok: false, why: 'CHANGELOG.md at the release has no entry for v2.1.0.0, only for the older v2.0.5.0; write the entry before cutting the release' }); + }); + + // Value: protects=a fragment links the PR of the commit that added it even when its own text cites another PR; fails_when=the lookup reads the + // commit's patch along with its subject and takes the last "(#N)" it finds; why_new=git log with --diff-merges printed the patch; seam=a real git repo. + test('a fragment whose body cites another PR still links the PR of the commit that added it', () => { + const f = fixture(); + fs.mkdirSync(path.join(f.seed, 'changelog.d'), { recursive: true }); + fs.writeFileSync(path.join(f.seed, 'changelog.d', 'redact.md'), '- **gstack-redact now says its size limit.** It follows the limit #7 added (#7).\n'); + git(f.seed, 'add', '-A'); + git(f.seed, 'commit', '-q', '-m', 'Say the redact size limit (#42)'); + fs.writeFileSync(path.join(f.seed, 'CHANGELOG.md'), fs.readFileSync(path.join(f.seed, 'CHANGELOG.md'), 'utf8').replace('# Changelog\n', '# Changelog\n\n## [1.0.4] - 2026-10-24\n\n- **gstack-redact now says its size limit.** It follows the limit #7 added (#7).\n')); + fs.rmSync(path.join(f.seed, 'changelog.d', 'redact.md')); + git(f.seed, 'add', '-A'); + git(f.seed, 'commit', '-q', '-m', 'v1.0.4 release (#43)'); + git(f.seed, 'push', '-q', 'origin', 'main'); + f.refresh(); + const sources = changeSources(f.git, f.shas['1.0.3']!, 'origin/main'); + expect(sources.versions['1.0.4']?.pr).toBeNull(); + expect(sources.versions['1.0.4']?.fragments.map(s => s.pr)).toEqual([42]); + }); + + // Value: protects=planRelease reads each change's PR from git and refuses a cut whose CHANGELOG lacks the version; fails_when=the fragment's + // own PR is not found along main, the release commit's PR is linked instead, or a missing entry still cuts; why_new=the notes never read git. + test('a cut links the PR that added each fragment, not the release commit, and refuses a version with no entry', () => { + const f = fixture(); + const first = planRelease({ repo: f.repo, git: f.git, gh: f.gh }); + expect(first.ok).toBe(true); + if (!first.ok) return; + expect(cutRelease(first.plan, { repo: f.repo, git: f.git, gh: f.gh, notesDir: f.base }).ok).toBe(true); + const fragment = '- **The lease no longer blocks a push.** It waits instead.\n'; + fs.mkdirSync(path.join(f.seed, 'changelog.d'), { recursive: true }); + fs.writeFileSync(path.join(f.seed, 'changelog.d', 'lease.md'), fragment); + fs.writeFileSync(path.join(f.seed, 'lease.ts'), 'export const lease = 1;\n'); + git(f.seed, 'add', '-A'); + git(f.seed, 'commit', '-q', '-m', 'Stop the lease blocking a push (#42)'); + const changelog = fs.readFileSync(path.join(f.seed, 'CHANGELOG.md'), 'utf8').replace('# Changelog\n', '# Changelog\n\n## [1.0.4] - 2026-10-24\n\n' + fragment); + fs.writeFileSync(path.join(f.seed, 'CHANGELOG.md'), changelog); + fs.writeFileSync(path.join(f.seed, 'VERSION'), '1.0.4\n'); + fs.rmSync(path.join(f.seed, 'changelog.d', 'lease.md')); + git(f.seed, 'add', '-A'); + git(f.seed, 'commit', '-q', '-m', 'v1.0.4 release (#43)'); + git(f.seed, 'push', '-q', 'origin', 'main'); + const stamp = git(f.seed, 'rev-parse', 'HEAD'); + f.refresh(); + const r = planRelease({ repo: f.repo, ref: stamp, git: f.git, gh: f.gh, now: pastFloor }); + expect(r.ok, JSON.stringify(r)).toBe(true); + if (!r.ok) return; + expect(r.plan.notes).toContain('### Fixes\n\n- The lease no longer blocks a push. ([#42](https://github.com/o/r/pull/42))'); + expect(r.plan.notes).not.toContain('#43'); + + fs.writeFileSync(path.join(f.seed, 'VERSION'), '1.0.5\n'); + fs.writeFileSync(path.join(f.seed, 'CHANGELOG.md'), changelog.replace('# Changelog\n', '# Changelog\n\n## [1.0.5] - 2026-10-25\n\n')); + git(f.seed, 'commit', '-q', '-am', 'v1.0.5 with an empty entry'); + git(f.seed, 'push', '-q', 'origin', 'main'); + const bare = git(f.seed, 'rev-parse', 'HEAD'); + f.refresh(); + const refused = planRelease({ repo: f.repo, ref: bare, git: f.git, gh: f.gh, now: pastFloor }); + expect(refused.ok).toBe(false); + if (!refused.ok) expect([refused.code, refused.message]).toEqual(['NOTES_MISSING', 'no change to list in the CHANGELOG entry of v1.0.5; write the entry before cutting the release']); + }); + // Value: protects=each change links the PR whose squash commit added its own fragment file; fails_when=a change links another fragment's PR because + // its words appear inside that fragment, or a fragment file name reused after a release links the later PR; why_new=the lookup matched CHANGELOG + // prose against fragment bodies and took a file name's newest add; seam=a real git repo; no_claim=merge-commit histories. + test('each change links the PR that added its own fragment file, even with overlapping words or a reused fragment name', () => { + const f = fixture(); + const first = planRelease({ repo: f.repo, git: f.git, gh: f.gh }); + expect(first.ok).toBe(true); + if (!first.ok) return; + expect(cutRelease(first.plan, { repo: f.repo, git: f.git, gh: f.gh, notesDir: f.base }).ok).toBe(true); + fs.mkdirSync(path.join(f.seed, 'changelog.d'), { recursive: true }); + const commit = (subject: string, files: Record<string, string | null>) => { + for (const [file, text] of Object.entries(files)) { + if (text === null) fs.rmSync(path.join(f.seed, file)); + else fs.writeFileSync(path.join(f.seed, file), text); + } + git(f.seed, 'add', '-A'); + git(f.seed, 'commit', '-q', '-m', subject); + }; + const lease = '- **The lease no longer blocks a push.**\n'; + const retry = '- **The lease retries once.** It builds on the fix where the lease no longer blocks a push.\n'; + const tar = '- **The tar path is safe again.**\n'; + commit('Stop the lease blocking a push (#42)', { 'changelog.d/fix.md': lease }); + commit('Retry the lease once (#44)', { 'changelog.d/a-retry.md': retry }); + let changelog = fs.readFileSync(path.join(f.seed, 'CHANGELOG.md'), 'utf8').replace('# Changelog\n', '# Changelog\n\n## [1.0.4] - 2026-10-24\n\n' + retry + '\n' + lease); + commit('v1.0.4 release (#43)', { 'CHANGELOG.md': changelog, VERSION: '1.0.4\n', 'changelog.d/fix.md': null, 'changelog.d/a-retry.md': null }); + commit('Make the tar path safe (#50)', { 'changelog.d/fix.md': tar }); + changelog = changelog.replace('# Changelog\n', '# Changelog\n\n## [1.0.5] - 2026-10-25\n\n' + tar); + commit('v1.0.5 release (#51)', { 'CHANGELOG.md': changelog, VERSION: '1.0.5\n', 'changelog.d/fix.md': null }); + git(f.seed, 'push', '-q', 'origin', 'main'); + const stamp = git(f.seed, 'rev-parse', 'HEAD'); + f.refresh(); + const r = planRelease({ repo: f.repo, ref: stamp, git: f.git, gh: f.gh, now: pastFloor }); + expect(r.ok, JSON.stringify(r)).toBe(true); + if (!r.ok) return; + const link = (n: number) => '([#' + n + '](https://github.com/o/r/pull/' + n + '))'; + expect(r.plan.notes).toContain('- The lease no longer blocks a push. ' + link(42)); + expect(r.plan.notes).toContain('- The lease retries once. ' + link(44)); + expect(r.plan.notes).toContain('- The tar path is safe again. ' + link(50)); + expect(r.plan.notes.match(/\/pull\//g)?.length).toBe(3); + }); + + // Value: protects=a long span still publishes, cut to the cap with a pointer to the full changelog; fails_when=notes over the cap refuse the + // cut, run past the cap, or drop changes without saying how many; why_new=the cap refused the whole release; seam=none; no_claim=GitHub's own limit. + test('notes over the cap keep the newest changes and send the rest to the full changelog', () => { + const entries = Array.from({ length: 1000 }, (_, i) => ({ version: '2.0.' + (i + 1) + '.0', date: '2026-11-10', changes: [{ text: 'Change number ' + i + ' with enough words to take some room in the body.', heading: '' }] })); + const long = releaseNotes({ repo: 'o/r', date: '2026-11-14', prevVersion: '2.0.0.0', prevTag: 'v2.0.0.0', hotfix: false, version: '2.0.1000.0', entries }); + expect(long.ok).toBe(true); + if (!long.ok) return; + expect(long.versions).toBe(1000); + expect(long.body.length).toBeLessThanOrEqual(NOTES_CAP); + expect(long.body).toContain('- Change number 999 with enough words'); + expect(long.body).not.toContain('- Change number 0 with'); + const more = /\n(\d+) more changes are in the \[full changelog\]\(https:\/\/github\.com\/o\/r\/blob\/v2\.0\.1000\.0\/CHANGELOG\.md\)\.\n/.exec(long.body); + expect(more).not.toBeNull(); + expect(long.body.match(/^- Change number/gm)!.length + Number(more![1])).toBe(1000); + expect(long.body.trimEnd().endsWith('[Full changelog](https://github.com/o/r/blob/v2.0.1000.0/CHANGELOG.md)')).toBe(true); + }); + + // Value: protects=a "## " heading a fragment carries into the CHANGELOG keeps every change after it in that version; fails_when=the version's + // section ends at that heading and later changes vanish from the notes; why_new=any "## " line ended a version; seam=none; no_claim=lib/restamp.ts. + test('a "## " heading inside a version keeps the changes after it', () => { + const entries = changelogEntries('# Changelog\n\n## [2.1.0.0] - 2026-11-14\n\n- **One.**\n\n## Notes for contributors\n\n- **Two.**\n\n## [2.0.0.0] - 2026-11-01\n\n- Old.\n'); + expect(entries.map(e => [e.version, e.changes.map(c => [c.text, c.heading])])).toEqual([ + ['2.1.0.0', [['**One.**', ''], ['**Two.**', 'Notes for contributors']]], + ['2.0.0.0', [['Old.', '']]], + ]); + }); + + // Value: protects=a parenthetical that only starts like an issue code (SHA-256 ..., UTF-8 ...) stays in the line while a list of issue codes still + // drops; fails_when=the stripper removes "(SHA-256 of its bytes, ...)"; why_new=the stripper dropped any parenthetical opening with CODE-123; + // seam=none; no_claim=a bare "(SHA-256)", which has an issue code's shape. + test('a change line keeps a parenthetical that only starts like an issue code', () => { + expect(changeLine('**Receipts now pin each file (SHA-256 of its bytes, not its name).** More.')).toBe('Receipts now pin each file (SHA-256 of its bytes, not its name).'); + expect(changeLine('**Reports lead with failures (GST-1455, GST-2349).** More.')).toBe('Reports lead with failures.'); }); }); diff --git a/docs/releases.md b/docs/releases.md index 322c4d318ac..ca1ce0dfe8e 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -30,9 +30,10 @@ change or a week-old stable can trigger one. A cut takes the newest green commit on main and: 1. tags it `v<VERSION>` (the VERSION file at that commit, an annotated tag); -2. publishes a GitHub Release whose notes are one line per CHANGELOG version - since the previous release, with a compare link and a link to the full - CHANGELOG at that tag; +2. publishes a GitHub Release whose notes list every change in the CHANGELOG + versions since the previous release, one plain line each with the pull + request that made it, then a compare link and a link to the full CHANGELOG + at that tag ([Release notes](#release-notes)); 3. fast-forwards the `stable` branch to it. A tag and its release never change. `stable` is a moving pointer: always a @@ -101,6 +102,45 @@ finished by the next run, by cron or by hand: `stable` itself stays a candidate until its release exists, and its notes compare against the release tag before it. +## Release notes + +A release's notes list every change in the CHANGELOG versions it ships. A +change is a top-level bullet of a version's entry, or a paragraph that is not a +bullet. Its line is the bullet's bold lead when that lead is a whole sentence, +else its first sentence, so a fragment's first sentence is what people read on +the release page: say what changed for them, in plain words. A parenthesis +that holds only issue codes, such as `(GST-101)` or `(GST-1455, GST-2349)`, +is dropped; one that says more, such as `(SHA-256 of the file)`, and CVE and +GHSA ids stay. "Outside voice" reads "second-model review". A `## ` heading +inside a fragment is read like a `### ` one and never ends its version. + +Each line links the pull request that made the change, read from git and never +from the change's words. The commit that added a version's `## [version]` +heading folded the `changelog.d/` fragments it deleted, in path order, so the +version lists each of those fragments' changes, as the fragment read just +before the fold, linked to the trailing `(#N)` of the squash commit that added +that file (wherever that commit sits, since a release can fold fragments that +landed before the previous one; a later pull request that reuses the file name +never takes the link). Changes the version holds past its fragments', and every +change of an older version written straight into the CHANGELOG, link the +commit that added the version's heading; a release commit links nothing. +Lines sit under three headings, read in this order: + +1. the heading the change sits under, inside its fragment when it has one: + `### Added` is What's new, `### Fixed` is Fixes, and `### Tests` or + `### For contributors` is Changes for maintainers; +2. Changes for maintainers when its pull request touched only tests, CI and + gstack's own release tooling (`test/`, `crew/`, `.github/`), or its line + names that machinery (receipts, the release gate, the merge queue); +3. Fixes when the line says "no longer", "again" or "fix"; What's new otherwise. + +A cut whose CHANGELOG has no entry for its version, or holds a version entry +that lists no change, stops with `NOTES_MISSING` instead of publishing empty +notes. Notes over 60,000 characters keep the changes that fit, dropping +maintainer changes first, and say how many more are in the full changelog. An upgrade step or a summary +sentence can be added by hand after the cut with +`gh release edit v<X> --notes-file <file>`; that edits the release page only. + <a id="the-daily-check"></a> ## The daily check @@ -441,7 +481,7 @@ first, then promote. Run the workflow with `dry_run=true` (the default for a manual run) to see the plan without changing anything: the candidate, its VERSION and tag, the stable -move, how many version lines the notes would carry, every skipped commit with +move, how many change lines the notes would carry, every skipped commit with its reason, the floor verdict, and the exact commands a real cut would run. The scheduled runs are never dry runs. @@ -454,8 +494,8 @@ gh run watch The step summary carries the same plan plus the full release notes. A pull request that touches `.github/workflows/weekly-release.yml`, -`crew/scripts/release-cut.ts`, `crew/scripts/release-cadence.ts` or -`lib/changelog-fragments.ts` runs the same dry run against main as its own job +`crew/scripts/release-cut.ts`, `crew/scripts/release-notes.ts`, +`crew/scripts/release-cadence.ts` or `lib/changelog-fragments.ts` runs the same dry run against main as its own job (`Dry run against main`, read-only token), once plain and once as the daily check, so a change to the release tooling is exercised against real check runs before it merges. @@ -542,4 +582,5 @@ reset --hard 'v<good version>'`. Its next update check fast-forwards it to | `DAILY: no-op: ...`, `DAILY: wait: ...` | the daily check found no trigger, or an important change still under its 24-hour floor (`NEXT_ALLOWED:` follows); exit 0 with a notice | | `IMPORTANT_UNGATED: ...` | an important change landed but no green, gated commit holds it yet; informational | | `NO_RELEASE_PR: ...` | the candidate's VERSION is already released on an earlier commit (no release PR landed since that cut): the Captain stamps a release PR. A plain cut always reports it; the daily check reports it only when a trigger is due. Exit 1 (0, with a warning, on a dry run) | +| `NOTES_MISSING: ...` | the CHANGELOG at the candidate has no entry for its version, or a version in the span lists no change ([Release notes](#release-notes)); nothing is tagged or published. Exit 1 | | `STABLE_STALE: ...` | stable is 7 days old and main moved, but nothing newer is green and gated; exit 1 (0 on a dry run) | diff --git a/scripts/harness-pins/scripts/test-pr-profile.ts.json b/scripts/harness-pins/scripts/test-pr-profile.ts.json index c22d2e373e3..1c96603f13f 100644 --- a/scripts/harness-pins/scripts/test-pr-profile.ts.json +++ b/scripts/harness-pins/scripts/test-pr-profile.ts.json @@ -1 +1 @@ -{"blob":"285f2a8b910fdf6503c555810a96995c7615f9df","since":6,"nonBehavioral":"test-pr-profile.ts only repoints paths and an import to files that moved unchanged into crew/ (GST-1833), on top of main's plain-title entries that no PR-gate case reads; no verdict can change"} +{"blob":"6f9f93ff672653c72d9e0d97ff9499b6062890a3","since":6,"nonBehavioral":"adds crew/scripts/release-notes.ts to the free-only list beside release-cut.ts"} diff --git a/scripts/test-pr-profile.ts b/scripts/test-pr-profile.ts index 285f2a8b910..6f9f93ff672 100644 --- a/scripts/test-pr-profile.ts +++ b/scripts/test-pr-profile.ts @@ -292,6 +292,7 @@ export const FREE_ONLY_PR_FILES = [ '.github/workflows/release-gate.yml', // The 8-hour release gate on main: it dispatches evals.yml on main's head; no PR-gate case reads it, and it never gates a PR. '.github/workflows/weekly-release.yml', // The Monday release cut (tag, stable, GitHub Release): reads check runs on main; no paid case reads it, and it never gates a PR. 'crew/scripts/release-cut.ts', // The release cut's logic, run only by weekly-release.yml; covered by the free crew/test/release-cut.test.ts. + 'crew/scripts/release-notes.ts', // The release cut's notes, run only by weekly-release.yml; covered by the free crew/test/release-cut.test.ts. '.github/actionlint.yaml', // Runner labels for actionlint only. 'scripts/ship-measure-sweep.ts', // The weekly sweep CLI; it launches paid cases, never runs inside one. '.github/workflows/version-gate.yml', diff --git a/test/weekly-release-workflow.test.ts b/test/weekly-release-workflow.test.ts index 0ad32aaef2c..bbd68f31d23 100644 --- a/test/weekly-release-workflow.test.ts +++ b/test/weekly-release-workflow.test.ts @@ -40,7 +40,7 @@ describe('weekly-release.yml', () => { expect(wf.on.workflow_dispatch.inputs.regression).toMatchObject({ type: 'string', default: '' }); expect(wf.on.workflow_dispatch.inputs.dry_run).toMatchObject({ type: 'boolean', default: true }); expect(wf.on.workflow_dispatch.inputs.ref).toMatchObject({ type: 'string', default: '' }); - expect(wf.on.pull_request).toEqual({ paths: ['.github/workflows/weekly-release.yml', 'crew/scripts/release-cut.ts', 'crew/scripts/release-cadence.ts', 'lib/changelog-fragments.ts'] }); + expect(wf.on.pull_request).toEqual({ paths: ['.github/workflows/weekly-release.yml', 'crew/scripts/release-cut.ts', 'crew/scripts/release-notes.ts', 'crew/scripts/release-cadence.ts', 'lib/changelog-fragments.ts'] }); expect(wf.concurrency).toEqual({ group: "weekly-release-${{ github.event.pull_request.number || 'cut' }}", 'cancel-in-progress': false }); expect(wf.permissions).toEqual({}); expect(Object.keys(wf.jobs)).toEqual(['cut', 'dry-run']); From 88da124dbc68ad886f4aef467d4b09375041ad86 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 01:39:04 +0800 Subject: [PATCH 45/62] Plan a trial of /ship without its separate conductor subagent (GST-3003) (#4456) Adds the locked plan for a paid trial: does /ship cost less and catch as much when the pull request's own thread runs it, instead of a separate subagent? Why: that subagent's own steps cost about $22 of a $35 /ship run, and the keep-or-drop decision is written down here before anything is spent. Nothing to do: no code changes; paid runs start only after this merges and the budget is approved. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/outside-voice#1 reader=outside-voice --- changelog.d/capy-plan-a-trial-of.md | 1 + docs/evals/ship-conductor-fold-prereg.md | 190 +++++++++++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 changelog.d/capy-plan-a-trial-of.md create mode 100644 docs/evals/ship-conductor-fold-prereg.md diff --git a/changelog.d/capy-plan-a-trial-of.md b/changelog.d/capy-plan-a-trial-of.md new file mode 100644 index 00000000000..0f4dad30063 --- /dev/null +++ b/changelog.d/capy-plan-a-trial-of.md @@ -0,0 +1 @@ +- **A locked plan for a trial of /ship without its separate conductor subagent (GST-3003).** `docs/evals/ship-conductor-fold-prereg.md` fixes, before any paid run, the bars, arms (today's /ship, the folded /ship and a no-gstack review), cases, scoring and stop rules for testing whether a pull request's own thread can run /ship's phases and start its reviewers itself, at no extra cost and with nothing missed that today's /ship catches. diff --git a/docs/evals/ship-conductor-fold-prereg.md b/docs/evals/ship-conductor-fold-prereg.md new file mode 100644 index 00000000000..ad5479b529c --- /dev/null +++ b/docs/evals/ship-conductor-fold-prereg.md @@ -0,0 +1,190 @@ +# Prereg: does /ship need its conductor subagent? (GST-3003) + +frozen: 2026-11-17 + +Status: locked at merge, before any paid call. Owner: GStack Minder (GSTA-36); runner GSTA-589. Paid runs start only +after this file merges and the owner approves the budget below. + +## Question +When a Capy thread ships a pull request today, it starts one extra subagent, the conductor, whose only job is to run +/ship's phases (`ship/DRIVER.md`) and start /ship's reviewers. A profile of 12 recent runs (gstack 5dcd76b) counted +the conductor's own steps at $21.62 of a $34.66 run, carrying about 231k tokens of context a step. Since #4451 +(0ee59146), `gstack-ship-phase run|program` runs one DRIVER phase per call, the receipt counts `calls=`, and a run +prints `STOP: past 100 minutes`. So the pull request's own thread could run each phase itself and start the reviewers +itself, with no conductor in between. + +Does that folded /ship cost no more than today's /ship, and does it miss nothing today's /ship catches? + +## Bars +- lesson: whether a frontier model shipping a pull request needs a separate subagent to run its review procedure, or can run the procedure itself at no loss in what review catches +- cost per run, F minus C (thread plus all its subagents, cost.dollars): pass when the paired 95% interval's upper bound is at or below $0 or the interval contains $0; lower is better +- planted-bug catch rate, F minus C: pass when no case is a structural loss (below) and the paired 95% interval's upper bound is not below 0; higher is better +- real-problem catch rate, F minus C: the same bar as planted bugs, over the real problems found in the case (below); higher is better +- reader fidelity in F: every reviewer the run's printed review plan names is started and collected, in 30 of 30 F trials; higher is better +- wall time per run and `calls=` from the receipt: reported paired with 95% intervals, no bar (diagnostics) + +A **structural loss** is a case where C catches the problem in all 3 of its trials and F in none of its 3. If the two +arms are equally good, the chance of seeing at least one structural loss somewhere in 10 cases is at most 14.6% (worst +case, at a per-trial catch rate of 0.5). A literal "F misses one thing C caught once" rule with one trial each would +fire 83% of the time at a shared catch rate of 0.8, so it would decide on noise, not on the fold. + +## Decisions +- if F costs no more than C and misses nothing C catches (every bar above passes): the conductor goes. A follow-up pull request makes the folded procedure ship/DRIVER.md's default for Capy threads, and the crew rule that starts one /ship subagent per head (R104, CREW.md rule 4) is retired through GStack Minder and FOUN-32 +- if both cost and catch rates are a tie inside the run-to-run variation (both 95% intervals contain 0, no structural loss, fidelity 30 of 30): the conductor goes, as above, because the fold removes one agent layer at no measured loss; the results say plainly that differences smaller than the stated mdd could not be seen +- if F costs clearly more (the cost interval's lower bound is above $0): the conductor stays, R104 stands, and the results name the phase where the fold's extra spend went +- if F misses something C catches (a structural loss, a catch-rate interval entirely below 0, or fidelity under 30 of 30): the conductor stays, and the fold's reviewer dispatch gets one FIX-METHOD cycle; any retry is a new preregistration +- if the no-gstack arm's planted-bug catch rate is not below the better /ship arm's (paired interval contains 0 or is above it) at a quarter of that arm's cost or less: /ship's review panel gets one R48 "Why null?" cycle under G3 (which reviewers earn their place), and Garry hears the result as a cut-candidate question; the conductor decision above is unchanged +- if the no-gstack arm catches less, or costs more than a quarter of the better /ship arm: nothing changes beyond the conductor decision; its row is reported beside the others +- if the run stops incomplete (spend cap, a harness stop, or a scorer or judge below its bar): no decision is taken, R104 stands, and every finished trial is reported + +## Arms +- `claude-opus-5-5#ship-conductor` (C): today's /ship. A fresh Capy thread on Claude Opus 5.5 (reasoning high) starts one /ship subagent on a fresh machine, which runs ship/DRIVER.md through `gstack-ship-phase` and starts its reviewers. Planned at $38 a run ($34.66 counted mean plus about $3 for the thread itself) +- `claude-opus-5-5#ship-folded` (F): the same thread, brief and gstack revision, except that the thread runs ship/DRIVER.md itself, one `gstack-ship-phase` program per phase, and starts the reviewers as its own subagents. Planned at $38 a run (the same as C, so the budget does not assume the saving) +- `claude-opus-5-5#no-gstack` (N): the same model and case, no gstack, a plain review prompt (below). Scored on catches and cost only. Planned at $6 a run + +## Briefs +Reviewer models are /ship's own in both C and F (the second-model reviewer from `voice-models.json`); only who runs +the procedure differs. GPT-6.1 Sol is not an arm: the decision concerns Capy threads, which run on Opus 5.5 (R38). + +Briefs, frozen. Shared part: "You own branch `<branch>` on garrytan/gstack; its base is `<base>`. Install gstack for +ship, then run /ship at the branch head against `<base>`. Stop at `SHIP_RECEIPT:` or wherever /ship stops, skip +`gstack-ship-queue ready`, and never merge. Report the receipt line, the `CALLS:` line and the stop reason if any." +C adds: "Run /ship the usual way: one fresh /ship subagent (machine: fresh) runs it." F adds: "Run /ship yourself in +this thread: follow ship/DRIVER.md phase by phase with gstack-ship-phase, and start its reviewers as your own +subagents. Do not start a subagent to run /ship." + +## Comparison +stack: loaded + +C and F load gstack by design; the question is about gstack's /ship procedure. + +## No-gstack arm +- arms: `claude-opus-5-5#no-gstack` +- inputs: the same 10 cases, the same branch and base, the same planted bug +- prompt: "Review this PR (branch `<branch>` against `<base>`, checked out here) for bugs that would fail a test, break production or lose data. List each as path:line and the cause." No SKILL.md, preamble, hooks, installed skills or routing lines +- panel: the same kind (`behavior`, 3 independent trials per case), the same catch rule and the same real-problem judge +- harness: the Claude Agent SDK with the `claude_code` preset, reasoning effort high, Bash, Read and Grep tools; cost from the SDK's reported total at list price. This differs from C and F (Capy threads), because a Capy thread cannot hide the owner's drives; its cost is comparable to theirs in size, not to the cent +- report: its row sits beside C and F in every results table and verdict, including when it wins +- masking: a container on a runner VM that sees no Capy drive, holding only the case checkout +- install: `test ! -e ~/.local/share/gstack && test ! -e ~/.claude/skills` inside the container before each run +- audit: each transcript is scanned for reads under `.capy/drive`, `.local/share/gstack` or `.claude/skills`; a trial that read a gstack skill file is contaminated and scores zero + +## Cases +Ten cases, the same ten in every arm (fully paired, the strongest form of matching by size class). A separate +sealing subagent picks them after this file merges, by these rules: + +1. **Host pull request.** A garrytan/gstack pull request merged on or after 2026-07-01 (after Opus 5.5's training + cutoff), whose revert applies cleanly to one frozen main commit, and whose reverted tree passes typecheck and the + host's own tests. Excluded: changes to docs, generated files, VERSION or CHANGELOG only, and changes to /ship or + review tooling itself (`ship/`, `lib/ship-*`, `bin/gstack-ship-*`, `bin/gstack-review-*`). +2. **Size class**, by changed lines without generated files and lockfiles: 3 small (under 150), 4 medium (150 to + 600), 3 large (over 600). At least 3 of the 10 are hosts that `gstack-review-plan` sends to the full panel + (security, user data, money or merge-check code), so reviewer dispatch runs at its widest. +3. **Planted bug.** One hunk of at most 15 changed lines inside the host's own diff that re-introduces a bug a later + gstack commit fixed (a revert, or a fix whose description or regression test names the failure), adapted only as + far as needed to apply. Before sealing, each plant must (a) make that fix's regression test, or a test the sealer + writes from the fix's description, fail on the planted tree and pass without the plant, which proves it is a real + defect at the blocking floor; and (b) leave the host's existing tests passing. A plant the existing suite already + catches would be caught the same way by C and F, spending about $76 a trial pair to learn nothing about the + conductor, so the trial uses plants that a reviewer, or a test the run writes, has to find. +4. **Branches.** Per case, one base branch: frozen main with the host reverted and this file and its results file + removed, as one commit with a plain message. Per trial, one branch: the base plus the host's commit with the + plant folded in, under the host's original title. Pull requests target the case's base branch, never main, so + nothing a trial does can land on main; every trial pull request is closed unmerged and its branches deleted once + it is scored. +5. **Labels.** The sealer writes one private label file: per case the host and its merge commit, base commit, size + and review class, the plant (path, labelled line, the hunk, the source fix, 2 to 4 cause words), and the random + seed that orders the cases. Its SHA-256 is posted on GST-3003 before the first trial starts, and the results + print it. The file never enters the repository. + +## Procedure +Trials run in waves. Each wave starts C and F on the same case and trial at the same time, each in a new thread with +no earlier context, so time of day and CI load hit both alike; N runs separately, since it shares nothing with them. +Wave 1 is the pilot: trial 1 of the first 3 cases in all three arms. It counts toward the run unless a stop rule +fires. The order of cases follows the sealed seed. + +Measured per trial: cost.dollars of the arm's thread and all its subagents at its final report; wall time from the +brief to the final report; `calls=` from `SHIP_RECEIPT:` and the `CALLS:` line; whether `STOP: past 100 minutes` +printed; for F, the reviewers the printed plan named against those started and collected. + +## Scoring +judge: gpt-6-astra +labels: 48 +agreement: 0.6 +paired: yes +interval: 95% +mdd: about $7 a run on cost (20% of C's $35; estimated from the profile's 121 to 308 conductor steps, so a per-run spread near $8, and 3 trials a case), and about 35 percentage points on catch rate; the pilot's measured spread is printed beside these and the bars do not move + +**Catches, by rule (no judge).** A trial catches its planted bug when either (a) a finding in the run's findings +record (`merged.jsonl`) or final report names the labelled path, a line within 3 of the labelled line, and at least +one cause word; or (b) the sealed regression test for the plant (from the label file, run by the runner, never shown to +the arm) passes at the run's final head, and one of the run's findings or commit messages names that file. A case's catch rate in an arm is its catches over 3 trials. The script that applies this +rule is checked against the decoys below before any trial runs. + +**Real problems, by judge.** Every finding that is not the plant and that the run marked blocking, or that led to a +fix, goes to GPT-6 Astra with the case diff. It answers two questions: does this meet the blocking floor (would fail +a test, break production, or lose data or secrets), and which other findings name the same problem. A case's real +problems are the union of judged-real problems across all arms and trials; each arm's catch rate on them uses the +rule above, with the judge's grouping in place of the planted label. The judge sees findings as A, B and C, never an +arm name, model or cost. It is checked first against 48 hand-checked labels: findings from merged gstack pull +requests outside the case set, 24 that led to a fix and 24 dismissed below the floor, each read against its diff by +the runner and frozen with a SHA-256 before the judge sees any. `gstack-eval-plan judge --check` must print +`JUDGE_AGREEMENT: ok` (Cohen's kappa at least 0.6) before its numbers count. + +**Comparisons.** Every comparison is paired by case: the per-case difference of means (cost, wall time, `calls=`) +or of catch rates, with a 95% t interval over the 10 cases. Every trial is reported; nothing is averaged away. + +## Decoys +Before any trial, the catch script scores 50 synthetic finding lists built from the sealed labels, 5 per case: the +right file with the line 4 or more away; the right line with no cause word; the cause words on another file; a final +head with the planted lines reworded but the bug kept (the sealed regression test still fails); and one exact match. It must score the 40 decoys 0 and the 10 +matches 1. A decoy pass proves the rule rejects near misses and does not credit a cosmetic edit as a fix. + +## Blinding +- Arms see a real project: the garrytan/gstack checkout, plain branch names taken from each host's own branch, and + the host's own commit title. No branch, file, commit message, prompt or label the trial controls carries an eval word. +- This file and its results file are removed from every case base, and the label file never enters the repository. + The installed gstack copy (`~/.local/share/gstack`) still holds this file, so every C and F transcript is scanned + for reads of it or of the label file's path, and a trial that read either scores zero. +- Each arm's checkout keeps git history, where the original fix commit lives. Lookups of the planted path's history + (`git log -S`, `git log -p`, `git blame` on that file) are counted per trial, and catches made after one are + reported separately as well as in the totals. +- The judge sees A, B and C, never an arm, model or price. + +## Stop rules +- Spend cap: $3,250 cost.dollars for everything in the budget table (the approved figure replaces it if lower). `budget_exhausted` stops the run with every finished trial reported, and the run does not resume. +- Per trial: $150 or 4 hours. A trial stopped there is recorded as incomplete, with its cost at the stop counted (a lower bound, flagged), and scored on what it caught by then. +- Pilot: if any pilot C or F trial ends without a receipt for a harness reason (machine, install, CI wiring), the run stops; the fix is a dated change to this file before the first counted trial, or a new preregistration if a bar, arm or decision changes. +- The catch script below 50 of 50 on decoys, or the judge below kappa 0.6: stop before any trial; fix the script or the judge prompt and relabel; never lower a bar. +- Projection: if the pilot's projection for all 90 trials plus the fixed costs exceeds the approved budget, stop and ask again with the new figure. +- No retries of a counted trial, with the one exception AGENTS.md allows: a red case may rerun once at the same head as a new panel, reported as flaky. Harness or infrastructure failures never rerun. + +## Budget (all-in estimate, cost.dollars) +| Item | Count | Each | Total | +|---|---|---|---| +| C trials | 30 | $38 | $1,140 | +| F trials | 30 | $38 | $1,140 | +| N trials | 30 | $6 | $180 | +| Sealing: picking hosts and plants, proving each plant | 1 | $60 | $60 | +| Judge: 48 labels plus about 300 findings on GPT-6 Astra | 1 | $80 | $80 | +| Runner: waves, audits, scoring, results write-up | 1 | $150 | $150 | +| /ship of the results pull request | 1 | $35 | $35 | +| **Estimate** | | | **$2,785** | +| Cap (estimate plus about 15%) | | | $3,250 | + +That sits under R71's $4,000 guideline for an eval with a GPT-6 Astra judge. If F saves what the profile predicts +(about $10 a run), the actual total is near $2,500. Machines, CI minutes and the runner VM are not in cost.dollars and +are reported separately. Each case gets 3 trials because AGENTS.md gives a `behavior` case a panel of 3, and because +one trial each would let noise decide the "misses nothing" bar (see Bars). + +## Held-out exposure +| set | prior exposure (which runs, which models) | reservation (what this run may read) | +|---|---|---| +| the 10 sealed cases (hosts, plants, labels) | none: picked after this file merges; hosts and fixes are public on GitHub, all merged after Opus 5.5's June 2026 training cutoff | arms read only their case checkout; the runner reads labels to score; the judge reads findings and the case diff, never the labels | +| the 48 judge labels | findings already read by /ship reviewers on their own pull requests, none in the case set | the judge reads them once for `judge --check` | + +## After the run +Results go to `docs/evals/ship-conductor-fold-results.md`, opening with two or three plain takeaways, with one table +holding a filled row for C, F and N, checked with `gstack-eval-plan results --check` before any number leaves the +run. Counts that may be zero (structural losses, contaminated trials, history lookups) are reported in prose, outside +the tables. A null gets one R48 "Why null?" cycle and a KEEP, FIX-METHOD or CUT-CANDIDATE verdict. From bc64f5e21082deab992c256811f23def0bec5bf1 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 02:34:52 +0800 Subject: [PATCH 46/62] /sync-gbrain reports failed pushes and imports instead of OK, and one bad queued path no longer blocks artifacts sync (#4455) /sync-gbrain now says when an artifacts push failed or memory pages failed to import, instead of printing OK and "pushed", and one malformed queued path (from a skill started where the project slug was empty) no longer stops artifacts sync for every project. Why: people trusted those rows and lost track of unsynced work; fixes #4445, #4418 and #4417. Nothing to do after upgrading: a stuck `projects//timeline.jsonl` record is dropped and reported on the next sync. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/specialist-batched#2 reader=testing Review-Finding: p1/specialist-batched#3 reader=testing --- bin/gstack-brain-enqueue | 13 ++ bin/gstack-brain-sync | 54 ++++++-- bin/gstack-gbrain-sync.ts | 127 +++++++++++++----- bin/gstack-memory-ingest.ts | 16 ++- changelog.d/sync-gbrain-reports-failures.md | 3 + docs/gbrain-sync-errors.md | 33 +++++ sync-gbrain/SKILL.md | 16 ++- sync-gbrain/SKILL.md.tmpl | 16 ++- test/brain-sync.test.ts | 66 +++++++++ ...gstack-gbrain-sync-transcript-mode.test.ts | 54 ++++++++ test/gstack-gbrain-sync.test.ts | 111 ++++++++++++++- 11 files changed, 451 insertions(+), 58 deletions(-) create mode 100644 changelog.d/sync-gbrain-reports-failures.md diff --git a/bin/gstack-brain-enqueue b/bin/gstack-brain-enqueue index b6706a04247..98183abf3c8 100755 --- a/bin/gstack-brain-enqueue +++ b/bin/gstack-brain-enqueue @@ -15,6 +15,9 @@ # - ~/.gstack/.git doesn't exist (feature not initialized) # - <file-path> matches a line in ~/.gstack/.brain-skip.txt # +# Refuses (exit 1, nothing queued) a <file-path> with an empty, "." or ".." +# component, such as projects//timeline.jsonl from an empty project slug. +# # Env: # GSTACK_HOME — override ~/.gstack state directory (aligns with writers). # Tests use GSTACK_HOME=/tmp/test-$$ for isolation. @@ -32,6 +35,16 @@ set -uo pipefail FILE="${1:-}" [ -z "$FILE" ] && exit 0 +# A path with an empty, "." or ".." component (projects//timeline.jsonl from an +# empty project slug, #4445) names a file git stages under another spelling, +# and the drain refuses that batch. Refuse it here instead of spooling it. +case "/$FILE/" in + *//*|*/./*|*/../*) + echo "gstack-brain-enqueue: refusing malformed path '$FILE' (empty, '.' or '..' component; an empty project slug?); nothing queued" >&2 + exit 1 + ;; +esac + # Plan B1: an unattended session never spools for cross-machine sync, whatever # the inherited mode; every writer (timeline, decision, learnings, review log) # is covered here, at the one entrypoint, instead of per caller. diff --git a/bin/gstack-brain-sync b/bin/gstack-brain-sync index fd89a98d316..2c1c713e64b 100755 --- a/bin/gstack-brain-sync +++ b/bin/gstack-brain-sync @@ -193,6 +193,23 @@ with open(path, "w") as f: PYEOF } +# Status for a drain that pushed nothing. While local commits are still not on +# origin, push_failed replaces ok and idle: writing those instead erased a +# failed push one run later, so a push that never recovered went silent +# (#4418). held and collision keep their code (their attention line names the +# files to fix) and carry the unpushed count in the message. +# $1 code, $2 message, $3 unpushed local commits. +write_drain_status() { + local unpushed="$3 local commit(s) are not pushed yet; the push retries at a skill start at most every 10 minutes (commits made outside gstack-brain-sync are never auto-pushed: push them with 'git -C $GSTACK_HOME push origin HEAD')" + if [ "${3:-0}" -eq 0 ]; then + write_status "$1" "$2" + elif [ "$1" = held ] || [ "$1" = collision ]; then + write_status "$1" "$2; $unpushed" + else + write_status "push_failed" "$unpushed; this drain: $2" + fi +} + # Read config; return 0 if sync active, 1 otherwise. sync_active() { if [ ! -d "$GSTACK_HOME/.git" ]; then @@ -464,8 +481,11 @@ for p in sorted(queue_paths): if p in skip_lines or any(m in skip_lines for m in members): classified["dropped"]["skipped"].append(p) continue - # Must be under GSTACK_HOME root. Reject absolute + reject ../ escape. - if p.startswith("/") or ".." in p.split("/"): + # Must be under GSTACK_HOME root and spelled the way git stages it: an + # absolute path, a ../ escape, or an empty or "." component (#4445: + # projects//timeline.jsonl from an empty slug, staged by git as + # projects/timeline.jsonl, made the index check refuse the whole batch). + if any(c in ("", ".", "..") for c in p.split("/")): classified["dropped"]["invalid"].append(p) continue # Must match at least one allowlist glob. @@ -677,7 +697,8 @@ finalize_queue() { # Fail-open by design (a failed finalize self-corrects next run: re-stage → # nothing-to-commit), but say so — a silent failure here would let the # subsequent "ok/idle" status claim a drain that did not happen. - python3 - "$QUEUE_DIR" "$snapshot_file" "$class_file" "$paths_file" "$GSTACK_HOME/.brain-sync-drops.json" <<'PYEOF' || echo "BRAIN_SYNC: warning: queue finalize failed — entries retained; next run re-drains" >&2 + local finalized=1 + python3 - "$QUEUE_DIR" "$snapshot_file" "$class_file" "$paths_file" "$GSTACK_HOME/.brain-sync-drops.json" <<'PYEOF' || { finalized=0; echo "BRAIN_SYNC: warning: queue finalize failed — entries retained; next run re-drains" >&2; } import json, os, sys, time spool_dir, snapshot_file, class_file, paths_file, drops_file = sys.argv[1:6] @@ -762,6 +783,16 @@ if dropped: json.dump({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "dropped": classified.get("dropped", {})}, f) PYEOF + [ "$finalized" = 1 ] || return 0 + # #4445: report malformed records once finalize has dropped them; an early + # exit before finalize keeps them queued and must not claim the drop. + local malformed + malformed=$(python3 -c 'import json, sys; print(len((json.load(open(sys.argv[1])).get("dropped") or {}).get("invalid") or []))' "$class_file" 2>/dev/null || echo 0) + case "$malformed" in ''|*[!0-9]*) malformed=0 ;; esac + if [ "$malformed" -gt 0 ]; then + ST_NOTE="$ST_NOTE; dropped $malformed queued record(s) with a malformed path (absolute, or an empty, '.' or '..' component), listed in $GSTACK_HOME/.brain-sync-drops.json" + echo "BRAIN_SYNC: dropped $malformed queued record(s) with a malformed path; see $GSTACK_HOME/.brain-sync-drops.json" >&2 + fi } # Human-readable classification counts for status messages. @@ -1316,14 +1347,9 @@ subcmd_once() { # the queue is empty.) The lock-release trap installed at acquisition # covers this exit. if ! spool_has_records && [ ! -s "$QUEUE" ] && [ ! -s "$QUEUE.migrating" ]; then - # Stranded local commits that this run did not push keep the status at - # push_failed: an "idle" here used to erase the failure one boundary later, - # so a push that never recovered went silent. - if [ "$det_total" -gt 0 ]; then - write_status "push_failed" "$det_total local commit(s) are not pushed yet; the push retries at a skill start at most every 10 minutes (commits made outside gstack-brain-sync are never auto-pushed: push them with git -C $GSTACK_HOME push origin HEAD)" - exit 0 - fi - if [ "$REMOVALS_PUSHED" = 1 ]; then write_status "ok" "queue empty"; else write_status "idle" "queue empty"; fi + local empty_code=idle + [ "$REMOVALS_PUSHED" = 1 ] && empty_code=ok + write_drain_status "$empty_code" "queue empty" "$det_total" exit 0 fi @@ -1362,7 +1388,7 @@ subcmd_once() { local summary idle_code=idle summary=$(queue_summary "$class_file") [ "$ST_CASE_HELD" -gt 0 ] && idle_code=collision - write_status "$idle_code" "no stageable changes${summary:+ ($summary)}" + write_drain_status "$idle_code" "no stageable changes${summary:+ ($summary)}" "$det_total" exit 0 fi local n_stageable @@ -1419,9 +1445,9 @@ subcmd_once() { if [ "$cached_rc" -eq 0 ]; then finalize_queue "$snapshot_file" "$class_file" "$paths_file" if [ "$ok_code" != "ok" ]; then - write_status "$ok_code" "nothing else to sync" + write_drain_status "$ok_code" "nothing else to sync" "$det_total" else - write_status "idle" "queue drained but no new changes to commit" + write_drain_status "idle" "queue drained but no new changes to commit" "$det_total" fi exit 0 fi diff --git a/bin/gstack-gbrain-sync.ts b/bin/gstack-gbrain-sync.ts index 4087df64460..9b8113f21aa 100644 --- a/bin/gstack-gbrain-sync.ts +++ b/bin/gstack-gbrain-sync.ts @@ -29,10 +29,10 @@ * than building a gstack-side daemon. */ -import { existsSync, statSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, renameSync, realpathSync, readdirSync, appendFileSync } from "fs"; +import { existsSync, statSync, mkdirSync, mkdtempSync, writeFileSync, readFileSync, rmSync, unlinkSync, renameSync, realpathSync, readdirSync, appendFileSync } from "fs"; import { join, dirname, basename, isAbsolute } from "path"; import { execSync, spawnSync } from "child_process"; -import { homedir, hostname } from "os"; +import { homedir, hostname, tmpdir } from "os"; import { createHash } from "crypto"; import "../lib/conductor-env-shim"; @@ -262,32 +262,88 @@ function isArtifactsSourceRow(r: { local_path?: string }, env?: NodeJS.ProcessEn } /** - * A5 (#2670): after a successful artifacts push, report what gbrain actually - * holds. A git push is not indexing; a maintained artifacts source with zero - * pages is the one provably broken state and fails the stage. + * A5 (#2670): after an artifacts drain, report what gbrain actually holds. A + * git push is not indexing; a maintained artifacts source with zero pages is + * the one provably broken state and fails the stage. `lead` says what the + * drain did. */ -export function brainSyncIndexVerdict(env: NodeJS.ProcessEnv = process.env): { ok: boolean; summary: string } { +export function brainSyncIndexVerdict( + env: NodeJS.ProcessEnv = process.env, + lead = "curated artifacts pushed to git", +): { ok: boolean; summary: string } { const raw = execGbrainJson(["sources", "list", "--json"], { baseEnv: env, timeout: 10_000 }); if (raw === null) { - return { ok: true, summary: "curated artifacts pushed to git; gbrain page count unavailable (gbrain sources list failed)" }; + return { ok: true, summary: `${lead}; gbrain page count unavailable (gbrain sources list failed)` }; } const explicit = env.GSTACK_BRAIN_SOURCE_ID; const row = parseSourcesList(raw).find((r) => (explicit ? r.id === explicit : isArtifactsSourceRow(r, env))); if (!row?.id) { - return { ok: true, summary: "curated artifacts pushed to git (no gbrain artifacts source on this machine, so indexing is not checked here)" }; + return { ok: true, summary: `${lead} (no gbrain artifacts source on this machine, so indexing is not checked here)` }; } if (typeof row.page_count !== "number") { - return { ok: true, summary: `curated artifacts pushed to git; gbrain source ${row.id} did not report a page count` }; + return { ok: true, summary: `${lead}; gbrain source ${row.id} did not report a page count` }; } if (row.page_count === 0) { return { ok: false, - summary: - `curated artifacts pushed to git, but gbrain source ${row.id} has 0 indexed pages. ` + - `Fix: gbrain sync --source ${row.id}, then re-run /sync-gbrain`, + summary: `${lead}, but gbrain source ${row.id} has 0 indexed pages. Fix: gbrain sync --source ${row.id}, then re-run /sync-gbrain`, }; } - return { ok: true, summary: `curated artifacts pushed; gbrain source ${row.id} has ${row.page_count} pages` }; + return { ok: true, summary: `${lead}; gbrain source ${row.id} has ${row.page_count} pages` }; +} + +/** + * The brain-sync row (#4418). `gstack-brain-sync --once` exits 0 when its push + * fails (the commit is kept and retried), so the row comes from the status the + * drain wrote, and only a drain whose status is ok says "pushed". `drain` is + * null when this run wrote no status (sync off, or another drain held the lock). + */ +export function brainSyncStageVerdict( + drain: { status?: unknown; message?: unknown } | null, + env: NodeJS.ProcessEnv = process.env, +): { ok: boolean; warn?: boolean; summary: string } { + if (!drain) return brainSyncIndexVerdict(env, "no artifacts drain ran (artifacts sync is off, or another sync held the lock), so nothing was pushed"); + const status = typeof drain.status === "string" ? drain.status : "unknown"; + const message = (typeof drain.message === "string" ? drain.message : "").slice(0, 400); + const detail = `${status}: ${message || "no message"}; details: gstack-brain-sync --status`; + if (status === "ok") return brainSyncIndexVerdict(env); + if (status === "idle") return brainSyncIndexVerdict(env, `nothing new to push (${message || "idle"})`); + if (status === "held" || status === "collision") { + const v = brainSyncIndexVerdict(env, `artifacts not all pushed (${detail})`); + return { ...v, warn: v.ok }; + } + return { ok: false, summary: `artifacts not pushed (${detail})` }; +} + +/** + * The memory row (#4417). gstack-memory-ingest exits 0 when single pages fail + * (they are retried next run), so the exit code alone printed OK with every + * page refused. The counts decide: a failed page makes the row WARN, and a run + * that imported nothing while pages failed is ERR. A source file that could not + * be parsed is never retried as an import, so it is a note, not a failure. + */ +export function memoryStageVerdict( + status: number | null, + stderr: string, + counts: { written?: unknown; failed?: unknown; parse_failed?: unknown } | null, +): { ok: boolean; warn?: boolean; summary: string } { + const memLines = stderr.split("\n").filter((l) => l.includes("[memory-ingest]")); + const errLine = memLines.find((l) => l.includes("[memory-ingest] ERR")); + const summary = (errLine || memLines.slice(-1)[0] || "ingest pass complete") + .replace(/^.*\[memory-ingest\]\s*/, "") + .replace(/^ERR:\s*/, ""); + if (status !== 0) { + return { ok: false, summary: `${summary}${status === null ? " (killed by signal / timeout)" : ` (exit ${status})`}` }; + } + const parseFailed = typeof counts?.parse_failed === "number" ? counts.parse_failed : 0; + const failed = Math.max(0, (typeof counts?.failed === "number" ? counts.failed : 0) - parseFailed); + const unparsed = parseFailed > 0 ? `; ${parseFailed} source file(s) could not be parsed and were skipped` : ""; + if (failed === 0) return { ok: true, summary: summary + unparsed }; + const written = typeof counts?.written === "number" ? counts.written : 0; + const first = memLines.find((l) => l.includes("[memory-ingest] FAILED ")); + const cause = first ? `; first: ${first.replace(/^.*\[memory-ingest\] FAILED\s*/, "").slice(0, 240)}` : ""; + const line = `${written} imported, ${failed} failed (retried next run; each failure: gstack-memory-ingest --incremental)${cause}${unparsed}`; + return written === 0 ? { ok: false, summary: line } : { ok: true, warn: true, summary: line }; } export interface MemorySourceSelection { @@ -1634,36 +1690,27 @@ function runMemoryIngest(args: CliArgs, previous: SyncState, consent: Transcript process.env.GSTACK_SYNC_MEMORY_TIMEOUT_MS, "GSTACK_SYNC_MEMORY_TIMEOUT_MS", ); + // D6: the child's [memory-ingest] stderr lines carry the summary and any + // system error; its counts (GSTACK_INGEST_RESULT_FILE) decide whether pages + // failed, since per-page failures exit 0 (#4417). + const resultFile = join(mkdtempSync(join(tmpdir(), "gstack-ingest-result-")), "result.json"); + childEnv.GSTACK_INGEST_RESULT_FILE = resultFile; const result = spawnSync(process.execPath, ingestArgs, { encoding: "utf-8", timeout: memoryTimeoutMs, env: childEnv, }); + let counts: { written?: unknown; failed?: unknown } | null = null; + try { + counts = JSON.parse(readFileSync(resultFile, "utf-8")); + } catch {} + rmSync(dirname(resultFile), { recursive: true, force: true }); - // D6: parse [memory-ingest] lines from the child's stderr. ERR-prefixed - // lines indicate a system-level failure (gbrain crashed or CLI missing) - // and the child exits non-zero. Per-file failures are summarized in the - // last non-ERR [memory-ingest] line but do NOT make the verdict ERR. - const stderrLines = (result.stderr || "").split("\n"); - const memLines = stderrLines.filter((l) => l.includes("[memory-ingest]")); - const errLine = memLines.find((l) => l.includes("[memory-ingest] ERR")); - const lastMemLine = memLines.slice(-1)[0]; - const rawSummary = errLine || lastMemLine || "ingest pass complete"; - // Strip the "[memory-ingest] " prefix and any leading "ERR: " for cleaner - // verdict output. The orchestrator's own formatStage will prefix with OK/ERR. - const summary = rawSummary - .replace(/^.*\[memory-ingest\]\s*/, "") - .replace(/^ERR:\s*/, ""); - - const ok = result.status === 0; return { name: "memory", ran: true, - ok, duration_ms: Date.now() - t0, - summary: ok - ? summary - : `${summary}${result.status === null ? " (killed by signal / timeout)" : ` (exit ${result.status})`}`, + ...memoryStageVerdict(result.status, result.stderr || "", counts), memory_sources: selected, transcript_consent: consentRecord, }; @@ -1708,12 +1755,24 @@ function runBrainSyncPush(args: CliArgs): StageResult { : ["ignore", "inherit", "inherit"]; spawnSync(discover.cmd, discover.argv, { stdio, timeout: 60 * 1000, shell: discover.shell }); + const statusPath = join(GSTACK_HOME, ".brain-sync-status.json"); + const statusStamp = () => (existsSync(statusPath) ? `${statSync(statusPath).mtimeMs}:${readFileSync(statusPath, "utf-8")}` : null); + const before = statusStamp(); const result = spawnSync(once.cmd, once.argv, { stdio, timeout: 60 * 1000, shell: once.shell }); if (result.status !== 0) { return { name: "brain-sync", ran: true, ok: false, duration_ms: Date.now() - t0, summary: `gstack-brain-sync exited ${result.status}` }; } - return { name: "brain-sync", ran: true, duration_ms: Date.now() - t0, ...brainSyncIndexVerdict() }; + let drain: { status?: unknown; message?: unknown } | null = null; + const after = statusStamp(); + if (after !== null && after !== before) { + try { + drain = JSON.parse(readFileSync(statusPath, "utf-8")); + } catch { + drain = { status: "unknown", message: `${statusPath} is unreadable` }; + } + } + return { name: "brain-sync", ran: true, duration_ms: Date.now() - t0, ...brainSyncStageVerdict(drain) }; } /** diff --git a/bin/gstack-memory-ingest.ts b/bin/gstack-memory-ingest.ts index 51a7963fb84..924ccbb059a 100644 --- a/bin/gstack-memory-ingest.ts +++ b/bin/gstack-memory-ingest.ts @@ -195,6 +195,8 @@ interface BulkResult { /** #2392: transcripts skipped because their remote's trust tier is `deny`. */ skipped_policy_deny: number; failed: number; + /** Source files that could not be parsed, counted in failed; not import failures. */ + parse_failed?: number; duration_ms: number; partial_pages: number; /** A1: pages gbrain refused or that were not found after import (retried next run). */ @@ -2134,6 +2136,7 @@ async function ingestPassScoped(args: CliArgs, state: IngestState, scope: Transc skipped_policy_readonly: prep.skippedPolicyReadonly, skipped_policy_deny: prep.skippedPolicyDeny, failed: prep.parseFailed + prep.prepared.length, + parse_failed: prep.parseFailed, duration_ms: Date.now() - t0, partial_pages: prep.partialPages, system_error: prep.policyError, @@ -2159,6 +2162,7 @@ async function ingestPassScoped(args: CliArgs, state: IngestState, scope: Transc skipped_policy_readonly: prep.skippedPolicyReadonly, skipped_policy_deny: prep.skippedPolicyDeny, failed: prep.parseFailed, + parse_failed: prep.parseFailed, duration_ms: Date.now() - t0, partial_pages: prep.partialPages, }; @@ -2180,6 +2184,7 @@ async function ingestPassScoped(args: CliArgs, state: IngestState, scope: Transc skipped_policy_readonly: prep.skippedPolicyReadonly, skipped_policy_deny: prep.skippedPolicyDeny, failed: prep.parseFailed, + parse_failed: prep.parseFailed, duration_ms: Date.now() - t0, partial_pages: prep.partialPages, }; @@ -2198,6 +2203,7 @@ async function ingestPassScoped(args: CliArgs, state: IngestState, scope: Transc skipped_policy_readonly: prep.skippedPolicyReadonly, skipped_policy_deny: prep.skippedPolicyDeny, failed: prep.parseFailed + prep.prepared.length, + parse_failed: prep.parseFailed, duration_ms: Date.now() - t0, partial_pages: prep.partialPages, system_error: msg, @@ -2262,6 +2268,7 @@ async function ingestPassScoped(args: CliArgs, state: IngestState, scope: Transc written: 0, skipped_secret: prep.skippedSecret + (r.scannerFailed ? 1 : 0), failed: prep.parseFailed + prep.prepared.length, + parse_failed: prep.parseFailed, duration_ms: Date.now() - t0, system_error: r.error, }; @@ -2287,7 +2294,7 @@ async function ingestPassScoped(args: CliArgs, state: IngestState, scope: Transc const msg = `EGRESS_RECEIPT_FAILED: ${(err as Error).message} — ingest refused`; console.error(`[memory-ingest] ERR: ${msg}`); if (resumed && !args.scanSecrets) cleanupStagingDir(resumed.stagingDir); - return { ...base, state_untouched: true, written: 0, failed: prep.parseFailed + prep.prepared.length, duration_ms: Date.now() - t0, system_error: msg }; + return { ...base, state_untouched: true, written: 0, failed: prep.parseFailed + prep.prepared.length, parse_failed: prep.parseFailed, duration_ms: Date.now() - t0, system_error: msg }; } const run: RunContext = { @@ -2343,6 +2350,7 @@ async function ingestPassScoped(args: CliArgs, state: IngestState, scope: Transc ...base, written: run.written, failed: run.failed + prep.parseFailed, + parse_failed: prep.parseFailed, refused: run.refused, unverified: check.unverified, quarantined: run.quarantined, @@ -3236,6 +3244,12 @@ async function runLocked(args: CliArgs): Promise<number> { const t0 = Date.now(); const result = await ingestPass(args, state); + // /sync-gbrain reads the counts here: per-page failures exit 0 (#4417). + if (process.env.GSTACK_INGEST_RESULT_FILE) { + try { + writeFileSync(process.env.GSTACK_INGEST_RESULT_FILE, JSON.stringify({ written: result.written, failed: result.failed, parse_failed: result.parse_failed ?? 0 })); + } catch {} + } if (!result.state_untouched) { // A pending reconcile (set by the upgrade migration or a schema migration) // gets one bounded pass per ingest run until it completes. diff --git a/changelog.d/sync-gbrain-reports-failures.md b/changelog.d/sync-gbrain-reports-failures.md new file mode 100644 index 00000000000..7da52d1a8e7 --- /dev/null +++ b/changelog.d/sync-gbrain-reports-failures.md @@ -0,0 +1,3 @@ +- **One queued record with a malformed path no longer stops artifacts sync for every project.** A skill started where the project slug was empty (for example from `/`) queued `projects//timeline.jsonl`; git staged it under another spelling, the drain refused the whole batch, and every later record waited until the queue was dropped by hand. `gstack-brain-enqueue` now refuses a path with an empty, `.` or `..` component, and the drain drops such a record, syncs the rest, and reports it (#4445). +- **A failed artifacts push stays reported until a push succeeds.** A later drain with nothing new to commit used to write `idle` over `push_failed` while the commits were still unpushed, and /sync-gbrain printed "curated artifacts pushed" because `gstack-brain-sync` exits 0 on a failed push. The status now stays `push_failed`, and the brain-sync row reads the drain's status. It says "pushed" only after a push, "nothing new to push" when there was nothing to send, and `ERR artifacts not pushed (...)` otherwise (#4418). +- **The /sync-gbrain memory row no longer says OK when pages failed to import.** It read only the ingest's exit code, which stays 0 for per-page failures, so it printed `OK ... 126 failed`. The row now reads the ingest's counts: `WARN` when some pages failed, `ERR` when pages failed and none imported, with the failed count and the first cause. A transcript that cannot be parsed is listed as a note and leaves the row `OK` (#4417). diff --git a/docs/gbrain-sync-errors.md b/docs/gbrain-sync-errors.md index aba6258e76c..3c3fc7e7ef2 100644 --- a/docs/gbrain-sync-errors.md +++ b/docs/gbrain-sync-errors.md @@ -465,6 +465,39 @@ If it stays at zero, re-register the source with `gstack-gbrain-source-wireup`. --- +## `artifacts not pushed (push_failed: ...; details: gstack-brain-sync --status)` + +**Problem.** `/sync-gbrain`'s brain-sync stage is `ERR`. + +**Cause.** The artifacts push failed, was blocked, or stopped before +committing (`push_failed`, `blocked` or `error`). The commits and queue are +kept and retried. A failed push stays `push_failed` until a push succeeds, +even when later runs have nothing new to commit. Before this release the +stage read only the exit code and said "curated artifacts pushed". + +**Fix.** Run `gstack-brain-sync --status` and follow the fix its message +names (usually `gh auth status`, or a merge conflict to resolve in +`~/.gstack`). + +--- + +## `BRAIN_SYNC: dropped <N> queued record(s) with a malformed path` + +**Problem.** A queued sync record named an absolute path, or a path with an +empty, `.` or `..` component, such as `projects//timeline.jsonl` from a +skill started where the project slug was empty (the working directory `/`). + +**Cause.** Git stages such a path under another spelling, so the drain used +to refuse the whole batch and every later record waited behind it. The drain +now drops the record, syncs the rest, and lists the dropped paths in +`~/.gstack/.brain-sync-drops.json`. `gstack-brain-enqueue` refuses these +paths, so new ones are not queued. + +**Fix.** Nothing to do. A stray `~/.gstack/projects/timeline.jsonl` left by +such a run is local only and can be deleted. + +--- + ## `[gbrain-sync] gbrain source <id>: path unavailable (<path>); gstack skips it.` **Problem.** A gbrain code source points at a directory that no longer diff --git a/sync-gbrain/SKILL.md b/sync-gbrain/SKILL.md index 56942cd94d8..45517662984 100644 --- a/sync-gbrain/SKILL.md +++ b/sync-gbrain/SKILL.md @@ -352,6 +352,16 @@ still run. State is persisted to `~/.gstack/.gbrain-sync-state.json` via tmp-file + atomic rename. Concurrent runs are blocked by a lock file at `~/.gstack/.sync-gbrain.lock` (5-min stale-takeover). +Report each stage row as printed, never better than it is: +- **memory**: `OK` only when no page failed. `WARN` means some pages failed and + `ERR` means pages failed and none imported; give the failed count and the + first cause from the row, and say failed pages retry next run. +- **brain-sync**: say artifacts were pushed only when the row says + `curated artifacts pushed`. `nothing new to push` means this run had nothing + to send; `artifacts not pushed (<status>: ...)` means the push failed, was + blocked or stopped, and the commits and queue are kept for the next run. + Point the user at `gstack-brain-sync --status` for the cause. + --- ## Step 3: Code-index health check @@ -679,9 +689,9 @@ transient or machine-local failure. Agents must not treat unknown as ready. ## Status reporting End with a Completion Status (per the preamble protocol): -- **DONE** — all stages green, CLAUDE.md guidance block present, verdict GREEN. -- **DONE_WITH_CONCERNS** — sync ran but at least one stage failed or capability - read was unverified. List which and preserve retry guidance. +- **DONE** — all stages `OK`, CLAUDE.md guidance block present, verdict GREEN. +- **DONE_WITH_CONCERNS** — sync ran but at least one stage is `WARN` or `ERR`, or + the capability read was unverified. List which and preserve retry guidance. - **BLOCKED** — could not acquire lock, gbrain not on PATH, or per-repo policy is deny. State the blocker. - **NEEDS_CONTEXT** — /setup-gbrain has not been run, or `gbrain doctor` shows diff --git a/sync-gbrain/SKILL.md.tmpl b/sync-gbrain/SKILL.md.tmpl index 3612a62da1e..e757826fa0b 100644 --- a/sync-gbrain/SKILL.md.tmpl +++ b/sync-gbrain/SKILL.md.tmpl @@ -280,6 +280,16 @@ still run. State is persisted to `~/.gstack/.gbrain-sync-state.json` via tmp-file + atomic rename. Concurrent runs are blocked by a lock file at `~/.gstack/.sync-gbrain.lock` (5-min stale-takeover). +Report each stage row as printed, never better than it is: +- **memory**: `OK` only when no page failed. `WARN` means some pages failed and + `ERR` means pages failed and none imported; give the failed count and the + first cause from the row, and say failed pages retry next run. +- **brain-sync**: say artifacts were pushed only when the row says + `curated artifacts pushed`. `nothing new to push` means this run had nothing + to send; `artifacts not pushed (<status>: ...)` means the push failed, was + blocked or stopped, and the commits and queue are kept for the next run. + Point the user at `gstack-brain-sync --status` for the cause. + --- ## Step 3: Code-index health check @@ -607,9 +617,9 @@ transient or machine-local failure. Agents must not treat unknown as ready. ## Status reporting End with a Completion Status (per the preamble protocol): -- **DONE** — all stages green, CLAUDE.md guidance block present, verdict GREEN. -- **DONE_WITH_CONCERNS** — sync ran but at least one stage failed or capability - read was unverified. List which and preserve retry guidance. +- **DONE** — all stages `OK`, CLAUDE.md guidance block present, verdict GREEN. +- **DONE_WITH_CONCERNS** — sync ran but at least one stage is `WARN` or `ERR`, or + the capability read was unverified. List which and preserve retry guidance. - **BLOCKED** — could not acquire lock, gbrain not on PATH, or per-repo policy is deny. State the blocker. - **NEEDS_CONTEXT** — /setup-gbrain has not been run, or `gbrain doctor` shows diff --git a/test/brain-sync.test.ts b/test/brain-sync.test.ts index 6ff7036ef9d..88d5e4a830c 100644 --- a/test/brain-sync.test.ts +++ b/test/brain-sync.test.ts @@ -1568,6 +1568,72 @@ describe('gstack-brain-sync per-file hold', () => { expect(statusJson().message).toContain('not pushed yet'); }); + // #4418: a drain whose queue held records but committed nothing used to + // write idle over a push_failed whose commits were still unpushed. + for (const [name, requeue] of [ + ['a queued file with no new changes', (CLEAN_PATH: string) => run(['gstack-brain-enqueue', CLEAN_PATH])], + ['a queued file that is gone from disk', () => run(['gstack-brain-enqueue', 'projects/p/ceo-plans/gone.md'])], + ] as const) { + test(`a push that keeps failing stays push_failed after a drain of ${name} (#4418)`, () => { + init(); + write(CLEAN, '# a plan\n'); + drain(); + const hook = path.join(bareRemote, 'hooks', 'pre-receive'); + fs.writeFileSync(hook, '#!/bin/sh\necho "403 forbidden" >&2\nexit 1\n', { mode: 0o755 }); + write(CLEAN, '# a plan, revised\n'); + drain(); + expect(statusJson().status).toBe('push_failed'); + requeue(CLEAN); + expect(spoolFiles()).toHaveLength(1); + drain(); + expect(spoolFiles()).toEqual([]); + const s = statusJson(); + expect(s.status).toBe('push_failed'); + expect(s.message).toContain('1 local commit(s) are not pushed yet'); + expect(run(['gstack-brain-sync', '--attention']).stdout).toContain('status=push_failed'); + fs.rmSync(hook); + fs.writeFileSync(path.join(tmpHome, '.brain-last-push-attempt'), '0'); + drain(); + expect(statusJson().status).not.toBe('push_failed'); + expect(remoteShow(CLEAN).stdout).toContain('revised'); + }); + } + + // #4445: a skill started where the project slug is empty spooled + // projects//timeline.jsonl; git staged it as projects/timeline.jsonl, the + // index check refused the batch, and every later record waited behind it. + test('enqueue refuses a path with an empty, "." or ".." component (#4445)', () => { + init(); + for (const bad of ['projects//timeline.jsonl', '/projects/p/timeline.jsonl', 'projects/p/', 'projects/./p/timeline.jsonl', 'projects/../timeline.jsonl']) { + const r = run(['gstack-brain-enqueue', bad]); + expect(r.status).not.toBe(0); + expect(r.stderr).toContain('malformed path'); + } + expect(spoolFiles()).toEqual([]); + expect(run(['gstack-brain-enqueue', CLEAN]).status).toBe(0); + expect(spoolFiles()).toHaveLength(1); + }); + + test('a malformed queued path is dropped and reported; the rest of the queue syncs (#4445)', () => { + init(); + fs.writeFileSync(path.join(tmpHome, 'projects/timeline.jsonl'), '{"skill":"codex","event":"started"}\n'); + seedSpool('{"file":"projects//timeline.jsonl","ts":"2026-11-17T13:06:00Z"}'); + write(CLEAN, '# a plan\n'); + const r = drain(); + expect(r.status).toBe(0); + expect(r.stderr).toContain('1 queued record(s) with a malformed path'); + const s = statusJson(); + expect(s.status).toBe('ok'); + expect(s.message).toContain('pushed 1 file(s)'); + expect(s.message).toContain('dropped 1 queued record(s) with a malformed path'); + expect(remoteFiles()).toContain(CLEAN); + expect(remoteFiles()).not.toContain('projects/timeline.jsonl'); + expect(staged()).toBe(''); + expect(spoolFiles()).toEqual([]); + const drops = JSON.parse(fs.readFileSync(path.join(tmpHome, '.brain-sync-drops.json'), 'utf-8')); + expect(drops.dropped.invalid).toEqual(['projects//timeline.jsonl']); + }); + describe('coupled groups (decision log and its active snapshot)', () => { test('a clean update publishes the group in one commit', () => { init(); diff --git a/test/gstack-gbrain-sync-transcript-mode.test.ts b/test/gstack-gbrain-sync-transcript-mode.test.ts index ac09c8142a1..70d365e2c4c 100644 --- a/test/gstack-gbrain-sync-transcript-mode.test.ts +++ b/test/gstack-gbrain-sync-transcript-mode.test.ts @@ -164,6 +164,14 @@ case "$1" in fi echo '${sources}' ;; import) + if [ -n "$GBRAIN_REFUSE_IMPORTS" ]; then + ( cd "$2" && find . -name '*.md' -type f | sed 's#^[.]/##' ) | while read -r p; do + echo " Warning: skipped $p: Managed import must run on the active canonical owner for the selected source." >&2 + done + n=$( cd "$2" && find . -name '*.md' -type f | wc -l | tr -d ' ') + echo "{\\"status\\":\\"success\\",\\"imported\\":0,\\"skipped\\":0,\\"errors\\":$n,\\"total_files\\":$n}" + exit 0 + fi # One import per gbrain source (A4): pages of one ingest run accumulate; # a new run (different parent pid) starts a fresh list. if [ "$(cat "${stagedList}.ppid" 2>/dev/null)" != "$PPID" ]; then echo "$PPID" > "${stagedList}.ppid"; : > "${stagedList}"; fi @@ -459,3 +467,49 @@ describe.skipIf(process.platform === "win32")("memory stage transcript consent", } }); }); + +// #4417: gstack-memory-ingest exits 0 when gbrain refuses single pages (they +// are retried next run), and the memory row used to read only that exit code, +// so it printed OK with every page refused. +describe.skipIf(process.platform === "win32")("memory stage failure counts (#4417)", () => { + test("pages gbrain refuses make the row ERR with the count and the first cause", () => { + const sb = sandbox(); + try { + const r = runSync(sb, ["--incremental"], { GBRAIN_REFUSE_IMPORTS: "1" }); + const stage = memoryStage(sb) as { ok: boolean; warn?: boolean; summary: string }; + expect(stage.ok).toBe(false); + expect(stage.summary).toMatch(/^0 imported, [1-9][0-9]* failed [(]retried next run/); + expect(stage.summary).toContain("Managed import must run on the active canonical owner"); + expect(r.stdout).toMatch(/ERR +memory +0 imported, [1-9][0-9]* failed/); + expect(r.stdout).not.toMatch(/OK +memory/); + expect(r.status).toBe(1); + + // The refusal clears: the same pages import and the row is OK again. + const ok = runSync(sb, ["--incremental"]); + expect(ok.status).toBe(0); + expect(memoryStage(sb).ok).toBe(true); + expect(ok.stdout).toMatch(/OK +memory/); + } finally { + sb.cleanup(); + } + }); + + // A transcript that cannot be parsed is never stamped, so it is counted on + // every run; it must not turn the row ERR for good. + test("an unparseable transcript is a note on an OK row, every run", () => { + const sb = sandbox({ mode: "all" }); + try { + writeFileSync(join(sb.home, ".claude", "projects", "work-acme", "empty0001.jsonl"), ""); + for (let run = 0; run < 2; run++) { + const r = runSync(sb, ["--incremental"]); + const stage = memoryStage(sb) as { ok: boolean; warn?: boolean; summary: string }; + expect(stage.ok).toBe(true); + expect(stage.warn).toBeUndefined(); + expect(stage.summary).toContain("1 source file(s) could not be parsed and were skipped"); + expect(r.status).toBe(0); + } + } finally { + sb.cleanup(); + } + }); +}); diff --git a/test/gstack-gbrain-sync.test.ts b/test/gstack-gbrain-sync.test.ts index 32bf537c22d..63cf693a53c 100644 --- a/test/gstack-gbrain-sync.test.ts +++ b/test/gstack-gbrain-sync.test.ts @@ -10,11 +10,13 @@ import { describe, it, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, mkdirSync, chmodSync, symlinkSync } from "fs"; import { tmpdir } from "os"; -import { join } from "path"; +import { dirname, join } from "path"; import { spawnSync } from "child_process"; import { + brainSyncStageVerdict, derivePathOnlyHashLegacyId, + memoryStageVerdict, planHostnameFoldMigration, sourceLocalPath, _resetGbrainSupportsRenameCache, @@ -544,10 +546,11 @@ esac rmSync(home, { recursive: true, force: true }); }); - // A5 (#2670): a successful git push is not gbrain indexing. + // A5 (#2670): a successful git push is not gbrain indexing. Artifacts sync is + // off here, so the row says nothing was pushed (#4418) and still checks gbrain. for (const [pageCount, ok, expected] of [ [0, false, "gbrain source fixture-artifacts has 0 indexed pages. Fix: gbrain sync --source fixture-artifacts"], - [7, true, "curated artifacts pushed; gbrain source fixture-artifacts has 7 pages"], + [7, true, "nothing was pushed; gbrain source fixture-artifacts has 7 pages"], ] as const) { it(`brain-sync stage reports the artifacts source's ${pageCount} indexed pages (ok=${ok})`, () => { const home = makeTestHome(); @@ -574,6 +577,68 @@ esac }); } + // #4418: gstack-brain-sync --once exits 0 when its push fails, so the row + // must come from the drain's status, and a failed push stays failed on the + // runs after it until a push succeeds. + it.skipIf(process.platform === "win32")("brain-sync stage says pushed only when the push went through (#4418)", () => { + const home = makeTestHome(); + const gstackHome = join(home, ".gstack"); + const fakeBin = join(home, "fake-bin"); + const remote = join(home, "remote.git"); + mkdirSync(gstackHome, { recursive: true }); + mkdirSync(fakeBin, { recursive: true }); + writeFileSync(join(fakeBin, "gbrain"), `#!/bin/sh +case "$*" in + "sources list --json") printf '%s\\n' '{"sources":[{"id":"fixture-artifacts","local_path":"${gstackHome}","page_count":7}]}' ;; + *) exit 1 ;; +esac +`); + chmodSync(join(fakeBin, "gbrain"), 0o755); + const env = { + HOME: home, + GSTACK_HOME: gstackHome, + GIT_CONFIG_NOSYSTEM: "1", + GIT_CONFIG_GLOBAL: join(home, ".gitconfig"), + PATH: `${fakeBin}:${process.env.PATH || ""}`, + }; + const bin = (name: string, ...args: string[]) => + spawnSync(join(import.meta.dir, "..", "bin", name), args, { encoding: "utf-8", timeout: 60000, env: { ...process.env, ...env } }); + const plan = join(gstackHome, "projects", "p", "ceo-plans", "plan.md"); + const brainSyncRow = () => { + const r = runScript(["--incremental", "--no-code", "--no-memory", "--quiet"], env); + const state = JSON.parse(readFileSync(join(gstackHome, ".gbrain-sync-state.json"), "utf-8")); + return { exitCode: r.exitCode, stage: state.last_stages.find((entry: { name: string }) => entry.name === "brain-sync") }; + }; + try { + spawnSync("git", ["init", "--bare", "-q", "-b", "main", remote], { timeout: 30000 }); + expect(bin("gstack-artifacts-init", "--remote", remote).status).toBe(0); + expect(bin("gstack-config", "set", "artifacts_sync_mode", "full").status).toBe(0); + mkdirSync(dirname(plan), { recursive: true }); + writeFileSync(plan, "# a plan\n"); + bin("gstack-brain-enqueue", "projects/p/ceo-plans/plan.md"); + let row = brainSyncRow(); + expect(row.stage.summary).toMatch(/^curated artifacts pushed.*gbrain source fixture-artifacts has 7 pages/); + expect(row.stage.ok).toBe(true); + + writeFileSync(join(remote, "hooks", "pre-receive"), '#!/bin/sh\necho "403 forbidden" >&2\nexit 1\n', { mode: 0o755 }); + writeFileSync(plan, "# a plan, revised\n"); + bin("gstack-brain-enqueue", "projects/p/ceo-plans/plan.md"); + row = brainSyncRow(); + expect(row.stage.ok).toBe(false); + expect(row.stage.summary).toContain("artifacts not pushed (push_failed: push failed"); + expect(row.stage.summary).not.toContain("pushed to git"); + expect(row.exitCode).toBe(1); + + // The next run still reports the failure, not "pushed". + bin("gstack-brain-enqueue", "projects/p/ceo-plans/plan.md"); + row = brainSyncRow(); + expect(row.stage.ok).toBe(false); + expect(row.stage.summary).toContain("artifacts not pushed (push_failed: "); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }, 60_000); + it("brain-sync stage resolves the sibling binary, not a HOME-rooted path", () => { // Regression for Codex M9: pre-fix the orchestrator looked up // ~/.claude/skills/gstack/bin/gstack-brain-sync, which silently no-op'd @@ -1189,3 +1254,43 @@ esac expect(commands).not.toMatch(/^sync /m); }); }); + +describe("stage verdicts (#4417, #4418)", () => { + const noGbrain = { PATH: "/nonexistent" }; + + it("memory: failed pages beside imported ones are WARN with the count and first cause", () => { + const v = memoryStageVerdict(0, "[memory-ingest] FAILED a.md: refused\n[memory-ingest] done\n", { written: 3, failed: 2 }); + expect(v).toMatchObject({ ok: true, warn: true }); + expect(v.summary).toMatch(/^3 imported, 2 failed [(]retried next run/); + expect(v.summary).toContain("first: a.md: refused"); + }); + + it("memory: parse failures are a note, not an import failure", () => { + const v = memoryStageVerdict(0, "[memory-ingest] done\n", { written: 0, failed: 2, parse_failed: 2 }); + expect(v).toEqual({ ok: true, summary: "done; 2 source file(s) could not be parsed and were skipped" }); + const mixed = memoryStageVerdict(0, "", { written: 0, failed: 3, parse_failed: 1 }); + expect(mixed.ok).toBe(false); + expect(mixed.summary).toMatch(/^0 imported, 2 failed .*; 1 source file[(]s[)] could not be parsed/); + }); + + it("memory: a non-zero exit or a signal is ERR whatever the counts", () => { + expect(memoryStageVerdict(2, "[memory-ingest] ERR: gbrain missing\n", { written: 0, failed: 0 })).toEqual({ ok: false, summary: "gbrain missing (exit 2)" }); + expect(memoryStageVerdict(null, "", null)).toEqual({ ok: false, summary: "ingest pass complete (killed by signal / timeout)" }); + }); + + for (const [status, ok, warn, lead] of [ + ["idle", true, undefined, "nothing new to push (queue empty)"], + ["held", true, true, "artifacts not all pushed (held: queue empty;"], + ["collision", true, true, "artifacts not all pushed (collision: queue empty;"], + ["error", false, undefined, "artifacts not pushed (error: queue empty;"], + ["blocked", false, undefined, "artifacts not pushed (blocked: queue empty;"], + [42, false, undefined, "artifacts not pushed (unknown: queue empty;"], + ] as const) { + it(`brain-sync: drain status ${status} reads ok=${ok} warn=${warn}`, () => { + const v = brainSyncStageVerdict({ status, message: "queue empty" }, noGbrain); + expect(v.ok).toBe(ok); + expect(v.warn).toBe(warn); + expect(v.summary.startsWith(lead)).toBe(true); + }); + } +}); From e1cfceae6a3442f4e27818ac8e6885dc68dbb006 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 02:47:18 +0800 Subject: [PATCH 47/62] Secrets check stops flagging three code shapes and catches concatenated and commented secrets (GST-3004) (#4457) The secrets check no longer stops a push on three kinds of ordinary code that only look like secrets: TypeScript types with spaced generic arguments, Python arguments that read a settings constant, and camelCase dotted field paths. It also catches two kinds of real secrets it used to miss, one built with `+` from short pieces and one written in a comment, so pushes are both quieter and safer. Nothing to do; a secret in any of the loosened positions still fails the check. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/adversarial-native#1 reader=adversarial-native Review-Finding: p1/outside-voice#1 reader=outside-voice Review-Finding: p1/outside-voice#2 reader=outside-voice --- changelog.d/secrets-check-code-shapes.md | 1 + docs/pregate.md | 23 +++ lib/redact-patterns.ts | 166 ++++++++++++++++++-- test/pregate-secrets-source-context.test.ts | 12 ++ test/redact-env-kv-code-shapes.test.ts | 119 ++++++++++++++ test/redact-env-kv-misses.test.ts | 72 +++++++++ 6 files changed, 379 insertions(+), 14 deletions(-) create mode 100644 changelog.d/secrets-check-code-shapes.md create mode 100644 test/redact-env-kv-code-shapes.test.ts create mode 100644 test/redact-env-kv-misses.test.ts diff --git a/changelog.d/secrets-check-code-shapes.md b/changelog.d/secrets-check-code-shapes.md new file mode 100644 index 00000000000..e0645620d3b --- /dev/null +++ b/changelog.d/secrets-check-code-shapes.md @@ -0,0 +1 @@ +- **The secrets check stops flagging three kinds of ordinary code as a secret, and catches two misses.** TypeScript types with spaced generic arguments, Python keyword arguments that read a settings constant (`aws_secret_access_key=settings.S3_SECRET_KEY,`), and camelCase dotted field paths (`"form.section.fieldName"`) no longer stop a push. A secret built with `+` from short pieces, or written in a trailing or whole-line comment, is now reported. A secret in any of those positions still fails the check. Template keys, arrays of names and string-literal generic types still report and are documented as known limits. (#4289) diff --git a/docs/pregate.md b/docs/pregate.md index 4f72ae55b41..35da657667b 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -1841,6 +1841,29 @@ those, each with its scope and its reason: Any other call's literal (`make_password("orange_monkey_pass")`), a later argument or fallback (`os.getenv("SECRET_KEY", "orange_monkey_pass")`) and a kebab passphrase still report. +- Three more code shapes are names, not credentials (GST-3004): a TypeScript + type with spaced generic arguments + (`session: Awaited<ReturnType<typeof launch>>;`), a Python keyword + argument that reads a CONSTANT_CASE setting + (`aws_secret_access_key=settings.S3_SECRET_KEY,`, #4289), and a quoted + camelCase dotted field path of three word segments + (`"form.section.fieldName"`; an all-lowercase one still reports). Each is + read from the value, never from the key's name or the file's path, and a + secret in the same position, a literal after it on the line, or the same text + in a config file still reports. +- Known limits, still reported, allowlist them by value: a JS/TS template key + built from `${…}` slots (#4287), an array of names in source code + (`"get_token": [load_auth, "authOperations"]`), and a generic type with + string-literal arguments (`Pick<Session, "id" | "forkedFrom">`). Exempting + them needed an entropy test on their text alone, which let random hex and + encoded literals through. +- Two misses are closed (#4289): the string pieces of a `+` chain are joined + and checked (`KEY = "form.x" + "<secret>"`), and a secret-named assignment + right after `#`, `//`, `/*` or `<!--` reports in a trailing or + whole-line comment unless its value is prose or key-naming text + (letters-only words joined by `_ . - | : / #`). An array whose first + element is a quoted secret (`"get_token": ["<secret>"]`) still reports + only through a provider rule such as `stripe.secret`. The `secrets` row says `N allowlisted (<ids>)` and lists each allowlisted finding with the entry (`allowlisted env.kv (evals/receipts/t1.json, added line diff --git a/lib/redact-patterns.ts b/lib/redact-patterns.ts index e951c24bf8c..6137672da5c 100644 --- a/lib/redact-patterns.ts +++ b/lib/redact-patterns.ts @@ -1065,6 +1065,33 @@ function expressionTail(line: string, comment: string): string | null { return depth > 0 || /(?:[=+\\]|\?\?|\|\||&&|\b(?:or|and))\s*$/.test(rest) ? null : rest; } +/** + * GST-3004: the value capture stops at a type's first space, so an annotation + * with spaced generic arguments (`session: Awaited<ReturnType<typeof launch>>;`) + * never reached the name-chain test as a closed type. Read on its line, the + * type is names, `<>`, `[]`, `|`, `&`, `,` and `?` only; it ends at a `,` + * `;`, `)` or `=` outside the brackets, or at the line end, and the rest of + * the line carries no secret literal or template. A string-literal type + * (CAPY-1's `Pick<Session, "id" | "forkedFrom">`) still reports: an entropy + * test on the literal alone let random hex through, so that shape is a known + * limit, allowlisted by value. + */ +const GENERIC_TYPE_HEAD = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*</; +function isGenericType(line: string): boolean { + let depth = 0; + let i = 0; + for (; i < line.length; i += 1) { + const c = line[i]!; + if (c === "<") depth += 1; + else if (c === ">") { + if (--depth < 0) return false; + } else if (depth === 0 && /[,;)=]/.test(c)) break; + else if (!/[\w$.\s|&[\],?]/.test(c)) return false; + } + const rest = line.slice(i); + return depth === 0 && !carriesSecretLiteral(rest) && !rest.includes("`"); +} + function isSourceExpression(span: string, match: RegExpExecArray, sourcePath: string | undefined): boolean { if (!sourcePath || !CODE_SOURCE.test(sourcePath)) return false; const { start, end } = spanBounds(match); @@ -1078,7 +1105,8 @@ function isSourceExpression(span: string, match: RegExpExecArray, sourcePath: st } else { const head = match[0].slice(0, match[0].length - span.length).trimEnd(); const separator = head.slice(-1); - if (separator !== ":" || !CODE_NAME_CHAIN.test(span.replace(/[,;)=|]+$/, ""))) return false; + if (separator !== ":") return false; + if (!CODE_NAME_CHAIN.test(span.replace(/[,;)=|]+$/, ""))) return GENERIC_TYPE_HEAD.test(span) && isGenericType(match.input.slice(start).split("\n", 1)[0]!) && !insideString(match.input, start, sourcePath); const rest = (span.endsWith("=") ? "=" : "") + match.input.slice(end).split("\n", 1)[0]; if (!/[,;]$/.test(span)) { const tail = expressionTail(rest, /\.pyi?$/i.test(sourcePath) ? "#" : "//"); @@ -1096,15 +1124,22 @@ function isSourceExpression(span: string, match: RegExpExecArray, sourcePath: st * the same line inside a `"""`/`'''` block still reports. Every segment must be * name-shaped (snake_case, camelCase, PascalCase or CONSTANT_CASE), so a dotted * random token still reports, and only a `;` and a comment may follow it on - * the line: a literal after it (`or "…"`, `, "…"`), a continuation or a - * keyword argument's comma still reports. A quoted value, a bare name, a + * the line: a literal after it (`or "…"`, `, "…"`) or a continuation still + * reports. A keyword argument's closing `,` or `)` is allowed only when the + * last segment is a CONSTANT_CASE setting + * (`aws_secret_access_key=settings.S3_SECRET_KEY,`, #4289), so + * `password=request.password,` still reports. A quoted value, a bare name, a * config, .env or TS file, and a scan without a path are unchanged. */ const ATTRIBUTE_SEGMENT = /^_*(?:[a-z][a-z0-9]*(?:_+[a-z0-9]+)*|[A-Z][A-Z0-9]*(?:_+[A-Z0-9]+)*|[A-Za-z][a-z0-9]*(?:[A-Z][a-z0-9]+)*)_*$/; +const CONSTANT_SEGMENT = /^_*[A-Z][A-Z0-9]*(?:_+[A-Z0-9]+)*_*$/; function isAttributeReference(span: string, match: RegExpExecArray, sourcePath: string | undefined): boolean { if (!sourcePath || !STRING_SPAN_SOURCE.test(sourcePath)) return false; - const chain = span.replace(/;$/, "").split("."); + const read = span.replace(/[,;)]+$/, ""); + const chain = read.split("."); if (chain.length < 2 || !chain.every((segment) => ATTRIBUTE_SEGMENT.test(segment))) return false; + const closer = span.slice(read.length); + if (closer !== "" && closer !== ";" && !CONSTANT_SEGMENT.test(chain.at(-1)!)) return false; const { start, end } = spanBounds(match); if (!/=[ \t]*$/.test(match.input.slice(match.index, start))) return false; const rest = match.input.slice(end).split("\n", 1)[0]; @@ -1112,6 +1147,93 @@ function isAttributeReference(span: string, match: RegExpExecArray, sourcePath: return !insideString(match.input, start, sourcePath); } +/** + * GST-3004: text that names or builds a key rather than holding one. Read with + * its whitespace removed, so a password with spaces is read whole, it must be + * short (under 8), a placeholder, under 3.0 bits, or letters-only words, + * lowercase or camelCase with an optional leading capital, joined by + * `_ . - | : / #` (`over_tough`, `secretsOperations`, `|over_tough|`). A + * generated credential carries digits or adjacent capitals, so it keeps + * reporting; a letters-only passphrase in this shape (`correctHorseBattery`) + * is the accepted residue. Comment prose is read run by run instead + * (isCommentText). + */ +const KEY_TEXT = /^[_.\-|:/#]*[A-Za-z][a-z]+(?:[A-Z][a-z]+)*(?:[_.\-|:/#]+[A-Za-z][a-z]+(?:[A-Z][a-z]+)*)*[_.\-|:/#]*$/; +function isSecretRun(run: string): boolean { + return run.length >= 8 && !isPlaceholderSpan(run) && shannonEntropy(run) >= 3.0 && !KEY_TEXT.test(run); +} +function holdsSecretText(text: string): boolean { + return isSecretRun(text.replace(/\s+/g, "")); +} + +/** The text of the `"…"` or `'…'` literal whose quote is at `i` and the index after it, or null when it does not close on the line. */ +function quotedAt(line: string, i: number): { text: string; end: number } | null { + for (let j = i + 1; j < line.length; j += line[j] === "\\" ? 2 : 1) if (line[j] === line[i]) return { text: line.slice(i + 1, j), end: j + 1 }; + return null; +} + +/** + * #4289: `KEY = "form.x" + "<secret>"` builds the value from pieces, and the + * value capture read only the first. When the value is a `+` chain of quoted + * literals and names on its line, the literals' text is joined, so a secret + * placed after a short piece or split across pieces is whole again, and checked + * with holdsSecretText. Names add no text. A chain that breaks off at a call, + * template or other operand is checked as far as it reads. + */ +const CHAIN_NAME = /[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*/y; +const CHAIN_PLUS = /[ \t]*\+[ \t]*/y; +function concatenationHoldsSecret(match: RegExpExecArray): boolean { + const { start } = spanBounds(match); + const line = match.input.slice(/["']/.test(match.input[start - 1] ?? "") ? start - 1 : start).split("\n", 1)[0]!; + let joined = ""; + let pieces = 0; + for (let i = 0; ; i = CHAIN_PLUS.lastIndex) { + const literal = line[i] === '"' || line[i] === "'" ? quotedAt(line, i) : null; + CHAIN_NAME.lastIndex = i; + if (!literal && !CHAIN_NAME.exec(line)) break; + pieces += 1; + if (literal) joined += literal.text; + CHAIN_PLUS.lastIndex = literal ? literal.end : CHAIN_NAME.lastIndex; + if (!CHAIN_PLUS.exec(line)) break; + } + return pieces > 1 && holdsSecretText(joined); +} + +/** + * #4289: the regex also starts a name right after a comment marker, and + * comments are prose: `# Auth: authentication, authorization, sessions`. A + * match that starts after other text on its line is a comment's, and its value, + * less trailing punctuation, reports only when it is a secret run by + * isSecretRun. Code before the comment is matched from the line start and + * checked as before. + */ +function isCommentText(span: string, match: RegExpExecArray): boolean { + const lineStart = match.input.lastIndexOf("\n", match.index - 1) + 1; + if (/^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?[ \t]*$/.test(match.input.slice(lineStart, match.index))) return false; + return !isSecretRun(span.replace(/[,;.)]+$/, "")); +} + +/** + * #4289: a quoted dotted path of three or more letters-only segments, each + * lowercase or camelCase and at least one camelCase + * (`KEY = "form.section.fieldName"`), names a form field. A segment with a + * digit, a capital first letter or adjacent capitals (`"form.<secret>"`) + * reports, and so do a path of one or two segments and an all-lowercase one, + * which #4209 keeps reporting as a quoted literal (`session = "self.client.session"`). + * Only source files qualify, and the rest of the line must carry no secret + * literal or template, so `PASSWORD="form.section.fieldName"` in a config + * file and `password = "form.section.fieldName" or "<secret>"` still report. + */ +const DOTTED_FIELD_PATH = /^[a-z]+(?:[A-Z][a-z]+)*(?:\.[a-z]+(?:[A-Z][a-z]+)*){2,}$/; +function isDottedFieldPath(span: string, match: RegExpExecArray, sourcePath: string | undefined): boolean { + if (!sourcePath || !CODE_SOURCE.test(sourcePath)) return false; + const { start, end } = spanBounds(match); + const quote = match.input[start - 1]; + if ((quote !== '"' && quote !== "'") || match.input[end] !== quote || !DOTTED_FIELD_PATH.test(span) || !/[A-Z]/.test(span)) return false; + const rest = match.input.slice(end + 1).split("\n", 1)[0]!; + return !carriesSecretLiteral(rest) && !rest.includes("`"); +} + /** The files isPropertyRead exempts in: TS, Dart and Python. JSX text in .tsx and .jsx can hold a host on any line, so those report as before. */ const PROPERTY_READ_SOURCE = /\.(?:[cm]?ts|dart|pyi?)$/i; /** How far back on its line isPropertyRead reads from a span. A span further from its line start than this is never exempted. */ @@ -1565,7 +1687,15 @@ export const PATTERNS: RedactPattern[] = [ // and text is a Markdown bullet or YAML list item, not a marker, so those // read as they did before. ENV_KV_NAME and SCHEMA_FIELD_NAME take the same // marker so the name-shape and schema exemptions hold on a diff line. - regex: /^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?[ \t]*(?:export[ \t]+)?["']?[A-Za-z0-9_.-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)["']?[ \t]*[:=][ \t]*["']?([^\s'"]{8,})["']?/i, + // GST-3004 (#4289): a name may also start right after a comment marker + // (`#`, `//`, `/*`, `<!--`) at the line start or after a space, so a + // secret in a trailing or whole-line comment reports; that start is a + // bounded lookbehind (a run of spaces is matched after it, not inside it, + // so a long run stays linear), and the code before the comment is still + // matched on its own from the line start. A short first piece followed by + // `+` is captured so concatenationHoldsSecret can read the rest of the + // chain. + regex: /(?:^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?|(?<=(?:^|[ \t])(?:#{1,6}|\/{2,3}|\/\*{1,2}|<!--)))[ \t]*(?:export[ \t]+)?["']?[A-Za-z0-9_.-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)["']?[ \t]*[:=][ \t]*["']?([^\s'"]{8,}|[^\s'"]{1,7}(?=["']?[ \t]*\+))["']?/i, // Only fire on credential-shaped names with high-entropy values — kills // `FOO_KEY=changeme` and `cacheKey: <entropic-id>` FPs. #2912: a value // that is exactly an environment read (`os.environ["X"]`, @@ -1578,17 +1708,25 @@ export const PATTERNS: RedactPattern[] = [ // #4209: so is a dotted attribute read assigned with = in Python or Dart (isAttributeReference). // #3208: so is a schema field identifier (isSchemaFieldIdentifier). // GST-1894: so is a self-named fixture label in a test file (isTestFixtureLabel). + // GST-3004: so is a dotted field path (isDottedFieldPath, #4289), and so + // is key-naming text in a comment + // (isCommentText). A secret literal in a `+` chain reports first, + // whatever the exemptions say about the chain's first piece + // (concatenationHoldsSecret). validate: (span, match, opts) => isCredentialShapedEnvName(match[0]) && - !isPlaceholderSpan(span) && - !/^\$\{?[A-Za-z_]/.test(span) && - !isBareEnvRead(span, match) && - !isCallExpression(span, match) && - !isSourceExpression(span, match, opts?.sourcePath) && - !isAttributeReference(span, match, opts?.sourcePath) && - !isSchemaFieldIdentifier(span, match) && - !isTestFixtureLabel(span, opts?.sourcePath) && - shannonEntropy(span) >= 3.0, + (concatenationHoldsSecret(match) || + (!isPlaceholderSpan(span) && + !/^\$\{?[A-Za-z_]/.test(span) && + !isBareEnvRead(span, match) && + !isCallExpression(span, match) && + !isSourceExpression(span, match, opts?.sourcePath) && + !isAttributeReference(span, match, opts?.sourcePath) && + !isDottedFieldPath(span, match, opts?.sourcePath) && + !isCommentText(span, match) && + !isSchemaFieldIdentifier(span, match) && + !isTestFixtureLabel(span, opts?.sourcePath) && + shannonEntropy(span) >= 3.0)), }, { id: "auth.bearer", diff --git a/test/pregate-secrets-source-context.test.ts b/test/pregate-secrets-source-context.test.ts index 0c26a363ebc..1686b5ee00a 100644 --- a/test/pregate-secrets-source-context.test.ts +++ b/test/pregate-secrets-source-context.test.ts @@ -117,6 +117,18 @@ describe('pregate secrets: source context and diff integrity', () => { } finally { cleanup(fx); } }); + // Value: protects=a TS annotation with spaced generic arguments and a Python settings read pass the never-downgradable secrets check, while a secret + // in a + chain or a trailing comment fails it; fails_when=the GST-3004 false positives return at the pregate level, or the concatenation or comment + // read is lost there; why_new=GST-3004's cases came from pregate runs, and TS files reach the scanner as added lines under their base name; seam=fixture repo; no_claim=Dart files + test('a spaced generic type and a Python settings read pass; a secret in a + chain or a trailing comment still fails (GST-3004)', () => { + const secret = ['Qx9vL2mZ', 'p8Rt4Kw7', 'Yn3Bh2Jd'].join(''); + const ts = 'export interface Launch {\n session: Awaited<ReturnType<typeof launchSession>>;\n credentials: Record<string, CredentialEntry>;\n}\n'; + const py = 'client = boto3.client(\n "s3",\n aws_secret_access_key=settings.S3_SECRET_KEY,\n)\n'; + expect(repo({ 'src/launch.ts': ts, 'app/storage.py': py }).secrets()).toMatchObject({ status: 'pass', lines: [] }); + const r = repo({ 'src/launch.ts': ts + 'export const client = {\n apiKey: "sk" + "' + secret + '",\n', 'app/storage.py': py + 'RETRIES = 3 # API_KEY = "' + secret + '"\n' }).secrets(); + expect({ status: r.status, rows: r.lines.filter((l) => l.includes('env.kv')).sort() }).toEqual({ status: 'fail', rows: [expect.stringContaining('(app/storage.py, line 5)'), expect.stringContaining('(src/launch.ts, added line 6)')] }); + }); + test('parseAddedLineNumbers numbers each added line from its hunk header', () => { const diff = ['diff --git a/a.py b/a.py', '--- a/a.py', '+++ b/a.py', '@@ -3,0 +4,2 @@', '+one', '+two', '@@ -9 +11 @@', '-old', '+new'].join('\n'); expect([...parseAddedLineNumbers(diff)]).toEqual([['a.py', [4, 5, 11]]]); diff --git a/test/redact-env-kv-code-shapes.test.ts b/test/redact-env-kv-code-shapes.test.ts new file mode 100644 index 00000000000..4a1d8a85d1f --- /dev/null +++ b/test/redact-env-kv-code-shapes.test.ts @@ -0,0 +1,119 @@ +/** + * GST-3004: env.kv ("secret-named assignment with high-entropy value") flagged + * code as a secret, and the pregate secrets check, which cannot be downgraded, + * stopped pushes on it. Three shapes are now read as code, each by the value's + * shape and never by the key's name or the file's path, and each pass has a + * hold case putting a real-looking secret in the same position: a TypeScript + * type with spaced generic arguments, a Python keyword argument reading a + * CONSTANT_CASE setting, and a quoted camelCase dotted field path (#4289). + * Three reported shapes stay known limits: a JS/TS template key (#4287), an + * array of names (GBRA-615) and a string-literal generic type (CAPY-1). An + * entropy test on their text alone let random hex and encoded literals through + * (the second-model audit's bypasses below), so they still report. + */ +// Value: protects=env.kv passes three code shapes while a secret in the same position, a config file or a string still reports, and the three known-limit shapes and the audit's bypass lines keep reporting; fails_when=one of the fixed false positives returns, or an exemption lets a high-entropy, hex, encoded or provider-shaped value through; why_new=the cases had no test; seam=none; no_claim=scanner-level only, the pregate case lives in pregate-secrets-source-context.test.ts +import { describe, expect, test } from "bun:test"; +import { scan } from "../lib/redact-engine"; + +const ids = (text: string, sourcePath?: string) => + scan(text, { repoVisibility: "private", processEnv: {}, ...(sourcePath ? { sourcePath } : {}) }).findings.map((f) => f.id); +const kv = (text: string, sourcePath?: string) => ids(text, sourcePath).includes("env.kv"); +const S = "Qx9vL2mZp8Rt4Kw7Yn3Bh2Jd"; +const HEX = ["9d1e7ebb", "51b069eb", "1bd6"].join(""); +const STRIPE = ["sk", "live", S].join("_"); +const SPACED = "R7m!2pX K4v@8Q j9W#3s"; +const BT = "~"; +const passes = (cases: ReadonlyArray<readonly [string, string | undefined]>) => { + for (const [code, file] of cases) expect({ code, file, kv: kv(code, file) }).toEqual({ code, file, kv: false }); +}; +const holds = (cases: ReadonlyArray<readonly [string, string | undefined]>) => { + for (const [code, file] of cases) expect({ code, file, kv: kv(code, file) }).toEqual({ code, file, kv: true }); +}; + +describe("env.kv: code shapes are not secrets (GST-3004)", () => { + test("a TypeScript annotation with spaced generic arguments passes", () => { + passes([ + [" session: Awaited<ReturnType<typeof launchClaudePty>>;", "test/trust.test.ts"], + [" credentials: Record<string, CredentialEntry>;", "src/vault.ts"], + [" auth: Map<string, AuthInfo> | undefined,", "src/context.ts"], + [" session: Pick<ClaudePtySession, Send | Close> | null,", "src/launch.ts"], + ]); + }); + test("hold: a literal type, a default value, an object-literal value and a config file still report", () => { + holds([ + [' session: Pick<Session, "' + S + '"> | null,', "src/orchestrator.ts"], + [' session: Pick<Session, "' + HEX + '">,', "src/orchestrator.ts"], + ['password: Pick<Session, "' + SPACED + '">,', "src/client.ts"], + [' session: Awaited<ReturnType<typeof launch>> = "' + S + '",', "src/orchestrator.ts"], + [' session: Map<string, AuthInfo>, other: "' + S + '",', "src/orchestrator.ts"], + [' session: "' + S + '",', "src/orchestrator.ts"], + [" session: Awaited<ReturnType<typeof " + S + ">>;", "deploy/values.yaml"], + [" session: Awaited<ReturnType<typeof launchClaudePty>>;", undefined], + ]); + expect(ids(' session: Pick<Session, "' + STRIPE + '">,', "src/a.ts")).toEqual(expect.arrayContaining(["env.kv", "stripe.secret"])); + }); + + test("a Python keyword argument reading a CONSTANT_CASE setting passes (#4289)", () => { + passes([ + [" aws_secret_access_key=settings.S3_SECRET_KEY,", "app/storage.py"], + [" aws_secret_access_key=settings.S3_SECRET_KEY)", "app/storage.py"], + [" aws_secret_access_key=settings.S3_SECRET_KEY, # from the env", "app/storage.py"], + [" password=django_settings.DATABASES_DEFAULT_PASSWORD,", "app/db.py"], + ]); + }); + test("hold: a literal beside the read, a lowercase attribute, a .env file and a string still report (#4289's table)", () => { + holds([ + [' aws_secret_access_key=settings.S3_SECRET_KEY or "' + S + '",', "app/storage.py"], + [' aws_secret_access_key=settings.S3_SECRET_KEY + "' + S + '",', "app/storage.py"], + [' aws_secret_access_key=settings.S3_SECRET_KEY.replace("a", "' + S + '"),', "app/storage.py"], + [' password=settings.DB_PASSWORD; token="' + S + '"', "app/storage.py"], + [" aws_secret_access_key=settings.S3_SECRET_KEY, region=" + S, "app/storage.py"], + [" password=request.password,", "app/api/handlers.py"], + ["SECRET_KEY=settings.S3_SECRET_KEY", ".env"], + ['CONFIG = """\n aws_secret_access_key=settings.S3_SECRET_KEY,\n"""', "app/storage.py"], + ]); + }); + + test("a quoted camelCase dotted field path of three word segments passes (#4289)", () => { + passes([ + ['KEY = "form.section.fieldName"', "app/forms.py"], + [' field_key="form.section.fieldName",', "app/forms.py"], + [" KEY = 'form.section.fieldName';", "src/forms.ts"], + ]); + }); + test("hold: a secret segment, a digit, a two-segment or all-lowercase path and an unclosed quote still report", () => { + holds([ + [' session = "self.client.session"', "tests/test_views.py"], + ['KEY = "form.' + S + '"', "app/forms.py"], + ['KEY = "form.section.' + S + '"', "app/forms.py"], + ['KEY = "form.section2.fieldName"', "app/forms.py"], + ['KEY = "section.fieldNameValue"', "app/forms.py"], + ['KEY = "form.section.fieldName', "app/forms.py"], + ]); + }); + test("hold: a dotted field path with a secret literal after it, or outside source code, still reports", () => { + holds([ + ['password = "form.section.fieldName" or "' + S + '"', "app/forms.py"], + ['SECRET_KEY = "form.section.fieldName", "' + S + '"', "app/forms.py"], + [' apiKey: "form.section.fieldName" || "' + S + '",', "src/forms.ts"], + ['PASSWORD="form.section.fieldName"', ".env"], + ['session_key: "form.section.fieldName"', "config/app.yml"], + ['PASSWORD="form.section.fieldName"', undefined], + ]); + }); + + test("known limits: template keys, arrays of names and string-literal generic types still report, and so do the audit's bypass lines", () => { + const template = (text: string) => text.replaceAll(BT, "\x60").replaceAll("@{", "$" + "{"); + holds([ + [template(" key: ~@{over.day}|@{over.groomerId}|over_tough|~,"), "src/cache.ts"], + [' "reveal_secret": [load_secrets, "secretsOperations"],', "src/core/operation-loaders.generated.ts"], + [' session: Pick<Session, "id" | "forkedFrom"> | null,', "src/orchestrator.ts"], + [template("password = ~" + SPACED + "@{suffix}~;"), "src/client.ts"], + [template("password = ~@{tenant}" + HEX + "~;"), "src/client.ts"], + [template("password = ~@{/m4Fq8Wz2Rn7Yb3Hd9Vk6Lp5C/.source}~;"), "src/client.ts"], + [template("password = ~@{String.fromCharCode(109,52,70,113,56,87,122,50)}~;"), "src/client.ts"], + ['password: [load_auth, "' + SPACED + '"],', "src/client.ts"], + ['password: [load_auth, "' + HEX + '"],', "src/client.ts"], + ]); + }); +}); diff --git a/test/redact-env-kv-misses.test.ts b/test/redact-env-kv-misses.test.ts new file mode 100644 index 00000000000..0688862f26e --- /dev/null +++ b/test/redact-env-kv-misses.test.ts @@ -0,0 +1,72 @@ +/** + * GST-3004 (#4289 cases 3 and 4): env.kv read only the first token after a + * secret-named assignment at the start of a line, so a secret placed after a + * short concatenated piece (`KEY = "form.x" + "<secret>"`) or written in a + * comment (`x = 1 # API_KEY = "<secret>"`) gave no finding. A `+` chain's + * literals are now joined and checked, and a name may start right after a + * comment marker. The benign cases are the same shapes holding text that names + * a key, so the new reads add no finding there. + */ +// Value: protects=env.kv reports a secret in a + chain or a comment; fails_when=either miss returns, or the comment read starts reporting prose and key-naming text; why_new=#4289 cases 3 and 4 had no test; seam=none; no_claim=scanner-level only, the pregate case lives in pregate-secrets-source-context.test.ts +import { describe, expect, test } from "bun:test"; +import { scan } from "../lib/redact-engine"; + +const findings = (text: string, sourcePath?: string) => + scan(text, { repoVisibility: "private", processEnv: {}, ...(sourcePath ? { sourcePath } : {}) }).findings.filter((f) => f.id === "env.kv"); +const kv = (text: string, sourcePath?: string) => findings(text, sourcePath).length > 0; +const S = "Qx9vL2mZp8Rt4Kw7Yn3Bh2Jd"; +const S2 = ["Zz8Kq2Lm", "7Np4Rs9T", "v3Wx6Yb"].join(""); + +describe("env.kv: secrets built by concatenation or written in comments (GST-3004, #4289)", () => { + test("a secret after a short concatenated piece, or split across pieces, reports", () => { + for (const [code, file] of [ + ['KEY = "form.x" + "' + S + '"', "app/forms.py"], + ["KEY = 'form.x' + '" + S + "'", "app/forms.py"], + [' apiKey: "sk" + "' + S + '",', "src/client.ts"], + [' apiKey: base + "' + S + '",', "src/client.ts"], + ['TOKEN = "Qx9vL2m" + "Zp8Rt4K" + "w7Yn3Bh"', "app/client.py"], + ['TOKEN = "Qx9vL2m" + region + "Zp8Rt4K" + "w7Yn3Bh"', "app/client.py"], + ['TOKEN = "Qx9vL2m" + "Zp8Rt4K" + fetch_rest()', "app/client.py"], + ['TOKEN="abc"+"' + S + '"', ".env"], + ] as const) expect({ code, file, kv: kv(code, file) }).toEqual({ code, file, kv: true }); + }); + test("a secret in a trailing or whole-line comment reports", () => { + for (const [code, file] of [ + ['x = 1 # API_KEY = "' + S + '"', "app/settings.py"], + ["# API_KEY=" + S, "deploy/env.sh"], + ['const a = 1; // apiKey: "' + S + '"', "src/client.ts"], + ['// apiKey: "' + S + '"', "src/client.ts"], + ['/* token: "' + S + '" */', "src/client.ts"], + ["<!-- password: " + S + " -->", "docs/setup.html"], + ["retries: 3 # token: " + S, "deploy/values.yaml"], + ] as const) expect({ code, file, kv: kv(code, file) }).toEqual({ code, file, kv: true }); + }); + test("a secret in the code and another in its comment report separately", () => { + expect(findings('API_KEY="' + S + '" # TOKEN="' + S2 + '"', "app/settings.py").map((f) => f.col)).toEqual([10, 46]); + }); + test("a long run of spaces or comment markers scans in linear time", () => { + for (const text of [" ".repeat(40_000) + "x", "# " + " ".repeat(40_000) + "x", "#".repeat(40_000) + "x", "/".repeat(40_000)]) { + const started = performance.now(); + scan(text, { repoVisibility: "private", processEnv: {}, sourcePath: "src/client.ts", maxBytes: 1 << 20 }); + expect(performance.now() - started).toBeLessThan(500); + } + }); + test("a line whose code is exempt still reports a secret in its comment", () => { + expect(kv(' session = self.client.session # TOKEN="' + S + '"', "tests/test_views.py")).toBe(true); + }); + + test("benign: chains of key-naming text and names, prose and key-naming text in comments, and placeholders give no finding", () => { + for (const [code, file] of [ + ['sessionKey = "user:" + user_id + ":sessions_active"', "app/cache.py"], + ['token = "Bearer " + jwt', "app/client.py"], + ['KEY = "form." + "section.fieldName"', "app/forms.py"], + [" sessionKey: prefix + suffix,", "src/cache.ts"], + ["# Auth: authentication, authorization, sessions, permissions. A data file", "bin/diff-scope"], + ["// signal_key: 'test-discipline',", "hooks/preference.ts"], + ["# password: changeme", "deploy/values.yaml"], + ["# token: ${GITHUB_TOKEN}", "deploy/env.sh"], + ["x = 1 # see docs/token: for details", "app/settings.py"], + ["url = 'https://example.test/#token=abcdefgh'", "app/settings.py"], + ] as const) expect({ code, file, kv: kv(code, file) }).toEqual({ code, file, kv: false }); + }); +}); From e671a531f4ede3d63b3143c96903466c960aca58 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 03:54:16 +0800 Subject: [PATCH 48/62] Unattended /autoplan runs its configured second-model review in the foreground, and run ids no longer collide (GST-3015) (#4459) Unattended `/autoplan --full` now runs the second-model review when `codex_reviews: enabled` is set, runs it in the foreground with a 9-minute limit, and records a timeout with the standard failure line instead of ending the session. Two runs started in the same second also get different run ids now. Why: in a planning test, Opus 5.5 skipped the second reviewer in 2 of 3 runs over consent the config had already given, and ended the third session while the review ran in the background. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- autoplan/DRIVER.md | 2 +- autoplan/DRIVER.md.tmpl | 2 +- autoplan/sections/unattended.md | 7 +-- autoplan/sections/unattended.md.tmpl | 7 +-- ...attended-autoplan-runs-its-second-voice.md | 2 + docs/troubleshooting.md | 3 +- lib/approval-record.ts | 2 +- lib/autoplan-run.ts | 5 +- scripts/resolvers/autoplan-driver.ts | 8 +++ scripts/resolvers/index.ts | 3 +- test/approval-classes.test.ts | 4 +- test/autoplan-run-id.test.ts | 39 +++++++++++++++ test/autoplan-unattended-voice.test.ts | 50 +++++++++++++++++++ test/outside-consent.test.ts | 11 ++++ 14 files changed, 130 insertions(+), 15 deletions(-) create mode 100644 changelog.d/unattended-autoplan-runs-its-second-voice.md create mode 100644 test/autoplan-run-id.test.ts create mode 100644 test/autoplan-unattended-voice.test.ts diff --git a/autoplan/DRIVER.md b/autoplan/DRIVER.md index a117116ed00..91d970bc22f 100644 --- a/autoplan/DRIVER.md +++ b/autoplan/DRIVER.md @@ -26,7 +26,7 @@ line yourself; gstack never writes the plan. **Kinds (R65), first `next` only.** 1. `next` prints one `ATTEMPT: <id> phase=<p> voice=native|outside prompt=<file> result=<file>` per voice. Dispatch the native prompt to a subagent on your model and the outside prompt to - a subagent on another model family (or `gstack-outside-voice run`). Each writes `result=`. The first `next` also prints `REVIEW_ESTIMATE:` (most attempts and reservations the review can take). + a subagent on another model family (or `gstack-outside-voice run`). Each writes `result=`. The first `next` also prints `REVIEW_ESTIMATE:` (most attempts and reservations the review can take). **Outside voice, unattended.** A stored `codex_reviews: enabled` is the owner's standing consent to send each phase's review input to the outside model (`next` prints `OUTSIDE_CONSENT: given by codex_reviews=enabled`), so run the outside attempt: the preamble's unattended consent rule does not cover it, and you never close it `--unavailable` over consent or data leaving the machine. The runner itself enforces `disabled` or an unreadable config (`OUTSIDE: <phase> not_run reason=consent_missing`, no outside attempt); an unset `codex_reviews` keeps its existing handling. Run the voice in the foreground, inside this turn: `gstack-outside-voice run ... --timeout-ms 540000` with the tool's own timeout above it (Claude Code Bash `timeout: 600000`), or a subagent you await. Never `run_in_background`, never a monitor, never end the turn to wait for it: an unattended session ends with its turn. When the voice fails, `submit --voice outside --unavailable "<line>"` with the matching line and carry on in the same turn, the native voice still counting: **Auth failure:** If stderr contains "auth", "login", "unauthorized", or "API key": "Codex authentication failed. Run `codex login` to authenticate." **Timeout:** "Codex timed out after 9 minutes and was terminated; this pass produced NO findings." A timed-out pass is MISSING COVERAGE, not a clean bill — say so explicitly rather than continuing as if Codex had reviewed. **Empty response:** "Codex returned no response. Stderr: <paste relevant error>." 2. Submit each voice exactly once (`BOUND:`). Both voices in closes the phase (`PHASE_CLOSED:`). 3. Repeat `next` until `status=gate_pending` (`GATE: gate_rev=<n>`); render it with `gstack-gate render <dir>/gate.json --all` and relay every page with the two cost lines printed under `GATE:`: `GATE_SPEND:` (spent, worst case, cap, headroom, attempts; host-subagent attempts are priced unknown and counted at their reservation, so quote their real figure from the host's cost view) and `GATE_REC_COST:` (the phases `rec` can reopen and the estimate for them, an upper bound; `gate_cost` in `--json`). You never approve the gate for the owner. Offer `rec` (every recommendation, plan changes included) as the default. diff --git a/autoplan/DRIVER.md.tmpl b/autoplan/DRIVER.md.tmpl index b4b64d887dc..c9f84eb4ae2 100644 --- a/autoplan/DRIVER.md.tmpl +++ b/autoplan/DRIVER.md.tmpl @@ -23,7 +23,7 @@ line yourself; gstack never writes the plan. **Kinds (R65), first `next` only.** 1. `next` prints one `ATTEMPT: <id> phase=<p> voice=native|outside prompt=<file> result=<file>` per voice. Dispatch the native prompt to a subagent on your model and the outside prompt to - a subagent on another model family (or `gstack-outside-voice run`). Each writes `result=`. The first `next` also prints `REVIEW_ESTIMATE:` (most attempts and reservations the review can take). + a subagent on another model family (or `gstack-outside-voice run`). Each writes `result=`. The first `next` also prints `REVIEW_ESTIMATE:` (most attempts and reservations the review can take). {{AUTOPLAN_UNATTENDED_VOICE}} 2. Submit each voice exactly once (`BOUND:`). Both voices in closes the phase (`PHASE_CLOSED:`). 3. Repeat `next` until `status=gate_pending` (`GATE: gate_rev=<n>`); render it with `gstack-gate render <dir>/gate.json --all` and relay every page with the two cost lines printed under `GATE:`: `GATE_SPEND:` (spent, worst case, cap, headroom, attempts; host-subagent attempts are priced unknown and counted at their reservation, so quote their real figure from the host's cost view) and `GATE_REC_COST:` (the phases `rec` can reopen and the estimate for them, an upper bound; `gate_cost` in `--json`). You never approve the gate for the owner. Offer `rec` (every recommendation, plan changes included) as the default. diff --git a/autoplan/sections/unattended.md b/autoplan/sections/unattended.md index 06e5a41010b..a3d181f6ba7 100644 --- a/autoplan/sections/unattended.md +++ b/autoplan/sections/unattended.md @@ -3,9 +3,10 @@ ## Unattended profile `SESSION_KIND: unattended`: a parent drives the run through -`~/.claude/skills/gstack/bin/gstack-autoplan` (`next`/`submit`/`answer --gate-rev`/ -`export`; docs/unattended.md) and reads artifacts, never prose. Phases close -themselves, Eng runs last, the outside voice (none when lean) runs through `gstack-outside-voice`, +`~/.claude/skills/gstack/bin/gstack-autoplan` (DRIVER.md; +docs/unattended.md) and reads artifacts, never prose. Phases close +themselves, Eng runs last, the outside voice (none when lean) runs per DRIVER.md +(enabled `codex_reviews` is consent; foreground only), and the run stops at `status=gate_pending`: never approve. `gstack-artifact validate <dir>/run.json` is the completion check. End with `GSTACK_RESULT: skill=autoplan status=<status> run=<dir>`. diff --git a/autoplan/sections/unattended.md.tmpl b/autoplan/sections/unattended.md.tmpl index f41f0b09a54..e5a2cd6f80b 100644 --- a/autoplan/sections/unattended.md.tmpl +++ b/autoplan/sections/unattended.md.tmpl @@ -1,9 +1,10 @@ ## Unattended profile `SESSION_KIND: unattended`: a parent drives the run through -`~/.claude/skills/gstack/bin/gstack-autoplan` (`next`/`submit`/`answer --gate-rev`/ -`export`; docs/unattended.md) and reads artifacts, never prose. Phases close -themselves, Eng runs last, the outside voice (none when lean) runs through `gstack-outside-voice`, +`~/.claude/skills/gstack/bin/gstack-autoplan` (DRIVER.md; +docs/unattended.md) and reads artifacts, never prose. Phases close +themselves, Eng runs last, the outside voice (none when lean) runs per DRIVER.md +(enabled `codex_reviews` is consent; foreground only), and the run stops at `status=gate_pending`: never approve. `gstack-artifact validate <dir>/run.json` is the completion check. End with `GSTACK_RESULT: skill=autoplan status=<status> run=<dir>`. diff --git a/changelog.d/unattended-autoplan-runs-its-second-voice.md b/changelog.d/unattended-autoplan-runs-its-second-voice.md new file mode 100644 index 00000000000..23c75fae41e --- /dev/null +++ b/changelog.d/unattended-autoplan-runs-its-second-voice.md @@ -0,0 +1,2 @@ +- **Unattended /autoplan now runs the second-model review you turned on, and waits for it instead of ending the session.** With `codex_reviews: enabled` in the config, Opus 5.5 still skipped the second reviewer in 2 of 3 unattended `--full` runs, saying the owner had not agreed to send the plan off the machine; in the third it started the review in the background and ended its turn, which ends a headless session. `gstack-autoplan next` now prints `OUTSIDE_CONSENT: given by codex_reviews=enabled` beside the outside attempt, and autoplan/DRIVER.md says that an explicit `enabled` is the owner's standing consent, that the review runs in the foreground with a 9-minute limit, and that a timeout or failure is recorded with the standard failure line while the run carries on. `disabled` is still enforced by the runner, and an unset `codex_reviews` is handled as before. +- **Two /autoplan runs started in the same second no longer share a run id.** Run ids were the run directory's name plus a time stamp to the second, so two runs whose directories were both named `autoplan` got the same id and the same checkpoint folder. Each id now carries six random letters before the stamp. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 1357386a7f5..48451b01959 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2118,7 +2118,8 @@ Nothing was written, locally or to the Drive mirror. `import --autoplan` skips a `pii.phone.e164` or `pii.cc` finding that starts inside the autoplan run id's 14-digit stamp, or the thread-code digits right before it, where import places the id (the ask's `autoplan run <id>` and the source's `autoplan:<id>@`), when -the id has the minted shape `<name>-<14 digits>` (GST-2047); a phone number in +the id has the minted shape `<name>-<14 digits>` (GST-2047; since GST-3015 the +name ends in six random letters); a phone number in the rest of the directory name, the same id anywhere else, and every other finding in the row still refuse. diff --git a/lib/approval-record.ts b/lib/approval-record.ts index 4e3f0d6c30b..f28373a3991 100644 --- a/lib/approval-record.ts +++ b/lib/approval-record.ts @@ -153,7 +153,7 @@ function validDate(d: string): boolean { export interface NewRow { ask: string; words: string; by: string; scope: string; pending?: string; outcome?: string; date?: string; source?: string } -/** An autoplan run id as gstack-autoplan mints it: the run directory's name, a hyphen, then a 14-digit time stamp. */ +/** An autoplan run id as gstack-autoplan mints it: the run directory's name, a hyphen, six random letters (since GST-3015), a hyphen, then a 14-digit time stamp. */ const MINTED_RUN_ID = /^[A-Za-z0-9._-]{1,64}-\d{14}$/; /** The part of a minted run id the exemption covers: the 14-digit stamp and, when the name ends in a thread code, its digits. */ const RUN_ID_STAMP = /(?:(?<!\d)\d{1,6}-)?\d{14}$/; diff --git a/lib/autoplan-run.ts b/lib/autoplan-run.ts index 1a63fadc55a..49ffe23c76c 100644 --- a/lib/autoplan-run.ts +++ b/lib/autoplan-run.ts @@ -30,7 +30,7 @@ import { FILES, RunError, journal, now, pendingAmendments, readDecisions, readJo import { checkPlanReality, checkRealityRows, PLAN_REALITY_CHECKER } from './plan-reality'; import type { RunStatus } from './headless-artifacts'; import { sha256File } from './headless-artifacts'; -import { outsideConsent } from './outside-consent'; +import { outsideConsent, readStoredCodexReviews } from './outside-consent'; import { familyConflict, modelFamily } from './outside-voice-runner'; import { SpendCapExceeded, release, renderSpend, reserve, settle, summarize, readLedger } from './spend-ledger'; import { DEFAULT_MAX_ROUNDS, attemptEstimate, overCap, resumeStop, roundCap, roundOf, roundsLine, stopForBudget, stopLines } from './autoplan-budget'; @@ -116,7 +116,7 @@ export function initRun(o: InitOptions, lines: string[] = []): RunState { const sessionKind = o.sessionKind ?? process.env.GSTACK_SESSION_KIND ?? 'unattended'; const lean = leanMode({ kind: o.kind, full: o.full, ceoOnly: o.ceoOnly, base: o.base, sessionKind, env: process.env }); const order: Phase[] = o.ceoOnly ? ['ceo'] : lean ? ['eng'] : phaseOrder(scope); - const run = o.runId ?? `${path.basename(out)}-${new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14)}`; + const run = o.runId ?? `${path.basename(out)}-${Array.from(crypto.randomBytes(6), b => String.fromCharCode(97 + b % 26)).join('')}-${new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14)}`; // codex_reviews gates the outside voice here, before any dispatch: a refusal is a terminal not_run outcome per phase. const consent = (o.outsideEnabled ?? true) && !lean ? outsideConsent({ userInvoked: false }) : undefined; const consentMissing = consent && !consent.allowed ? consent.lines[0] : undefined; @@ -283,6 +283,7 @@ export function nextStep(o: NextOptions): NextResult { state.status = 'awaiting_result'; writeState(state); for (const a of result.attempts) lines.push(`ATTEMPT: ${a.attempt} phase=${phase} voice=${a.voice} prompt=${a.prompt} result=${a.result} model_family=${a.model_family}${a.new ? '' : ' (open)'}`); + if (result.attempts.some(a => a.voice === 'outside') && readStoredCodexReviews().value === 'enabled') lines.push("OUTSIDE_CONSENT: given by codex_reviews=enabled (the owner's standing consent to send this review input to the outside model: run the outside attempt in the foreground, ask nothing, and never close it --unavailable over consent)"); lines.push(renderSpend(summarize(readLedger(path.join(state.out, FILES.spend)))), roundsLine(state)); return result; } diff --git a/scripts/resolvers/autoplan-driver.ts b/scripts/resolvers/autoplan-driver.ts index 5b8153e7dc7..e24cb6dcbdb 100644 --- a/scripts/resolvers/autoplan-driver.ts +++ b/scripts/resolvers/autoplan-driver.ts @@ -13,6 +13,7 @@ import { PHASES, RESULT_FORMAT } from '../../lib/autoplan-prompts'; import { SCOPE_FLAG_TOKENS } from '../../lib/autoplan-scope'; import { RESULT_CODES } from '../../lib/result-codes'; import { DEFAULT_HOST_ESTIMATE_USD, DEFAULT_MAX_ROUNDS } from '../../lib/autoplan-budget'; +import { outsideVoiceFailurePolicy } from './outside-voice'; import type { ResolverFn } from './types'; /** One entry per command line the loop runs, as the field-wave plan specifies them. */ @@ -75,3 +76,10 @@ export const generateAutoplanDriverCodes: ResolverFn = () => DRIVER_CODES.map(co const row = (RESULT_CODES as Record<string, { fix: string }>)[code]; return `- \`${code}\`: ${row?.fix ?? PENDING_FIX[code]}`; }).join('\n'); + +/** GST-3015: the outside voice in an unattended run, one line so it sits inside the loop's dispatch step. An explicit codex_reviews: enabled is consent; the voice runs in the foreground with a bounded timeout. */ +export const generateAutoplanUnattendedVoice: ResolverFn = ctx => [ + "**Outside voice, unattended.** A stored `codex_reviews: enabled` is the owner's standing consent to send each phase's review input to the outside model (`next` prints `OUTSIDE_CONSENT: given by codex_reviews=enabled`), so run the outside attempt: the preamble's unattended consent rule does not cover it, and you never close it `--unavailable` over consent or data leaving the machine. The runner itself enforces `disabled` or an unreadable config (`OUTSIDE: <phase> not_run reason=consent_missing`, no outside attempt); an unset `codex_reviews` keeps its existing handling.", + "Run the voice in the foreground, inside this turn: `gstack-outside-voice run ... --timeout-ms 540000` with the tool's own timeout above it (Claude Code Bash `timeout: 600000`), or a subagent you await. Never `run_in_background`, never a monitor, never end the turn to wait for it: an unattended session ends with its turn. When the voice fails, `submit --voice outside --unavailable \"<line>\"` with the matching line and carry on in the same turn, the native voice still counting:", + ...outsideVoiceFailurePolicy(ctx, { timeoutMinutes: 9, onTimeout: 'missing-coverage', stderrOnEmpty: true, fallback: 'none', escape: 0 }).split('\n').map(l => l.replace(/^- /, '')), +].join(' '); diff --git a/scripts/resolvers/index.ts b/scripts/resolvers/index.ts index 2fd070d7447..e68656396ea 100644 --- a/scripts/resolvers/index.ts +++ b/scripts/resolvers/index.ts @@ -53,7 +53,7 @@ import { generateImplementerDispatchRules } from './dispatch-rules'; import { generatePlanRealityRows } from './plan-reality'; import { generateSidewaysSweep, generateFlakeFixNumber } from './sideways'; import { generateCoordinatorContract } from './coordinator-contract'; -import { generateAutoplanDriverCodes, generateAutoplanDriverCommands, generateAutoplanDriverFiles, generateAutoplanDriverGate, generateAutoplanDriverPhases, generateAutoplanDriverResultFormat } from './autoplan-driver'; +import { generateAutoplanDriverCodes, generateAutoplanDriverCommands, generateAutoplanDriverFiles, generateAutoplanDriverGate, generateAutoplanDriverPhases, generateAutoplanDriverResultFormat, generateAutoplanUnattendedVoice } from './autoplan-driver'; import { generateShipDriverStops } from './ship-driver'; import { generateQAScope, generateQAExploratory, generateQAFunctional, generateQAResource, generateQAReview, generateQAReviewPreflight, generateQAMethodReads } from './qa'; import { generateVoiceTriggerRouting } from './voice-triggers'; @@ -193,6 +193,7 @@ export const RESOLVERS: Record<string, ResolverFn> = { AUTOPLAN_DRIVER_GATE: generateAutoplanDriverGate, AUTOPLAN_DRIVER_FILES: generateAutoplanDriverFiles, AUTOPLAN_DRIVER_CODES: generateAutoplanDriverCodes, + AUTOPLAN_UNATTENDED_VOICE: generateAutoplanUnattendedVoice, SHIP_DRIVER_STOPS: generateShipDriverStops, SECTION, SECTION_INDEX, diff --git a/test/approval-classes.test.ts b/test/approval-classes.test.ts index 0b9b5e262b2..e86b957a489 100644 --- a/test/approval-classes.test.ts +++ b/test/approval-classes.test.ts @@ -237,11 +237,11 @@ describe('gstack-ship-receipt write enforces declared classes (APPROVAL_CITATION const other = run('docs-plan', 'Rewrite the quickstart in docs/quickstart.md with a shorter first step. Tests cover the links.', true); const ok = write(repo, `Approved by Garry 2026-10-16 via ${good.sha}\n`, ['--approval-run', other.out, '--approval-run', good.out]); expect(ok.status, ok.err).toBe(EXIT.ok); - expect(JSON.parse(ok.out).approval.classes[0]).toMatchObject({ class: 'data-repair', citation: 'verified', binding: 'paths', via: good.sha, evidence: expect.stringMatching(/^plan run-\d+ gate_rev=1 p1=b answered_by=human$/) }); + expect(JSON.parse(ok.out).approval.classes[0]).toMatchObject({ class: 'data-repair', citation: 'verified', binding: 'paths', via: good.sha, evidence: expect.stringMatching(/^plan run-[a-z]{6}-\d{14} gate_rev=1 p1=b answered_by=human$/) }); const notApproved = write(repo, `Approved by Garry 2026-10-16 via ${pending.sha}\n`, ['--approval-run', pending.out]); expect(notApproved.err).toMatch(/holds this plan but its gate is not APPROVED \(status gate_pending, p1 unanswered\).*\(APPROVAL_CITATION_MISSING\)$/m); const unrelated = write(repo, `Approved by Garry 2026-10-16 via ${other.sha}\n`, ['--approval-run', other.out]); - expect(unrelated.err).toMatch(/plan run-\d+ gate_rev=1 p1=b answered_by=human names neither/); + expect(unrelated.err).toMatch(/plan run-[a-z]{6}-\d{14} gate_rev=1 p1=b answered_by=human names neither/); const noRun = write(repo, `Approved by Garry 2026-10-16 via ${good.sha}\n`); expect(noRun.err).toMatch(/plan sha [0-9a-f]{8}: pass the autoplan run with --approval-run <dir>.*must attest "for data-repair@[0-9a-f]{12}"/); fs.appendFileSync(path.join(good.out, 'plan.md'), '\nsrc/commands/repair/later.ts\n'); diff --git a/test/autoplan-run-id.test.ts b/test/autoplan-run-id.test.ts new file mode 100644 index 00000000000..af7b6b18a1a --- /dev/null +++ b/test/autoplan-run-id.test.ts @@ -0,0 +1,39 @@ +/** + * Run ids from gstack-autoplan (GST-3015, from GBRA-108): two runs started in the + * same second whose run directories share a name ("autoplan") minted the same id, + * autoplan-20261117010353, and so shared one checkpoint collection. Each run id now + * carries a random part between the directory name and the 14-digit stamp, which + * stays last so the approval importer's stamp exemption still reads it. + */ +import { afterAll, afterEach, expect, setSystemTime, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { buildRow } from '../lib/approval-record'; +import { initRun } from '../lib/autoplan-run'; +import { ROOT, SMALL_PLAN } from './helpers/autoplan-run-fixture'; + +const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'autoplan-run-id-')); +afterAll(() => fs.rmSync(TMP, { recursive: true, force: true })); +afterEach(() => setSystemTime()); + +test('two runs started in the same second in same-named directories get different run ids', () => { + const plan = path.join(TMP, 'plan.md'); + fs.writeFileSync(plan, SMALL_PLAN); + setSystemTime(new Date('2026-11-17T01:03:53.250Z')); + const first = initRun({ plan, out: path.join(TMP, 'a', 'autoplan'), cwd: ROOT, full: true, sessionKind: 'unattended', outsideEnabled: false }); + const second = initRun({ plan, out: path.join(TMP, 'b', 'autoplan'), cwd: ROOT, full: true, sessionKind: 'unattended', outsideEnabled: false }); + expect(first.run).not.toBe(second.run); + for (const run of [first.run, second.run]) { + expect(run).toMatch(/^autoplan-[a-z]{6}-20261117010353$/); + const ask = `autoplan run ${run}`; + const row = buildRow({ ask, words: 'do it', by: 'agent:test', scope: 'this plan', source: `autoplan:${run}@gate_rev=1` }, 'main', new Date(), { id: run, at: { ask: ask.indexOf(run), source: 'autoplan:'.length } }); + expect('code' in row ? row.code : 'ok').toBe('ok'); + } +}); + +test('an explicit run id is kept as given', () => { + const plan = path.join(TMP, 'plan.md'); + fs.writeFileSync(plan, SMALL_PLAN); + expect(initRun({ plan, out: path.join(TMP, 'c', 'autoplan'), cwd: ROOT, full: true, sessionKind: 'unattended', outsideEnabled: false, runId: 'autoplan-fixed-20261117010353' }).run).toBe('autoplan-fixed-20261117010353'); +}); diff --git a/test/autoplan-unattended-voice.test.ts b/test/autoplan-unattended-voice.test.ts new file mode 100644 index 00000000000..24761ba2552 --- /dev/null +++ b/test/autoplan-unattended-voice.test.ts @@ -0,0 +1,50 @@ +/** + * GST-3015: in the GST-2944 smoke (gstack c5250ded), unattended /autoplan --full on Opus + * closed the outside voice --unavailable "needs the owner's consent" in 2 of 3 sessions + * although the config said codex_reviews: enabled, and in the third it ran the voice with + * run_in_background and ended its turn, which ends a headless session. The text an + * unattended driver reads (autoplan/DRIVER.md and the unattended profile) must say that an + * explicit enabled is the owner's standing consent, that the voice runs in the foreground + * under a bounded timeout, and that a failure binds outsideVoiceFailurePolicy()'s line. + */ +import { describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { outsideVoiceFailurePolicy } from '../scripts/resolvers/outside-voice'; +import { generateAutoplanUnattendedVoice } from '../scripts/resolvers/autoplan-driver'; +import type { TemplateContext } from '../scripts/resolvers/types'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), 'utf8'); +const flat = (s: string) => s.replace(/\s+/g, ' '); +const ctx = { host: 'claude', skillName: 'autoplan' } as unknown as TemplateContext; +const policy = outsideVoiceFailurePolicy(ctx, { timeoutMinutes: 9, onTimeout: 'missing-coverage', stderrOnEmpty: true, fallback: 'none', escape: 0 }); + +describe('autoplan/DRIVER.md, step 1 of the loop', () => { + const text = flat(read('autoplan/DRIVER.md')); + test('an explicit codex_reviews: enabled is the owner\'s standing consent; disabled stays with the runner and unset is unchanged', () => { + expect(text).toContain("A stored `codex_reviews: enabled` is the owner's standing consent to send each phase's review input to the outside model"); + expect(text).toContain('`OUTSIDE_CONSENT: given by codex_reviews=enabled`'); + expect(text).toContain("the preamble's unattended consent rule does not cover it, and you never close it `--unavailable` over consent or data leaving the machine"); + expect(text).toContain('`OUTSIDE: <phase> not_run reason=consent_missing`'); + expect(text).toContain('an unset `codex_reviews` keeps its existing handling'); + }); + test('the voice runs in the foreground in this turn with a bounded timeout, never in the background', () => { + expect(text).toContain('Run the voice in the foreground, inside this turn: `gstack-outside-voice run ... --timeout-ms 540000`'); + expect(text).toContain('Claude Code Bash `timeout: 600000`'); + expect(text).toContain('Never `run_in_background`, never a monitor, never end the turn to wait for it'); + }); + test('a failed or timed-out voice binds the documented outside-voice failure line and the run carries on', () => { + expect(text).toContain('`submit --voice outside --unavailable "<line>"` with the matching line and carry on in the same turn'); + for (const line of policy.split('\n')) expect(text).toContain(flat(line.replace(/^- /, ''))); + expect(policy).toContain('timed out after 9 minutes and was terminated; this pass produced NO findings.'); + }); +}); + +test('the unattended profile points at that step and states the two rules', () => { + expect(flat(read('autoplan/sections/unattended.md'))).toContain('the outside voice (none when lean) runs per DRIVER.md (enabled `codex_reviews` is consent; foreground only)'); +}); + +test('the resolver renders the same block the generated files carry', () => { + expect(flat(read('autoplan/DRIVER.md'))).toContain(flat(generateAutoplanUnattendedVoice(ctx))); +}); diff --git a/test/outside-consent.test.ts b/test/outside-consent.test.ts index 104323609bd..239a57fc33a 100644 --- a/test/outside-consent.test.ts +++ b/test/outside-consent.test.ts @@ -218,4 +218,15 @@ describe('API sends: gstack-outside-voice and the unattended runner', () => { const sent = await outsideVoice(f, path.join(out, 'ceo-outside-prompt.md'), path.join(f.dir, 'ceo-outside.md')); expect([sent.status, requests - before], sent.stderr).toEqual([0, 1]); }); + + test('unattended runner (GST-3015): an explicit codex_reviews: enabled is printed as the owner\'s standing consent beside the outside attempt; unset is not', () => { + const enabled = initRun(fixture('enabled')).r; + expect(enabled.status, enabled.stderr).toBe(0); + expect(enabled.stdout).toContain('voice=outside'); + expect(enabled.stdout).toMatch(/^OUTSIDE_CONSENT: given by codex_reviews=enabled \(the owner's standing consent .*\)$/m); + const unset = initRun(fixture('unset')).r; + expect(unset.status, unset.stderr).toBe(0); + expect(unset.stdout).toContain('voice=outside'); + expect(unset.stdout).not.toContain('OUTSIDE_CONSENT:'); + }); }); From 76535826f5d50c721f95820f300037a3efe833a9 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 04:08:56 +0800 Subject: [PATCH 49/62] /ship stops asking owners to clear base-side merge text and reviewers' confirmation prose (GST-2975, GST-2972) (#4458) /ship no longer stops for an owner's ruling when a base merge only changes base-side text, such as the preamble hash in regenerated SKILL.md files, and a reviewer's confirmation prose becomes a finding the lead can lower with a reason. Why: each of these cost a stopped /ship and an owner ruling on recent PRs (#4383, ghome#16, #4431), which keeps unattended shipping from finishing. Nothing to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- ...y-ship-base-side-and-confirmation-prose.md | 9 ++ docs/review-policy.md | 6 +- docs/ship-policy.md | 10 ++ lib/review-ledger.ts | 22 +-- lib/ship-patch.ts | 103 ++++++++++-- lib/ship-release.ts | 4 +- scripts/lib/windows-curation.ts | 4 + test/review-ledger-quiet-reply.test.ts | 90 +++++++++++ test/ship-base-side-masks.test.ts | 151 ++++++++++++++++++ 9 files changed, 376 insertions(+), 23 deletions(-) create mode 100644 changelog.d/capy-ship-base-side-and-confirmation-prose.md create mode 100644 test/review-ledger-quiet-reply.test.ts create mode 100644 test/ship-base-side-masks.test.ts diff --git a/changelog.d/capy-ship-base-side-and-confirmation-prose.md b/changelog.d/capy-ship-base-side-and-confirmation-prose.md new file mode 100644 index 00000000000..24dcbbb779a --- /dev/null +++ b/changelog.d/capy-ship-base-side-and-confirmation-prose.md @@ -0,0 +1,9 @@ +--- +important: blocker +--- +**/ship stops asking owners to clear two kinds of bookkeeping noise: base-side merge text and a reviewer's confirmation prose.** + +### Fixed +- **A base merge that only touched base-side text no longer stops `/ship` finish for an owner's grant.** After a main merge, finish counted two base-side differences as "behavior, tests or build inputs changed since review": the shared-preamble hash id in every regenerated skill file the branch also touched (#4383, 94 files), and an expected-value list where main's new entry was spliced next to the branch's own (ghome#16). The path comparison now reads both sides with the shared-preamble ids masked (a file whose only branch change is that id compares as unchanged), and a line that is the base's new line plus exactly the tokens the branch added to the reviewed line counts as base context, so it goes to the one scoped reader instead. A resolution that drops, invents or rewrites anything on the branch's own lines still stops as a behavior change. + +- **A reviewer's confirmation prose no longer becomes a Critical finding that only an owner can clear.** The collector read prose that named a file and line while confirming code, such as "a High or Critical challenge…", as an anchored Critical finding that judgment could not lower, even when the reply's own `REVIEW_VERDICT` said `blocking=0` or it said `NO FINDINGS`, so each one cost an owner ruling and a stopped `/ship` (twice on #4431). A file:line in prose, or a list item or the native voice's FIXABLE tag in a reply that says `NO FINDINGS`, no longer anchors a finding, so under a `blocking=0` verdict such a row is a summary candidate the lead can lower with a reason. It still blocks until then, so prose that names a real blocker ("no Critical issues except the token leak in log.ts:3") is never dropped. Structured findings (JSON, a lead severity label, a label heading, a numbered finding heading, a `Severity` or `Blocks: yes` field, or the native voice's FIXABLE/INVESTIGATE tag) still collect as anchored and still disagree with the verdict, and a reply whose verdict declares a blocker is read as before. diff --git a/docs/review-policy.md b/docs/review-policy.md index f38b993b115..4c1a321f8d5 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -1032,7 +1032,9 @@ ones, and the arm lost blockers. `bin/gstack-review-dispatch` closes both ends: reverted that. A reply that says `NO FINDINGS` keeps only its structured findings (GST-2122). Those are JSON objects (malformed JSON included), lead labels, label headings, numbered finding headings, `Severity` fields, `Blocks: yes`, the native voice's FIXABLE or INVESTIGATE tag, and anything naming a file:line, which still collect at their label. - Its other prose collects nothing. Outside such a reply prose collects as described above. A denial that a change + Only a field, lead label, heading or JSON anchors there: a file:line in prose, a list item or the FIXABLE or + INVESTIGATE tag may be the reader confirming code (GST-2972), so under a valid verdict that declares fewer blockers such a row is a summary candidate (below) and still + blocks until lead judgment lowers it with a reason. Its other prose collects nothing. Outside such a reply prose collects as described above. A denial that a change introduced a severity ("No fix introduced a CRITICAL defect") is a no-defect clause too, and a line led by a bold, unlabelled lead ("**1. Coverage:** …", "- **Callers:** …") is read for those clauses after its lead. Each prose finding's line also records the Severity and Blocks its own text states as `stated`, beside the collected label and never in its place; @@ -1068,7 +1070,7 @@ ones, and the arm lost blockers. `bin/gstack-review-dispatch` closes both ends: | Malformed line (bad count, bad `at=`, more locations than `<n>`, two different lines) | Findings as parsed. `declared=malformed`, with the reason in `why=`. | | `blocking=<n>` equals the blocking rows parsed | Findings as parsed. `agrees=yes`. | | `<n>` is more than parsed | Every parsed row stays, and collect adds CRITICAL rows (ids `<reader>#v1`, `#v2`…): one per `at=` location that no parsed blocking row names, then one more row for the declared blockers left over. The added rows count toward what blocks like any other. | - | `<n>` is less than parsed | Nothing is lowered automatically. Each blocking row with no list item, heading, field, lead label, JSON or file:line, and no `Blocks: yes` (a row that blocks only because a sentence uses the word CRITICAL or P0, or because the native voice's FIXABLE raises it) is marked `summary_candidate`, so lead judgment may lower it with a written reason, which `judge` records as `dismissed`. Anchored rows keep blocking. | + | `<n>` is less than parsed | Nothing is lowered automatically. Each blocking row with no list item, heading, field, lead label or JSON (a file:line in prose is not an anchor, nor, in a reply that says `NO FINDINGS`, is a list item or the FIXABLE or INVESTIGATE tag, GST-2972), and no `Blocks: yes` (a row that blocks only because a sentence uses the word CRITICAL or P0, or because the native voice's FIXABLE raises it) is marked `summary_candidate`, so lead judgment may lower it with a written reason, which `judge` records as `dismissed`. Anchored rows keep blocking. | A valid line never lowers a row by itself. FOUN-298's native "nothing blocks … all FIXABLE" sentence with `blocking=0` still collects as CRITICAL, as a summary candidate the lead lowers with a reason. An automatic relabel diff --git a/docs/ship-policy.md b/docs/ship-policy.md index c2692252d68..29eee8355be 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -2292,6 +2292,16 @@ whose plan reviews it in full (`lib/ship-patch.ts` `comparePath`). GST-1561 had sent it to the one scoped reader instead. A [mechanical retake](#mechanical-retake) does not apply here, since the branch retook nothing. +Two base-side differences are not the branch's own change (GST-2975). +`comparePath` reads every side with the shared-preamble hash id masked, so a +generated skill file whose only branch-side difference after a base merge is +that id compares as unchanged. A reviewed line that the base also replaced, +where the current line is the base's new line plus exactly the tokens the +branch added to the reviewed line (both sides appended an entry to one +expected-value list), is base context: it goes to the one scoped reader, never +through silently. A resolution that drops, invents or rewrites anything on the +branch's own lines stays a changed path. + **Rewritten history.** `write` records `head_tree` (the reviewed head's tree) and `product_patch_id` (its product patch against the base), and every carry rebinds both to the new head and keeps the earlier trees in `carry.trees`. diff --git a/lib/review-ledger.ts b/lib/review-ledger.ts index b2d4473043f..634a2a7cafd 100644 --- a/lib/review-ledger.ts +++ b/lib/review-ledger.ts @@ -188,11 +188,13 @@ export interface MergedLine { id: string; reader: string; label: string; stated? * A native FIXABLE finding that states `Blocks: no` and one Severity field collects at that field on every class (GST-1031 ruling A); * one with no Blocks: no, no Severity field or only a FIXABLE field stays CRITICAL. fixableRaises false (a code or docs review with no * risk, error, history or floor reason, GST-987) also drops FIXABLE's raise from label headings and leads. - * In a reply that says NO FINDINGS (GST-2122) a finding with no structure (JSON, lead label, label heading, numbered finding heading, - * Severity or Blocks: yes field, the native voice's FIXABLE or INVESTIGATE, or a file:line on it or on the line it runs on from) collects - * nothing; elsewhere it collects as above. A line led by a bold, unlabelled lead ("**1. Coverage:** …") is read for a closing summary after it. + * In a reply that says NO FINDINGS (GST-2122) a finding with no file:line in its prose or on the line it runs on from, and no structure + * (JSON, lead label, label heading, numbered finding heading, Severity or Blocks: yes field, the native voice's FIXABLE or INVESTIGATE), + * collects nothing. One with a file:line but no structure still collects, since it may name a real blocker. parseReply anchors a row + * there only by a field, lead label, heading or JSON: a file:line, a list item or the FIXABLE or INVESTIGATE tag does not (GST-2972: a + * reader confirming code names its lines). Elsewhere it collects as above. A line led by a bold, unlabelled lead ("**1. Coverage:** …") is read for a closing summary after it. */ -function parseLabelled(reader: string, output: string, fixableRaises: boolean): Array<{ label: string; raw: string; shaped: boolean; anchored: boolean }> { +function parseLabelled(reader: string, output: string, fixableRaises: boolean): Array<{ label: string; raw: string; shaped: boolean; fielded: boolean; anchored: boolean }> { type Finding = { label: string; raw: string; fields: Set<string>; list: boolean; lead?: string; fixable?: boolean; heading?: boolean; item?: boolean; nested?: boolean; closed?: boolean; section?: boolean; context?: string }; const out: Finding[] = []; let section: string | null = null; @@ -313,11 +315,11 @@ function parseLabelled(reader: string, output: string, fixableRaises: boolean): const unblocked = (f: Finding) => fixableRaises || role !== 'adversarial-native' || !(f.fixable || f.label.toUpperCase() === 'FIXABLE' || /(?<![A-Za-z0-9])FIXABLE(?![A-Za-z0-9])/.test(f.raw)) || statesNoBlocks(f.raw); const relaxed = fixableRaises && role === 'adversarial-native' ? parseLabelled(reader, output, false) : undefined; const statesSeverity = (raw: string) => { const ls = [...raw.matchAll(SEVERITY_FIELD)].flatMap(m => (m[1] ?? m[2]!).match(FIELD_LABELS)!); return ls.length === 1 && !!rank(ls[0]); }; - const shaped = (f: Finding, tag = true) => f.section || f.heading || [...f.raw.split(' | '), f.context ?? ''].some(t => t.startsWith('{') || LEAD_LABEL.test(t) || META.test(t) || !!t.match(STATED_SEVERITY) || BLOCKS_YES.test(t) - || LOCUS.test(t) || PATH_LOCUS.test(t) || (tag && role === 'adversarial-native' && /(?<![A-Za-z0-9])(?:FIXABLE|INVESTIGATE)(?![A-Za-z0-9])/i.test(t))); + const shaped = (f: Finding, tag = true, loci = true) => f.section || f.heading || [...f.raw.split(' | '), f.context ?? ''].some(t => t.startsWith('{') || LEAD_LABEL.test(t) || META.test(t) || !!t.match(STATED_SEVERITY) || BLOCKS_YES.test(t) + || (loci && (LOCUS.test(t) || PATH_LOCUS.test(t))) || (tag && role === 'adversarial-native' && /(?<![A-Za-z0-9])(?:FIXABLE|INVESTIGATE)(?![A-Za-z0-9])/i.test(t))); return out.map((f, i) => { const own = relaxed?.length === out.length && relaxed[i]!.raw === f.raw && statesNoBlocks(f.raw) && statesSeverity(f.raw) ? relaxed[i]!.label : undefined; - return { label: own ?? (unblocked(f) ? f.label : 'CRITICAL'), raw: f.raw, shaped: shaped(f), anchored: f.list || shaped(f, false) }; + return { label: own ?? (unblocked(f) ? f.label : 'CRITICAL'), raw: f.raw, shaped: shaped(f), fielded: shaped(f, false, false), anchored: f.list || shaped(f, false, false) }; }); } @@ -333,15 +335,15 @@ const blockingRow = (f: { label: string; raw: string }) => (rank(f.label) ?? 0) * A reply's findings, and with asked (its render carried the verdict ask, GST-2495) the check of its REVIEW_VERDICT line * (lib/review-verdict.ts, docs/review-policy.md#verdict-line). A well-formed verdict line never parses as a finding, and a valid * line lowers nothing by itself. Declared more than parsed adds CRITICAL rows, one per unmatched at= location and one for the - * rest; declared fewer marks each blocking row with no anchor (no list item, heading, field, lead label, JSON or file:line) and - * no Blocks: yes a summary candidate, whether a CRITICAL or P0 word or the native voice's FIXABLE raise made it block. It still + * rest; declared fewer marks each blocking row with no anchor (no list item, heading, field, lead label or JSON; a file:line in prose + * is not one, and in a NO FINDINGS reply a list item is not one either, GST-2972) and no Blocks: yes a summary candidate, whether a CRITICAL or P0 word or the native voice's FIXABLE raise made it block. It still * blocks until lead judgment lowers it with a reason. */ export function parseReply(reader: string, output: string, fixableRaises = true, asked = false): { findings: ReplyFinding[]; verdict?: VerdictCheck } { const verdict = asked ? parseVerdict(output) : undefined; const text = asked ? withoutVerdictLines(output) : output; const clean = text.split('\n').some(l => /^NO FINDINGS\.?$/.test(l.trim())); - const rows = parseLabelled(reader, text, fixableRaises).filter(r => r.shaped || !clean); + const rows = parseLabelled(reader, text, fixableRaises).filter(r => r.shaped || !clean).map(r => clean ? { ...r, anchored: r.fielded } : r); if (verdict?.state !== 'valid') { const findings = rows.map(({ label, raw }) => ({ label, raw })); return { findings, ...(verdict ? { verdict: { state: verdict.state, parsed: findings.filter(blockingRow).length, ...(verdict.state === 'malformed' ? { why: verdict.why } : {}) } } : {}) }; diff --git a/lib/ship-patch.ts b/lib/ship-patch.ts index 5155ad25976..47f8d383067 100644 --- a/lib/ship-patch.ts +++ b/lib/ship-patch.ts @@ -112,6 +112,45 @@ function sameSpot(r: ZeroHunk, c: ZeroHunk, map: (line: number) => number | null return c.oldStart >= low && c.oldStart <= map(above)! - 1; } +/** + * Ids a generator derives from base-side text (GST-2975, #4383): every generated skill file names the shared preamble's + * content hash, so a base edit to the shared preamble changes that id in every file the branch also regenerated. The + * comparison reads each side with these ids masked; nothing else in the file is masked. + */ +const GENERATED_IDS: ReadonlyArray<[RegExp, string]> = [[/(gstack shared preamble `)[0-9a-f]{12}(`)/g, '$1<id>$2'], [/^(# gstack shared preamble )[0-9a-f]{12}$/gm, '$1<id>']]; +const maskIds = (text: string) => GENERATED_IDS.reduce((t, [re, to]) => t.replace(re, to), text); + +/** + * The path's diffs between two of the sides, read with GENERATED_IDS masked when any side's text carries one (a scratch + * object directory holds the masked blobs, so the repository gains no object); null masking when a side lacks the path, + * is binary, or names no id, and the diffs are then the plain ones. + */ +function sideDiffs(repoRoot: string, s: PatchSides, rel: string): { diff: (from: string, to: string, context: number) => string | null; done: () => void } { + const plain = { diff: (from: string, to: string, context: number) => pathDiff(repoRoot, from, to, rel, context), done: () => {} }; + const refs = [...new Set([s.reviewedBase, s.reviewed, s.currentBase, s.current])]; + const texts = refs.map(ref => spawnSync('git', ['cat-file', 'blob', `${ref}:${rel}`], { cwd: repoRoot, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 })); + if (texts.some(t => t.status !== 0 || t.stdout.includes(0))) return plain; + const raw = texts.map(t => t.stdout.toString('utf8')); + if (!raw.some(t => maskIds(t) !== t)) return plain; + const objects = git(repoRoot, ['rev-parse', '--git-path', 'objects'])?.trim(); + if (!objects) return plain; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ship-patch-mask-')); + const env = { ...process.env, GIT_OBJECT_DIRECTORY: dir, GIT_ALTERNATE_OBJECT_DIRECTORIES: path.resolve(repoRoot, objects) }; + const run = (args: string[], input?: string) => spawnSync('git', ['-c', 'core.quotepath=off', ...args], { cwd: repoRoot, env, encoding: 'utf8', input, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 }); + const blobs = new Map(refs.map((ref, i) => [ref, run(['hash-object', '-w', '--stdin'], maskIds(raw[i]!)).stdout.trim()])); + const done = () => fs.rmSync(dir, { recursive: true, force: true }); + if ([...blobs.values()].some(b => !/^[0-9a-f]{40,64}$/.test(b))) { done(); return plain; } + return { + diff: (from, to, context) => { + const [a, b] = [blobs.get(from)!, blobs.get(to)!]; + const r = run(['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--binary', '--full-index', `-U${context}`, a, b]); + if (r.status !== 0) return null; + return r.stdout.split('\n').map(l => /^(diff --git|--- |\+\+\+ )/.test(l) ? l.replaceAll(`a/${a}`, `a/${rel}`).replaceAll(`b/${b}`, `b/${rel}`) : l).join('\n'); + }, + done, + }; +} + /** The verdict for one path the branch touches on either side (module header). */ export function comparePath(repoRoot: string, s: PatchSides, rel: string): PathVerdict { const r3 = pathDiff(repoRoot, s.reviewedBase, s.reviewed, rel, 3); @@ -119,16 +158,60 @@ export function comparePath(repoRoot: string, s: PatchSides, rel: string): PathV if (r3 === null || c3 === null || (!r3.trim() && !c3.trim())) return 'changed'; const modes = (d: string) => d.split('\n').filter(l => /^(old mode|new mode|new file mode|deleted file mode) /.test(l)).join('\n'); if (modes(r3) !== modes(c3)) return 'changed'; - const ids = [patchId(repoRoot, r3), patchId(repoRoot, c3)]; - if (ids[0] === null || ids[1] === null) return 'changed'; - const r0 = zeroHunks(pathDiff(repoRoot, s.reviewedBase, s.reviewed, rel, 0) ?? ''); - const c0 = zeroHunks(pathDiff(repoRoot, s.currentBase, s.current, rel, 0) ?? ''); - if (ids[0] === ids[1] && r0 === null) return 'same'; - const b0 = zeroHunks(pathDiff(repoRoot, s.reviewedBase, s.currentBase, rel, 0) ?? ''); - if (!r0?.length || !c0 || !b0 || r0.length !== c0.length) return 'changed'; - const map = mapper(b0); - if (!r0.every((h, i) => h.body === c0[i]!.body && sameSpot(h, c0[i]!, map))) return 'changed'; - return ids[0] === ids[1] ? 'same' : 'context'; + const sides = sideDiffs(repoRoot, s, rel); + try { + const [mr3, mc3] = [sides.diff(s.reviewedBase, s.reviewed, 3), sides.diff(s.currentBase, s.current, 3)]; + if (mr3 === null || mc3 === null) return 'changed'; + if (!mr3.trim() && !mc3.trim()) return 'same'; + const ids = [patchId(repoRoot, mr3), patchId(repoRoot, mc3)]; + if (ids[0] === null || ids[1] === null) return 'changed'; + const r0 = zeroHunks(sides.diff(s.reviewedBase, s.reviewed, 0) ?? ''); + const c0 = zeroHunks(sides.diff(s.currentBase, s.current, 0) ?? ''); + if (ids[0] === ids[1] && r0 === null) return 'same'; + const b0 = zeroHunks(sides.diff(s.reviewedBase, s.currentBase, 0) ?? ''); + if (!r0?.length || !c0 || !b0 || r0.length !== c0.length) return 'changed'; + const map = mapper(b0); + let spliced = false; + for (const [i, h] of r0.entries()) { + if (h.body === c0[i]!.body && sameSpot(h, c0[i]!, map)) continue; + if (!splicedHunk(h, c0[i]!, b0)) return 'changed'; + spliced = true; + } + return ids[0] === ids[1] && !spliced ? 'same' : 'context'; + } finally { + sides.done(); + } +} + +const TOKEN = /\s+|[\w$.]+|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`|[^]/g; +/** The tokens `to` adds to `from` when `from` is `to` with tokens left out (a greedy embedding), else null. */ +function insertedTokens(from: string, to: string): string[] | null { + const [f, t] = [from.match(TOKEN) ?? [], to.match(TOKEN) ?? []]; + const added: string[] = []; + let k = 0; + for (const tok of t) { if (k < f.length && tok === f[k]) k++; else added.push(tok); } + return k === f.length ? added : null; +} + +/** + * A hunk the base merge spliced (GST-2975, ghome#16): the base replaced exactly the lines the branch's hunk replaces, line + * for line, and each current line is the base's new line with the very tokens the branch added to the reviewed line, as + * when both sides appended an entry to one expected-value list. The branch removes nothing on those lines, so its own change + * is the reviewed one and the merge only kept both; the caller still routes the path to a scoped reader (context), never + * through silently. + */ +function splicedHunk(r: ZeroHunk, c: ZeroHunk, base: ZeroHunk[]): boolean { + if (!r.oldCount || r.oldCount !== r.newCount || c.oldCount !== r.oldCount || c.newCount !== r.newCount) return false; + const b = base.find(h => h.oldStart === r.oldStart && h.oldCount === r.oldCount && h.newCount === r.oldCount && h.newStart === c.oldStart); + if (!b) return false; + const side = (h: ZeroHunk, sign: string) => h.body.split('\n').filter(l => l.startsWith(sign)).map(l => l.slice(1)); + const [rm, ra, cm, ca, bm, ba] = [side(r, '-'), side(r, '+'), side(c, '-'), side(c, '+'), side(b, '-'), side(b, '+')]; + if (rm.join('\n') !== bm.join('\n') || cm.join('\n') !== ba.join('\n')) return false; + return rm.every((was, k) => { + const mine = insertedTokens(was, ra[k]!); + const kept = insertedTokens(cm[k]!, ca[k]!); + return !!mine?.length && !!kept && mine.length === kept.length && mine.every((x, j) => x === kept[j]); + }); } /** diff --git a/lib/ship-release.ts b/lib/ship-release.ts index e0711fe1af5..7f36f8b3448 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -397,13 +397,15 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review const by: Routed = { behavior: [], docs: [], metadata: [], tests: [], base: [], context: [], bounded: [], mechanical: [], accepted: [], fix_checked: [], sidecar: [] }; const isMetadata = (p: string) => parent && shipped.has(p) ? opts.baseRelease!.includes(p) || harnessRepin(cwd, sides!.currentBase, now, p) : release.includes(p) || harnessRepin(cwd, reviewed, now, p); const onlyShipped = new Set(parent ? [...shipped].filter(p => !changedSet.has(p)) : []); + const baseSide = new Set<string>(); for (const p of [...changedSet, ...onlyShipped].sort()) { const verdict = sides ? (!touched.has(p) || (parent && !shipped.has(p) && baseHolds(cwd, sides, p)) ? 'same' : comparePath(cwd, sides, p)) : 'changed'; + if (verdict === 'context') baseSide.add(p); const metadata = isMetadata(p); by[verdict === 'same' ? 'base' : metadata ? 'metadata' : sides && isTestCode(p, opts.testCode) ? 'tests' : classifyPath(p, cwd) === 'docs' && !matchesAny(opts.bookkeeping, p) ? 'docs' : verdict === 'context' ? 'context' : 'behavior'].push(p); } const shippedTests = by.tests.filter(p => onlyShipped.has(p)); - const gated = new Set([...(gateEditedPaths(cwd, reviewed, now, by.tests.filter(p => !onlyShipped.has(p))) ?? by.tests), ...(gateEditedPaths(cwd, sides?.currentBase ?? reviewed, now, shippedTests) ?? shippedTests)]); + const gated = new Set([...(gateEditedPaths(cwd, reviewed, now, by.tests.filter(p => !onlyShipped.has(p) && !baseSide.has(p))) ?? by.tests), ...(gateEditedPaths(cwd, sides?.currentBase ?? reviewed, now, shippedTests) ?? shippedTests)]); by.behavior.push(...by.tests.filter(p => gated.has(p))); by.tests = by.tests.filter(p => !gated.has(p)); const mech = mechanicalPaths(cwd, { sides, base, candidates: parent ? [] : [...by.behavior, ...by.tests, ...by.docs], declared: opts.mechanical }); diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index 9258d0e38fc..e778bb67f5f 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -444,6 +444,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'test/ship-receipt-carry-mixed.test.ts', reason: 'drives bin/gstack-ship-receipt, gstack-ship-release, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-mechanical-retake.test.ts; windows-latest fails every case at the first bin spawn (windows-scoped-shard, run 42167292675)', }, + { + file: 'test/ship-base-side-masks.test.ts', + reason: 'drives bin/gstack-ship-release, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-rereview-triggers.test.ts; windows-latest fails every case at the first bin spawn (windows-scoped-shard, run 41950236362)', + }, { file: 'test/ship-uid-sidecar.test.ts', reason: 'drives bin/gstack-ship-release, gstack-ship-receipt, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-mechanical-retake.test.ts; windows-latest fails every case at the first bin spawn (windows-scoped-shard, run 42205201312)', diff --git a/test/review-ledger-quiet-reply.test.ts b/test/review-ledger-quiet-reply.test.ts new file mode 100644 index 00000000000..73241013637 --- /dev/null +++ b/test/review-ledger-quiet-reply.test.ts @@ -0,0 +1,90 @@ +/** + * GST-2972 (#4431, twice): the collector minted Critical findings from a reader's confirmation prose. A fix-check whose own + * REVIEW_VERDICT said blocking=0 (p1fc at 00155f5) wrote "a High or Critical challenge" in a paragraph naming + * autoplan-revise.ts:103, and a clean one (blocking=0 and NO FINDINGS, p3fc at b1b3c3c) had a nested bullet under a line naming + * lib/autoplan-gate.ts:197. The file:line made each an anchored Critical that lead judgment could not lower, so each cost an owner + * ruling. Captain ruling D1 (2026-11-14, test/review-verdict.test.ts) holds: a verdict line lowers nothing by itself, and neither + * does NO FINDINGS (Captain, 2026-11-17: prose that names a real blocker must not vanish). So the prose rows still collect and block, + * but a file:line in prose, or a list item in a NO FINDINGS reply, no longer anchors them: under a valid verdict that declares fewer + * blockers each is a summary candidate the lead may lower with a reason, instead of an owner ruling. + */ +import { describe, expect, test } from 'bun:test'; +import { parseReply } from '../lib/review-ledger'; + +// The two replies as the readers returned them (GSTA-573 subagents 3.3 and 3.9). +const P1FC = "REVIEWED_TREE: 00155f52976c3d27c8c874c16ba0f16b401ed97f /workspace/gstack\nREVIEW_VERDICT: blocking=0\n\n{\"severity\":\"INFORMATIONAL\",\"path\":\"lib/autoplan-confirm.ts\",\"line\":125,\"summary\":\"Fix 1 still lets an ordinary finding close an unrelated open challenge when that finding is marked settled_by. annotateConfirm (line 163) sets row.correlates to every earlier row whose title scores at least 0.6, but it sets settled_by from only one of them (`prior`). Take a later-round Low row whose title matches both earlier challenge A, which was answered at the gate, and earlier challenge B, which is still open. That row gets settled_by A's decision and correlates [A, B], so openEarlier counts B as covered, and buildGate (line 221) never carries B to the owner. Fix 1 was meant to stop this kind of silent close. Fix: count a settled row's correlates only for the ids that settledIds actually contains.\"}\n\nFixes 2 and 3 look sound. Fix 2 now sends a quoted-plan user_challenge that has no valid owner_quote to propose(), whatever its severity. The one behaviour change is for a High or Critical challenge like that: it used to become a `|finding` item with a \"carry into the build as a blocking task\" option, and now it becomes a proposal. That is the same treatment challenges that carry `changes` already get, the twin bundling is unchanged, and the rerun agentDecision path isn't reachable from the new branch. Fix 3 only appends a fourth origin segment. Every origin parser I found (settledIds, decisionSeverity in autoplan-revise.ts:103, and autoplan-shadow.ts:198) reads segments [0] and [1], so none of them break. The day-one titles it hashes are stable (the `reason` strings in autoplan-owner-text.ts are fixed text), so a change only asks again when the list or a row's wording actually changed. A gate answered before this commit gets re-asked once after the upgrade, which errs on the side of asking again. The commit only adds tests and doesn't weaken any existing one. I reran `bun test test/autoplan-day-one-gate.test.ts` at this tree: 21 pass, 0 fail.\n"; +const P3FC = "REVIEWED_TREE: b1b3c3cca68f1087cbca0d4f24c94e168daeb920 /workspace/gstack\nREVIEW_VERDICT: blocking=0\n\nNO FINDINGS\n\nEvery statement in 9c1e407 and ed1dd85 matches the code at HEAD ed1dd85. I checked each one against its source:\n\n- **Result-format contract (docs/unattended.md).** It matches `RESULT_FORMAT` in lib/autoplan-prompts.ts:126 and the parser. `CHANGES` in lib/autoplan-reconcile.ts:36 accepts scope, cost, direction, packaging and ordering, and the parser takes `owner_quote` (positive integer) and `resolves`.\n- **Gate step.** It matches `buildGate` (lib/autoplan-gate.ts:197-288) and lib/autoplan-gate-items.ts:\n - With an Owner's words section, a `changes` or `user_challenge` row that names no quote becomes a `proposal` uc approval item. Its `b` keeps the draft, and that becomes a blocking build task when any row is Critical or High (`blockingProposal`, `FINDING_ORIGIN`).\n - Without that section, `confirm_direction` is a d/auto item, added only when a one-voice challenge1 was kept.\n - Earlier open challenges come back through `openEarlier`, and only a later `resolves` row or an owner's answer closes them.\n - `day_one` items (missing page when `scope.ui` is set, plus each assumed row) and `cut` items (a cut that drops a day-one row or quote) are uc approvals. The other cuts form one `cuts` d/auto item.\n- **Owner-only replies (troubleshooting `OWNER_REPLY_REQUIRED`, unattended step 4).** The guard at lib/autoplan-gate.ts:455 refuses agent words on any non-p1 `approval` item. That covers proposal, day_one and cut, and correctly leaves out the auto items `cuts` and `confirm_direction`.\n- **Redaction (`ARTIFACT_OWNER_WORDS` and the public-copy text).** lib/autoplan-owner-words.ts:277-278 reads quotes from plan-active, plan-source*, plan-at-gate.r*, and plan-file.* files, so a quote a later revision removed stays redacted.\n- **Shadow item_class list.** It equals `ItemClass` in lib/gate-list.ts:51-52.\n- **Brief order, owner brief.** lib/owner-brief.ts:89-96 renders URGENT, then `renderDayOne`, then the summary.\n- **Brief order, captain.md.** lib/captain-brief.ts:146 renders URGENT, the header, then Day one / What it won't do yet / \"Your words this plan follows\" (each only when present), then ELI5 and the sections. So captain.md's new order still tells agents the right thing.\n- **Changelog.** The High/Critical decline sentence matches `proposalItem`'s `b` text and `settledIds` (a finding-origin decision settles only on `a`). The removed-quote redaction sentence matches the redaction code above. Dropping the tracker code passes `changelog-fragments.test.ts`.\n\n**Tests.** The fix list's 10 files (730 pass) didn't cover the files that read these docs or the fragment, so I also ran changelog-fragments, capy-skill-wrapper, captain-brief, host-conformance and docs-only at this tree: 155 pass, 0 fail.\n\nThe fixes change no code symbols, so there are no callers to break.\n"; + +const blocking = (r: ReturnType<typeof parseReply>) => r.findings.filter(f => /^(CRITICAL|P0|P1|HIGH)$/i.test(f.label)); + +describe('confirmation prose in a reply that says nothing blocks (GST-2972)', () => { + // Value: protects=the two #4431 replies: each prose Critical is a summary candidate the lead may lower, and p1fc keeps its JSON + // finding; fails_when=either prose row is an anchored Critical (the owner-ruling stop), or the JSON line is lost; + // seam=parseReply as collect calls it (verdict asked); no_claim=what the lead decides about the candidate + test('p3fc and p1fc prose rows are summary candidates, not anchored Criticals; p1fc keeps its JSON finding', () => { + const p3 = parseReply('fix-check', P3FC, true, true); + expect(p3.findings.map(f => [f.label, f.summary ?? false])).toEqual([['Critical', true]]); + expect(p3.findings[0]!.raw).toStartWith("- With an Owner's words section"); + expect(p3.verdict).toMatchObject({ state: 'valid', declared: 0, parsed: 1, agrees: false }); + const p1 = parseReply('fix-check', P1FC, true, true); + expect(p1.findings.map(f => [f.label, f.summary ?? false])).toEqual([['INFORMATIONAL', false], ['Critical', true]]); + expect(p1.findings[0]!.raw).toContain('"path":"lib/autoplan-confirm.ts"'); + expect(p1.findings[1]!.raw).toStartWith('Fixes 2 and 3 look sound.'); + expect(p1.verdict).toMatchObject({ state: 'valid', declared: 0, parsed: 1, agrees: false }); + }); + + // Value: protects=negative controls: a structured blocker in a blocking=0 or NO FINDINGS reply still collects as CRITICAL, is no summary candidate, and the + // verdict disagrees, and the same prose under a verdict that declares a blocker still collects; fails_when=the quiet rule drops a + // lead-labelled, Severity-field, Blocks: yes or JSON blocker, or prose in a reply that declares one; seam=parseReply + test('a structured blocker still collects in a quiet reply, and prose still collects when the verdict declares a blocker', () => { + const head = 'REVIEWED_TREE: ' + 'a'.repeat(40) + ' /workspace/gstack\nREVIEW_VERDICT: blocking=0\n\n'; + for (const line of [ + '**CRITICAL** lib/store.ts:40: the migration drops the rows it was meant to copy.', + 'lib/store.ts:40: the migration drops the rows it was meant to copy.\nSeverity: Critical', + 'lib/store.ts:40: the migration drops the rows it was meant to copy. Blocks: yes', + '{"severity":"CRITICAL","path":"lib/store.ts","line":40,"summary":"the migration drops the rows it was meant to copy"}', + ]) { + for (const tail of ['', '\nNO FINDINGS\n']) { + const r = parseReply('fix-check', head + line + '\n' + tail, true, true); + expect(blocking(r).length).toBe(1); + expect(blocking(r)[0]!.summary).toBeUndefined(); + expect(r.verdict).toMatchObject({ declared: 0, parsed: 1, agrees: false }); + } + } + const declared = parseReply('fix-check', P1FC.replace('REVIEW_VERDICT: blocking=0', 'REVIEW_VERDICT: blocking=1 at=lib/autoplan-gate.ts:257'), true, true); + expect(blocking(declared).length).toBeGreaterThanOrEqual(1); + expect(blocking(declared).every(f => !f.summary)).toBe(true); + const unasked = parseReply('fix-check', P1FC, true, false); + expect(blocking(unasked).map(f => f.summary ?? false)).toEqual([false]); + }); + + // Value: protects=a NO FINDINGS reply whose prose names a real blocker still blocks (Captain, 2026-11-17; the GPT-6.1 Sol trail read + // on #4449): under blocking=0 it is a summary candidate the lead must lower with a reason, and with no verdict asked it is an + // ordinary CRITICAL; negative control: NO FINDINGS prose with no file:line still collects nothing (GST-2122); + // fails_when=the token-leak line vanishes or the verdict agrees, or unlocated prose starts collecting; seam=parseReply + test('a NO FINDINGS reply whose prose names a token leak still blocks', () => { + const leak = 'No CRITICAL issues except the token leak in log.ts:3.'; + const head = 'REVIEWED_TREE: ' + 'a'.repeat(40) + ' /workspace/gstack\nREVIEW_VERDICT: blocking=0\n\nNO FINDINGS\n\n'; + const asked = parseReply('fix-check', head + leak + '\n', true, true); + expect(blocking(asked).map(f => [f.raw, f.summary ?? false])).toEqual([[leak, true]]); + expect(asked.verdict).toMatchObject({ state: 'valid', declared: 0, parsed: 1, agrees: false }); + const unasked = parseReply('fix-check', 'NO FINDINGS\n\n' + leak + '\n', true, false); + expect(blocking(unasked).map(f => [f.raw, f.summary ?? false])).toEqual([[leak, false]]); + const unlocated = parseReply('fix-check', head + 'I read every changed file and the critical paths look right.\n', true, true); + expect(unlocated.findings).toEqual([]); + expect(unlocated.verdict).toMatchObject({ state: 'valid', declared: 0, parsed: 0, agrees: true }); + }); + + // Value: protects=the native voice's FIXABLE tag does not anchor a prose row in a NO FINDINGS reply (#4449's read-only final review), + // so under blocking=0 it stays a summary candidate as on main; negative control: with no verdict asked it is a plain CRITICAL; + // fails_when=the FIXABLE-only row is anchored (an owner stop) or stops blocking; seam=parseReply with the native voice + test('a FIXABLE-only prose row in a NO FINDINGS reply is a summary candidate, not an anchored Critical', () => { + const row = "The cache key ignores the user id, so one user can read another user's cached page. FIXABLE: key on the user id too."; + const head = 'REVIEWED_TREE: ' + 'a'.repeat(40) + ' /workspace/gstack\nREVIEW_VERDICT: blocking=0\n\nNO FINDINGS\n\n'; + const asked = parseReply('adversarial-native', head + row + '\n', true, true); + expect(blocking(asked).map(f => [f.label, f.summary ?? false])).toEqual([['CRITICAL', true]]); + expect(asked.verdict).toMatchObject({ state: 'valid', declared: 0, parsed: 1, agrees: false }); + const unasked = parseReply('adversarial-native', 'NO FINDINGS\n\n' + row + '\n', true, false); + expect(blocking(unasked).map(f => [f.label, f.summary ?? false])).toEqual([['CRITICAL', false]]); + }); +}); diff --git a/test/ship-base-side-masks.test.ts b/test/ship-base-side-masks.test.ts new file mode 100644 index 00000000000..fb3f0756744 --- /dev/null +++ b/test/ship-base-side-masks.test.ts @@ -0,0 +1,151 @@ +/** + * GST-2975: /ship finish stopped with "behavior, tests or build inputs changed since review" after a base merge whose only + * effect on the branch's files was base-side: the shared-preamble hash id in regenerated skill files (#4383, 94 files), and + * main's new entry spliced into an expected-value list the branch also appended to (ghome#16). Both now compare with the + * base-side difference masked; the spliced list goes to the scoped reader, and a real change to the branch's own lines + * still stops. + */ +import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { comparePath } from '../lib/ship-patch'; +import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; + +setDefaultTimeout(90_000); +const BIN = path.dirname(RELEASE); +const LANE = 'tests=printf " 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [5.00ms]\\n"'; +const ships: ShipFx[] = []; +afterEach(() => { while (ships.length) ships.pop()!.cleanup(); }); +const fx = (...a: Parameters<typeof shipFixture>) => { const f = shipFixture(...a); ships.push(f); return f; }; +const wtree = (f: ShipFx) => f.run(path.join(BIN, 'gstack-wtree'), []).stdout.trim(); +const mergeBase = (f: ShipFx) => f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(); +const snapshot = (f: ShipFx) => { + const out = path.join(f.root, 'post.json'); + expect(f.run(path.join(BIN, 'gstack-docs-candidate'), ['snapshot', '--out', out, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']).status).toBe(0); + return out; +}; +const mergeMain = (f: ShipFx, resolved: Record<string, string>) => { + f.git('fetch', '-q', 'origin'); + if (f.git('merge', '-q', '--no-edit', 'origin/main').status !== 0) { f.write(resolved); f.commit('merge main'); } +}; +const finish = (f: ShipFx, reviewed: string, post: string, reviewedBase: string) => + f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--lane', LANE, '--reviewed-base', reviewedBase]); +const sidesOf = (f: ShipFx, reviewed: string, reviewedBase: string) => + ({ reviewedBase, reviewed, currentBase: mergeBase(f), current: f.git('rev-parse', 'HEAD').stdout.trim() }); + +/** A generated skill file as gen-skill-docs writes it: the shared-preamble id twice, then rules the branch edits. */ +const SKILL = 'ship/SKILL.md'; +const PREAMBLE = 'ship/sections/preamble.md'; +const skill = (id: string, rules: string[], tail = 'Run the review.') => + ['---', 'name: ship', '---', '', `This skill follows gstack shared preamble \`${id}\` (AskUserQuestion format, voice, writing). Read it once.`, '', '## Rules', '', ...rules.map(r => `- ${r}`), '', '## Steps', '', tail, ''].join('\n'); +const preamble = (id: string, rules: string[]) => [`# gstack shared preamble ${id}`, '', ...rules, ''].join('\n'); +const MAIN_RULES = ['Ask one question at a time.', 'Write plain English.']; +const BRANCH_RULES = [...MAIN_RULES, 'Never print secrets.']; +const MAIN_PREAMBLE = ['Voice: direct.', 'Completeness: finish the task.']; + +/** #4383 (dfab3a0): reviewed at the branch's regeneration, then main changed the shared preamble, so every id moved. */ +function preambleMerge(resolvedRules = BRANCH_RULES) { + const f = fx({ [SKILL]: skill('aaaaaaaaaaaa', MAIN_RULES), [PREAMBLE]: preamble('aaaaaaaaaaaa', MAIN_PREAMBLE) }, + { [SKILL]: skill('bbbbbbbbbbbb', BRANCH_RULES), [PREAMBLE]: preamble('bbbbbbbbbbbb', [...MAIN_PREAMBLE, 'Never print secrets.']) }); + const reviewed = wtree(f); + const reviewedBase = mergeBase(f); + const post = snapshot(f); + f.advanceBase({ [SKILL]: skill('cccccccccccc', MAIN_RULES, 'Run the review, then the docs audit.'), [PREAMBLE]: preamble('cccccccccccc', ['Voice: direct and brief.', 'Completeness: finish the task.']) }); + mergeMain(f, { [SKILL]: skill('dddddddddddd', resolvedRules, 'Run the review, then the docs audit.'), [PREAMBLE]: preamble('dddddddddddd', ['Voice: direct and brief.', 'Completeness: finish the task.', 'Never print secrets.']) }); + return { f, reviewed, reviewedBase, post }; +} + +describe('regenerated skill files whose only base-side change is the shared-preamble id (#4383)', () => { + // Value: protects=#4383: a main merge that only moved the shared-preamble hash id in the branch's regenerated files is a + // base merge, not a behavior change; fails_when=finish stops with behavior=N for the id lines; seam=comparePath via finish; + // no_claim=a hash id outside the two generated forms + test('the id lines are masked: the paths route as base or context and finish never stops for a behavior change', () => { + const { f, reviewed, reviewedBase, post } = preambleMerge(); + const sides = sidesOf(f, reviewed, reviewedBase); + expect(comparePath(f.work, sides, SKILL)).toBe('same'); + expect(comparePath(f.work, sides, PREAMBLE)).toBe('context'); + const r = finish(f, reviewed, post, reviewedBase); + expect(lineOf(r.stdout, 'ROUTE')).toMatch(/ behavior=0 .* base=1 context=1$/); + expect(r.stdout).not.toContain('behavior, tests or build inputs changed since review'); + expect(r.stdout).toContain(`STOP: base context moved next to the reviewed hunks in ${PREAMBLE}`); + }); + + // Value: protects=#4383's own files: a branch that edits the shared preamble changes every generated file by its id alone, and + // a main merge that moves the id again compares as same; fails_when=the empty masked diffs read as changed and finish stops; + // seam=comparePath; no_claim=the preamble file itself, which keeps its own comparison + test('a regenerated file whose only branch change is the id compares as same, and a rule changed in the merge still stops', () => { + const idOnly = (rules: string[]) => { + const f = fx({ [SKILL]: skill('aaaaaaaaaaaa', MAIN_RULES) }, { [SKILL]: skill('bbbbbbbbbbbb', MAIN_RULES) }); + const reviewed = wtree(f); + const reviewedBase = mergeBase(f); + f.advanceBase({ [SKILL]: skill('cccccccccccc', MAIN_RULES) }); + mergeMain(f, { [SKILL]: skill('dddddddddddd', rules) }); + return comparePath(f.work, sidesOf(f, reviewed, reviewedBase), SKILL); + }; + expect(idOnly(MAIN_RULES)).toBe('same'); + expect(idOnly([...MAIN_RULES, 'Print secrets when asked.'])).toBe('changed'); + }); + + // Value: protects=negative control: masking the id never hides the branch's own lines; fails_when=a resolution that drops a + // rule the branch added, or edits one, routes as base or context; seam=comparePath via finish; no_claim=none + test('a resolution that changes the branch\'s own rule still stops as a behavior change', () => { + for (const rules of [MAIN_RULES, [...MAIN_RULES, 'Print secrets when asked.']]) { + const { f, reviewed, reviewedBase, post } = preambleMerge(rules); + expect(comparePath(f.work, sidesOf(f, reviewed, reviewedBase), SKILL)).toBe('changed'); + const r = finish(f, reviewed, post, reviewedBase); + expect(r.status).toBe(3); + expect(r.stdout).toContain('behavior, tests or build inputs changed since review'); + expect(r.stdout).toContain(SKILL); + } + }); +}); + +const LIST = 'test/methods.test.ts'; +const methods = (entries: string[], check = 'expect(METHODS).toEqual(EXPECTED)') => + ["import { expect, test } from 'bun:test';", "import { METHODS } from '../src/methods';", '', `const EXPECTED = [${entries.map(e => `"${e}"`).join(', ')}];`, '', `test('the plugin registers every method', () => ${check});`, ''].join('\n'); +const BASE_METHODS = ['ghome.prep', 'ghome.lookup']; + +/** ghome#16 (feb89ba): the branch appended ghome.brief, main appended ghome.talk.target, and the merge kept both. */ +function listMerge(resolved: string) { + const f = fx({ [LIST]: methods(BASE_METHODS) }, { [LIST]: methods([...BASE_METHODS, 'ghome.brief']) }); + const reviewed = wtree(f); + const reviewedBase = mergeBase(f); + const post = snapshot(f); + f.advanceBase({ [LIST]: methods([...BASE_METHODS, 'ghome.talk.target']) }); + mergeMain(f, { [LIST]: resolved }); + return { f, reviewed, reviewedBase, post }; +} + +describe('an expected-value list the base merge spliced (ghome#16)', () => { + // Value: protects=ghome#16: a resolved line that is main's line plus exactly the entry the branch added goes to the scoped + // reader of its test hunks, not to an owner grant; fails_when=gateEditedPaths sends it to behavior (the owner-grant stop) or + // it passes with no reader; seam=comparePath + finish route; no_claim=the scoped reader's verdict + test('the union is context: finish stops for the scoped reader, never for a behavior change', () => { + const { f, reviewed, reviewedBase, post } = listMerge(methods([...BASE_METHODS, 'ghome.talk.target', 'ghome.brief'])); + expect(comparePath(f.work, sidesOf(f, reviewed, reviewedBase), LIST)).toBe('context'); + const r = finish(f, reviewed, post, reviewedBase); + expect(lineOf(r.stdout, 'ROUTE')).toMatch(/ behavior=0 .*tests=1 /); + expect(r.stdout).not.toContain('behavior, tests or build inputs changed since review'); + expect(r.status).toBe(3); + const packet = /STOP: test code changed since review in test\/methods\.test\.ts: .* reads (\S+),/.exec(r.stdout)?.[1]; + expect(packet).toBeDefined(); + expect(fs.readFileSync(packet!, 'utf8')).toContain('"ghome.talk.target", "ghome.brief"'); + }); + + // Value: protects=negative control: a resolution that is not main's line plus the branch's entry is the branch's own change; + // one that invents an entry or changes the check still stops for the full loop; fails_when=any of them is context, or an + // invented entry or a weakened check routes to the scoped reader; seam=comparePath + gateEditedPaths via finish; + // no_claim=a same-count literal swap, which gateEditedPaths already sends to the scoped reader (literalOnly) + test('a resolution that drops, invents or changes anything is changed, and an invented entry or a new check still stops', () => { + const changed = (resolved: string) => { const x = listMerge(resolved); expect(comparePath(x.f.work, sidesOf(x.f, x.reviewed, x.reviewedBase), LIST)).toBe('changed'); return x; }; + changed(methods(['ghome.prep', 'ghome.talk.target', 'ghome.brief'])); + changed(methods([...BASE_METHODS, 'ghome.brief'])); + changed(methods([...BASE_METHODS, 'ghome.brief', 'ghome.talk.target'])); + for (const resolved of [methods([...BASE_METHODS, 'ghome.talk.target', 'ghome.brief', 'ghome.admin']), methods([...BASE_METHODS, 'ghome.talk.target', 'ghome.brief'], 'expect(METHODS.length).toBeGreaterThan(0)')]) { + const { f, reviewed, reviewedBase, post } = changed(resolved); + const r = finish(f, reviewed, post, reviewedBase); + expect(r.status).toBe(3); + expect(r.stdout).toContain(`behavior, tests or build inputs changed since review (${LIST})`); + } + }); +}); From da98d0a0eb0072bc5825b1f361a92aa34bdb273b Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 04:56:07 +0800 Subject: [PATCH 50/62] /ship reuses CI's passing run when a base merge changed no file, and stops before long local test runs or an unknown base (GST-3019) (#4461) /ship's preflight and its CI-run lookup now reuse a passing CI test run when a base merge left the files unchanged, stop instead of quietly starting an hour-long test suite on the local machine, and refuse a `--base` that names no commit instead of reporting an empty diff. Why: gbrain #9662 lost a green CI run to a no-op base merge, then ran a 50-minute suite on a 4-CPU box, and its audit read a commit sha as a branch and saw zero changed files. Nothing to do: `--run-uncarried-here` restores running an uncovered suite locally under `--tests-only`. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: s11/outside-voice#1 reader=outside-voice Review-Finding: s11/outside-voice#2 reader=outside-voice --- bin/gstack-ci-carry | 15 ++-- bin/gstack-evidence | 6 +- .../ci-same-tree-reuse-and-preflight-stops.md | 1 + docs/pregate.md | 16 +++- docs/ship-policy.md | 13 ++++ docs/troubleshooting.md | 44 +++++++++++ lib/ci-carry.ts | 53 +++++++++---- lib/run-evidence.ts | 6 ++ lib/ship-audit.ts | 15 +++- lib/ship-bin-common.ts | 29 ++++--- lib/ship-preflight.ts | 35 +++++++-- ship/sections/tests.md | 3 +- ship/sections/tests.md.tmpl | 3 +- test/ci-carry.test.ts | 47 +++++++++++ test/docs-only-carry.test.ts | 14 ++++ test/ship-ci-carry.test.ts | 78 ++++++++++++++++++- test/ship-preflight.test.ts | 17 ++++ ...run-and-stops-before-long-local-tests.json | 4 + 18 files changed, 354 insertions(+), 45 deletions(-) create mode 100644 changelog.d/ci-same-tree-reuse-and-preflight-stops.md create mode 100644 test/size-ledger/ship/ship-reuses-same-tree-ci-run-and-stops-before-long-local-tests.json diff --git a/bin/gstack-ci-carry b/bin/gstack-ci-carry index 1771c028739..c777cbc213d 100755 --- a/bin/gstack-ci-carry +++ b/bin/gstack-ci-carry @@ -9,13 +9,15 @@ * find: the newest verified run of each profile (default: every profile the base branch's * ship_lanes_from names) at HEAD's clean tree. With --command, the base branch's mapping for that exact lane * command supplies the profiles and the inventory the runs must cover (a pin-file command, so it needs - * --allow-repo-commands). Prints CI_CARRY: accepted <receipt> (exit 0) or CI_CARRY: none (<reason>) (exit 1). + * --allow-repo-commands). Prints CI_CARRY: accepted <receipt> (exit 0) or CI_CARRY: none (<reason>) (exit 1). A run at + * one of HEAD's ancestors whose tree git reads as HEAD's (a base merge that changed no file) carries too, and CI_CARRY_FROM + * names that run and commit (GST-3019). * wait: polls the newest run of the profile's workflow at HEAD (REST, at least 60 s apart) until it completes (default timeout 1800 s), * prints CI_WAIT: green|red|running|none, and on green runs find. Exit 0 green and carried, 1 red or not * carried, 3 still running or no run. Logic: lib/ci-carry.ts; the run checks are lib/run-evidence.ts. */ import { spawnSync } from 'node:child_process'; -import { findCarry, laneMapping, mappingCoverage, waitForRun } from '../lib/ci-carry'; +import { carriedFromLine, findCarry, laneMapping, mappingCoverage, treeTwins, waitForRun } from '../lib/ci-carry'; import { isConfigUnavailable, loadConfigFromBase, loadConfigFromHead } from '../lib/pregate/config'; import { buildRunCheck } from '../lib/pregate/run-check'; import { wtreeFingerprint } from '../lib/script-invocation'; @@ -24,11 +26,12 @@ import { resolveBaseBranch } from '../lib/ship-policy'; const HELP = `gstack-ci-carry — use a verified CI run at HEAD's exact tree instead of running the suite again (docs/pregate.md#ci-carry) find [--base <branch>] [--profile <name>]... [--command <exact lane command> --allow-repo-commands] [--json] - CI_CARRY: accepted <receipt> (exit 0) or CI_CARRY: none (<reason>) (exit 1) + CI_CARRY: accepted <receipt> (exit 0) or CI_CARRY: none (<reason>) (exit 1); a run at an earlier commit with + HEAD's exact tree (git rev-parse <sha>^{tree}) carries too, and CI_CARRY_FROM: names that run and commit --policy-from head --simulate: the same check under the branch's own map and profiles, every line starting SIMULATION:; a dry run that proves a new mapping before it lands (find never writes evidence; nothing clears) wait [--base <branch>] [--profile <name>] [--timeout <s>] [--interval <s>] - poll the newest run at HEAD (default 1800 s, every 60 s at least, plus jitter): CI_WAIT: green|red|running|none, then find on green; + poll the newest run at HEAD or an earlier commit with its tree (default 1800 s, every 60 s at least, plus jitter): CI_WAIT: green|red|running|none, then find on green; exit 0 carried, 1 red or not carried, 3 still running or no run Profiles and ship_lanes_from come from origin/<base>'s .gstack/pregate.json only (a simulation reads the branch's). Only a clean, committed tree @@ -70,6 +73,8 @@ function find(): number { const v = findCarry(check as Exclude<typeof check, { error: string }>, { profiles, head, tree, wtree, ...(mapping ? mappingCoverage(mapping, root) : {}) }); if (argv.includes('--json')) out(JSON.stringify(v)); else out(v.ok ? `CI_CARRY: accepted ${v.receipt}` : `CI_CARRY: none (${v.reason}: ${v.detail})`); + const from = v.ok && !argv.includes('--json') ? carriedFromLine(v.runs, head) : undefined; + if (from) out(from); return v.ok ? 0 : 1; } @@ -79,6 +84,6 @@ const interval = Number(flag('--interval') ?? '60'); if (!(timeout >= 0 && timeout <= 21_600) || !(interval >= 1 && interval <= 600)) usage('--timeout is 0-21600 seconds and --interval 1-600'); const profile = check.profiles[profiles[0]!]; if (!profile) usage(`${profiles[0]} is not a run_profiles name on origin/${base}`); -const w = await waitForRun(check.deps, { workflow: profile!.workflow, events: profile!.events, head, timeoutMs: timeout * 1000, intervalMs: interval * 1000, sleep: ms => Bun.sleep(ms), clock: Date.now }); +const w = await waitForRun(check.deps, { workflow: profile!.workflow, events: profile!.events, head, also: treeTwins(check.deps, head, tree), timeoutMs: timeout * 1000, intervalMs: interval * 1000, sleep: ms => Bun.sleep(ms), clock: Date.now }); out(`CI_WAIT: ${w.state} ${profiles[0]} ${'run' in w ? `run=${w.run.id}/${w.run.run_attempt}${w.state === 'red' ? ` failing=${w.failing.join(',') || '-'}` : ''}` : w.reason}`); process.exit(w.state === 'green' ? find() : w.state === 'red' ? 1 : 3); diff --git a/bin/gstack-evidence b/bin/gstack-evidence index 26dd4c83ef7..753a4c4453b 100755 --- a/bin/gstack-evidence +++ b/bin/gstack-evidence @@ -100,7 +100,7 @@ import { resultLine } from "../lib/result-codes"; import { isUnavailable, loadPolicyFromBase, resolveBaseBranch } from "../lib/ship-policy"; import { versionAtRef } from "../lib/restamp"; import { bashCommandInvocation, runScriptSync, wtreeFingerprint } from "../lib/script-invocation"; -import { findCarry, laneMapping, mappingCoverage, perFileCommand } from "../lib/ci-carry"; +import { carriedFromLine, findCarry, laneMapping, mappingCoverage, perFileCommand } from "../lib/ci-carry"; import { DEFAULT_MAX_AGE_HOURS, runChanged } from "../lib/run-evidence"; import { isConfigUnavailable, loadConfigFromBase } from "../lib/pregate/config"; import { buildRunCheck } from "../lib/pregate/run-check"; @@ -806,6 +806,8 @@ async function cmdRecordCi(argv: string[]): Promise<number> { if (prior) { console.error(recordedCiLine(prior)); if (prior.not_owed) console.error(`gstack-evidence: not owed: ${prior.not_owed}`); + const priorFrom = carriedFromLine(v.runs, head); + if (priorFrom) console.error(priorFrom); console.error(`CI_RECORD_REUSED: label=${label} runs=${runs.join(",")} tree=${tree.slice(0, 12)} policy=${loaded.label} (the ledger's CI row for this exact tree, run and selection; nothing ran here)`); return 0; } @@ -870,6 +872,8 @@ async function cmdRecordCi(argv: string[]): Promise<number> { appendJsonl(paths.file, rec, { mode: 0o600 }); console.error(recordedCiLine(rec)); if (v.notOwed) console.error(`gstack-evidence: not owed: ${v.notOwed}`); + const from = carriedFromLine(v.runs, head); + if (from) console.error(from); if (exception) console.error(`TEST_LANE_EXCEPTION: ${testLaneExceptionText(exception)}`); return 0; } diff --git a/changelog.d/ci-same-tree-reuse-and-preflight-stops.md b/changelog.d/ci-same-tree-reuse-and-preflight-stops.md new file mode 100644 index 00000000000..7814a18523d --- /dev/null +++ b/changelog.d/ci-same-tree-reuse-and-preflight-stops.md @@ -0,0 +1 @@ +- **/ship reuses CI's passing test run when merging the base changed no file, and stops instead of quietly starting hour-long test runs or reviewing an empty diff (GST-3019).** When git reads a commit's file tree as identical to an earlier commit's, a passed CI run of the earlier commit now counts for it, under the same workflow, command and freshness rules, and the output names the commit and run it used. `gstack-ship-preflight --tests-only` now stops with `SHIP_LANE_NOT_CARRIED` and the CI command to run when a mapped test suite has no passing CI run to reuse, instead of running it on this machine (`--run-uncarried-here` still runs it). `--audit --base <commit sha>` now diffs against that commit, and a base that names no commit stops with `SHIP_BASE_UNKNOWN` instead of reporting zero changed files. diff --git a/docs/pregate.md b/docs/pregate.md index 35da657667b..c5e01a53a3e 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -1075,6 +1075,17 @@ it accepts a run only when all of these hold: running run on HEAD, within `max_age_hours`, and a `tree.json` naming HEAD's tree. A `pull_request` run counts only when the pull request already contained its base. +- <a id="same-tree-commits"></a>HEAD's runs include those of its newest + ancestors (up to 20 back) whose tree `git rev-parse <sha>^{tree}` reads as + HEAD's own, so a base merge that changed no file keeps the green run of the + commit before it (GST-3019). Git decides which commits those are; a run's + own `tree.json` never does. Every rule above still applies to that run, and + a newer red or running run on HEAD or on any of those commits vetoes it. + `gstack-ci-carry find` then prints `CI_CARRY_FROM: run <id>/<attempt> at + commit <sha>, not HEAD <sha>; git rev-parse reads the same tree <tree> for + both`, a Step 5 lane reads `LANE: <label> carried run=… from=<sha> (same + tree as HEAD)`, and the receipt's `heads=` names that commit. + `gstack-ci-carry wait` watches those commits' runs too. - Every run executed tests, and with an inventory command, the runs' `tree.json` files cover every file it prints, none of them a file whose every test skipped there (`skipped_files`). A lane mapped by `jobs` @@ -1295,7 +1306,10 @@ with every character outside `A-Za-z0-9._-` turned into `_` (`pnpm lint` is `pnpm_lint`, `db:test` is `db_test`), and `run`, `record-ci` and `check` all use that one spelling, so `check --label 'pnpm lint'` finds the row; `ci_carried` and `CI_CARRIED:` name the stored spelling. A mapped lane that cannot -carry prints `CI_CARRY: none label=<label> (<reason>)` and runs here. Every +carry prints `CI_CARRY: none label=<label> (<reason>)` and runs here, except +under `gstack-ship-preflight --tests-only`, which stops before any lane runs +with [`SHIP_LANE_NOT_CARRIED`](troubleshooting.md#ship-lane-not-carried) unless +it is given `--run-uncarried-here`. Every other lane runs through `gstack-evidence run --reuse`: the newest row for its label, command and working tree is reused when it passed with a counted run under the same runtime (bun and node versions, OS, architecture, runner image) diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 29eee8355be..3dbda57606f 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1291,6 +1291,19 @@ which carry the workflow consequences the skill prose would otherwise spell out: | `ship: review_scope …` | Step 9.4 item 0 runs `gstack-review-scope classify` on each pass's findings; see [review_scope](#review-scope) | | `ship: changelog_fragments <dir>: …` | Step 12 writes no version; Step 13 writes the entry as `<dir>/<branch-slug>.md` (entry text only, `bump:` front matter only when the change warrants more than the policy bump), never an `[Unreleased]` section, linted with `gstack-prose-lint <file> --gate`; `gstack-ship-queue land` assigns the version; see [changelog fragments](#changelog-fragments) | +<a id="preflight-result-codes"></a> +`gstack-ship-preflight` stops with a named code where a quiet fallback would cost +an hour or hide an empty diff (GST-3019): + +| Code | When | Next | +|---|---|---| +| `SHIP_LANE_NOT_CARRIED` | `--tests-only` was given a lane `ship_lanes_from` maps, and no verified CI run carries it at this tree. Nothing runs, not even the other lanes. | Push, dispatch the workflow the `NEXT:` line names, `gstack-ci-carry wait`, rerun; or rerun with `--run-uncarried-here` to run it here. A full preflight still runs a lane that does not carry. [Troubleshooting](troubleshooting.md#ship-lane-not-carried) | +| `SHIP_BASE_UNKNOWN` | `--audit --base <base>` resolves to no commit: a sha-like value is tried as a commit first, then `origin/<base>`. | Fetch the base branch or the commit, then rerun. [Troubleshooting](troubleshooting.md#ship-base-unknown) | + +A lane carries from a run at an earlier commit when git reads that commit's tree as HEAD's (a base merge +that changed no file); the LANE line names it as `from=<sha> (same tree as HEAD)`. See +[same-tree commits](pregate.md#same-tree-commits). + The ship receipt (`gstack-ship-receipt write … --body`) goes in the PR body's closing Agent notes section, written by the pr-body section of `/ship` after the body is composed. A body from before that layout keeps its receipt at the top. That receipt is still read while it opens the body, also after the diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 48451b01959..d6a0c68cae1 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -725,6 +725,50 @@ before the fetch instead of going on unprotected. **Fix.** Do what the parenthesized `gstack-lease` line names (wait for the process holding `<git dir>/gstack-leases/.lock`), then rerun. +<a id="ship-lane-not-carried"></a> +### `STOP: SHIP_LANE_NOT_CARRIED: lane <label> did not carry from a verified CI run at this tree, and --tests-only never starts a lane on its own ...` + +**Meaning.** `gstack-ship-preflight --tests-only` was given a lane whose exact +command `origin/<base>`'s `.gstack/pregate.json` maps in `ship_lanes_from`, +and no verified CI run carries it at this tree: the `CI_CARRY: none +label=<label> (<reason>)` line above the STOP says why (`no_run`: CI has not +run this tree yet; `dirty_tree`: uncommitted work). A mapped lane is the full +suite, which can take most of an hour on a small machine (gbrain #9662: a +50-minute unit lane on 4 CPUs), so `--tests-only` no longer starts it on its +own (GST-3019). + +**What is kept.** Nothing ran: no lane, mapped or not, started. The pregate +line above it is the pregate's own verdict. + +**Fix.** Follow the `NEXT:` lines. Commit and push the tree, dispatch the +workflow they name (`gh workflow run <workflow> --ref <branch>`), wait with +`gstack-ci-carry wait --base <base>`, and once it prints `CI_WAIT: green` +rerun the same `--tests-only` command, which then carries the lane. To run the +lane on this machine instead, rerun with `--run-uncarried-here`. + +**Expected result.** `LANE: <label> carried run=<id>/<attempt> …`, or with +`--run-uncarried-here`, `LANE: <label> pass …` from the run here. + +<a id="ship-base-unknown"></a> +### `STOP: SHIP_BASE_UNKNOWN: --base <base> names no commit here ...` + +**Meaning.** `gstack-ship-preflight --audit --base <base>` could not resolve +the base to a commit. A value that looks like a commit sha (7 to 64 hex +characters) is tried as a commit this checkout holds first, then +`origin/<base>`. Before GST-3019 a sha was read as `origin/<sha>`, which +resolved to nothing and printed `CONTEXT: … files=0`, an empty diff that +looked like a branch with no changes. + +**What is kept.** Nothing ran: no diff, commit list, coverage map or plan +lookup was written. + +**Fix.** Pass the base branch name after `git fetch origin ++refs/heads/<name>:refs/remotes/origin/<name>`, or a commit sha this checkout +holds (`git fetch origin <sha>` first when it does not), then rerun. + +**Expected result.** `CONTEXT: diff=… files=<n> commits=<n>` for the diff +against that base. + <a id="review-fingerprint-tmpdir"></a> ### `gstack-wtree: cannot create a temp index under <dir>; set TMPDIR to a writable directory` / `gstack-review-log: cannot create a private object directory under <dir>; no working-tree fingerprint. Set TMPDIR to a writable directory.` diff --git a/lib/ci-carry.ts b/lib/ci-carry.ts index 23f1b205d67..d183da7ebdd 100644 --- a/lib/ci-carry.ts +++ b/lib/ci-carry.ts @@ -4,8 +4,9 @@ * they use it instead of running the suite again. * * `findCarry` looks up the newest verified run of each named run profile (the - * base branch's `.gstack/pregate.json` `run_profiles`) for HEAD and accepts it - * only when every rule holds: + * base branch's `.gstack/pregate.json` `run_profiles`) for HEAD, or for one of + * HEAD's newest ancestors whose tree git reads as HEAD's own (a base merge that + * changed no file, GST-3019; treeTwins), and accepts it only when every rule holds: * * the working tree is HEAD's committed tree (gstack-wtree), before and after * the lookup, so admitted dirty or untracked work never carries; @@ -23,7 +24,7 @@ * suite as before. Security and advisory scans and the sealed guard are never * carried: callers carry test lanes only. * - * waitForRun polls the newest run of one workflow on HEAD (REST) until it + * waitForRun polls the newest run of one workflow on HEAD (and `also`, the commits with its tree) (REST) until it * completes, at least 60 s apart (lib/gh-poll.ts), bounded by a timeout, and * returns green, red with the failing jobs, still running, or none. */ @@ -47,17 +48,40 @@ export type CarryVerdict = { ok: true; runs: RunEvidence[]; tests: number | 'n/a /** How many of HEAD's runs per workflow are tried, newest first. */ const CANDIDATES = 10; +/** How many of HEAD's newest ancestors are read for a commit with HEAD's exact tree. */ +const TWIN_DEPTH = 20; const no = (reason: CarryRefusal, detail: string): CarryRefused => ({ ok: false, reason, detail }); const newestFirst = (a: ApiRun, b: ApiRun) => (b.created_at ?? '').localeCompare(a.created_at ?? '') || b.id - a.id; -/** The newest run of `profile` on `head` that verifies; a refusal lists each candidate's reason, newest first. */ -function newestVerified(src: RunSource, name: string, profile: RunProfile, head: string, jobs: string[]): { ok: true; evidence: RunEvidence } | CarryRefused { +/** + * The commits among HEAD's newest ancestors whose tree git reads as `tree` (a base merge that changed no file, GST-3019), newest + * first, HEAD itself left out. Each is checked with git rev-parse <sha>^{tree}; a run's own record never makes a commit one of these. + */ +export function treeTwins(deps: RunDeps, head: string, tree: string): string[] { + return (deps.ancestors?.(head, TWIN_DEPTH) ?? []).filter(sha => sha !== head && deps.commitTree(sha) === tree); +} + +/** The line naming each carried run that ran at a commit other than HEAD, or undefined when every run ran at HEAD. */ +export function carriedFromLine(runs: RunEvidence[], head: string): string | undefined { + const away = runs.filter(e => e.head_sha !== head); + if (!away.length) return undefined; + return `CI_CARRY_FROM: ${away.map(e => `run ${e.run_id}/${e.run_attempt} at commit ${e.head_sha.slice(0, 12)}`).join('; ')}, not HEAD ${head.slice(0, 12)}; git rev-parse reads the same tree ${away[0]!.tree.slice(0, 12)} for both`; +} + +/** + * The newest run of `profile` on `heads` (HEAD, then the commits with its exact tree) that verifies; a refusal lists each + * candidate's reason, newest first. A newer red or running run on any of them vetoes. A docs-only skipped run at another + * commit is owed nothing only when HEAD itself is docs-only against the base too. + */ +function newestVerified(src: RunSource, name: string, profile: RunProfile, heads: string[], jobs: string[]): { ok: true; evidence: RunEvidence } | CarryRefused { if (jobs.length) profile = { ...profile, jobs: [...new Set([...profile.jobs, ...jobs])] }; - const listed = src.deps.runsForHead(profile.workflow, head).filter(r => profile.events.includes(r.event)).sort(newestFirst).slice(0, CANDIDATES); - if (!listed.length) return no('no_run', `no ${profile.workflow} run (${profile.events.join(', ')}) on ${head.slice(0, 12)} yet`); + const listed = heads.flatMap(h => src.deps.runsForHead(profile.workflow, h)).filter(r => profile.events.includes(r.event)).sort(newestFirst).slice(0, CANDIDATES); + const twins = heads.slice(1).map(h => h.slice(0, 12)); + if (!listed.length) return no('no_run', `no ${profile.workflow} run (${profile.events.join(', ')}) on ${heads[0]!.slice(0, 12)}${twins.length ? ` or on ${twins.join(', ')}, which git reads as the same tree` : ''} yet`); const refusals: string[] = []; + const docsOnly = src.docsOnly && ((sha: string) => src.docsOnly!(sha) && (sha === heads[0] || src.docsOnly!(heads[0]!))); for (const run of listed) { - const v = verifyRun(src.deps, { repo: src.repo, runRef: String(run.id), profileName: name, profile, vetoHeads: [head], now: src.now, unchanged: src.unchanged, docsOnly: src.docsOnly }); + const v = verifyRun(src.deps, { repo: src.repo, runRef: String(run.id), profileName: name, profile, vetoHeads: heads, now: src.now, unchanged: src.unchanged, docsOnly }); if (v.ok) return v; refusals.push(`run ${run.id}: ${v.reason}${v.fix ? ` (the pull request's base moved after the run; fix: ${v.fix})` : ''}`); } @@ -84,10 +108,11 @@ export function findCarry(src: RunSource, o: { profiles: string[]; head: string; if (!o.profiles.length) return no('no_profile', 'no run profile is named'); const runs: RunEvidence[] = []; try { + const heads = [o.head, ...treeTwins(src.deps, o.head, o.tree)]; for (const name of o.profiles) { const profile = src.profiles[name]; if (!profile) return no('no_profile', `${name} is not a run_profiles name on the base branch`); - const v = newestVerified(src, name, profile, o.head, jobs); + const v = newestVerified(src, name, profile, heads, jobs); if (!v.ok) return v; runs.push(v.evidence); } @@ -147,10 +172,10 @@ const PASSING = ['success', 'skipped', 'neutral']; * Poll the newest `workflow` run on `head` (among `events`) until it completes or `timeoutMs` passes; polls are at least 60 s * apart, so the last poll can land up to one poll interval (75 s with jitter) after `timeoutMs`. */ -export async function waitForRun(deps: RunDeps, o: { workflow: string; events: string[]; head: string; timeoutMs: number; intervalMs: number; sleep: (ms: number) => Promise<void>; clock: () => number; random?: () => number }): Promise<WaitVerdict> { +export async function waitForRun(deps: RunDeps, o: { workflow: string; events: string[]; head: string; also?: string[]; timeoutMs: number; intervalMs: number; sleep: (ms: number) => Promise<void>; clock: () => number; random?: () => number }): Promise<WaitVerdict> { const end = o.clock() + o.timeoutMs; for (;;) { - const newest = deps.runsForHead(o.workflow, o.head).filter(r => o.events.includes(r.event)).sort(newestFirst)[0]; + const newest = [o.head, ...(o.also ?? [])].flatMap(h => deps.runsForHead(o.workflow, h)).filter(r => o.events.includes(r.event)).sort(newestFirst)[0]; if (newest?.status === 'completed') { if (newest.conclusion === 'success') return { state: 'green', run: newest }; const failing = deps.jobs(newest.id, newest.run_attempt).filter(j => !PASSING.includes(j.conclusion ?? '')).map(j => j.name); @@ -212,7 +237,7 @@ export function importedTestLines(cwd: string, missing: string[], candidates: st * not-owed reason, or the last CARRY_NONE reason. A lane the cleared remote gate stood in for (--remote-gate-stands-in, GST-1688) * reads as its receipt, its count and why the CI carry refused. */ -export function recordCiResult(stderr: string): { runs?: string; tests?: string; files?: boolean; notOwed?: string; here?: string; exception?: string; reused?: string; none?: string; diagnosis?: string[]; remoteGate?: string; standIn?: string } { +export function recordCiResult(stderr: string): { runs?: string; tests?: string; files?: boolean; notOwed?: string; here?: string; exception?: string; reused?: string; from?: string; none?: string; diagnosis?: string[]; remoteGate?: string; standIn?: string } { const lines = stderr.split('\n'); const last = lines.findLast(x => x.startsWith('gstack-evidence: recorded label=')); const gateRow = last && / tests_ran=(\d+) log=- source=remote_gate receipt=(.+)$/.exec(last); @@ -227,7 +252,9 @@ export function recordCiResult(stderr: string): { runs?: string; tests?: string; const here = / skipped_here=(\d+) tests_ran_here=(\S+)( not_owed_here=\d+)?$/.exec(lines[at]!); const notOwed = lines.slice(at + 1).find(x => x.startsWith('gstack-evidence: not owed: '))?.slice('gstack-evidence: not owed: '.length); const reused = lines.slice(at + 1).map(x => /^CI_RECORD_REUSED: .* tree=([0-9a-f]+) /.exec(x)?.[1]).find(Boolean); - return { runs: got?.[3], tests: got?.[1], files: !!got?.[2], ...(notOwed ? { notOwed } : {}), ...(here ? { here: `skipped_here=${here[1]} file(s) tests_ran_here=${here[2]}${here[3] ?? ''}` } : {}), ...(exception ? { exception } : {}), ...(reused ? { reused } : {}) }; + const fromLine = lines.slice(at + 1).find(x => x.startsWith('CI_CARRY_FROM: ')); + const from = fromLine ? [...new Set([...fromLine.matchAll(/ at commit ([0-9a-f]{12})/g)].map(m => m[1]!))].join(',') : ''; + return { runs: got?.[3], tests: got?.[1], files: !!got?.[2], ...(notOwed ? { notOwed } : {}), ...(here ? { here: `skipped_here=${here[1]} file(s) tests_ran_here=${here[2]}${here[3] ?? ''}` } : {}), ...(exception ? { exception } : {}), ...(reused ? { reused } : {}), ...(from ? { from } : {}) }; } /** The per_file runner command for `files`: `{files}` replaced by the paths, each anchored with ./ (Bun reads a bare relative path as a substring filter) and single-quoted for bash. */ diff --git a/lib/run-evidence.ts b/lib/run-evidence.ts index f913fd6c80c..4d51dada620 100644 --- a/lib/run-evidence.ts +++ b/lib/run-evidence.ts @@ -72,6 +72,8 @@ export interface RunDeps { /** The tree.json of the run's unexpired artifact `name`: the only one, or with one per rerun attempt of its job, the one that records run_attempt `attempt`. */ artifact(id: number, name: string, attempt: number): TreeRecord; commitTree(sha: string): string | null; + /** `sha` and its ancestors, newest first, at most `max` (git rev-list): where a commit with `sha`'s exact tree is looked for (GST-3019). */ + ancestors?(sha: string, max: number): string[]; } export type RunRefusal = 'run_ref_invalid' | 'other_repository' | 'fork_run' | 'workflow_mismatch' | 'event_mismatch' | 'run_in_progress' @@ -396,6 +398,10 @@ export function ghRunDeps(repo: string, repoRoot: string): RunDeps { const tree = (r.stdout ?? '').trim(); return r.status === 0 && /^[0-9a-f]{40,64}$/.test(tree) ? tree : null; }, + ancestors: (sha, max) => { + const r = spawnSync('git', ['rev-list', `--max-count=${max}`, sha], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 }); + return r.status === 0 ? (r.stdout ?? '').split('\n').filter(s => SHA.test(s)) : []; + }, }; } diff --git a/lib/ship-audit.ts b/lib/ship-audit.ts index e970836279d..0633bdb8834 100644 --- a/lib/ship-audit.ts +++ b/lib/ship-audit.ts @@ -63,13 +63,24 @@ function planCandidates(cwd: string, fork: string, branch: string): string[] { return found; } +/** + * The commit --base names: a commit sha this checkout holds, tried first, else origin/<base>; null when neither resolves + * (GST-3019: --base <sha> was read as origin/<sha>, which diffed as files=0). + */ +export function resolveAuditBase(cwd: string, base: string): string | null { + const commit = (rev: string) => git(cwd, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`]).stdout.trim() || null; + return (/^[0-9a-f]{7,64}$/i.test(base) ? commit(base) : null) ?? commit(`refs/remotes/origin/${base}`); +} + export function audit(cwd: string, base: string, out: string): Report { const r = new Report(); - const fork = git(cwd, ['merge-base', `origin/${base}`, 'HEAD']).stdout.trim() || `origin/${base}`; + const resolved = resolveAuditBase(cwd, base); + if (!resolved) return r.stop(`SHIP_BASE_UNKNOWN: --base ${base} names no commit here (not a commit this checkout holds, and no origin/${base}); pass the base branch fetched into origin/<name>, or a commit sha after git fetch origin <sha>, then rerun (docs/troubleshooting.md#ship-base-unknown)`); + const fork = git(cwd, ['merge-base', resolved, 'HEAD']).stdout.trim() || resolved; fs.mkdirSync(out, { recursive: true, mode: 0o700 }); const diff = git(cwd, ['diff', fork]).stdout; const files = git(cwd, ['diff', '--name-only', fork]).stdout.split('\n').filter(Boolean); - const commits = git(cwd, ['log', '--oneline', `origin/${base}..HEAD`]).stdout; + const commits = git(cwd, ['log', '--oneline', `${resolved}..HEAD`]).stdout; fs.writeFileSync(path.join(out, 'diff.patch'), diff, { mode: 0o600 }); fs.writeFileSync(path.join(out, 'commits.txt'), commits, { mode: 0o600 }); r.add(`CONTEXT: diff=${path.join(out, 'diff.patch')} bytes=${Buffer.byteLength(diff)} files=${files.length} commits=${commits.split('\n').filter(Boolean).length} log=${path.join(out, 'commits.txt')}`); diff --git a/lib/ship-bin-common.ts b/lib/ship-bin-common.ts index 4072a073d00..62968d798fd 100644 --- a/lib/ship-bin-common.ts +++ b/lib/ship-bin-common.ts @@ -184,7 +184,7 @@ export function laneConcurrency(mode: string | undefined, cpus = os.availablePar return cpus <= 4 ? 1 : Infinity; } -export interface LaneResult { label: string; exit: number | null; testsRan: string; log: string; carried?: string; reused?: string; carryNone?: string; diagnosis?: string[]; notOwed?: string; here?: string; exception?: string; remoteGate?: string; standIn?: string } +export interface LaneResult { label: string; exit: number | null; testsRan: string; log: string; carried?: string; from?: string; held?: true; reused?: string; carryNone?: string; diagnosis?: string[]; notOwed?: string; here?: string; exception?: string; remoteGate?: string; standIn?: string } /** The base branch's `ship_lanes_from` entry for each lane whose command is a key or a declared alias, byte for byte (the ledger binds its sha256). */ export function mappedLanes(cwd: string, base: string, list: { label: string; command: string }[]): Map<string, ShipLaneMapping> { @@ -205,7 +205,7 @@ export function carryLane(cwd: string, base: string, l: { label: string; command const rec = bin(cwd, 'gstack-evidence', ['record-ci', '--label', l.label, '--base', base, '--remote-gate-stands-in', '--', l.command], timeoutS * 1000); const got = recordCiResult(rec.stderr); if (rec.status === 0 && got.remoteGate) return { label: l.label, exit: 0, testsRan: got.tests!, log: '-', remoteGate: got.remoteGate, standIn: got.standIn ?? 'not carried' }; - if (rec.status === 0 && got.runs) return { label: l.label, exit: 0, testsRan: got.files ? `${got.tests} (files)` : got.tests!, log: '-', carried: got.runs, ...(got.notOwed ? { notOwed: got.notOwed } : {}), ...(got.here ? { here: got.here } : {}), ...(got.exception ? { exception: got.exception } : {}), ...(got.reused ? { reused: got.reused } : {}) }; + if (rec.status === 0 && got.runs) return { label: l.label, exit: 0, testsRan: got.files ? `${got.tests} (files)` : got.tests!, log: '-', carried: got.runs, ...(got.notOwed ? { notOwed: got.notOwed } : {}), ...(got.here ? { here: got.here } : {}), ...(got.exception ? { exception: got.exception } : {}), ...(got.reused ? { reused: got.reused } : {}), ...(got.from ? { from: got.from } : {}) }; return { label: l.label, exit: null, testsRan: 'unknown', log: '-', carryNone: got.none ?? `record_failed: ${firstLine(rec.stderr)}`, ...(got.diagnosis ? { diagnosis: got.diagnosis } : {}) }; } @@ -219,20 +219,30 @@ export function recordCiTimeout(policy: Record<string, any> | null, base: string /** * Run each lane, at most `concurrency` at a time; results keep the lanes' order. With `base`, a lane the base branch maps in - * `ship_lanes_from` is carried from a verified CI run at this exact tree when one exists. Every other lane runs through - * gstack-evidence run --reuse (a pass at this tree, command and runtime is reused; `reuse: false` forces a run). + * `ship_lanes_from` is carried from a verified CI run at this exact tree when one exists; every mapped lane's carry is + * decided before any lane runs. With `hold`, a mapped lane that does not carry stops the call: nothing runs, and every + * lane that did not carry comes back `held` (GST-3019: --tests-only never starts a long lane on its own). Under `hold`, + * gstack-ci-carry find checks every mapped lane read-only first, so a refusal stops before any lane's record-ci runs its + * per_file remainder or exception preflight here; only the refused lanes go to record-ci, for a cleared remote gate. Every other + * lane runs through gstack-evidence run --reuse (a pass at this tree, command and runtime is reused; `reuse: false` forces a run). */ -export async function runLanes(cwd: string, list: { label: string; command: string }[], concurrency = Infinity, opts: { base?: string; reuse?: boolean } = {}): Promise<LaneResult[]> { +export async function runLanes(cwd: string, list: { label: string; command: string }[], concurrency = Infinity, opts: { base?: string; reuse?: boolean; hold?: boolean } = {}): Promise<LaneResult[]> { const out: LaneResult[] = []; const mapped = opts.base ? mappedLanes(cwd, opts.base, list) : new Map<string, ShipLaneMapping>(); + const refused = list.map(l => !!opts.hold && mapped.has(l.label) && bin(cwd, 'gstack-ci-carry', ['find', '--base', opts.base!, '--command', l.command, '--allow-repo-commands']).status !== 0); + const carries = list.map((l, i) => (refused[i] ? carryLane(cwd, opts.base!, l) : null)); + const done = (c: LaneResult | null) => !!(c?.carried || c?.remoteGate); + const held = () => list.map((l, i) => { const c = carries[i]; return c && done(c) ? c : { ...(c ?? { label: l.label, exit: null, testsRan: 'unknown', log: '-' }), held: true as const }; }); + if (opts.hold && carries.some(c => c && !done(c))) return held(); + for (const [i, l] of list.entries()) if (!carries[i] && mapped.has(l.label)) carries[i] = carryLane(cwd, opts.base!, l); + if (opts.hold && carries.some(c => c && !done(c))) return held(); let next = 0; const worker = async () => { while (next < list.length) { const i = next++; const l = list[i]!; - const m = mapped.get(l.label); - const carry = m ? carryLane(cwd, opts.base!, l) : null; - if (carry?.carried || carry?.remoteGate) { out[i] = carry; continue; } + const carry = carries[i]; + if (carry && done(carry)) { out[i] = carry; continue; } const r = await binAsync(cwd, 'gstack-evidence', ['run', ...(opts.reuse === false ? [] : ['--reuse']), '--label', l.label, '--', l.command]); const rec = /gstack-evidence: recorded label=\S+ exit=(\S+) tests_ran=(\S+) log=(\S+)/.exec(r.stderr); const reused = /gstack-evidence: reused label=\S+ tree=\S+ from=(\S+)/.exec(r.stderr)?.[1]; @@ -246,8 +256,9 @@ export async function runLanes(cwd: string, list: { label: string; command: stri /** Step 5's lane verdict: a lane passes on its runner count, never exit 0 alone; a carried lane names its CI runs. */ export function laneLine(l: LaneResult): { line: string; ok: boolean } { if (l.notOwed) return { line: `LANE: ${l.label} not owed: ${l.notOwed} run=${l.carried}`, ok: true }; - if (l.carried) return { line: `LANE: ${l.label} carried run=${l.carried} tests_ran=${l.testsRan}${l.here ? ` ${l.here}` : ''}${l.reused ? ` (reused the CI record at tree ${l.reused})` : ''}`, ok: true }; + if (l.carried) return { line: `LANE: ${l.label} carried run=${l.carried} tests_ran=${l.testsRan}${l.here ? ` ${l.here}` : ''}${l.from ? ` from=${l.from} (same tree as HEAD)` : ''}${l.reused ? ` (reused the CI record at tree ${l.reused})` : ''}`, ok: true }; if (l.remoteGate) return { line: `LANE: ${l.label} satisfied by remote_gate receipt=${l.remoteGate}`, ok: true }; + if (l.held) return { line: `LANE: ${l.label} held: not run`, ok: false }; const zero = l.exit === 0 && l.testsRan === '0'; const state = l.exit !== 0 ? 'FAIL' : zero ? 'ZERO-RUN' : l.testsRan === 'unknown' ? 'pass (count unavailable)' : 'pass'; return { line: `LANE: ${l.label} ${state} exit=${l.exit} tests_ran=${l.testsRan} log=${l.log}${l.reused ? ` reused=${l.reused}` : ''}`, ok: l.exit === 0 && !zero }; diff --git a/lib/ship-preflight.ts b/lib/ship-preflight.ts index beedbd4ffc4..197394a2fa6 100644 --- a/lib/ship-preflight.ts +++ b/lib/ship-preflight.ts @@ -10,13 +10,13 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { findCarry, laneMapping, mappingCoverage } from './ci-carry'; import { defaultBaseBranch } from './default-base'; -import { isConfigUnavailable, loadConfigFromHead } from './pregate/config'; +import { isConfigUnavailable, loadConfigFromBase, loadConfigFromHead } from './pregate/config'; import { buildRunCheck } from './pregate/run-check'; import { classifyDiff } from './review-depth'; import { wtreeFingerprint } from './script-invocation'; import { audit } from './ship-audit'; import { withGateLock } from './gate-dispositions'; -import { bin, carryNoneLines, firstLine, flagReader, gh, git, hostedOrigin, laneConcurrency, laneLine, lanes, Report, runLanes, shipPolicy, shipRunMarker, short } from './ship-bin-common'; +import { bin, carryNoneLines, firstLine, flagReader, gh, git, hostedOrigin, laneConcurrency, laneLine, lanes, mappedLanes, Report, runLanes, shipPolicy, shipRunMarker, short } from './ship-bin-common'; export const PREFLIGHT_HELP = `gstack-ship-preflight — /ship Steps 1-3 and Step 5's pregate and lanes in one call (ship/SKILL.md) @@ -25,6 +25,8 @@ export const PREFLIGHT_HELP = `gstack-ship-preflight — /ship Steps 1-3 and Ste this checkout's git dir and opened on its lease, and a later full preflight stops until finish clears it or 120 minutes pass, because its merge would move the tree the run's readers diff (GST-1204) gstack-ship-preflight --tests-only --base <base> --lane <label>=<command>... Step 5 only (after a repair) + --run-uncarried-here run a lane origin/<base> maps in ship_lanes_from here when its CI carry refuses; without it a refused + carry stops with SHIP_LANE_NOT_CARRIED before any lane runs, naming the CI dispatch (GST-3019) --lanes serial|parallel how Step 5 runs its lanes; unset, one at a time on 4 or fewer cores, all at once above --policy-from head Step 5's pregate reads the branch's .gstack/pregate.json, which may only add test lanes (a branch that adds the lane for a file it touches); anything else is PREGATE_HEAD_POLICY_LOOSENS @@ -37,13 +39,15 @@ export const PREFLIGHT_HELP = `gstack-ship-preflight — /ship Steps 1-3 and Ste CI run at this tree. Every line starts SIMULATION:; no lane runs, no evidence or ledger row is written and no obligation clears (a real carry reads origin/<base>'s map only). An inventory-mapped lane runs the branch's inventory command, so it needs --allow-repo-commands. Exit 0 when every mapped lane would carry, else 1 - gstack-ship-preflight --audit --base <base> --out <dir> the single reads and Steps 7-8's deterministic audits + gstack-ship-preflight --audit --base <base|commit sha> --out <dir> the single reads and Steps 7-8's deterministic audits; + a base that names no commit stops with SHIP_BASE_UNKNOWN instead of an empty diff (CONTEXT, TODOS, COVERAGE_MAP, Coverage, PLAN_*, READER: coverage=needed|none plan=needed|none) Prints at most 30 lines: BRANCH, STATUS, DIFF, PR/CARRY, APPLE, SCOPE, MERGE, DISTRIBUTION, POLICY, RUNTIME_LINES, PREGATE (with up to three PREGATE_DETAIL lines when it does not pass), LANES, one LANE line per lane (a lane the base maps in .gstack/pregate.json ship_lanes_from is carried from a verified CI run at this exact clean tree: -LANE: <label> carried run=<id>/<attempt> tests_ran=<n>, else CI_CARRY: none (<reason>) and it runs; any other lane that +LANE: <label> carried run=<id>/<attempt> tests_ran=<n>, else CI_CARRY: none (<reason>) and it runs, under --tests-only only with +--run-uncarried-here; any other lane that passed at this tree, command and runtime is reused: reused=<original time>), then NEXT: lines. STOP: names what the agent must decide or repair; nothing after it ran. Exit codes: 0 ok · 2 usage · 3 STOP`; @@ -197,7 +201,7 @@ function merge(cwd: string, base: string, r: Report): boolean { return true; } -async function tests(cwd: string, base: string, list: { label: string; command: string }[], policyFrom: string, timeout: string | undefined, step: { seconds: number; source: string }, run: { concurrency: number; line: string }, r: Report): Promise<void> { +async function tests(cwd: string, base: string, list: { label: string; command: string }[], policyFrom: string, timeout: string | undefined, step: { seconds: number; source: string }, run: { concurrency: number; line: string; hold: boolean }, r: Report): Promise<void> { const pg = bin(cwd, 'gstack-pregate', ['--allow-repo-commands', '--base', base, '--policy-from', policyFrom, ...(timeout ? ['--timeout', timeout] : [])], step.seconds * 1000); if (pg.timedOut) { r.add(`PREGATE: time limit hit (Step 5's whole pregate ran past its ${step.seconds} s budget, ${step.source}, and was stopped with exit ${pg.status ?? 'none'}; no verdict)`); @@ -214,9 +218,22 @@ async function tests(cwd: string, base: string, list: { label: string; command: } if (/uncleared/.test(verdict)) r.next('pregate requires-remote: gstack-pregate clear, or --remote --spend-cap <usd> under a user cap, before Step 18'); r.add(run.line); - const ran = await runLanes(cwd, list, run.concurrency, { base }); + const ran = await runLanes(cwd, list, run.concurrency, { base, hold: run.hold }); const results = ran.map(laneLine); for (const [i, l] of results.entries()) { for (const none of carryNoneLines(ran[i]!)) r.add(none); r.add(l.line); } + const refused = ran.filter(l => l.held && l.carryNone); + if (refused.length) { + const names = refused.map(l => l.label).join(', '); + const lane = `lane${refused.length > 1 ? 's' : ''} ${names}`; + const loaded = loadConfigFromBase(cwd, base); + const mapped = mappedLanes(cwd, base, list); + const workflows = isConfigUnavailable(loaded) ? [] : [...new Set(refused.flatMap(l => mapped.get(l.label)?.profiles ?? []).map(p => loaded.config.run_profiles?.[p]?.workflow).filter((w): w is string => !!w))]; + const branch = git(cwd, ['branch', '--show-current']).stdout.trim() || '<branch>'; + r.stop(`SHIP_LANE_NOT_CARRIED: ${lane} did not carry from a verified CI run at this tree, and --tests-only never starts a lane on its own: nothing ran here (docs/troubleshooting.md#ship-lane-not-carried)`); + r.next(`commit and push this tree, then ${workflows.length ? workflows.map(w => `gh workflow run ${w} --ref ${branch}`).join(' and ') : 'run its CI workflow on the branch'} and gstack-ci-carry wait --base ${base}; once it prints CI_WAIT: green, rerun this command`); + r.next(`or rerun this command with --run-uncarried-here to run ${lane} on this machine`); + return; + } const bad = results.filter(l => !l.ok); if (bad.length) { r.stop(`${bad.length} lane(s) failed or ran zero tests: Step 5 triage (read each log; a free-suite shard failure reruns its file list per measure.md); in-branch failures stop the ship`); return; } r.next('Step 6: select eval suites for prompt-related changes with the project\'s selector, then Step 7'); @@ -264,7 +281,8 @@ export async function preflight(argv: readonly string[], cwd: string): Promise<{ if (has('--audit')) { const out = flag('--out'); if (!base || !out) return { text: 'gstack-ship-preflight: --audit needs --base <base> --out <dir>\n', exit: 2 }; - return { text: audit(cwd, base, out).render(), exit: 0 }; + const r = audit(cwd, base, out); + return { text: r.render(), exit: r.exit }; } const policyFrom = flag('--policy-from') ?? 'base'; if (!['base', 'head'].includes(policyFrom)) return { text: 'gstack-ship-preflight: --policy-from needs base|head\n', exit: 2 }; @@ -277,13 +295,14 @@ export async function preflight(argv: readonly string[], cwd: string): Promise<{ const run = flag('--run'); if (has('--run') && !(run && RUN_ID.test(run))) return { text: 'gstack-ship-preflight: --run needs a run id: letters, digits, dot, underscore or dash, at most 128\n', exit: 2 }; if (has('--tests-only') && !list.length) return { text: 'gstack-ship-preflight: --tests-only needs at least one --lane <label>=<command>\n', exit: 2 }; + if (has('--run-uncarried-here') && !has('--tests-only')) return { text: 'gstack-ship-preflight: --run-uncarried-here goes with --tests-only (a full preflight runs a lane that does not carry here)\n', exit: 2 }; if (has('--simulate')) return has('--tests-only') && policyFrom === 'head' && list.length ? simulate(cwd, base, list, has('--allow-repo-commands')) : { text: 'gstack-ship-preflight: --simulate needs --tests-only --policy-from head and at least one --lane <label>=<command>\n', exit: 2 }; const mode = flag('--lanes'); const concurrency = has('--lanes') && mode === undefined ? '--lanes needs serial or parallel' : laneConcurrency(mode); if (typeof concurrency === 'string') return { text: `gstack-ship-preflight: ${concurrency}\n`, exit: 2 }; const r = new Report(); if (has('--tests-only') || integrate(cwd, base, run, r)) { - if (list.length) await tests(cwd, base, list, policyFrom, timeout, step, { concurrency, line: `LANES: ${concurrency === 1 ? 'serial' : 'parallel'} (${mode ? '--lanes' : `${os.availableParallelism()} cores`})` }, r); + if (list.length) await tests(cwd, base, list, policyFrom, timeout, step, { concurrency, line: `LANES: ${concurrency === 1 ? 'serial' : 'parallel'} (${mode ? '--lanes' : `${os.availableParallelism()} cores`})`, hold: has('--tests-only') && !has('--run-uncarried-here') }, r); else if (r.exit === 0) r.next('Step 4: confirm the test framework, then rerun with --tests-only --lane <label>=<command> per suite (Step 5)'); } return { text: r.render(), exit: r.exit }; diff --git a/ship/sections/tests.md b/ship/sections/tests.md index c35ff949ce8..d9643b7eb75 100644 --- a/ship/sections/tests.md +++ b/ship/sections/tests.md @@ -234,7 +234,8 @@ merge-check code: `lib/ship-*`, `lib/pregate/*`, the ship and pregate bins, (`gstack-post pr-create --base <base> --draft --title-file <f> --body-file <f>`), then `gstack-ci-carry wait` in the background; once it prints `CI_WAIT: green`, rerun `--tests-only` and the mapped lane is carried. A red run is a failed lane: triage it below. Batch review fixes into one commit and one push. `CI_CARRY: none -label=<l> (<reason>)` names why a mapped lane ran here. A docs-only change ([docs/pregate.md#docs-only](../../docs/pregate.md#docs-only)) owes no test lane: pregate runs +label=<l> (<reason>)` names why a mapped lane did not carry; under `--tests-only` that is `STOP: SHIP_LANE_NOT_CARRIED` before +any lane runs: dispatch CI and wait as its `NEXT:` lines say, or rerun with `--run-uncarried-here` to run the lane here. A docs-only change ([docs/pregate.md#docs-only](../../docs/pregate.md#docs-only)) owes no test lane: pregate runs the docs lane, and a mapped lane prints `LANE: <label> not owed: docs-only change …` from CI's skipped run. Any other lane that already passed at this tree, command and runtime is reused (`reused=<time>`). In Step 16, `finish` defers a mapped lane it cannot carry (`EVIDENCE: DEFERRED`); after Step 17's push, `gstack-ship-release accept --base <base> diff --git a/ship/sections/tests.md.tmpl b/ship/sections/tests.md.tmpl index 0e3e6da86c7..a18b54912c2 100644 --- a/ship/sections/tests.md.tmpl +++ b/ship/sections/tests.md.tmpl @@ -30,7 +30,8 @@ merge-check code: `lib/ship-*`, `lib/pregate/*`, the ship and pregate bins, (`gstack-post pr-create --base <base> --draft --title-file <f> --body-file <f>`), then `gstack-ci-carry wait` in the background; once it prints `CI_WAIT: green`, rerun `--tests-only` and the mapped lane is carried. A red run is a failed lane: triage it below. Batch review fixes into one commit and one push. `CI_CARRY: none -label=<l> (<reason>)` names why a mapped lane ran here. A docs-only change ([docs/pregate.md#docs-only](../../docs/pregate.md#docs-only)) owes no test lane: pregate runs +label=<l> (<reason>)` names why a mapped lane did not carry; under `--tests-only` that is `STOP: SHIP_LANE_NOT_CARRIED` before +any lane runs: dispatch CI and wait as its `NEXT:` lines say, or rerun with `--run-uncarried-here` to run the lane here. A docs-only change ([docs/pregate.md#docs-only](../../docs/pregate.md#docs-only)) owes no test lane: pregate runs the docs lane, and a mapped lane prints `LANE: <label> not owed: docs-only change …` from CI's skipped run. Any other lane that already passed at this tree, command and runtime is reused (`reused=<time>`). In Step 16, `finish` defers a mapped lane it cannot carry (`EVIDENCE: DEFERRED`); after Step 17's push, `gstack-ship-release accept --base <base> diff --git a/test/ci-carry.test.ts b/test/ci-carry.test.ts index a4c00de91da..12b292f37cc 100644 --- a/test/ci-carry.test.ts +++ b/test/ci-carry.test.ts @@ -79,6 +79,53 @@ describe('findCarry', () => { }); }); +describe('GST-3019: a run at another commit whose tree git reads as HEAD\'s carries', () => { + const TWIN = 'c'.repeat(40); + const ELSE = 'e'.repeat(40); + const twins = (runs: ApiRun[], records: Record<number, TreeRecord>, trees: Record<string, string> = { [HEAD]: TREE, [TWIN]: TREE, [ELSE]: 'f'.repeat(40) }): RunSource => { + const src = source(runs, records); + return { ...src, deps: { ...src.deps, commitTree: sha => trees[sha] ?? null, ancestors: (sha, max) => [sha, TWIN, ELSE].slice(0, max) } }; + }; + const atTwin = (id: number, over: Partial<ApiRun> = {}) => run(id, { head_sha: TWIN, ...over }); + const recTwin = (id: number, over: Partial<TreeRecord> = {}) => record(id, { sha: TWIN, ...over }); + + // Value: protects=a base merge that changed no file keeps the green CI run of the commit before it (gbrain #9662: 0dc0d1d had 5840295's tree 369fa767 and carried nothing); + // fails_when=only runs on HEAD's own sha are listed, or the carried run's commit is not the one git read; why_new=GST-3019; seam=RunDeps.ancestors and commitTree + test('a green run of the same workflow at an ancestor with HEAD\'s tree carries, and the evidence names that commit', () => { + const v = carry(twins([atTwin(4)], { 4: recTwin(4) }), { inventory: () => ['test/a.test.ts', 'test/b.test.ts'] }); + expect(why(v)).toBe('ok'); + if (!v.ok) return; + expect(v.runs.map(e => [e.run_id, e.head_sha, e.tree])).toEqual([[4, TWIN, TREE]]); + expect(v.receipt).toContain(`runs=4/1 profiles=ci-reuse/free-tests heads=${TWIN.slice(0, 12)} `); + const both = carry(twins([atTwin(4), run(5)], { 4: recTwin(4), 5: record(5) })); + expect(both.ok && both.runs.map(e => [e.run_id, e.head_sha])).toEqual([[5, HEAD]]); + }); + + // Value: protects=tree identity comes from git, and every other carry rule still holds at the other commit; fails_when=a different tree, a failed or cancelled run, + // another workflow, or a newer red run at HEAD carries; why_new=GST-3019 negative controls; seam=verifyRun + test('negative controls: another tree, a failed or cancelled run, another workflow and a newer red run at HEAD never carry', () => { + expect(why(carry(twins([run(4, { head_sha: ELSE })], { 4: record(4, { sha: ELSE, tree: TREE }) })))).toBe('no_run'); + expect(why(carry(twins([atTwin(4)], { 4: recTwin(4) }, { [HEAD]: TREE, [TWIN]: 'd'.repeat(40) })))).toBe('no_run'); + const failed = carry(twins([atTwin(4, { conclusion: 'failure' })], { 4: recTwin(4) })); + expect([why(failed), failed.ok ? '' : failed.detail]).toEqual(['no_verified_run', expect.stringContaining('run 4: run_not_success')]); + const cancelled = carry(twins([atTwin(4, { conclusion: 'cancelled' })], { 4: recTwin(4) })); + expect([why(cancelled), cancelled.ok ? '' : cancelled.detail]).toEqual(['no_verified_run', expect.stringContaining('run 4: run_not_success')]); + const other = carry(twins([atTwin(4, { path: '.github/workflows/other.yml' })], { 4: recTwin(4) })); + expect([why(other), other.ok ? '' : other.detail]).toEqual(['no_verified_run', expect.stringContaining('run 4: workflow_mismatch')]); + const vetoed = carry(twins([atTwin(4), run(6, { conclusion: 'failure' })], { 4: recTwin(4), 6: record(6) })); + expect([why(vetoed), vetoed.ok ? '' : vetoed.detail]).toEqual(['no_verified_run', expect.stringContaining('run 4: newer_run_vetoes')]); + expect(why(carry(twins([atTwin(4)], { 4: recTwin(4, { tree: 'd'.repeat(40) }) })))).toBe('no_verified_run'); + }); + + // Value: protects=gstack-ci-carry wait sees the green run at the commit with HEAD's tree instead of waiting out its timeout; fails_when=wait reads HEAD's sha alone; + // why_new=GST-3019; seam=waitForRun + test('waitForRun reads runs at the commits with HEAD\'s tree too', async () => { + const src = twins([atTwin(4)], { 4: recTwin(4) }); + const w = await waitForRun(src.deps, { workflow: 'free-tests.yml', events: ['workflow_dispatch'], head: HEAD, also: [TWIN], timeoutMs: 0, intervalMs: 60_000, sleep: async () => {}, clock: () => 0 }); + expect(w.state === 'green' && w.run.id).toBe(4); + }); +}); + describe('waitForRun', () => { const clockAt = () => { let t = 0; return { clock: () => t, sleep: async (ms: number) => { t += ms; } }; }; // Value: protects=the bounded wait reports green, red with failing jobs, still running and none; fails_when=it waits forever or calls a red run green diff --git a/test/docs-only-carry.test.ts b/test/docs-only-carry.test.ts index 4dca66daa50..3c991d0d888 100644 --- a/test/docs-only-carry.test.ts +++ b/test/docs-only-carry.test.ts @@ -55,3 +55,17 @@ test('a run whose gate job failed never counts its skipped suites', () => { const v = verifyRun(failed, { repo: REPO, runRef: '7', profileName: 'ci-reuse/free-tests', profile: PROFILE, now: NOW, unchanged: () => null, docsOnly: () => true }); expect(v.ok ? 'ok' : v.reason).toBe('job_skipped'); }); + +// Value: protects=a docs-only skipped run at a commit with HEAD's tree (GST-3019) carries as not owed only when HEAD itself is docs-only; +// fails_when=the ancestor's classification exempts a HEAD whose base merge changed runtime code against the new base; why_new=GST-3019 review; seam=RunDeps.ancestors +test('a docs-only run at a same-tree ancestor carries only when HEAD is docs-only too', () => { + const TWIN = 'c'.repeat(40); + const atTwin: ApiRun = { ...RUN, head_sha: TWIN }; + const twinDeps: RunDeps = { ...deps, run: () => atTwin, runsForHead: (_wf, sha) => (sha === TWIN ? [atTwin] : []), commitTree: sha => (sha === HEAD || sha === TWIN ? TREE : null), ancestors: sha => [sha, TWIN] }; + const at = (docsOnly: (h: string) => boolean) => carry({ ...source(docsOnly), deps: twinDeps }); + const ancestorOnly = at(h => h === TWIN); + expect(ancestorOnly.ok).toBe(false); + if (!ancestorOnly.ok) expect(ancestorOnly.detail).toContain('artifact_missing'); + const both = at(() => true); + expect(both.ok && both.notOwed).toContain('docs-only change'); +}); diff --git a/test/ship-ci-carry.test.ts b/test/ship-ci-carry.test.ts index ccd50c66d40..cffd7a44398 100644 --- a/test/ship-ci-carry.test.ts +++ b/test/ship-ci-carry.test.ts @@ -41,7 +41,9 @@ function world(f: ShipFx, over: { run?: Record<string, unknown>; tree?: Record<s fs.writeFileSync(file, JSON.stringify(w)); f.gh(fakeGhScript(file)); } -const preflight = (f: ShipFx, lanes = [`free=${FREE}`, `unit=${UNIT}`]) => f.run(PREFLIGHT, ['--tests-only', '--base', 'main', ...lanes.flatMap(l => ['--lane', l])]); +const preflight = (f: ShipFx, lanes = [`free=${FREE}`, `unit=${UNIT}`], extra: string[] = []) => f.run(PREFLIGHT, ['--tests-only', '--base', 'main', ...extra, ...lanes.flatMap(l => ['--lane', l])]); +/** --tests-only with --run-uncarried-here: a mapped lane whose carry refuses runs here (GST-3019; without the flag it stops). */ +const UNCARRIED_HERE = ['--run-uncarried-here']; const lane = (out: string, label: string) => out.split('\n').find(l => l.startsWith(`LANE: ${label} `)) ?? ''; describe('Step 5 lanes: CI carry and the tree cache', () => { @@ -75,7 +77,7 @@ describe('Step 5 lanes: CI carry and the tree cache', () => { let expected = 0; for (const [reason, setup] of cases) { setup(); - const out = preflight(f, [`free=${FREE}`]).stdout; + const out = preflight(f, [`free=${FREE}`], UNCARRIED_HERE).stdout; expect([reason, out]).toEqual([reason, expect.stringContaining('CI_CARRY: none label=free (')]); expect(out).toContain(reason); expect(lane(out, 'free')).toMatch(/^LANE: free pass exit=0 tests_ran=3 /); @@ -424,7 +426,7 @@ describe('GST-1190: a file whose every test skipped on CI is not carried', () => world(f, { tree: { skipped_files: ['test/b.test.ts'] } }); const rec = f.run(path.join(BIN, 'gstack-evidence'), ['record-ci', '--label', 'free', '--base', 'main', '--', FREE]); expect([rec.status, rec.stderr]).toEqual([1, expect.stringMatching(/^CARRY_NONE: inventory_skipped: 1 of 2 inventory file\(s\) skipped every test in CI and the lane declares no per_file runner: test\/b\.test\.ts$/m)]); - const out = preflight(f, [`free=${FREE}`]); + const out = preflight(f, [`free=${FREE}`], UNCARRIED_HERE); expect(out.stdout).toContain('CI_CARRY: none label=free (inventory_skipped'); expect(runs(f, 'free-runs')).toBe(1); world(f, { tree: { skipped_files: [] } }); @@ -538,10 +540,21 @@ describe('GST-1190: a lane carries the covered files and runs only the skipped r const rec = f.run(path.join(BIN, 'gstack-evidence'), ['record-ci', '--label', 'free', '--base', 'main', '--', FREE]); expect([rec.status, rec.stderr]).toEqual([1, expect.stringMatching(/^CARRY_NONE: skipped_failed: the per_file run of test\/b\.test\.ts exited 1 \(label=free\.skipped\)$/m)]); expect(rows(f).filter(r => r.source === 'ci')).toEqual([]); - expect(preflight(f, [`free=${FREE}`]).stdout).toContain('CI_CARRY: none label=free (skipped_failed'); + expect(preflight(f, [`free=${FREE}`], UNCARRIED_HERE).stdout).toContain('CI_CARRY: none label=free (skipped_failed'); expect(runs(f, 'free-runs')).toBe(1); }); + // Value: protects=--tests-only decides its hold before any lane's record-ci runs a per_file remainder here (GST-3019 review: the hold ran + // remainders, then said nothing ran); fails_when=the carrying lane's skipped file runs while another mapped lane refuses; why_new=GST-3019; seam=fake gh, gstack-ci-carry find + test('a refused mapped lane stops --tests-only before another lane runs its skipped remainder here', () => { + const f = shipFixture({ ...BASE, '.gstack/pregate.json': JSON.stringify({ run_profiles: { 'ci/free': PROFILE }, ship_lanes_from: { [FREE]: { profiles: ['ci/free'], inventory: "printf 'test/a.test.ts\\ntest/b.test.ts\\n'", per_file: PER(0) }, [UNIT]: { profiles: ['ci/free'], jobs: ['lint'] } } }, null, 2) + '\n' }); fixtures.push(f); + world(f, { tree: { skipped_files: ['test/b.test.ts'] } }); + const held = preflight(f); + expect(held.status, held.stdout + held.stderr).toBe(3); + expect(lineOf(held.stdout, 'STOP')).toMatch(/^STOP: SHIP_LANE_NOT_CARRIED: lane unit did not carry /); + expect([args(f), runs(f, 'free-runs'), runs(f, 'unit-runs')]).toEqual(['', 0, 0]); + }); + test('a remainder file that registers no test here carries nothing: the lane runs whole', () => { const zero = { ...BASE, '.gstack/pregate.json': JSON.stringify({ run_profiles: { 'ci/free': PROFILE }, ship_lanes_from: { [FREE]: { profiles: ['ci/free'], inventory: "printf 'test/a.test.ts\\ntest/b.test.ts\\n'", per_file: "printf ' 0 pass\\n 0 fail\\nRan 0 tests across 1 file. [1.00ms]\\n' >&2 # {files}" } } }, null, 2) + '\n' }; const f = shipFixture(zero); fixtures.push(f); @@ -716,3 +729,60 @@ describe('GSTA-258 L6 review fixes: gate inputs, ledger CI rows, simulate consen expect(yes.stdout).toContain('SIMULATION: LANE: free would carry run=7/1 tests_ran=2 unit=files'); }); }); + +describe('GST-3019: a commit that changes no file carries the green run of the commit with its tree', () => { + // Value: protects=a base merge that changed no file reuses the passed CI run of the identical tree, and every surface says which commit and run it came from + // (gbrain #9662: 0dc0d1d, tree 369fa767, printed no_run beside 5840295's green run); fails_when=find, wait or Step 5 reads HEAD's sha alone, or a changed tree, + // an unmapped command or a red run carries; why_new=GST-3019; seam=fake gh, git rev-list and rev-parse in the fixture + test('find, wait and Step 5 carry from the earlier commit and name it; a changed tree, another command or a red run does not', () => { + const f = fx(); + world(f); + const before = f.git('rev-parse', 'HEAD').stdout.trim(); + const tree = f.git('rev-parse', 'HEAD^{tree}').stdout.trim(); + expect(f.git('commit', '--allow-empty', '-m', 'merge main: no file changes').status).toBe(0); + const head = f.git('rev-parse', 'HEAD').stdout.trim(); + expect([head !== before, f.git('rev-parse', 'HEAD^{tree}').stdout.trim()]).toEqual([true, tree]); + const cli = (args: string[]) => f.run(path.join(BIN, 'gstack-ci-carry'), args); + const found = cli(['find', '--base', 'main', '--command', FREE, '--allow-repo-commands']); + expect([found.status, lineOf(found.stdout, 'CI_CARRY')]).toEqual([0, expect.stringMatching(new RegExp(`^CI_CARRY: accepted ci-carry tree=${tree.slice(0, 12)} files=2 runs=7/1 profiles=ci/free heads=${before.slice(0, 12)} `))]); + expect(lineOf(found.stdout, 'CI_CARRY_FROM')).toBe(`CI_CARRY_FROM: run 7/1 at commit ${before.slice(0, 12)}, not HEAD ${head.slice(0, 12)}; git rev-parse reads the same tree ${tree.slice(0, 12)} for both`); + expect(cli(['wait', '--base', 'main', '--timeout', '0']).stdout).toContain('CI_WAIT: green ci/free run=7/1'); + const step5 = preflight(f, [`free=${FREE}`]); + expect([step5.status, lane(step5.stdout, 'free')]).toEqual([0, `LANE: free carried run=7/1 tests_ran=2 (files) from=${before.slice(0, 12)} (same tree as HEAD)`]); + expect(runs(f, 'free-runs')).toBe(0); + expect(cli(['find', '--base', 'main', '--command', 'bun run test', '--allow-repo-commands']).stdout).toContain('CI_CARRY: none (not_mapped'); + world(f, { run: { head_sha: before, conclusion: 'failure' }, tree: { sha: before } }); + expect(cli(['find', '--base', 'main', '--command', FREE, '--allow-repo-commands']).stdout).toContain('CI_CARRY: none (no_verified_run: ci/free: run 7: run_not_success'); + world(f, { run: { head_sha: before, conclusion: 'cancelled' }, tree: { sha: before } }); + expect(cli(['find', '--base', 'main', '--command', FREE, '--allow-repo-commands']).stdout).toContain('run 7: run_not_success'); + world(f, { run: { head_sha: before }, tree: { sha: before } }); + f.write({ 'src/c.ts': 'export const c = 1;\n' }); + expect(f.git('add', '-A').status).toBe(0); + expect(f.git('commit', '-m', 'a real change').status).toBe(0); + expect(cli(['find', '--base', 'main', '--command', FREE, '--allow-repo-commands']).stdout).toContain('CI_CARRY: none (no_run: no free.yml run (pull_request, workflow_dispatch) on '); + }); +}); + +describe('GST-3019: --tests-only never starts a lane on its own when its carry refuses', () => { + // Value: protects=a refused carry under --tests-only stops with SHIP_LANE_NOT_CARRIED and the next command instead of quietly running the lane here + // (gbrain #9662: a 50-minute unit lane on a 4-CPU box); fails_when=the mapped lane or any other lane runs, the stop has no code, or --run-uncarried-here + // does not run it; why_new=GST-3019; seam=fake gh, gstack-evidence ledger + test('a refused carry stops before any lane runs and names the CI dispatch; --run-uncarried-here runs it here', () => { + const f = fx(); + world(f, { run: { head_sha: '0'.repeat(40) } }); + const branch = f.git('branch', '--show-current').stdout.trim(); + const held = preflight(f); + expect(held.status).toBe(3); + expect(held.stdout).toContain('CI_CARRY: none label=free (no_run: '); + expect(lineOf(held.stdout, 'STOP')).toBe('STOP: SHIP_LANE_NOT_CARRIED: lane free did not carry from a verified CI run at this tree, and --tests-only never starts a lane on its own: nothing ran here (docs/troubleshooting.md#ship-lane-not-carried)'); + expect(held.stdout).toContain(`NEXT: commit and push this tree, then gh workflow run free.yml --ref ${branch} and gstack-ci-carry wait --base main; once it prints CI_WAIT: green, rerun this command`); + expect(held.stdout).toContain('NEXT: or rerun this command with --run-uncarried-here to run lane free on this machine'); + expect([runs(f, 'free-runs'), runs(f, 'unit-runs')]).toEqual([0, 0]); + const here = preflight(f, undefined, UNCARRIED_HERE); + expect(here.status).toBe(0); + expect(here.stdout).toContain('CI_CARRY: none label=free (no_run: '); + expect(lane(here.stdout, 'free')).toMatch(/^LANE: free pass exit=0 tests_ran=3 /); + expect([runs(f, 'free-runs'), runs(f, 'unit-runs')]).toEqual([1, 1]); + expect(f.run(PREFLIGHT, ['--base', 'main', '--run-uncarried-here', '--lane', `free=${FREE}`]).status).toBe(2); + }); +}); diff --git a/test/ship-preflight.test.ts b/test/ship-preflight.test.ts index 5ff7850cf5a..3f00dce8318 100644 --- a/test/ship-preflight.test.ts +++ b/test/ship-preflight.test.ts @@ -339,6 +339,23 @@ describe('gstack-ship-preflight --audit (GSTA-167 variant G)', () => { expect(lineOf(r.stdout, 'READER')).toBe('READER: coverage=none plan=needed'); expect(f.run(PREFLIGHT, ['--audit', '--base', 'main']).status).toBe(2); }); + + // Value: protects=--audit --base <sha> diffs against that commit, and a base that resolves to nothing stops with SHIP_BASE_UNKNOWN instead of an empty diff (gbrain #9662); + // fails_when=a commit sha is read as origin/<sha>, or an unknown base prints CONTEXT files=0; why_new=GST-3019; seam=git + test('a commit sha is a base; a base that resolves to nothing stops with SHIP_BASE_UNKNOWN, never files=0', () => { + const f = fx({}, { 'src/budget.ts': 'export const budget = 1;\n', 'src/other.ts': 'export const o = 1;\n' }); + const base = f.git('rev-parse', 'origin/main').stdout.trim(); + for (const sha of [base, base.slice(0, 12)]) { + const r = f.run(PREFLIGHT, ['--audit', '--base', sha, '--out', path.join(f.root, `a-${sha.length}`)], { HOME: f.root }); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(lineOf(r.stdout, 'CONTEXT')).toMatch(/ files=2 commits=1 /); + } + for (const bad of ['0'.repeat(40), 'no-such-branch']) { + const u = f.run(PREFLIGHT, ['--audit', '--base', bad, '--out', path.join(f.root, 'bad')], { HOME: f.root }); + expect([u.status, lineOf(u.stdout, 'STOP')]).toEqual([3, `STOP: SHIP_BASE_UNKNOWN: --base ${bad} names no commit here (not a commit this checkout holds, and no origin/${bad}); pass the base branch fetched into origin/<name>, or a commit sha after git fetch origin <sha>, then rerun (docs/troubleshooting.md#ship-base-unknown)`]); + expect(u.stdout).not.toContain('CONTEXT'); + } + }); }); describe('GSTA-167 part 4a: RUNTIME_LINES and REVIEW_DEPTH share one owner', () => { diff --git a/test/size-ledger/ship/ship-reuses-same-tree-ci-run-and-stops-before-long-local-tests.json b/test/size-ledger/ship/ship-reuses-same-tree-ci-run-and-stops-before-long-local-tests.json new file mode 100644 index 00000000000..4bb0f62a8a0 --- /dev/null +++ b/test/size-ledger/ship/ship-reuses-same-tree-ci-run-and-stops-before-long-local-tests.json @@ -0,0 +1,4 @@ +{ + "bytes": 192, + "why": "GST-3019: Step 5 prose names the SHIP_LANE_NOT_CARRIED stop under --tests-only and the --run-uncarried-here flag" +} From 44c904fe9bf7ae00fecf80dc4fbebf41a07b173a Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 06:43:07 +0800 Subject: [PATCH 51/62] Pre-push test selection finds tests in monorepo apps that use their own @/ alias (#4464) /ship's pre-push test selection now finds the tests of a monorepo app that imports through its own `@/` alias (for example `apps/mobile` mapping `@/*` to `./src/*`). Why: only the root tsconfig was read, so every touched file in such an app failed with `PREGATE_NO_LANE` even with a test beside it. Rebuilt from #4462 by @dtoelke, who found and fixed it; thank you. Nothing to do: a repo whose only tsconfig is at the root (gstack itself) resolves exactly as before. Co-authored-by: stackpt-agent <348614618+stackpt-agent@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p2v/outside-voice#1 reader=outside-voice --- changelog.d/nested-tsconfig-path-aliases.md | 1 + docs/pregate.md | 9 +++ lib/pregate/import-graph.ts | 60 ++++++++++++--- test/pregate-import-graph-paths.test.ts | 84 +++++++++++++++++++++ 4 files changed, 143 insertions(+), 11 deletions(-) create mode 100644 changelog.d/nested-tsconfig-path-aliases.md diff --git a/changelog.d/nested-tsconfig-path-aliases.md b/changelog.d/nested-tsconfig-path-aliases.md new file mode 100644 index 00000000000..e6dd791a399 --- /dev/null +++ b/changelog.d/nested-tsconfig-path-aliases.md @@ -0,0 +1 @@ +- **/ship's pre-gate finds the tests of a monorepo app that imports through its own `@/` alias.** The import graph read `paths` and `baseUrl` from the repository root's tsconfig only, so in an app like `apps/mobile` whose `tsconfig.json` maps `@/*` to `./src/*`, every touched source file failed with `PREGATE_NO_LANE` even with a test right beside it. Each file now takes its aliases from the nearest tsconfig.json or jsconfig.json above it that declares `paths` or `baseUrl`; a nested config that declares neither defers to the next one up, the root config governs the rest, and an `extends` outside the repository is still never followed. Thanks to @dtoelke for the report and the original fix (#4462). diff --git a/docs/pregate.md b/docs/pregate.md index c5e01a53a3e..b37dec29fc7 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -353,6 +353,15 @@ Two stages with separate clocks, both printed: modified file whose only test the branch deleted still has no lane, and a remaining test that reads a deleted file or directory is selected. /review lists a deleted test as a gate edit (RH-1) either way. + A JS/TS file's `paths` aliases and `baseUrl` come from the nearest + tsconfig.json (else jsconfig.json) above it that declares `paths` or + `baseUrl`, itself or through a relative `extends` chain inside the + repository (up to four hops), joined relative to the config that declares + them. A nested config that declares neither defers to the next one up, and + the repository root's config governs the rest, so `@/x` in + `apps/mobile/src/a.test.ts` resolves through `apps/mobile/tsconfig.json`. + A package-name `extends` or one that leaves the repository is not followed + and is named in the no-lane explanation. An extensionless JS/TS import (relative, a tsconfig/jsconfig `paths` alias or `baseUrl`) tries the exact path, then `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.mts`, `.cts`, then `index.ts`, `index.tsx`, `index.js`, `index.jsx` diff --git a/lib/pregate/import-graph.ts b/lib/pregate/import-graph.ts index 2445448c6b0..5d08ef36335 100644 --- a/lib/pregate/import-graph.ts +++ b/lib/pregate/import-graph.ts @@ -177,10 +177,10 @@ function normalize(p: string): string { return path.posix.normalize(p.replace(/\ /** One tsconfig/jsconfig `compilerOptions.paths` entry: `@/*` → [`./*`], already joined to its base. */ export interface PathAlias { prefix: string; suffix: string; wildcard: boolean; targets: string[] } -/** The effective `paths` of the root config, its `baseUrl` (repo-relative, or null) and what could not be read. */ +/** The effective `paths` of one config, its `baseUrl` (repo-relative, or null) and what could not be read. */ export interface PathAliases { aliases: PathAlias[]; baseUrl: string | null; notes: string[] } -/** How many relative `extends` hops are followed from the root tsconfig/jsconfig. */ +/** How many relative `extends` hops are followed from a tsconfig/jsconfig. */ export const MAX_TSCONFIG_EXTENDS = 4; /** JSONC → JSON: drop comments, and a comma whose next token closes an object or array, outside strings. */ @@ -213,7 +213,9 @@ interface ConfigOptions { baseUrl?: Located<string>; paths?: Located<Record<stri /** `baseUrl` and `paths` of one config after its relative `extends` chain (later entries and the config itself override). */ function effectiveOptions(repoRoot: string, rel: string, depth: number, seen: Set<string>, notes: string[]): ConfigOptions | null { let json: { extends?: unknown; compilerOptions?: { baseUrl?: unknown; paths?: unknown } }; - try { json = JSON.parse(stripJsonc(fs.readFileSync(path.join(repoRoot, rel), 'utf8'))) ?? {}; } catch { return null; } + const text = readRepoFile(repoRoot, rel); + if (text === null) return null; + try { json = JSON.parse(stripJsonc(text)) ?? {}; } catch { return null; } const dir = path.posix.dirname(rel); let options: ConfigOptions = {}; const parents = typeof json.extends === 'string' ? [json.extends] : Array.isArray(json.extends) ? json.extends.filter((e): e is string => typeof e === 'string') : []; @@ -234,16 +236,18 @@ function effectiveOptions(repoRoot: string, rel: string, depth: number, seen: Se } /** - * The root tsconfig.json (else jsconfig.json) `paths`, relative to the repo, - * following relative `extends` up to MAX_TSCONFIG_EXTENDS hops. Targets join + * The tsconfig.json (else jsconfig.json) `paths` in repo directory `dir` (the + * root by default), relative to the repo, following relative `extends` inside + * the repo up to MAX_TSCONFIG_EXTENDS hops. Targets join * `baseUrl` when one is set, else the directory of the config declaring * `paths`. What is not followed is recorded in `notes` for the no-lane * explanation; a missing alias leaves no edge (so `no lane`), never a wrong one. */ -export function readPathAliases(repoRoot: string): PathAliases { +export function readPathAliases(repoRoot: string, dir = '.'): PathAliases { for (const name of ['tsconfig.json', 'jsconfig.json']) { const notes: string[] = []; - const options = effectiveOptions(repoRoot, name, 0, new Set([name]), notes); + const rel = normalize(path.posix.join(dir, name)); + const options = effectiveOptions(repoRoot, rel, 0, new Set([rel]), notes); if (!options) continue; const baseUrl = options.baseUrl ? normalize(path.posix.join(options.baseUrl.dir, options.baseUrl.value)) : null; const base = baseUrl ?? options.paths?.dir ?? '.'; @@ -261,6 +265,40 @@ export function readPathAliases(repoRoot: string): PathAliases { const NO_ALIASES: PathAliases = { aliases: [], baseUrl: null, notes: [] }; +/** + * The aliases governing each file: those of the nearest nested tsconfig.json + * or jsconfig.json above it (its own directory first) that declares `paths` + * or `baseUrl`, itself or through `extends`, else the root config's. A nested + * config that declares neither defers upward, so a file never loses an alias + * the root gives it. With no nested config every file gets the root's. + */ +function pathAliasResolver(repoRoot: string, files: readonly string[]): { aliasesFor: (rel: string) => PathAliases; notes: string[] } { + const root = readPathAliases(repoRoot); + const notes = [...root.notes]; + const read = new Set<string>(); + const declaring = new Map<string, PathAliases>(); + for (const f of files) { + const dir = path.posix.dirname(f); + if (dir === '.' || read.has(dir) || !/^[tj]sconfig\.json$/.test(path.posix.basename(f))) continue; + read.add(dir); + const config = readPathAliases(repoRoot, dir); + for (const n of config.notes) if (!notes.includes(n)) notes.push(n); + if (config.aliases.length || config.baseUrl !== null) declaring.set(dir, config); + } + const byDir = new Map<string, PathAliases>(); + const aliasesFor = (rel: string): PathAliases => { + const start = path.posix.dirname(rel); + let hit = byDir.get(start); + if (hit) return hit; + let d = start; + while (d !== '.' && !declaring.has(d)) d = path.posix.dirname(d); + hit = declaring.get(d) ?? root; + byDir.set(start, hit); + return hit; + }; + return { aliasesFor, notes }; +} + /** * TypeScript's pattern choice: an exact pattern, else the matching wildcard * with the longest prefix. `chosen` is that pattern's expanded targets in @@ -483,8 +521,8 @@ export function buildGraph(repoRoot: string, opts: BuildOptions = {}): Graph { const files = new Set([...all, ...gone]); const dirs = new Set<string>(); for (const f of files) { let d = path.posix.dirname(f); while (d && d !== '.') { dirs.add(d); d = path.posix.dirname(d); } } - const config = readPathAliases(repoRoot); - const graph: Graph = { files, tests: new Set(all.filter(isTestFile)), reverse: new Map(), unresolved: new Map(), aliasNotes: config.notes }; + const aliases = pathAliasResolver(repoRoot, all); + const graph: Graph = { files, tests: new Set(all.filter(isTestFile)), reverse: new Map(), unresolved: new Map(), aliasNotes: aliases.notes }; const maxBytes = opts.maxBytes ?? 2 * 1024 * 1024; const packages = dartPackages(repoRoot, all); const pySources = new Map<string, string>(); @@ -494,7 +532,7 @@ export function buildGraph(repoRoot: string, opts: BuildOptions = {}): Graph { try { const st = fs.statSync(path.join(repoRoot, rel)); if (!st.isFile() || st.size > maxBytes) continue; source = fs.readFileSync(path.join(repoRoot, rel), 'utf8'); } catch { continue; } if (rel.endsWith('.py')) pySources.set(rel, source); const unresolved: string[] = []; - for (const { target, via } of referencesIn(files, dirs, rel, source, config, graph.tests.has(rel) ? unresolved : undefined, packages)) addEdge(graph, target, rel, via); + for (const { target, via } of referencesIn(files, dirs, rel, source, aliases.aliasesFor(rel), graph.tests.has(rel) ? unresolved : undefined, packages)) addEdge(graph, target, rel, via); if (unresolved.length) graph.unresolved!.set(rel, unresolved); } const rust = rustEdges(all, rel => readRepoFile(repoRoot, rel, maxBytes)); @@ -507,7 +545,7 @@ export function buildGraph(repoRoot: string, opts: BuildOptions = {}): Graph { const present = new Set(all); graph.goneSubjects = new Map(); for (const [rel, source] of opts.goneSources) { - const targets = [...referencesIn(files, dirs, rel, source, config, undefined, packages).map(r => r.target), ...conventionBins(rel, files)]; + const targets = [...referencesIn(files, dirs, rel, source, aliases.aliasesFor(rel), undefined, packages).map(r => r.target), ...conventionBins(rel, files)]; graph.goneSubjects.set(rel, [...new Set(targets)].filter(t => present.has(t) && !isTestFile(t) && !TEST_TREE.test(t)).sort()); } } diff --git a/test/pregate-import-graph-paths.test.ts b/test/pregate-import-graph-paths.test.ts index 2f9a9829304..f7586dd0d26 100644 --- a/test/pregate-import-graph-paths.test.ts +++ b/test/pregate-import-graph-paths.test.ts @@ -8,6 +8,8 @@ * — `@/…` was resolved as a repo path, so it never matched a file. */ import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; import { MAX_TSCONFIG_EXTENDS, buildGraph, testsFor } from '../lib/pregate/import-graph'; import { cleanup, commit, makeFixtureRepo, type FixtureRepo } from './helpers/pregate-fixture'; @@ -122,6 +124,88 @@ describe('import graph: route-group / dynamic-segment paths and tsconfig path al }); }); +describe('import graph: a nested tsconfig governs the files under it', () => { + // Value: protects=an `@/` import inside a monorepo app resolves through that app's own tsconfig `paths`, so its source maps to + // its tests; fails_when=only the root config is read again (every touched app file PREGATE_NO_LANE) or a nested extends leaves + // the repo; why_new=only root configs were tested (gstack#4462); seam=none; no_claim=TS project references, symlinked configs + test('an alias in a nested tsconfig maps a source file under it to the test that imports it', () => { + const repo = fixture(); + commit(repo, { + 'apps/mobile/tsconfig.json': '{ "extends": "expo/tsconfig.base", "compilerOptions": { "strict": true, "paths": { "@/*": ["./src/*"] } } }\n', + 'apps/mobile/src/media/close-bar.tsx': 'export const CloseBar = () => null;\n', + 'apps/mobile/src/media/close-bar.test.tsx': "import { CloseBar } from '@/media/close-bar';\nCloseBar;\n", + }); + const g = buildGraph(repo.work); + expect(testsFor(g, 'apps/mobile/src/media/close-bar.tsx').tests).toEqual(['apps/mobile/src/media/close-bar.test.tsx']); + expect(g.aliasNotes).toContain('apps/mobile/tsconfig.json extends expo/tsconfig.base: not a relative path, not followed'); + }); + + test('a nested config without paths or baseUrl defers to the root; a sibling app keeps its own alias', () => { + const repo = fixture(); + commit(repo, { + 'tsconfig.json': '{ "compilerOptions": { "paths": { "@/*": ["src/*"] } } }\n', + 'src/x.ts': 'export const x = "root";\n', + 'test/x.test.ts': "import { x } from '@/x';\nx;\n", + 'packages/core/tsconfig.json': '{ "compilerOptions": { "strict": true } }\n', + 'packages/core/test/x.test.ts': "import { x } from '@/x';\nx;\n", + 'apps/web/tsconfig.json': '{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["lib/*"] } } }\n', + 'apps/web/lib/x.ts': 'export const x = "web";\n', + 'apps/web/test/x.test.ts': "import { x } from '@/x';\nx;\n", + }); + const g = buildGraph(repo.work); + expect(testsFor(g, 'src/x.ts').tests).toEqual(['packages/core/test/x.test.ts', 'test/x.test.ts']); + expect(testsFor(g, 'apps/web/lib/x.ts').tests).toEqual(['apps/web/test/x.test.ts']); + }); + + test('a nested config takes paths through a relative extends, joined relative to the config that declares them', () => { + const repo = fixture(); + commit(repo, { + 'tsconfig.base.json': '{ "compilerOptions": { "paths": { "#core/*": ["packages/core/src/*"] } } }\n', + 'apps/api/tsconfig.json': '{ "extends": "../../tsconfig.base.json" }\n', + 'packages/core/src/plan.ts': 'export const plan = 1;\n', + 'apps/api/test/plan.test.ts': "import { plan } from '#core/plan';\nplan;\n", + }); + expect(testsFor(buildGraph(repo.work), 'packages/core/src/plan.ts').tests).toEqual(['apps/api/test/plan.test.ts']); + }); + + test('a repo whose only config is at the root resolves every file through the root config, as before', () => { + const repo = fixture(); + commit(repo, { + 'tsconfig.json': '{ "extends": "@tsconfig/node22", "compilerOptions": { "baseUrl": ".", "paths": { "~lib/*": ["lib/*"] } } }\n', + 'lib/plan.ts': 'export const plan = 1;\n', + 'apps/api/test/plan.test.ts': "import { plan } from '~lib/plan';\nplan;\n", + }); + const g = buildGraph(repo.work); + expect(g.aliasNotes).toEqual(['tsconfig.json extends @tsconfig/node22: not a relative path, not followed']); + expect(testsFor(g, 'lib/plan.ts').tests).toEqual(['apps/api/test/plan.test.ts']); + }); + + test('a nested extends that climbs out of the repository is not followed, even when the file exists there', () => { + const repo = fixture(); + fs.writeFileSync(path.join(repo.root, 'outside.json'), '{ "compilerOptions": { "paths": { "#core/*": ["packages/core/src/*"] } } }\n'); + commit(repo, { + 'apps/api/tsconfig.json': '{ "extends": "../../../outside.json" }\n', + 'packages/core/src/plan.ts': 'export const plan = 1;\n', + 'apps/api/test/plan.test.ts': "import { plan } from '#core/plan';\nplan;\n", + }); + const g = buildGraph(repo.work); + expect(testsFor(g, 'packages/core/src/plan.ts').tests).toEqual([]); + expect(g.aliasNotes).toEqual(['apps/api/tsconfig.json extends ../../../outside.json: outside the repo or a cycle, not followed']); + }); + + test.skipIf(process.platform === 'win32')('a nested tsconfig that is a symlink to a file outside the repository is not read', () => { + const repo = fixture(); + fs.writeFileSync(path.join(repo.root, 'outside.json'), '{ "compilerOptions": { "paths": { "#core/*": ["../../packages/core/src/*"] } } }\n'); + fs.mkdirSync(path.join(repo.work, 'apps', 'api'), { recursive: true }); + fs.symlinkSync(path.join(repo.root, 'outside.json'), path.join(repo.work, 'apps', 'api', 'tsconfig.json')); + commit(repo, { + 'packages/core/src/plan.ts': 'export const plan = 1;\n', + 'apps/api/test/plan.test.ts': "import { plan } from '#core/plan';\nplan;\n", + }); + expect(testsFor(buildGraph(repo.work), 'packages/core/src/plan.ts').tests).toEqual([]); + }); +}); + describe('import graph: alias precedence, extends and the no-lane explanation', () => { const twoAliases = (specificFirst: boolean) => { const specific = '"@/lib/*": ["src/lib/*"]'; From fc5c285035b58ce0552d25cf7cb71749795b6d30 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 06:47:26 +0800 Subject: [PATCH 52/62] /office-hours keeps its founder resources out of the skill file (GST-3024) (#4463) /office-hours no longer carries its 34 founder videos and essays in the skill file; the closing runs a new `gstack-founder-resources` command that prints the ones a user hasn't been shown yet. Why: the skill was 9 bytes from its size cap, and the approved partner-session improvements need room. This frees about 8.6 KB. Nothing to do as a reader. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=testing --- TODOS.md | 4 + bin/gstack-founder-resources | 35 ++++++ changelog.d/office-hours-resources-lookup.md | 1 + lib/founder-resources.ts | 71 ++++++++++++ office-hours/sections/design-and-handoff.md | 60 ++-------- .../sections/design-and-handoff.md.tmpl | 60 ++-------- test/fixtures/founder-resources-pool.txt | 43 ++++++++ test/founder-resources-bin.test.ts | 103 ++++++++++++++++++ test/founder-resources-optout.test.ts | 2 +- test/helpers/free-fixtures-data.ts | 1 + 10 files changed, 279 insertions(+), 101 deletions(-) create mode 100755 bin/gstack-founder-resources create mode 100644 changelog.d/office-hours-resources-lookup.md create mode 100644 lib/founder-resources.ts create mode 100644 test/fixtures/founder-resources-pool.txt create mode 100644 test/founder-resources-bin.test.ts diff --git a/TODOS.md b/TODOS.md index 3329db324d6..1303e4af3b2 100644 --- a/TODOS.md +++ b/TODOS.md @@ -2,6 +2,10 @@ ## NEXT PRIORITY +### P1: /office-hours parity pin after the resource move (filed 2026-11-17, GST-3024) + +- **Set the office-hours parity ratio in `test/helpers/carve-guards.ts` to the measured value.** The resource move (#4463) freed about 8.6 KB but left the pin at 1.1993. The content change that follows it sets the measured ratio with its reason; if that change slips, lower the pin on its own (a pin may go down freely). Deferred from plan: handoffs/office-hours-2026-11-17/plan.md (GStack Minder drive). **Effort:** S. **Priority:** P1. + ### P3: `/plan-eng-review` return follow-up (filed 2026-11-15, GST-2726) - **Decide whether `plan-eng-multi-finding-batching` rejoins the weekly lane.** The cut of the standalone skill (GST-1698) took it out through `PERIODIC_CI_EXCLUDE`, because /autoplan Phase 3 auto-decides findings. The standalone `/plan-eng-review` is back (GST-2726) and asks one question per eng finding again, so the case reaches a shipped entry. Running it weekly is paid spend, so the call belongs to the measurement plan in GST-1966. The standalone paid cases deleted with the cut (`plan-eng-plan-mode`, `plan-eng-finding-floor`, `plan-eng-review-artifact-full`) are not restored either. **Effort:** S. **Priority:** P3. diff --git a/bin/gstack-founder-resources b/bin/gstack-founder-resources new file mode 100755 index 00000000000..ce7bece391a --- /dev/null +++ b/bin/gstack-founder-resources @@ -0,0 +1,35 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * gstack-founder-resources — the office-hours founder-resource pool, served on demand. + * + * gstack-founder-resources [--shown <url,url,...>] + * + * Prints RESOURCES_TOTAL and RESOURCES_SHOWN_COUNT, then either + * `RESOURCES: exhausted` or every entry the user has not been shown yet, under + * its category header, exactly as the prompt used to carry it. Shown URLs come + * from the builder profile (`gstack-developer-profile --read`, RESOURCES_SHOWN) + * unless --shown is given; when the profile can't be read it prints + * `PROFILE_READ: failed` and treats nothing as shown, as the prompt did. + * Exit 0, or 2 on a usage error. Data: lib/founder-resources.ts. + */ +import * as path from 'node:path'; +import { renderIndex } from '../lib/founder-resources'; +import { runScriptSync } from '../lib/script-invocation'; + +const args = process.argv.slice(2); +const at = args.indexOf('--shown'); +if (args.length && !(at === 0 && args.length === 2)) { + process.stderr.write('usage: gstack-founder-resources [--shown <url,...>]\n'); + process.exit(args[0] === '--help' || args[0] === '-h' ? 0 : 2); +} + +let shown: string[] = []; +if (at === 0) { + shown = args[1]!.split(',').map(s => s.trim()).filter(Boolean); +} else { + const r = runScriptSync(path.join(import.meta.dir, 'gstack-developer-profile'), ['--read'], { encoding: 'utf8', timeout: 15_000 }); + const line = r.status === 0 ? (r.stdout ?? '').split('\n').find(l => l.startsWith('RESOURCES_SHOWN: ')) : undefined; + if (line === undefined) process.stdout.write('PROFILE_READ: failed\n'); + else shown = line.slice('RESOURCES_SHOWN: '.length).split(',').map(s => s.trim()).filter(Boolean); +} +process.stdout.write(renderIndex(shown)); diff --git a/changelog.d/office-hours-resources-lookup.md b/changelog.d/office-hours-resources-lookup.md new file mode 100644 index 00000000000..69a6bf2dfc9 --- /dev/null +++ b/changelog.d/office-hours-resources-lookup.md @@ -0,0 +1 @@ +- **/office-hours keeps its 34 founder videos and essays out of the skill file.** The list now lives in `lib/founder-resources.ts`, and the closing runs the new `gstack-founder-resources` command, which prints the ones a user hasn't been shown yet. The resources, the dedup and the opt-out work as before; the skill's own text is about 8.6 KB smaller. diff --git a/lib/founder-resources.ts b/lib/founder-resources.ts new file mode 100644 index 00000000000..a9f63f072cf --- /dev/null +++ b/lib/founder-resources.ts @@ -0,0 +1,71 @@ +/** + * The office-hours founder-resource pool (Phase 6 "Founder Resources"). + * + * The 34 entries used to sit inline in office-hours/sections/design-and-handoff.md. + * They live here now and bin/gstack-founder-resources prints the ones a user + * has not been shown yet, in the exact form the prompt carried. + * test/founder-resources-bin.test.ts checks the pool against + * test/fixtures/founder-resources-pool.txt, the prompt's last inline copy. + */ +export interface FounderResource { id: number; category: string; text: string } + +export const FOUNDER_RESOURCES: readonly FounderResource[] = [ + { id: 1, category: "GARRY TAN VIDEOS", text: "\"My $200 million startup mistake: Peter Thiel asked and I said no\" (5 min) — The single best \"why you should take the leap\" video. Peter Thiel writes him a check at dinner, he says no because he might get promoted to Level 60. That 1% stake would be worth $350-500M today. https://www.youtube.com/watch?v=dtnG0ELjvcM" }, + { id: 2, category: "GARRY TAN VIDEOS", text: "\"Unconventional Advice for Founders\" (48 min, Stanford) — The magnum opus. Covers everything a pre-launch founder needs: get therapy before your psychology kills your company, good ideas look like bad ideas, the Katamari Damacy metaphor for growth. No filler. https://www.youtube.com/watch?v=Y4yMc99fpfY" }, + { id: 3, category: "GARRY TAN VIDEOS", text: "\"The New Way To Build A Startup\" (8 min) — The 2026 playbook. Introduces the \"20x company\" — tiny teams beating incumbents through AI automation. Three real case studies. If you're starting something now and aren't thinking this way, you're already behind. https://www.youtube.com/watch?v=rWUWfj_PqmM" }, + { id: 4, category: "GARRY TAN VIDEOS", text: "\"How To Build The Future: Sam Altman\" (30 min) — Sam talks about what it takes to go from an idea to something real — picking what's important, finding your tribe, and why conviction matters more than credentials. https://www.youtube.com/watch?v=xXCBz_8hM9w" }, + { id: 5, category: "GARRY TAN VIDEOS", text: "\"What Founders Can Do To Improve Their Design Game\" (15 min) — Garry was a designer before he was an investor. Taste and craft are the real competitive advantage, not MBA skills or fundraising tricks. https://www.youtube.com/watch?v=ksGNfd-wQY4" }, + { id: 6, category: "YC BACKSTORY / HOW TO BUILD THE FUTURE", text: "\"Tom Blomfield: How I Created Two Billion-Dollar Fintech Startups\" (20 min) — Tom built Monzo from nothing into a bank used by 10% of the UK. The actual human journey — fear, mess, persistence. Makes founding feel like something a real person does. https://www.youtube.com/watch?v=QKPgBAnbc10" }, + { id: 7, category: "YC BACKSTORY / HOW TO BUILD THE FUTURE", text: "\"DoorDash CEO: Customer Obsession, Surviving Startup Death & Creating A New Market\" (30 min) — Tony started DoorDash by literally driving food deliveries himself. If you've ever thought \"I'm not the startup type,\" this will change your mind. https://www.youtube.com/watch?v=3N3TnaViyjk" }, + { id: 8, category: "LIGHTCONE PODCAST", text: "\"How to Spend Your 20s in the AI Era\" (40 min) — The old playbook (good job, climb the ladder) may not be the best path anymore. How to position yourself to build things that matter in an AI-first world. https://www.youtube.com/watch?v=ShYKkPPhOoc" }, + { id: 9, category: "LIGHTCONE PODCAST", text: "\"How Do Billion Dollar Startups Start?\" (25 min) — They start tiny, scrappy, and embarrassing. Demystifies the origin stories and shows that the beginning always looks like a side project, not a corporation. https://www.youtube.com/watch?v=HB3l1BPi7zo" }, + { id: 10, category: "LIGHTCONE PODCAST", text: "\"Billion-Dollar Unpopular Startup Ideas\" (25 min) — Uber, Coinbase, DoorDash — they all sounded terrible at first. The best opportunities are the ones most people dismiss. Liberating if your idea feels \"weird.\" https://www.youtube.com/watch?v=Hm-ZIiwiN1o" }, + { id: 11, category: "LIGHTCONE PODCAST", text: "\"Vertical AI Agents Could Be 10X Bigger Than SaaS\" (40 min) — The most-watched Lightcone episode. If you're building in AI, this is the landscape map — where the biggest opportunities are and why vertical agents win. https://www.youtube.com/watch?v=ASABxNenD_U" }, + { id: 12, category: "LIGHTCONE PODCAST", text: "\"The Truth About Building AI Startups Today\" (35 min) — Cuts through the hype. What's actually working, what's not, and where the real defensibility comes from in AI startups right now. https://www.youtube.com/watch?v=TwDJhUJL-5o" }, + { id: 13, category: "LIGHTCONE PODCAST", text: "\"Startup Ideas You Can Now Build With AI\" (30 min) — Concrete, actionable ideas for things that weren't possible 12 months ago. If you're looking for what to build, start here. https://www.youtube.com/watch?v=K4s6Cgicw_A" }, + { id: 14, category: "LIGHTCONE PODCAST", text: "\"Vibe Coding Is The Future\" (30 min) — Building software just changed forever. If you can describe what you want, you can build it. The barrier to being a technical founder has never been lower. https://www.youtube.com/watch?v=IACHfKmZMr8" }, + { id: 15, category: "LIGHTCONE PODCAST", text: "\"How To Get AI Startup Ideas\" (30 min) — Not theoretical. Walks through specific AI startup ideas that are working right now and explains why the window is open. https://www.youtube.com/watch?v=TANaRNMbYgk" }, + { id: 16, category: "LIGHTCONE PODCAST", text: "\"10 People + AI = Billion Dollar Company?\" (25 min) — The thesis behind the 20x company. Small teams with AI leverage are outperforming 100-person incumbents. If you're a solo builder or small team, this is your permission slip to think big. https://www.youtube.com/watch?v=CKvo_kQbakU" }, + { id: 17, category: "YC STARTUP SCHOOL", text: "\"Should You Start A Startup?\" (17 min, Harj Taggar) — Directly addresses the question most people are too afraid to ask out loud. Breaks down the real tradeoffs honestly, without hype. https://www.youtube.com/watch?v=BUE-icVYRFU" }, + { id: 18, category: "YC STARTUP SCHOOL", text: "\"How to Get and Evaluate Startup Ideas\" (30 min, Jared Friedman) — YC's most-watched Startup School video. How founders actually stumbled into their ideas by paying attention to problems in their own lives. https://www.youtube.com/watch?v=Th8JoIan4dg" }, + { id: 19, category: "YC STARTUP SCHOOL", text: "\"How David Lieb Turned a Failing Startup Into Google Photos\" (20 min) — His company Bump was dying. He noticed a photo-sharing behavior in his own data, and it became Google Photos (1B+ users). A masterclass in seeing opportunity where others see failure. https://www.youtube.com/watch?v=CcnwFJqEnxU" }, + { id: 20, category: "YC STARTUP SCHOOL", text: "\"Tips For Technical Startup Founders\" (15 min, Diana Hu) — How to leverage your engineering skills as a founder rather than thinking you need to become a different person. https://www.youtube.com/watch?v=rP7bpYsfa6Q" }, + { id: 21, category: "YC STARTUP SCHOOL", text: "\"Why Startup Founders Should Launch Companies Sooner Than They Think\" (12 min, Tyler Bosmeny) — Most builders over-prepare and under-ship. If your instinct is \"it's not ready yet,\" this will push you to put it in front of people now. https://www.youtube.com/watch?v=Nsx5RDVKZSk" }, + { id: 22, category: "YC STARTUP SCHOOL", text: "\"How To Talk To Users\" (20 min, Gustaf Alströmer) — You don't need sales skills. You need genuine conversations about problems. The most approachable tactical talk for someone who's never done it. https://www.youtube.com/watch?v=z1iF1c8w5Lg" }, + { id: 23, category: "YC STARTUP SCHOOL", text: "\"How To Find A Co-Founder\" (15 min, Harj Taggar) — The practical mechanics of finding someone to build with. If \"I don't want to do this alone\" is stopping you, this removes that blocker. https://www.youtube.com/watch?v=Fk9BCr5pLTU" }, + { id: 24, category: "YC STARTUP SCHOOL", text: "\"Should You Quit Your Job At A Unicorn?\" (12 min, Tom Blomfield) — Directly speaks to people at big tech companies who feel the pull to build something of their own. If that's your situation, this is the permission slip. https://www.youtube.com/watch?v=chAoH_AeGAg" }, + { id: 25, category: "PAUL GRAHAM ESSAYS", text: "\"How to Do Great Work\" — Not about startups. About finding the most meaningful work of your life. The roadmap that often leads to founding without ever saying \"startup.\" https://paulgraham.com/greatwork.html" }, + { id: 26, category: "PAUL GRAHAM ESSAYS", text: "\"How to Do What You Love\" — Most people keep their real interests separate from their career. Makes the case for collapsing that gap — which is usually how companies get born. https://paulgraham.com/love.html" }, + { id: 27, category: "PAUL GRAHAM ESSAYS", text: "\"The Bus Ticket Theory of Genius\" — The thing you're obsessively into that other people find boring? PG argues it's the actual mechanism behind every breakthrough. https://paulgraham.com/genius.html" }, + { id: 28, category: "PAUL GRAHAM ESSAYS", text: "\"Why to Not Not Start a Startup\" — Takes apart every quiet reason you have for not starting — too young, no idea, don't know business — and shows why none hold up. https://paulgraham.com/notnot.html" }, + { id: 29, category: "PAUL GRAHAM ESSAYS", text: "\"Before the Startup\" — Written specifically for people who haven't started anything yet. What to focus on now, what to ignore, and how to tell if this path is for you. https://paulgraham.com/before.html" }, + { id: 30, category: "PAUL GRAHAM ESSAYS", text: "\"Superlinear Returns\" — Some efforts compound exponentially; most don't. Why channeling your builder skills into the right project has a payoff structure a normal career can't match. https://paulgraham.com/superlinear.html" }, + { id: 31, category: "PAUL GRAHAM ESSAYS", text: "\"How to Get Startup Ideas\" — The best ideas aren't brainstormed. They're noticed. Teaches you to look at your own frustrations and recognize which ones could be companies. https://paulgraham.com/startupideas.html" }, + { id: 32, category: "PAUL GRAHAM ESSAYS", text: "\"Schlep Blindness\" — The best opportunities hide inside boring, tedious problems everyone avoids. If you're willing to tackle the unsexy thing you see up close, you might already be standing on a company. https://paulgraham.com/schlep.html" }, + { id: 33, category: "PAUL GRAHAM ESSAYS", text: "\"You Weren't Meant to Have a Boss\" — If working inside a big organization has always felt slightly wrong, this explains why. Small groups on self-chosen problems is the natural state for builders. https://paulgraham.com/boss.html" }, + { id: 34, category: "PAUL GRAHAM ESSAYS", text: "\"Relentlessly Resourceful\" — PG's two-word description of the ideal founder. Not \"brilliant.\" Not \"visionary.\" Just someone who keeps figuring things out. If that's you, you're already qualified. https://paulgraham.com/relres.html" }, +]; + +export const resourceUrl = (r: FounderResource): string => r.text.slice(r.text.lastIndexOf(' ') + 1); + +export function renderPool(entries: readonly FounderResource[] = FOUNDER_RESOURCES): string { + const out: string[] = []; + let category = ''; + for (const r of entries) { + if (r.category !== category) { + if (category) out.push(''); + out.push(`${r.category}:`); + category = r.category; + } + out.push(`${r.id}. ${r.text}`); + } + return out.join('\n') + '\n'; +} + +export function renderIndex(shownUrls: readonly string[]): string { + const shown = new Set(shownUrls); + const left = FOUNDER_RESOURCES.filter(r => !shown.has(resourceUrl(r))); + const head = [`RESOURCES_TOTAL: ${FOUNDER_RESOURCES.length}`, `RESOURCES_SHOWN_COUNT: ${FOUNDER_RESOURCES.length - left.length}`]; + if (!left.length) return [...head, 'RESOURCES: exhausted'].join('\n') + '\n'; + return [...head, `RESOURCES: ${left.length} not yet shown`, '', renderPool(left)].join('\n'); +} diff --git a/office-hours/sections/design-and-handoff.md b/office-hours/sections/design-and-handoff.md index e201e0c8530..bbf4ffac8d9 100644 --- a/office-hours/sections/design-and-handoff.md +++ b/office-hours/sections/design-and-handoff.md @@ -550,13 +550,19 @@ VERIFY the write (`gstack-config get founder_resources` must read back this session only. On success confirm in one line with the re-enable command and continue the handoff. -**Dedup check:** Read `RESOURCES_SHOWN` from the builder profile output above. -If `RESOURCES_SHOWN_COUNT` is 34 or more, skip this section entirely (all resources exhausted). -Otherwise, avoid selecting any URL that appears in the RESOURCES_SHOWN list. +**Resource pool and dedup check:** Print the resources this user hasn't been shown yet (it +reads `RESOURCES_SHOWN` from the builder profile itself), grouped by category, each as +`N. "Title" (length) — blurb. URL`: + +```bash +~/.claude/skills/gstack/bin/gstack-founder-resources +``` + +If it prints `RESOURCES: exhausted`, skip this section entirely (all resources shown). **Selection rules:** - Pick 2-3 resources. Mix categories — never 3 of the same type. -- Never pick a resource whose URL appears in the dedup log above. +- Pick only from the list above; it already leaves out everything shown before. - Match to session context (what came up matters more than random variety): - Hesitant about leaving their job → "My $200M Startup Mistake" or "Should You Quit Your Job At A Unicorn?" - Building an AI product → "The New Way To Build A Startup" or "Vertical AI Agents Could Be 10X Bigger Than SaaS" @@ -575,52 +581,6 @@ Otherwise, avoid selecting any URL that appears in the RESOURCES_SHOWN list. > {1-2 sentence blurb — direct, specific, encouraging. Match Garry's voice: tell them WHY this one matters for THEIR situation.} > {url} -**Resource Pool:** - -GARRY TAN VIDEOS: -1. "My $200 million startup mistake: Peter Thiel asked and I said no" (5 min) — The single best "why you should take the leap" video. Peter Thiel writes him a check at dinner, he says no because he might get promoted to Level 60. That 1% stake would be worth $350-500M today. https://www.youtube.com/watch?v=dtnG0ELjvcM -2. "Unconventional Advice for Founders" (48 min, Stanford) — The magnum opus. Covers everything a pre-launch founder needs: get therapy before your psychology kills your company, good ideas look like bad ideas, the Katamari Damacy metaphor for growth. No filler. https://www.youtube.com/watch?v=Y4yMc99fpfY -3. "The New Way To Build A Startup" (8 min) — The 2026 playbook. Introduces the "20x company" — tiny teams beating incumbents through AI automation. Three real case studies. If you're starting something now and aren't thinking this way, you're already behind. https://www.youtube.com/watch?v=rWUWfj_PqmM -4. "How To Build The Future: Sam Altman" (30 min) — Sam talks about what it takes to go from an idea to something real — picking what's important, finding your tribe, and why conviction matters more than credentials. https://www.youtube.com/watch?v=xXCBz_8hM9w -5. "What Founders Can Do To Improve Their Design Game" (15 min) — Garry was a designer before he was an investor. Taste and craft are the real competitive advantage, not MBA skills or fundraising tricks. https://www.youtube.com/watch?v=ksGNfd-wQY4 - -YC BACKSTORY / HOW TO BUILD THE FUTURE: -6. "Tom Blomfield: How I Created Two Billion-Dollar Fintech Startups" (20 min) — Tom built Monzo from nothing into a bank used by 10% of the UK. The actual human journey — fear, mess, persistence. Makes founding feel like something a real person does. https://www.youtube.com/watch?v=QKPgBAnbc10 -7. "DoorDash CEO: Customer Obsession, Surviving Startup Death & Creating A New Market" (30 min) — Tony started DoorDash by literally driving food deliveries himself. If you've ever thought "I'm not the startup type," this will change your mind. https://www.youtube.com/watch?v=3N3TnaViyjk - -LIGHTCONE PODCAST: -8. "How to Spend Your 20s in the AI Era" (40 min) — The old playbook (good job, climb the ladder) may not be the best path anymore. How to position yourself to build things that matter in an AI-first world. https://www.youtube.com/watch?v=ShYKkPPhOoc -9. "How Do Billion Dollar Startups Start?" (25 min) — They start tiny, scrappy, and embarrassing. Demystifies the origin stories and shows that the beginning always looks like a side project, not a corporation. https://www.youtube.com/watch?v=HB3l1BPi7zo -10. "Billion-Dollar Unpopular Startup Ideas" (25 min) — Uber, Coinbase, DoorDash — they all sounded terrible at first. The best opportunities are the ones most people dismiss. Liberating if your idea feels "weird." https://www.youtube.com/watch?v=Hm-ZIiwiN1o -11. "Vertical AI Agents Could Be 10X Bigger Than SaaS" (40 min) — The most-watched Lightcone episode. If you're building in AI, this is the landscape map — where the biggest opportunities are and why vertical agents win. https://www.youtube.com/watch?v=ASABxNenD_U -12. "The Truth About Building AI Startups Today" (35 min) — Cuts through the hype. What's actually working, what's not, and where the real defensibility comes from in AI startups right now. https://www.youtube.com/watch?v=TwDJhUJL-5o -13. "Startup Ideas You Can Now Build With AI" (30 min) — Concrete, actionable ideas for things that weren't possible 12 months ago. If you're looking for what to build, start here. https://www.youtube.com/watch?v=K4s6Cgicw_A -14. "Vibe Coding Is The Future" (30 min) — Building software just changed forever. If you can describe what you want, you can build it. The barrier to being a technical founder has never been lower. https://www.youtube.com/watch?v=IACHfKmZMr8 -15. "How To Get AI Startup Ideas" (30 min) — Not theoretical. Walks through specific AI startup ideas that are working right now and explains why the window is open. https://www.youtube.com/watch?v=TANaRNMbYgk -16. "10 People + AI = Billion Dollar Company?" (25 min) — The thesis behind the 20x company. Small teams with AI leverage are outperforming 100-person incumbents. If you're a solo builder or small team, this is your permission slip to think big. https://www.youtube.com/watch?v=CKvo_kQbakU - -YC STARTUP SCHOOL: -17. "Should You Start A Startup?" (17 min, Harj Taggar) — Directly addresses the question most people are too afraid to ask out loud. Breaks down the real tradeoffs honestly, without hype. https://www.youtube.com/watch?v=BUE-icVYRFU -18. "How to Get and Evaluate Startup Ideas" (30 min, Jared Friedman) — YC's most-watched Startup School video. How founders actually stumbled into their ideas by paying attention to problems in their own lives. https://www.youtube.com/watch?v=Th8JoIan4dg -19. "How David Lieb Turned a Failing Startup Into Google Photos" (20 min) — His company Bump was dying. He noticed a photo-sharing behavior in his own data, and it became Google Photos (1B+ users). A masterclass in seeing opportunity where others see failure. https://www.youtube.com/watch?v=CcnwFJqEnxU -20. "Tips For Technical Startup Founders" (15 min, Diana Hu) — How to leverage your engineering skills as a founder rather than thinking you need to become a different person. https://www.youtube.com/watch?v=rP7bpYsfa6Q -21. "Why Startup Founders Should Launch Companies Sooner Than They Think" (12 min, Tyler Bosmeny) — Most builders over-prepare and under-ship. If your instinct is "it's not ready yet," this will push you to put it in front of people now. https://www.youtube.com/watch?v=Nsx5RDVKZSk -22. "How To Talk To Users" (20 min, Gustaf Alströmer) — You don't need sales skills. You need genuine conversations about problems. The most approachable tactical talk for someone who's never done it. https://www.youtube.com/watch?v=z1iF1c8w5Lg -23. "How To Find A Co-Founder" (15 min, Harj Taggar) — The practical mechanics of finding someone to build with. If "I don't want to do this alone" is stopping you, this removes that blocker. https://www.youtube.com/watch?v=Fk9BCr5pLTU -24. "Should You Quit Your Job At A Unicorn?" (12 min, Tom Blomfield) — Directly speaks to people at big tech companies who feel the pull to build something of their own. If that's your situation, this is the permission slip. https://www.youtube.com/watch?v=chAoH_AeGAg - -PAUL GRAHAM ESSAYS: -25. "How to Do Great Work" — Not about startups. About finding the most meaningful work of your life. The roadmap that often leads to founding without ever saying "startup." https://paulgraham.com/greatwork.html -26. "How to Do What You Love" — Most people keep their real interests separate from their career. Makes the case for collapsing that gap — which is usually how companies get born. https://paulgraham.com/love.html -27. "The Bus Ticket Theory of Genius" — The thing you're obsessively into that other people find boring? PG argues it's the actual mechanism behind every breakthrough. https://paulgraham.com/genius.html -28. "Why to Not Not Start a Startup" — Takes apart every quiet reason you have for not starting — too young, no idea, don't know business — and shows why none hold up. https://paulgraham.com/notnot.html -29. "Before the Startup" — Written specifically for people who haven't started anything yet. What to focus on now, what to ignore, and how to tell if this path is for you. https://paulgraham.com/before.html -30. "Superlinear Returns" — Some efforts compound exponentially; most don't. Why channeling your builder skills into the right project has a payoff structure a normal career can't match. https://paulgraham.com/superlinear.html -31. "How to Get Startup Ideas" — The best ideas aren't brainstormed. They're noticed. Teaches you to look at your own frustrations and recognize which ones could be companies. https://paulgraham.com/startupideas.html -32. "Schlep Blindness" — The best opportunities hide inside boring, tedious problems everyone avoids. If you're willing to tackle the unsexy thing you see up close, you might already be standing on a company. https://paulgraham.com/schlep.html -33. "You Weren't Meant to Have a Boss" — If working inside a big organization has always felt slightly wrong, this explains why. Small groups on self-chosen problems is the natural state for builders. https://paulgraham.com/boss.html -34. "Relentlessly Resourceful" — PG's two-word description of the ideal founder. Not "brilliant." Not "visionary." Just someone who keeps figuring things out. If that's you, you're already qualified. https://paulgraham.com/relres.html - **After presenting resources — log to builder profile and offer to open:** 1. Log the selected resource URLs to the builder profile (single source of truth). diff --git a/office-hours/sections/design-and-handoff.md.tmpl b/office-hours/sections/design-and-handoff.md.tmpl index e9d57fe7a54..9e3c1b06feb 100644 --- a/office-hours/sections/design-and-handoff.md.tmpl +++ b/office-hours/sections/design-and-handoff.md.tmpl @@ -391,13 +391,19 @@ VERIFY the write (`gstack-config get founder_resources` must read back this session only. On success confirm in one line with the re-enable command and continue the handoff. -**Dedup check:** Read `RESOURCES_SHOWN` from the builder profile output above. -If `RESOURCES_SHOWN_COUNT` is 34 or more, skip this section entirely (all resources exhausted). -Otherwise, avoid selecting any URL that appears in the RESOURCES_SHOWN list. +**Resource pool and dedup check:** Print the resources this user hasn't been shown yet (it +reads `RESOURCES_SHOWN` from the builder profile itself), grouped by category, each as +`N. "Title" (length) — blurb. URL`: + +```bash +~/.claude/skills/gstack/bin/gstack-founder-resources +``` + +If it prints `RESOURCES: exhausted`, skip this section entirely (all resources shown). **Selection rules:** - Pick 2-3 resources. Mix categories — never 3 of the same type. -- Never pick a resource whose URL appears in the dedup log above. +- Pick only from the list above; it already leaves out everything shown before. - Match to session context (what came up matters more than random variety): - Hesitant about leaving their job → "My $200M Startup Mistake" or "Should You Quit Your Job At A Unicorn?" - Building an AI product → "The New Way To Build A Startup" or "Vertical AI Agents Could Be 10X Bigger Than SaaS" @@ -416,52 +422,6 @@ Otherwise, avoid selecting any URL that appears in the RESOURCES_SHOWN list. > {1-2 sentence blurb — direct, specific, encouraging. Match Garry's voice: tell them WHY this one matters for THEIR situation.} > {url} -**Resource Pool:** - -GARRY TAN VIDEOS: -1. "My $200 million startup mistake: Peter Thiel asked and I said no" (5 min) — The single best "why you should take the leap" video. Peter Thiel writes him a check at dinner, he says no because he might get promoted to Level 60. That 1% stake would be worth $350-500M today. https://www.youtube.com/watch?v=dtnG0ELjvcM -2. "Unconventional Advice for Founders" (48 min, Stanford) — The magnum opus. Covers everything a pre-launch founder needs: get therapy before your psychology kills your company, good ideas look like bad ideas, the Katamari Damacy metaphor for growth. No filler. https://www.youtube.com/watch?v=Y4yMc99fpfY -3. "The New Way To Build A Startup" (8 min) — The 2026 playbook. Introduces the "20x company" — tiny teams beating incumbents through AI automation. Three real case studies. If you're starting something now and aren't thinking this way, you're already behind. https://www.youtube.com/watch?v=rWUWfj_PqmM -4. "How To Build The Future: Sam Altman" (30 min) — Sam talks about what it takes to go from an idea to something real — picking what's important, finding your tribe, and why conviction matters more than credentials. https://www.youtube.com/watch?v=xXCBz_8hM9w -5. "What Founders Can Do To Improve Their Design Game" (15 min) — Garry was a designer before he was an investor. Taste and craft are the real competitive advantage, not MBA skills or fundraising tricks. https://www.youtube.com/watch?v=ksGNfd-wQY4 - -YC BACKSTORY / HOW TO BUILD THE FUTURE: -6. "Tom Blomfield: How I Created Two Billion-Dollar Fintech Startups" (20 min) — Tom built Monzo from nothing into a bank used by 10% of the UK. The actual human journey — fear, mess, persistence. Makes founding feel like something a real person does. https://www.youtube.com/watch?v=QKPgBAnbc10 -7. "DoorDash CEO: Customer Obsession, Surviving Startup Death & Creating A New Market" (30 min) — Tony started DoorDash by literally driving food deliveries himself. If you've ever thought "I'm not the startup type," this will change your mind. https://www.youtube.com/watch?v=3N3TnaViyjk - -LIGHTCONE PODCAST: -8. "How to Spend Your 20s in the AI Era" (40 min) — The old playbook (good job, climb the ladder) may not be the best path anymore. How to position yourself to build things that matter in an AI-first world. https://www.youtube.com/watch?v=ShYKkPPhOoc -9. "How Do Billion Dollar Startups Start?" (25 min) — They start tiny, scrappy, and embarrassing. Demystifies the origin stories and shows that the beginning always looks like a side project, not a corporation. https://www.youtube.com/watch?v=HB3l1BPi7zo -10. "Billion-Dollar Unpopular Startup Ideas" (25 min) — Uber, Coinbase, DoorDash — they all sounded terrible at first. The best opportunities are the ones most people dismiss. Liberating if your idea feels "weird." https://www.youtube.com/watch?v=Hm-ZIiwiN1o -11. "Vertical AI Agents Could Be 10X Bigger Than SaaS" (40 min) — The most-watched Lightcone episode. If you're building in AI, this is the landscape map — where the biggest opportunities are and why vertical agents win. https://www.youtube.com/watch?v=ASABxNenD_U -12. "The Truth About Building AI Startups Today" (35 min) — Cuts through the hype. What's actually working, what's not, and where the real defensibility comes from in AI startups right now. https://www.youtube.com/watch?v=TwDJhUJL-5o -13. "Startup Ideas You Can Now Build With AI" (30 min) — Concrete, actionable ideas for things that weren't possible 12 months ago. If you're looking for what to build, start here. https://www.youtube.com/watch?v=K4s6Cgicw_A -14. "Vibe Coding Is The Future" (30 min) — Building software just changed forever. If you can describe what you want, you can build it. The barrier to being a technical founder has never been lower. https://www.youtube.com/watch?v=IACHfKmZMr8 -15. "How To Get AI Startup Ideas" (30 min) — Not theoretical. Walks through specific AI startup ideas that are working right now and explains why the window is open. https://www.youtube.com/watch?v=TANaRNMbYgk -16. "10 People + AI = Billion Dollar Company?" (25 min) — The thesis behind the 20x company. Small teams with AI leverage are outperforming 100-person incumbents. If you're a solo builder or small team, this is your permission slip to think big. https://www.youtube.com/watch?v=CKvo_kQbakU - -YC STARTUP SCHOOL: -17. "Should You Start A Startup?" (17 min, Harj Taggar) — Directly addresses the question most people are too afraid to ask out loud. Breaks down the real tradeoffs honestly, without hype. https://www.youtube.com/watch?v=BUE-icVYRFU -18. "How to Get and Evaluate Startup Ideas" (30 min, Jared Friedman) — YC's most-watched Startup School video. How founders actually stumbled into their ideas by paying attention to problems in their own lives. https://www.youtube.com/watch?v=Th8JoIan4dg -19. "How David Lieb Turned a Failing Startup Into Google Photos" (20 min) — His company Bump was dying. He noticed a photo-sharing behavior in his own data, and it became Google Photos (1B+ users). A masterclass in seeing opportunity where others see failure. https://www.youtube.com/watch?v=CcnwFJqEnxU -20. "Tips For Technical Startup Founders" (15 min, Diana Hu) — How to leverage your engineering skills as a founder rather than thinking you need to become a different person. https://www.youtube.com/watch?v=rP7bpYsfa6Q -21. "Why Startup Founders Should Launch Companies Sooner Than They Think" (12 min, Tyler Bosmeny) — Most builders over-prepare and under-ship. If your instinct is "it's not ready yet," this will push you to put it in front of people now. https://www.youtube.com/watch?v=Nsx5RDVKZSk -22. "How To Talk To Users" (20 min, Gustaf Alströmer) — You don't need sales skills. You need genuine conversations about problems. The most approachable tactical talk for someone who's never done it. https://www.youtube.com/watch?v=z1iF1c8w5Lg -23. "How To Find A Co-Founder" (15 min, Harj Taggar) — The practical mechanics of finding someone to build with. If "I don't want to do this alone" is stopping you, this removes that blocker. https://www.youtube.com/watch?v=Fk9BCr5pLTU -24. "Should You Quit Your Job At A Unicorn?" (12 min, Tom Blomfield) — Directly speaks to people at big tech companies who feel the pull to build something of their own. If that's your situation, this is the permission slip. https://www.youtube.com/watch?v=chAoH_AeGAg - -PAUL GRAHAM ESSAYS: -25. "How to Do Great Work" — Not about startups. About finding the most meaningful work of your life. The roadmap that often leads to founding without ever saying "startup." https://paulgraham.com/greatwork.html -26. "How to Do What You Love" — Most people keep their real interests separate from their career. Makes the case for collapsing that gap — which is usually how companies get born. https://paulgraham.com/love.html -27. "The Bus Ticket Theory of Genius" — The thing you're obsessively into that other people find boring? PG argues it's the actual mechanism behind every breakthrough. https://paulgraham.com/genius.html -28. "Why to Not Not Start a Startup" — Takes apart every quiet reason you have for not starting — too young, no idea, don't know business — and shows why none hold up. https://paulgraham.com/notnot.html -29. "Before the Startup" — Written specifically for people who haven't started anything yet. What to focus on now, what to ignore, and how to tell if this path is for you. https://paulgraham.com/before.html -30. "Superlinear Returns" — Some efforts compound exponentially; most don't. Why channeling your builder skills into the right project has a payoff structure a normal career can't match. https://paulgraham.com/superlinear.html -31. "How to Get Startup Ideas" — The best ideas aren't brainstormed. They're noticed. Teaches you to look at your own frustrations and recognize which ones could be companies. https://paulgraham.com/startupideas.html -32. "Schlep Blindness" — The best opportunities hide inside boring, tedious problems everyone avoids. If you're willing to tackle the unsexy thing you see up close, you might already be standing on a company. https://paulgraham.com/schlep.html -33. "You Weren't Meant to Have a Boss" — If working inside a big organization has always felt slightly wrong, this explains why. Small groups on self-chosen problems is the natural state for builders. https://paulgraham.com/boss.html -34. "Relentlessly Resourceful" — PG's two-word description of the ideal founder. Not "brilliant." Not "visionary." Just someone who keeps figuring things out. If that's you, you're already qualified. https://paulgraham.com/relres.html - **After presenting resources — log to builder profile and offer to open:** 1. Log the selected resource URLs to the builder profile (single source of truth). diff --git a/test/fixtures/founder-resources-pool.txt b/test/fixtures/founder-resources-pool.txt new file mode 100644 index 00000000000..8d6531999cc --- /dev/null +++ b/test/fixtures/founder-resources-pool.txt @@ -0,0 +1,43 @@ +GARRY TAN VIDEOS: +1. "My $200 million startup mistake: Peter Thiel asked and I said no" (5 min) — The single best "why you should take the leap" video. Peter Thiel writes him a check at dinner, he says no because he might get promoted to Level 60. That 1% stake would be worth $350-500M today. https://www.youtube.com/watch?v=dtnG0ELjvcM +2. "Unconventional Advice for Founders" (48 min, Stanford) — The magnum opus. Covers everything a pre-launch founder needs: get therapy before your psychology kills your company, good ideas look like bad ideas, the Katamari Damacy metaphor for growth. No filler. https://www.youtube.com/watch?v=Y4yMc99fpfY +3. "The New Way To Build A Startup" (8 min) — The 2026 playbook. Introduces the "20x company" — tiny teams beating incumbents through AI automation. Three real case studies. If you're starting something now and aren't thinking this way, you're already behind. https://www.youtube.com/watch?v=rWUWfj_PqmM +4. "How To Build The Future: Sam Altman" (30 min) — Sam talks about what it takes to go from an idea to something real — picking what's important, finding your tribe, and why conviction matters more than credentials. https://www.youtube.com/watch?v=xXCBz_8hM9w +5. "What Founders Can Do To Improve Their Design Game" (15 min) — Garry was a designer before he was an investor. Taste and craft are the real competitive advantage, not MBA skills or fundraising tricks. https://www.youtube.com/watch?v=ksGNfd-wQY4 + +YC BACKSTORY / HOW TO BUILD THE FUTURE: +6. "Tom Blomfield: How I Created Two Billion-Dollar Fintech Startups" (20 min) — Tom built Monzo from nothing into a bank used by 10% of the UK. The actual human journey — fear, mess, persistence. Makes founding feel like something a real person does. https://www.youtube.com/watch?v=QKPgBAnbc10 +7. "DoorDash CEO: Customer Obsession, Surviving Startup Death & Creating A New Market" (30 min) — Tony started DoorDash by literally driving food deliveries himself. If you've ever thought "I'm not the startup type," this will change your mind. https://www.youtube.com/watch?v=3N3TnaViyjk + +LIGHTCONE PODCAST: +8. "How to Spend Your 20s in the AI Era" (40 min) — The old playbook (good job, climb the ladder) may not be the best path anymore. How to position yourself to build things that matter in an AI-first world. https://www.youtube.com/watch?v=ShYKkPPhOoc +9. "How Do Billion Dollar Startups Start?" (25 min) — They start tiny, scrappy, and embarrassing. Demystifies the origin stories and shows that the beginning always looks like a side project, not a corporation. https://www.youtube.com/watch?v=HB3l1BPi7zo +10. "Billion-Dollar Unpopular Startup Ideas" (25 min) — Uber, Coinbase, DoorDash — they all sounded terrible at first. The best opportunities are the ones most people dismiss. Liberating if your idea feels "weird." https://www.youtube.com/watch?v=Hm-ZIiwiN1o +11. "Vertical AI Agents Could Be 10X Bigger Than SaaS" (40 min) — The most-watched Lightcone episode. If you're building in AI, this is the landscape map — where the biggest opportunities are and why vertical agents win. https://www.youtube.com/watch?v=ASABxNenD_U +12. "The Truth About Building AI Startups Today" (35 min) — Cuts through the hype. What's actually working, what's not, and where the real defensibility comes from in AI startups right now. https://www.youtube.com/watch?v=TwDJhUJL-5o +13. "Startup Ideas You Can Now Build With AI" (30 min) — Concrete, actionable ideas for things that weren't possible 12 months ago. If you're looking for what to build, start here. https://www.youtube.com/watch?v=K4s6Cgicw_A +14. "Vibe Coding Is The Future" (30 min) — Building software just changed forever. If you can describe what you want, you can build it. The barrier to being a technical founder has never been lower. https://www.youtube.com/watch?v=IACHfKmZMr8 +15. "How To Get AI Startup Ideas" (30 min) — Not theoretical. Walks through specific AI startup ideas that are working right now and explains why the window is open. https://www.youtube.com/watch?v=TANaRNMbYgk +16. "10 People + AI = Billion Dollar Company?" (25 min) — The thesis behind the 20x company. Small teams with AI leverage are outperforming 100-person incumbents. If you're a solo builder or small team, this is your permission slip to think big. https://www.youtube.com/watch?v=CKvo_kQbakU + +YC STARTUP SCHOOL: +17. "Should You Start A Startup?" (17 min, Harj Taggar) — Directly addresses the question most people are too afraid to ask out loud. Breaks down the real tradeoffs honestly, without hype. https://www.youtube.com/watch?v=BUE-icVYRFU +18. "How to Get and Evaluate Startup Ideas" (30 min, Jared Friedman) — YC's most-watched Startup School video. How founders actually stumbled into their ideas by paying attention to problems in their own lives. https://www.youtube.com/watch?v=Th8JoIan4dg +19. "How David Lieb Turned a Failing Startup Into Google Photos" (20 min) — His company Bump was dying. He noticed a photo-sharing behavior in his own data, and it became Google Photos (1B+ users). A masterclass in seeing opportunity where others see failure. https://www.youtube.com/watch?v=CcnwFJqEnxU +20. "Tips For Technical Startup Founders" (15 min, Diana Hu) — How to leverage your engineering skills as a founder rather than thinking you need to become a different person. https://www.youtube.com/watch?v=rP7bpYsfa6Q +21. "Why Startup Founders Should Launch Companies Sooner Than They Think" (12 min, Tyler Bosmeny) — Most builders over-prepare and under-ship. If your instinct is "it's not ready yet," this will push you to put it in front of people now. https://www.youtube.com/watch?v=Nsx5RDVKZSk +22. "How To Talk To Users" (20 min, Gustaf Alströmer) — You don't need sales skills. You need genuine conversations about problems. The most approachable tactical talk for someone who's never done it. https://www.youtube.com/watch?v=z1iF1c8w5Lg +23. "How To Find A Co-Founder" (15 min, Harj Taggar) — The practical mechanics of finding someone to build with. If "I don't want to do this alone" is stopping you, this removes that blocker. https://www.youtube.com/watch?v=Fk9BCr5pLTU +24. "Should You Quit Your Job At A Unicorn?" (12 min, Tom Blomfield) — Directly speaks to people at big tech companies who feel the pull to build something of their own. If that's your situation, this is the permission slip. https://www.youtube.com/watch?v=chAoH_AeGAg + +PAUL GRAHAM ESSAYS: +25. "How to Do Great Work" — Not about startups. About finding the most meaningful work of your life. The roadmap that often leads to founding without ever saying "startup." https://paulgraham.com/greatwork.html +26. "How to Do What You Love" — Most people keep their real interests separate from their career. Makes the case for collapsing that gap — which is usually how companies get born. https://paulgraham.com/love.html +27. "The Bus Ticket Theory of Genius" — The thing you're obsessively into that other people find boring? PG argues it's the actual mechanism behind every breakthrough. https://paulgraham.com/genius.html +28. "Why to Not Not Start a Startup" — Takes apart every quiet reason you have for not starting — too young, no idea, don't know business — and shows why none hold up. https://paulgraham.com/notnot.html +29. "Before the Startup" — Written specifically for people who haven't started anything yet. What to focus on now, what to ignore, and how to tell if this path is for you. https://paulgraham.com/before.html +30. "Superlinear Returns" — Some efforts compound exponentially; most don't. Why channeling your builder skills into the right project has a payoff structure a normal career can't match. https://paulgraham.com/superlinear.html +31. "How to Get Startup Ideas" — The best ideas aren't brainstormed. They're noticed. Teaches you to look at your own frustrations and recognize which ones could be companies. https://paulgraham.com/startupideas.html +32. "Schlep Blindness" — The best opportunities hide inside boring, tedious problems everyone avoids. If you're willing to tackle the unsexy thing you see up close, you might already be standing on a company. https://paulgraham.com/schlep.html +33. "You Weren't Meant to Have a Boss" — If working inside a big organization has always felt slightly wrong, this explains why. Small groups on self-chosen problems is the natural state for builders. https://paulgraham.com/boss.html +34. "Relentlessly Resourceful" — PG's two-word description of the ideal founder. Not "brilliant." Not "visionary." Just someone who keeps figuring things out. If that's you, you're already qualified. https://paulgraham.com/relres.html diff --git a/test/founder-resources-bin.test.ts b/test/founder-resources-bin.test.ts new file mode 100644 index 00000000000..9d44d730a98 --- /dev/null +++ b/test/founder-resources-bin.test.ts @@ -0,0 +1,103 @@ +/** + * The office-hours founder-resource pool moved out of the prompt into + * lib/founder-resources.ts, printed by bin/gstack-founder-resources. These + * pins prove the command prints exactly what the prompt carried, minus what + * the user was already shown, and stops once everything has been shown. + */ +import { describe, expect, test } from 'bun:test'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { FOUNDER_RESOURCES, renderIndex, renderPool, resourceUrl } from '../lib/founder-resources'; +import { runScriptSync } from '../lib/script-invocation'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const FIXTURE = fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'founder-resources-pool.txt'), 'utf-8'); +const SECTION = fs.readFileSync(path.join(ROOT, 'office-hours', 'sections', 'design-and-handoff.md'), 'utf-8'); +const BIN = path.join(ROOT, 'bin', 'gstack-founder-resources'); + +describe('founder-resource pool', () => { + test('renders byte-for-byte the pool the prompt carried inline', () => { + expect(renderPool()).toBe(FIXTURE); + }); + + test('ids run 1..34 and every URL is distinct', () => { + expect(FOUNDER_RESOURCES.map(r => r.id)).toEqual(Array.from({ length: 34 }, (_, i) => i + 1)); + expect(new Set(FOUNDER_RESOURCES.map(resourceUrl)).size).toBe(34); + }); + + test('nothing shown prints the whole pool after the counts', () => { + expect(renderIndex([])).toBe(['RESOURCES_TOTAL: 34', 'RESOURCES_SHOWN_COUNT: 0', 'RESOURCES: 34 not yet shown', '', FIXTURE].join('\n')); + }); + + test('shown URLs are left out and only pool hits count', () => { + const out = renderIndex([resourceUrl(FOUNDER_RESOURCES[0]!), 'https://not-in-pool.example']); + expect(out).toContain('RESOURCES_SHOWN_COUNT: 1'); + expect(out).toContain('RESOURCES: 33 not yet shown'); + expect(out).not.toContain(resourceUrl(FOUNDER_RESOURCES[0]!)); + expect(out).toContain(`2. ${FOUNDER_RESOURCES[1]!.text}`); + }); + + test('exhausted once every resource has been shown', () => { + const out = renderIndex(FOUNDER_RESOURCES.map(resourceUrl)); + expect(out).toContain('RESOURCES_SHOWN_COUNT: 34'); + expect(out.trim().endsWith('RESOURCES: exhausted')).toBe(true); + }); +}); + +describe('gstack-founder-resources command', () => { + const run = (args: string[]) => runScriptSync(BIN, args, { encoding: 'utf8', timeout: 30_000 }); + + test('--shown filters the printed pool', () => { + const r = run(['--shown', `${resourceUrl(FOUNDER_RESOURCES[24]!)},${resourceUrl(FOUNDER_RESOURCES[33]!)}`]); + expect(r.status).toBe(0); + expect(r.stdout).toBe(renderIndex([resourceUrl(FOUNDER_RESOURCES[24]!), resourceUrl(FOUNDER_RESOURCES[33]!)])); + }); + + test('with no arguments it leaves out what the builder profile logged as shown', () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'founder-resources-')); + try { + const env = { ...process.env, GSTACK_STATE_ROOT: home, GSTACK_HOME: home }; + const shown = [resourceUrl(FOUNDER_RESOURCES[0]!), resourceUrl(FOUNDER_RESOURCES[9]!)]; + const session = JSON.stringify({ date: '2026-11-17', mode: 'startup', resources_shown: shown }); + expect(runScriptSync(path.join(ROOT, 'bin', 'gstack-developer-profile'), ['--log-session', session], { encoding: 'utf8', timeout: 30_000, env }).status).toBe(0); + const r = runScriptSync(BIN, [], { encoding: 'utf8', timeout: 30_000, env }); + expect(r.status).toBe(0); + expect(r.stdout).toBe(renderIndex(shown)); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + test('an unreadable builder profile prints PROFILE_READ: failed and the whole pool', () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'founder-resources-')); + try { + fs.writeFileSync(path.join(home, 'developer-profile.json'), 'not json'); + const r = runScriptSync(BIN, [], { encoding: 'utf8', timeout: 30_000, env: { ...process.env, GSTACK_STATE_ROOT: home, GSTACK_HOME: home } }); + expect(r.status).toBe(0); + expect(r.stdout).toBe('PROFILE_READ: failed\n' + renderIndex([])); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + test('unknown arguments are a usage error', () => { + const r = run(['show', '2']); + expect(r.status).toBe(2); + expect(r.stderr).toContain('usage: gstack-founder-resources'); + }); +}); + +describe('office-hours closing uses the command', () => { + test('the pool is no longer inlined in the generated section', () => { + for (const r of FOUNDER_RESOURCES) expect(SECTION).not.toContain(resourceUrl(r)); + }); + + test('the opt-out check runs before the command', () => { + const gate = SECTION.indexOf('gstack-config get founder_resources'); + const pool = SECTION.indexOf('bin/gstack-founder-resources'); + expect(gate).toBeGreaterThan(-1); + expect(pool).toBeGreaterThan(gate); + expect(SECTION).toContain('RESOURCES: exhausted'); + }); +}); diff --git a/test/founder-resources-optout.test.ts b/test/founder-resources-optout.test.ts index 8af21a97009..8e5cb6565cb 100644 --- a/test/founder-resources-optout.test.ts +++ b/test/founder-resources-optout.test.ts @@ -61,7 +61,7 @@ describe("office-hours section gates on the key (#538)", () => { test("the opt-out check precedes any resource content", () => { const gate = src.indexOf("gstack-config get founder_resources"); - const pool = src.indexOf("Resource Pool"); + const pool = src.indexOf("bin/gstack-founder-resources"); expect(gate).toBeGreaterThan(-1); expect(pool).toBeGreaterThan(-1); expect(gate).toBeLessThan(pool); diff --git a/test/helpers/free-fixtures-data.ts b/test/helpers/free-fixtures-data.ts index 13a6830af3c..726a5baf1df 100644 --- a/test/helpers/free-fixtures-data.ts +++ b/test/helpers/free-fixtures-data.ts @@ -151,6 +151,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = { 'test/fixtures/exercised-map-replay.json': ['scripts/exercised-map.ts'], 'test/fixtures/exit-propagation/**': ['test/exit-propagation.test.ts'], 'test/fixtures/factory-scorecard/**': ['test/factory-scorecard.test.ts'], + 'test/fixtures/founder-resources-pool.txt': ['test/founder-resources-bin.test.ts'], 'test/fixtures/free-shard-capture.ts': ['test/test-free-shards-capture.test.ts'], 'test/fixtures/gh-poll/**': ['test/gh-poll.test.ts'], 'test/fixtures/golden/**': ['test/host-config.test.ts', 'test/ship-review-loop.test.ts'], From d3d35019a07e010c9411030377ec79aa7f6aae0b Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 06:56:51 +0800 Subject: [PATCH 53/62] Tests and scratch repositories can no longer write approval rows into a real Capy Drive (GST-3027) (#4466) Tests and scratch repositories in the temp directory can no longer write approval rows into your real Capy Drive. When `gstack-approvals` runs under `bun test`, or its state root or repository sits in the temp directory, a Drive mirror that resolves outside the temp directory (links followed) is refused with `APPROVAL_RECORD_WRITE_FAILED`; the local row is kept. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team --- .../approvals-mirror-stays-inside-fixtures.md | 1 + docs/troubleshooting.md | 6 ++- lib/approval-record.ts | 51 +++++++++++++++---- test/approval-record.test.ts | 32 ++++++++++++ 4 files changed, 80 insertions(+), 10 deletions(-) create mode 100644 changelog.d/approvals-mirror-stays-inside-fixtures.md diff --git a/changelog.d/approvals-mirror-stays-inside-fixtures.md b/changelog.d/approvals-mirror-stays-inside-fixtures.md new file mode 100644 index 00000000000..33f60aeba15 --- /dev/null +++ b/changelog.d/approvals-mirror-stays-inside-fixtures.md @@ -0,0 +1 @@ +- **A test, or a scratch repository in the temp directory, can no longer write approval rows into your real Capy Drive (GST-3027).** On Capy, `gstack-approvals` mirrors every row to a Drive folder. When it runs under `bun test`, or its state root or repository sits in the temp directory, the mirror now has to resolve, links followed, inside that temp directory; otherwise the write fails with `APPROVAL_RECORD_WRITE_FAILED`, names the path it refused, keeps the local row and reads no rows from that Drive. A review probe on 2026-11-09 had written three QA rows into a real project-user Drive this way. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index d6a0c68cae1..f56f2ee8e9e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2201,9 +2201,13 @@ and, as `READ_ALSO:`, the other roots it still reads (a row mirrored before the **Meaning.** The local record or its Drive mirror could not be written; the line names the path and the error. A failed local append wrote nothing. A failed mirror write -leaves the local row in place. Exit 1. +leaves the local row in place. Exit 1. A fixture (a run under `bun test`, or a state root or +repository in the temp directory) also gets this when its mirror resolves outside the temp +directory: the line says `outside the temp root`, and nothing reaches that Drive. **Fix.** Make the named directory writable, then rerun `gstack-approvals sync` to mirror again. +For a fixture, point `HOME` or `GSTACK_APPROVALS_DIR` inside its temp directory, or set +`GSTACK_APPROVALS_MIRROR=0`. <a id="approval-import-unanswered"></a> ### `gstack-approvals import: ... (APPROVAL_IMPORT_UNANSWERED)` diff --git a/lib/approval-record.ts b/lib/approval-record.ts index f28373a3991..a1f8f2be2c4 100644 --- a/lib/approval-record.ts +++ b/lib/approval-record.ts @@ -20,8 +20,10 @@ * (`~/.capy/drive/captain-<name>/approvals/<slug>/<branch key>.jsonl`, which every * crew thread can read), else to the private project-user Drive folder * (`<drive>/approvals/<slug>/<branch key>.jsonl`). GSTACK_APPROVALS_MIRROR=0 - * turns the mirror off. Reads take the union of both. Every field passes the - * secret scanner before anything is written. + * turns the mirror off. Reads take the union of both. A fixture (bun test, or a + * state root or repository in the temp directory) only mirrors inside the temp + * directory, links resolved. Every field passes the secret scanner before + * anything is written. */ import { createHash } from 'node:crypto'; import { spawnSync } from 'node:child_process'; @@ -50,7 +52,8 @@ export interface ApprovalRow { } export type MirrorSource = 'GSTACK_APPROVALS_DIR' | 'captain drive' | 'project-user drive'; /** `mirror` is written and read; `read_also` are the other mirror roots' copies, read so a row mirrored under an earlier rule stays visible. */ -export interface StoreLocation { file: string; mirror?: string; mirror_source?: MirrorSource; read_also?: string[]; branch: string; slug: string; ephemeral: boolean } +/** `mirror_refused` names a mirror a fixture would have written outside its temp root; the write then fails and nothing reaches that Drive. */ +export interface StoreLocation { file: string; mirror?: string; mirror_source?: MirrorSource; read_also?: string[]; mirror_refused?: string; branch: string; slug: string; ephemeral: boolean } export interface RecordError { code: ResultCodeName; message: string } export type Env = NodeJS.ProcessEnv; @@ -72,6 +75,26 @@ function contained(root: string, file: string): boolean { return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel); } +/** Where a path really lands: the nearest existing ancestor with its links resolved, plus the rest of the path. */ +function resolvedTarget(p: string): string { + const rest: string[] = []; + for (let cur = path.resolve(p); ; cur = path.dirname(cur)) { + try { return path.join(fs.realpathSync(cur), ...rest.reverse()); } catch { if (path.dirname(cur) === cur) return path.resolve(p); rest.push(path.basename(cur)); } + } +} + +/** + * Why this run is a fixture, or undefined: under bun test, or with its state root or repository in the temp directory. + * A fixture's mirror must resolve inside that temp root, so a test or a probe in a scratch repository never writes + * the owner's real Drive (GST-3027: a review probe wrote approvals/fx/qa-fixture-*.jsonl into a project-user Drive). + */ +function fixtureReason(env: Env, stateRoot: string, toplevel: string | undefined, tmpRoot: string): string | undefined { + if (env.NODE_ENV === 'test') return 'running under bun test'; + if (contained(tmpRoot, resolvedTarget(stateRoot))) return `the state root ${stateRoot} is a temporary fixture`; + if (toplevel && contained(tmpRoot, resolvedTarget(toplevel))) return `the repository ${toplevel} is a temporary fixture`; + return undefined; +} + /** Where this branch's record lives, and its mirror. */ export function locate(o: { cwd: string; env: Env; branch?: string }): StoreLocation | RecordError { let branch = o.branch?.trim(); @@ -87,21 +110,30 @@ export function locate(o: { cwd: string; env: Env; branch?: string }): StoreLoca if (!contained(stateRoot, file)) return { code: 'APPROVAL_RECORD_INVALID', message: `record path escapes the state root: ${file}` }; // Every mirror root this machine can see, best first; the first is written, the rest are read so a // row mirrored before the Captain created approvals/ (or under an explicit directory) stays visible. - const roots: Array<[MirrorSource, string]> = []; + let toplevel: string | undefined | null = null; + const repoTop = () => { if (toplevel === null) { const top = git(o.cwd, ['rev-parse', '--show-toplevel']); toplevel = top.status === 0 ? top.stdout.trim() : undefined; } return toplevel; }; + let roots: Array<[MirrorSource, string]> = []; if (o.env.GSTACK_APPROVALS_DIR) roots.push(['GSTACK_APPROVALS_DIR', o.env.GSTACK_APPROVALS_DIR]); if (o.env.GSTACK_CAPY === '1' && o.env.GSTACK_APPROVALS_MIRROR !== '0') { const captain = captainApprovalsDir(o.env); if (captain) roots.push(['captain drive', captain]); - const top = git(o.cwd, ['rev-parse', '--show-toplevel']); - const folder = capyDriveFolder(o.env, top.status === 0 ? path.basename(top.stdout.trim()) : undefined); + const folder = capyDriveFolder(o.env, repoTop() ? path.basename(repoTop()!) : undefined); if (folder) roots.push(['project-user drive', path.join(path.dirname(folder), 'approvals')]); } const rel = path.join(slug, `${branchKey(branch)}.jsonl`); for (const [, root] of roots) if (!contained(root, path.join(root, rel))) return { code: 'APPROVAL_RECORD_INVALID', message: `mirror path escapes ${root}` }; - const [chosen, ...rest] = roots; + let mirror_refused: string | undefined; + if (roots.length) { + const tmpRoot = resolvedTarget(os.tmpdir()); + const fixture = fixtureReason(o.env, stateRoot, repoTop(), tmpRoot); + const escapes = ([, root]: [MirrorSource, string]) => !contained(tmpRoot, resolvedTarget(path.join(root, rel))); + if (fixture && escapes(roots[0]!)) mirror_refused = `mirror ${path.join(roots[0]![1], rel)} (${roots[0]![0]}) resolves to ${resolvedTarget(path.join(roots[0]![1], rel))}, outside the temp root ${tmpRoot}, and ${fixture}; a fixture never writes a real Drive, so point HOME or GSTACK_APPROVALS_DIR inside the fixture or set GSTACK_APPROVALS_MIRROR=0 (the local row is kept)`; + if (fixture) roots = roots.filter(r => !escapes(r)); + } + const [chosen, ...rest] = mirror_refused ? [undefined, ...roots] : roots; return { - file, mirror: chosen ? path.join(chosen[1], rel) : undefined, mirror_source: chosen?.[0], read_also: rest.map(([, root]) => path.join(root, rel)), - branch, slug, ephemeral: o.env.GSTACK_EPHEMERAL === '1', + file, mirror: chosen ? path.join(chosen[1], rel) : undefined, mirror_source: chosen?.[0], read_also: rest.map(r => path.join(r![1], rel)), + ...(mirror_refused ? { mirror_refused } : {}), branch, slug, ephemeral: o.env.GSTACK_EPHEMERAL === '1', }; } @@ -189,6 +221,7 @@ export function buildRow(input: NewRow, branch: string, now = new Date(), runId? } function writeMirror(loc: StoreLocation, rows: ApprovalRow[]): RecordError | undefined { + if (loc.mirror_refused) return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: loc.mirror_refused }; if (!loc.mirror) return undefined; try { fs.mkdirSync(path.dirname(loc.mirror), { recursive: true, mode: 0o700 }); diff --git a/test/approval-record.test.ts b/test/approval-record.test.ts index e12b5070154..701d273b24f 100644 --- a/test/approval-record.test.ts +++ b/test/approval-record.test.ts @@ -410,6 +410,38 @@ describe('Capy mirror', () => { expect(bin(['sync'], { cwd, env: { GSTACK_STATE_ROOT: fresh, GSTACK_APPROVALS_DIR: mirror } }).out).toMatch(/^APPROVAL_SYNCED: rows=1 /); }); + test('a fixture never mirrors into a Drive outside its temp root, through a symlink either (GST-3027)', () => { + const base = tmp('appr-fixture-'); + const fixtureTmp = path.join(base, 'tmp'); const real = path.join(base, 'real-home'); + const realDrive = path.join(real, '.capy', 'drive', 'project-user-gstack-dana'); + fs.mkdirSync(fixtureTmp, { recursive: true }); fs.mkdirSync(realDrive, { recursive: true }); + const fixtureRepo = () => { const d = fs.mkdtempSync(path.join(fixtureTmp, 'fx-')); spawnSync('git', ['init', '-q', '-b', 'qa-fixture'], { cwd: d, timeout: 30_000 }); return d; }; + const realFiles = () => fs.readdirSync(realDrive, { recursive: true }).filter(f => String(f).endsWith('.jsonl')); + const linkedHome = path.join(fixtureTmp, 'linked-home'); + fs.mkdirSync(path.join(linkedHome, '.capy'), { recursive: true }); + if (process.platform !== 'win32') fs.symlinkSync(path.join(real, '.capy', 'drive'), path.join(linkedHome, '.capy', 'drive'), 'dir'); + const cases: Array<[string, Record<string, string>]> = [ + ['fixture repository, real state root', { NODE_ENV: '', HOME: real, GSTACK_STATE_ROOT: path.join(real, '.gstack') }], + ['fixture state root', { NODE_ENV: '', HOME: real, GSTACK_STATE_ROOT: path.join(fixtureTmp, 'state') }], + ['explicit mirror directory', { NODE_ENV: '', HOME: path.join(fixtureTmp, 'home'), GSTACK_STATE_ROOT: path.join(fixtureTmp, 'state'), GSTACK_APPROVALS_DIR: path.join(realDrive, 'approvals') }], + ...(process.platform === 'win32' ? [] : [['Drive linked out of the fixture', { NODE_ENV: '', HOME: linkedHome, GSTACK_STATE_ROOT: path.join(fixtureTmp, 'state') }] as [string, Record<string, string>]]), + ]; + for (const [name, env] of cases) { + const r = bin(['add', '--ask', 'Spend cap', '--words', 'do it', '--by', 'QA', '--scope', 'spend cap'], { cwd: fixtureRepo(), env: { TMPDIR: fixtureTmp, GSTACK_CAPY: '1', ...env } }); + expect({ name, status: r.status }).toEqual({ name, status: 1 }); + expect(r.err).toContain('(APPROVAL_RECORD_WRITE_FAILED)'); + expect(r.err).toContain('outside the temp root'); + expect({ name, written: realFiles() }).toEqual({ name, written: [] }); + } + const underTest = bin(['add', '--ask', 'Spend cap', '--words', 'do it', '--by', 'QA', '--scope', 'spend cap'], { cwd: ROOT, env: { TMPDIR: fixtureTmp, NODE_ENV: 'test', GSTACK_CAPY: '1', HOME: real, GSTACK_STATE_ROOT: path.join(real, '.gstack'), GSTACK_PROJECT_SLUG: 'acme-widgets' } }); + expect(underTest.err).toContain('outside the temp root'); + expect(realFiles()).toEqual([]); + const inside = path.join(fixtureTmp, 'home'); fs.mkdirSync(path.join(inside, '.capy', 'drive', 'project-user-gstack-qa'), { recursive: true }); + const ok = bin(['add', '--ask', 'Spend cap', '--words', 'do it', '--by', 'QA', '--scope', 'spend cap'], { cwd: fixtureRepo(), env: { TMPDIR: fixtureTmp, NODE_ENV: '', GSTACK_CAPY: '1', HOME: inside, GSTACK_STATE_ROOT: path.join(fixtureTmp, 'state') } }); + expect(ok.status).toBe(0); + expect(ok.out).toContain(`mirror=${path.join(inside, '.capy', 'drive', 'project-user-gstack-qa', 'approvals', 'acme-widgets')}`); + }); + test('an ephemeral state root with no record and no mirror is unavailable, not empty', () => { const r = bin(['render'], { cwd: repo(), env: { GSTACK_STATE_ROOT: tmp('appr-state-'), GSTACK_EPHEMERAL: '1', HOME: tmp('appr-home-') } }); expect(r.status).toBe(1); From 0b656a171d649c630c8af18cf3fa3c16f4cc542b Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 07:13:14 +0800 Subject: [PATCH 54/62] Check a question against the owner's earlier answers before asking it again (GST-3025) (#4467) An agent can now check a draft question against the owner's earlier answers before sending it, so the owner isn't asked again about something they already said yes to. Why: owners repeat "don't ask me, just do it" across threads, because each new session forgets earlier answers. In a four-day sample, about 1% of 444 asks were repeats this could skip, so a two-week pilot decides whether it's kept. Nothing to do: the new command is opt-in, and no existing command, install output or factory rule changes. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/specialist-batched#2 reader=state-machines Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p3/outside-voice#1 reader=outside-voice Review-Finding: p3/outside-voice#2 reader=outside-voice --- bin/gstack-doctor-components.sh | 9 + bin/gstack-owner-answers | 164 ++++++++++++ changelog.d/owner-answers-record.md | 4 + docs/owner-answers.md | 201 ++++++++++++++ docs/troubleshooting.md | 68 +++++ lib/owner-answers.ts | 393 ++++++++++++++++++++++++++++ lib/result-codes-capy.ts | 45 ++++ test/owner-answers.test.ts | 329 +++++++++++++++++++++++ 8 files changed, 1213 insertions(+) create mode 100755 bin/gstack-owner-answers create mode 100644 changelog.d/owner-answers-record.md create mode 100644 docs/owner-answers.md create mode 100644 lib/owner-answers.ts create mode 100644 test/owner-answers.test.ts diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index 2b5bb7d3251..ee78184e68f 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -378,6 +378,15 @@ gstack_result_anchor() { APPROVAL_RECORD_UNAVAILABLE) printf '%s' 'approval-record-unavailable' ;; APPROVAL_RECORD_WRITE_FAILED) printf '%s' 'approval-record-write-failed' ;; APPROVAL_IMPORT_UNANSWERED) printf '%s' 'approval-import-unanswered' ;; + OWNER_ANSWERS_NO_DRIVE) printf '%s' 'owner-answers-no-drive' ;; + OWNER_ANSWERS_AMBIGUOUS) printf '%s' 'owner-answers-ambiguous' ;; + OWNER_ANSWERS_INVALID) printf '%s' 'owner-answers-invalid' ;; + OWNER_ANSWERS_SECRET) printf '%s' 'owner-answers-secret' ;; + OWNER_ANSWERS_WRITE_FAILED) printf '%s' 'owner-answers-write-failed' ;; + OWNER_ANSWERS_NOT_FOUND) printf '%s' 'owner-answers-not-found' ;; + OWNER_ANSWERS_CONFLICT) printf '%s' 'owner-answers-conflict' ;; + OWNER_ANSWERS_SELF_VERIFY) printf '%s' 'owner-answers-self-verify' ;; + OWNER_ANSWERS_NOT_TAKEABLE) printf '%s' 'owner-answers-not-takeable' ;; CAPTAIN_BRIEF_INCOMPLETE) printf '%s' 'captain-brief-incomplete' ;; PR_SHOTS_INPUT_NOT_FOUND) printf '%s' 'pr-shots-input-not-found' ;; PR_SHOTS_INPUT_REFUSED) printf '%s' 'pr-shots-input-refused' ;; diff --git a/bin/gstack-owner-answers b/bin/gstack-owner-answers new file mode 100755 index 00000000000..e4a0358a5df --- /dev/null +++ b/bin/gstack-owner-answers @@ -0,0 +1,164 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * gstack-owner-answers — the owner's record of answers and standing yeses, read before any ask to the + * owner (docs/owner-answers.md). Logic: lib/owner-answers.ts. + * + * gstack-owner-answers add --action <token> --target <token> --words <their exact words> --thread <code> --event <id> + * --by <who records it> [--kind standing-yes|decision|preference|ruling-ref] [--scope all|repo:<o/n>|captain:<name>] + * [--limits <text>] [--words-by owner|agent:<id>] [--rule R<n>] [--asked <the ask it answered>] [--json] + * gstack-owner-answers supersede <row id> (the add flags) | revoke <row id> --words <…> --thread <code> --event <id> --by <who> + * gstack-owner-answers verify <row id> --event <the source event it read> --by <a second actor> + * gstack-owner-answers check --ask-file <file> [--all] [--json] related answers per ask line (advisory) + * gstack-owner-answers screen --ask-file <file> [--json] KEEP or PROPOSE_TAKE per line; never edits the ask + * gstack-owner-answers log --thread <code> --line <letter> --decision taken|asked [--row <id>] --by <who> + * gstack-owner-answers list [--all] [--json] | status + * Every command takes [--owner <name>] (on Capy: which user-<name> Drive folder, when more than one is mounted). + */ +import * as fs from 'node:fs'; +import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; +import { resultLine } from '../lib/result-codes'; +import { + addAnswer, buildAnswer, currentRows, isAnswerError, logDecision, notTakeable, parseAskFile, rankRows, readStore, resolveStore, + screenAsks, takenLine, verifyAnswer, type AnswerError, type NewAnswer, type OwnerAnswer, type Store, +} from '../lib/owner-answers'; + +const HELP = `gstack-owner-answers — the owner's answers and standing yeses, checked before any ask (docs/owner-answers.md) + + add --action <token> --target <token> --words <the owner's exact words> --thread <code> --event <id> --by <who records it> + [--kind standing-yes|decision|preference|ruling-ref] [--scope all|repo:<owner>/<name>|captain:<name>] [--limits <text>] + [--words-by owner|agent:<id>] [--rule R<n>] [--asked <the ask it answered>] + one row, written once; --words-by defaults to agent:<by>, and only owner rows can ever be taken + supersede <row id> (add's flags) a new row that replaces <row id> + revoke <row id> --words <the owner's words> --thread <code> --event <id> --by <who> the row stops counting + verify <row id> --event <id> --by <who> a second actor reads the cited source event, names it, and confirms it + holds the row's words; the recorder cannot + check --ask-file <file> [--all] related answers per ask line, ranked by shared words (advisory; never a take) + screen --ask-file <file> per line: KEEP <reason> or PROPOSE_TAKE <row id>, with the line the Captain adds when it + confirms the take; the ask file is never edited. A take needs origin "captain", a typed action, target and scope, + no fresh-ask class, and a verified, current, unlimited standing-yes row matching exactly + log --thread <code> --line <letter> --decision taken|asked [--row <id>] --by <who> the thread's own log line + list [--all] current rows (--all adds superseded and revoked ones) + status where the record is, how many rows, how many can be taken, and any problem + Every command takes [--owner <name>] and [--json] where it prints rows. + +${exitTableHelp()}`; + +const VALUE_FLAGS = new Set(['--action', '--target', '--words', '--thread', '--event', '--by', '--kind', '--scope', '--limits', '--words-by', '--rule', '--asked', '--ask-file', '--line', '--decision', '--row', '--owner']); + +function parse(args: string[]): { pos: string[]; flags: Record<string, string>; bools: Set<string>; error?: string } { + const pos: string[] = []; const flags: Record<string, string> = {}; const bools = new Set<string>(); + for (let i = 0; i < args.length; i++) { + const a = args[i]!; + if (VALUE_FLAGS.has(a)) { + const v = args[i + 1]; + if (v === undefined) return { pos, flags, bools, error: `${a} needs a value` }; + flags[a] = v; i++; + } else if (a === '--json' || a === '--all') bools.add(a); + else if (a.startsWith('--')) return { pos, flags, bools, error: `unknown argument ${a}` }; + else pos.push(a); + } + return { pos, flags, bools }; +} + +function fail(cmd: string, e: AnswerError): number { + process.stderr.write(resultLine(`gstack-owner-answers ${cmd}`, e.code, e.message) + '\n'); + if (e.code === 'OWNER_ANSWERS_INVALID') return EXIT.usage; + if (e.code === 'OWNER_ANSWERS_WRITE_FAILED') return EXIT.fail; + return EXIT.refused; +} + +const newAnswer = (f: Record<string, string>, extra: Partial<NewAnswer> = {}): NewAnswer => ({ + kind: f['--kind'], action: f['--action'], target: f['--target'], scope: f['--scope'], limits: f['--limits'], words: f['--words'], + words_by: f['--words-by'], thread: f['--thread'], event: f['--event'], rule: f['--rule'], asked: f['--asked'], by: f['--by'], ...extra, +}); + +const brief = (r: OwnerAnswer) => `${r.id} ${r.kind} ${r.action || '-'} ${r.target || '-'} ${r.scope} "${r.words.replace(/\s+/g, ' ').slice(0, 120)}" (${r.recorded_at.slice(0, 10)}, ${r.source.thread}, words_by=${r.words_by})`; + +function write(cmd: string, store: Store, input: NewAnswer, json: boolean): number { + const row = buildAnswer(store, input); + if (isAnswerError(row)) return fail(cmd, row); + const res = addAnswer(store, row); + if (isAnswerError(res)) return fail(cmd, res); + if (json) process.stdout.write(JSON.stringify({ id: row.id, status: res }) + '\n'); + else process.stdout.write(`OWNER_ANSWER_RECORDED: ${row.id}${res === 'present' ? ' (already present)' : ''}\n`); + return EXIT.ok; +} + +function askFile(cmd: string, file: string | undefined) { + if (!file) return { code: 'OWNER_ANSWERS_INVALID', message: '--ask-file <file> is required' } as AnswerError; + let text: string; + try { text = fs.readFileSync(file, 'utf8'); } catch (e: any) { return { code: 'OWNER_ANSWERS_INVALID', message: `--ask-file ${file}: ${e?.code ?? e?.message}` } as AnswerError; } + return parseAskFile(text); +} + +function main(argv: string[]): number { + const [cmd, ...rest] = argv; + if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; } + const { pos, flags, bools, error } = parse(rest); + if (error) { process.stderr.write(`gstack-owner-answers: ${error}\n`); return EXIT.usage; } + const json = bools.has('--json'); + const store = resolveStore(process.env, flags['--owner']); + if (isAnswerError(store)) return fail(cmd, store); + switch (cmd) { + case 'add': return write(cmd, store, newAnswer(flags), json); + case 'supersede': return pos[0] ? write(cmd, store, newAnswer(flags, { supersedes: pos[0] }), json) : fail(cmd, { code: 'OWNER_ANSWERS_INVALID', message: 'supersede <row id>' }); + case 'revoke': return pos[0] ? write(cmd, store, newAnswer(flags, { kind: 'revoke', supersedes: pos[0] }), json) : fail(cmd, { code: 'OWNER_ANSWERS_INVALID', message: 'revoke <row id>' }); + case 'verify': { + if (!pos[0]) return fail(cmd, { code: 'OWNER_ANSWERS_INVALID', message: 'verify <row id> --event <id> --by <who>' }); + const res = verifyAnswer(store, pos[0], flags['--by'] ?? '', flags['--event'] ?? ''); + if (isAnswerError(res)) return fail(cmd, res); + process.stdout.write(`OWNER_ANSWER_VERIFIED: ${pos[0]}${res === 'present' ? ' (already present)' : ''}\n`); + return EXIT.ok; + } + case 'check': case 'screen': { + const asks = askFile(cmd, flags['--ask-file']); + if (isAnswerError(asks)) return fail(cmd, asks); + const read = readStore(store); + if (cmd === 'check') { + const rows = bools.has('--all') ? read.rows : currentRows(read); + const out = asks.map(a => ({ line: a.line, related: rankRows(rows, a, bools.has('--all') ? rows.length : 5).map(x => ({ id: x.row.id, score: x.score, takeable: !notTakeable(x.row, read), row: x.row })) })); + if (json) { process.stdout.write(JSON.stringify({ state: read.state, problems: read.problems, asks: out }) + '\n'); return EXIT.ok; } + process.stdout.write(`RECORD: ${read.state}${read.problems.length ? ` (${read.problems.length} problem(s); see status)` : ''}\n`); + for (const a of out) { + process.stdout.write(`LINE ${a.line}: ${a.related.length} related\n`); + for (const r of a.related) process.stdout.write(` ${r.takeable ? 'TAKEABLE' : 'CONTEXT'} ${brief(r.row)}\n`); + } + return EXIT.ok; + } + const screened = screenAsks(asks, read); + if (json) { process.stdout.write(JSON.stringify({ state: read.state, problems: read.problems, lines: screened.map(s => ({ ...s, taken_line: s.take ? takenLine(s.take) : undefined })) }) + '\n'); return EXIT.ok; } + for (const s of screened) { + if (s.verdict === 'PROPOSE_TAKE') process.stdout.write(`PROPOSE_TAKE ${s.line} ${s.take!.id}: ${takenLine(s.take!)}\n`); + else process.stdout.write(`KEEP ${s.line}: ${s.reason}\n`); + for (const r of s.related.filter(r => r.id !== s.take?.id)) process.stdout.write(` CONTEXT ${brief(r)}\n`); + } + process.stdout.write(`SCREENED: ${screened.length} line(s), ${screened.filter(s => s.verdict === 'PROPOSE_TAKE').length} proposed take(s); confirm each, then log it\n`); + return EXIT.ok; + } + case 'log': { + const res = logDecision(store, { thread: flags['--thread'] ?? '', line: flags['--line'] ?? '', decision: flags['--decision'] ?? '', row: flags['--row'], by: flags['--by'] ?? '' }); + if (isAnswerError(res)) return fail(cmd, res); + process.stdout.write(`OWNER_ANSWER_LOGGED: ${flags['--decision']} ${flags['--line']}${flags['--row'] ? ` ${flags['--row']}` : ''}\n`); + return EXIT.ok; + } + case 'list': { + const read = readStore(store); + const rows = bools.has('--all') ? read.rows : currentRows(read); + if (json) process.stdout.write(JSON.stringify({ state: read.state, rows }) + '\n'); + else for (const r of rows) process.stdout.write(`${notTakeable(r, read) ? 'CONTEXT ' : 'TAKEABLE'} ${brief(r)}\n`); + return EXIT.ok; + } + case 'status': { + const read = readStore(store); + const current = currentRows(read); + process.stdout.write(`RECORD: ${store.dir}\nOWNER: ${store.owner}\nSTATE: ${read.state}\nROWS: ${read.rows.length} current=${current.length} takeable=${current.filter(r => !notTakeable(r, read)).length} verifications=${read.verifications.length}\n`); + for (const p of read.problems) process.stdout.write(`PROBLEM: ${p}\n`); + return EXIT.ok; + } + default: + process.stderr.write(`gstack-owner-answers: unknown command ${cmd}\n`); + return EXIT.usage; + } +} + +process.exitCode = main(process.argv.slice(2)); diff --git a/changelog.d/owner-answers-record.md b/changelog.d/owner-answers-record.md new file mode 100644 index 00000000000..64738fad4ab --- /dev/null +++ b/changelog.d/owner-answers-record.md @@ -0,0 +1,4 @@ +--- +bump: minor +--- +- **A Captain can check an ask against the owner's earlier answers before sending it.** `gstack-owner-answers` keeps the owner's answers and standing yeses in one record, outside every repository: on Capy it is the owner's private Drive folder, which every thread the owner runs can read. `screen --ask-file` reads a Captain's draft ask and proposes leaving out only the lines that a verified, current standing yes in the owner's own words covers exactly. Every other line stays in, with any related answers shown beside it. That includes autoplan gate items, untyped or compound lines, and anything that always needs a fresh ask (product decisions, spend over a cap, access, publishing, thresholds, closing a contribution, destructive steps). A damaged, conflicting or unreadable record keeps every ask. Rows are one file each, written once; a row needs a second actor to verify its words before it can be taken, and the recorder can't verify its own. The file format and the two-week pilot are in docs/owner-answers.md. diff --git a/docs/owner-answers.md b/docs/owner-answers.md new file mode 100644 index 00000000000..4712718fe5c --- /dev/null +++ b/docs/owner-answers.md @@ -0,0 +1,201 @@ +# The owner's answers: check before you ask + +An agent that asks its owner something the owner already answered wastes the owner's +time. On a host where every session starts on a fresh machine (Capy cloud machines), the +agent has no memory of the earlier answer. `gstack-owner-answers` keeps the owner's +answers and standing yeses in one record, kept where every session the owner runs can read it. +A Captain screens each ask against that record before sending it. + +gstack ships the command and this file format. It never ships anyone's answers: the +record lives outside every repository, and the tests use made-up owners. + +## How much it helps (measured before launch) + +The first measurement was a sample of four days of one owner's Captain threads: 444 +asks reached the owner. + +- 6 were already covered by an earlier answer. +- 14 were covered but had to go to the owner anyway (spend, access, publishing and the like). +- The rest were new questions. + +Only about 3 of the 6 were standing yeses this tool could ever take, so about 1% of +asks were repeats it could skip. That is small. The pilot below measures it again +after launch, and the pilot's result decides whether the tool is kept or cut. + +## Where the record lives + +| Host | Record | +|---|---| +| Capy (`GSTACK_CAPY=1`) | `~/.capy/drive/user-<owner>/owner-answers/`, the owner's private user-level Drive folder. It is mounted in every thread the owner owns, in every project, subagents included. | +| Anywhere else | `$GSTACK_OWNER_ANSWERS_DIR`, else `<state root>/owner-answers/` | + +On Capy the record is bound to the one mounted `user-*` folder, or to the one +`--owner <name>` names. No folder (`OWNER_ANSWERS_NO_DRIVE`) or several +(`OWNER_ANSWERS_AMBIGUOUS`) stops the command. It never falls back to the machine's +thrown-away state root, and `GSTACK_OWNER_ANSWERS_DIR` is ignored there. +The record's own folders (`owner-answers/`, `rows/`, `verifications/`, `log/`) must +resolve inside that folder (elsewhere, inside the record): a link that leads out of it +is refused (`OWNER_ANSWERS_INVALID`), and the record is not read through it. +`gstack-owner-answers status` prints the path. It is the only command that does, so +ordinary output never names the owner's folder. + +## File format (schema_version 1) + +```text +owner-answers/ + rows/<id>.json one answer, created once with O_EXCL, never edited + verifications/<row id>--<key>.json a second actor's confirmation of a row's words + log/<thread>.jsonl one thread's taken and asked decisions (that thread is its only writer) +``` + +A row: + +| Field | Meaning | +|---|---| +| `id` | `oa-` plus 16 hex characters: a hash of owner, kind, action, target, scope, source thread, source event and supersedes. The same answer recorded twice is one file. | +| `owner` | The folder's owner. Rows for another owner make the record uncertain. | +| `kind` | `standing-yes` (may be taken), or `decision`, `preference`, `ruling-ref` (context only), or `revoke` | +| `action`, `target` | One lower-case token each, such as `merge-when-green` / `pull-request`. A take needs exact equality with the ask's tags. | +| `scope` | `all`, `repo:<owner>/<name>` or `captain:<name>`. A row's scope covers an ask with the same scope; `all` covers every scope. Record a Captain's grant with its `captain:` scope, never a wider one. | +| `limits` | Free text. A row with limits is context only, because the tool cannot check them. | +| `words` | The owner's exact words, secret-scanned, at most 2,000 characters | +| `words_by` | `owner` when these are the owner's own words at the source, else `agent:<id>` (the default) | +| `source` | `{ "thread": <code>, "event": <id> }`: where the owner said it | +| `rule` | Optional rule id (`R6`) when the answer is a ruling kept in a rules file. The rules file stays the ruling's home, and the record only points at it. | +| `asked` | The question it answered, when there was one | +| `supersedes` | The row this one replaces (`supersede`) or cancels (`revoke`) | +| `recorded_by`, `recorded_at` | Who wrote the row, and when | + +A verification is `{ schema_version, row, verified_by, verified_at, words_sha256 }`. +The verifier reads the cited source event itself, and names it with `--event`, which +must equal the row's source event. It then confirms that the owner wrote those words +there, granting that action, target and scope. +The recorder can't verify its own row (`OWNER_ANSWERS_SELF_VERIFY`). A +verification only counts while the row's words still hash to `words_sha256`. + +### When a row can be taken + +Every one of these must hold: + +1. The record reads cleanly (state `present`). +2. The row is a `standing-yes` with `words_by: owner` and no limits. +3. No row supersedes or revokes it. +4. Someone other than its recorder has verified its words. + +Everything else is shown as context, and the ask still goes to the owner. + +### Fail closed + +`readStore` marks the whole record `uncertain` in any of these cases, and then +nothing can be taken: + +- a row file is malformed, misnamed or not a regular file; +- a row's id doesn't match its fields; +- a row belongs to another owner; +- a row supersedes an id that is missing; +- two rows supersede the same id. + +A second `add` for the same source, action, target and scope with different words, +author or limits is refused (`OWNER_ANSWERS_CONFLICT`). It is never silently kept. +So is a `supersede` or `revoke` of a row that another row already replaces: supersede +the current row instead. Two such rows can still appear when two machines write at once +before their Drives sync, and then the record reads `uncertain` until one row file is removed. + +A write that fails after its file is created removes the file +(`OWNER_ANSWERS_WRITE_FAILED`), so it leaves no row and the same command can be rerun. +A crash in the middle of a write can still leave an empty file; the record then reads +`uncertain` and keeps every ask until that file is removed. + +`status` lists each problem. + +## Commands + +```bash +gstack-owner-answers add --action merge-when-green --target pull-request --scope all \ + --words "yes merge when green" --words-by owner --thread CAPT-1 --event evt_123 --by "Example Captain" +gstack-owner-answers verify oa-0123456789abcdef --event evt_123 --by "second reader" +gstack-owner-answers screen --ask-file ask.json +gstack-owner-answers log --thread CAPT-1 --line A --decision taken --row oa-0123456789abcdef --by "Example Captain" +gstack-owner-answers revoke oa-0123456789abcdef --words "ask me again about merges" --words-by owner --thread CAPT-1 --event evt_456 --by "Example Captain" +``` + +`check --ask-file` lists the related rows for each ask line, ranked by shared words. +The ranking is advisory: a high score never makes a row takeable. + +### The ask file + +The ask file is JSON, one entry per lettered line: + +```json +{ "asks": [ + { "line": "A", "origin": "captain", "text": "Merge #12 now that it is green?", + "action": "merge-when-green", "target": "pull-request", "scope": "repo:example/widgets" }, + { "line": "B", "origin": "captain", "text": "Spend $400 on the eval rerun?", "classes": ["spend-over-cap"] } +] } +``` + +A plain-text file with one ask per line also works. Its lines are untyped, so +`screen` keeps all of them, and only `check` is useful on it. + +`screen` keeps a line (`KEEP <reason>`) when any of these holds: + +- `origin` isn't `captain`. An autoplan gate item is answered at its gate and is never screened out, because dropping it would change what "do it" approves. +- `compound` is true, or the ask carries `limits` (an amount, a count, a deadline). +- It carries a fresh-ask class, or its words trip the fresh-ask keyword net. +- Its action, target or scope is missing. +- No takeable row matches it exactly. +- A matching row that can't be taken is newer than the takeable one, or narrower in scope (a + `repo:` or `captain:` row beside an `all` row). A later "no" or a scoped exception wins over an + older blanket yes. + +Otherwise it prints `PROPOSE_TAKE <line> <row id>` and the line the Captain adds to +its message, for example `Not asked, you already said: "yes merge when green" (2026-10-16, CAPT-1, R6).` + +`screen` never edits the ask. The Captain confirms each proposal, sends the rest, and +logs both outcomes. + +### Fresh-ask classes + +Fresh-ask classes are never taken from the record. They are the "Always a fresh ask" list in +[capy/skill/gstack/captain.md](../capy/skill/gstack/captain.md), with these tags: + +| Tag | Covers | +|---|---| +| `product-decision` | Product and behaviour decisions | +| `spend-over-cap` | Spend over a stated cap | +| `access` | Access and credentials | +| `publish` | Anything published outside the repository | +| `threshold-change` | Thresholds, budgets, trial counts and test kinds | +| `close-contribution` | Closing someone's contribution without landing it | +| `destructive` | Anything destructive or irreversible | + +An unknown tag keeps the line too. + +## The pilot + +The first version runs as a pilot on one Captain's own asks for two weeks: + +1. Before each ask to the owner, the Captain writes the ask file and runs `screen`. +2. The Captain reads every `PROPOSE_TAKE` itself before leaving that line out. A wrong proposal stops the pilot and gets corrected; it is never averaged away. +3. The Captain logs every line as `taken` or `asked`. + +The pilot's numbers are counted against a baseline taken before launch: + +- asks the owner received that an earlier answer of theirs already covered; +- wrong takes, from an audit of taken rows. + +Only after a keep decision does gstack's shared factory guidance tell every Captain to screen. + +**Known limit.** A Drive that hasn't finished syncing a newer supersede or revoke +looks exactly like a record without one. The tool can't detect that lag, which is +one reason the pilot Captain reads every proposal before leaving an ask out. + +## Export to a knowledge base (format only) + +Each current row maps to one page: + +- title: `<action> <target> (<scope>)`; +- body: the words, quoted, with the source thread and date; +- tags: `owner-answer` and the kind. + +Nothing in gstack writes such an export yet. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f56f2ee8e9e..3da9afc6687 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2134,6 +2134,74 @@ per-thread approval record), `gstack-owner-brief render --captain` (the plan ask the before/after shape) and `gstack-pr-shots` (before/after images for a PR body). The guide is `capy/skill/gstack/captain.md`. +<a id="owner-answers-no-drive"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_NO_DRIVE)` + +**Meaning.** On Capy the owner record lives only in the owner's own Drive folder +(`~/.capy/drive/user-<owner>/owner-answers/`), and none is mounted, or `--owner` names +one that is not. Exit 3. The tool never falls back to the machine's thrown-away state +root, so nothing can be taken and every ask goes to the owner. See +[owner-answers.md](owner-answers.md). + +<a id="owner-answers-ambiguous"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_AMBIGUOUS)` + +**Meaning.** Two or more `user-*` Drive folders are mounted, so the tool cannot tell +whose record to use. Exit 3. Pass `--owner <name>`. + +<a id="owner-answers-invalid"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_INVALID)` + +**Meaning.** A required flag is missing, a value is outside its format (an action or +target that is not one lower-case token, a scope other than `all`, +`repo:<owner>/<name>` or `captain:<name>`, a rule id not like `R6`), a field is +longer than its cap, or the ask file is not the JSON or plain-text form +[owner-answers.md](owner-answers.md) describes. Exit 2. Nothing was written. + +<a id="owner-answers-secret"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_SECRET)` + +**Meaning.** A field matched the secret scanner. Exit 3. Nothing was written; the +error names the field and the rule, never the text. + +<a id="owner-answers-write-failed"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_WRITE_FAILED)` + +**Meaning.** The record directory could not be written. Exit 1. A write that fails +after its file is created removes that file, so it leaves no row: fix the path or +permissions `gstack-owner-answers status` prints, then rerun the same command. A crash +in the middle of a write can still leave an empty file; the record then reads +`uncertain` and keeps every ask until that file (named by `status`) is removed. + +<a id="owner-answers-not-found"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_NOT_FOUND)` + +**Meaning.** `supersede`, `revoke`, `verify` or `log --decision taken` named a row id +that is not in the record. Exit 3. + +<a id="owner-answers-conflict"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_CONFLICT)` + +**Meaning.** One source, action, target and scope make one row id, and that row +already holds different words, a different author or different limits; or a +`supersede` or `revoke` names a row that another row already replaces. Exit 3. +Nothing was written. Check what the owner said at that source, then record the +correction with `supersede <row id>` on the current row (`list --all` shows which +row replaced which). + +<a id="owner-answers-self-verify"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_SELF_VERIFY)` + +**Meaning.** The actor that recorded the row tried to verify it. Exit 3. A second +actor reads the cited thread event and verifies under its own name. + +<a id="owner-answers-not-takeable"></a> +### `gstack-owner-answers: ... (OWNER_ANSWERS_NOT_TAKEABLE)` + +**Meaning.** `log --decision taken` named a row that cannot be taken (not a +verified, current, unlimited standing yes in the owner's own words, or the record is +uncertain). Exit 3. Send the ask to the owner and log it as `asked`. + <a id="approval-record-invalid"></a> ### `gstack-approvals: ... (APPROVAL_RECORD_INVALID)` diff --git a/lib/owner-answers.ts b/lib/owner-answers.ts new file mode 100644 index 00000000000..4efd11f4b5d --- /dev/null +++ b/lib/owner-answers.ts @@ -0,0 +1,393 @@ +/** + * owner-answers — the owner's record of answers and standing yeses that a thread reads before it asks + * the owner anything (docs/owner-answers.md). The record holds the owner's own words and lives where + * every thread the owner runs can read it: on Capy, the owner's private user-level Drive folder + * (`~/.capy/drive/user-<owner>/owner-answers/`); elsewhere, `<state root>/owner-answers/`. gstack ships + * only this mechanism and the file format; the rows never enter a repository. + * + * Layout: `rows/<id>.json` (one answer, written once with O_EXCL; a supersede or revoke is a new row + * naming the row it replaces), `verifications/<row id>--<verifier key>.json` (a second actor's + * confirmation that the cited source holds the row's words) and `log/<thread>.jsonl` (each thread's + * taken and asked decisions; one writer per file). + * + * Fail closed: an ask is dropped only on the pilot's confirmation of a PROPOSE_TAKE, and screen proposes + * one only when the whole record reads cleanly, a verified, current, unlimited standing-yes row + * matches the ask's typed action, target and scope exactly, and no newer or narrower matching row says + * otherwise. Anything malformed, conflicting, unverified, + * superseded, untyped, compound or in a fresh-ask class keeps the ask. One source and action is one row id: + * a second add with different words is refused (OWNER_ANSWERS_CONFLICT), never silently kept. + */ +import { createHash } from 'node:crypto'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import type { ResultCodeName } from './result-codes'; +import { scan } from './redact-engine'; +import { resolveStateRoot } from './state-root'; + +export const KINDS = ['standing-yes', 'decision', 'preference', 'ruling-ref', 'revoke'] as const; +export type Kind = typeof KINDS[number]; +/** The classes that always need a fresh ask (capy/skill/gstack/captain.md, "Always a fresh ask"). */ +export const FRESH_ASK_CLASSES = ['product-decision', 'spend-over-cap', 'access', 'publish', 'threshold-change', 'close-contribution', 'destructive'] as const; +export type FreshAskClass = typeof FRESH_ASK_CLASSES[number]; +/** A keyword net over untagged ask text: a hit keeps the ask even when the line was not tagged with the class. */ +const FRESH_ASK_WORDS: Record<FreshAskClass, RegExp> = { + 'product-decision': /\b(?:product|feature|design|behaviou?r|scope)\b/i, + 'spend-over-cap': /\$\s?\d|\b(?:spend|budget|cost|cap|dollars?)\b/i, + access: /\b(?:access|credentials?|keys?|tokens?|passwords?|secrets?|sign[ -]?in|log[ -]?in|permissions?)\b/i, + publish: /\b(?:publish|post|tweet|release notes?|advisory|announce|blog|email|dm)\b/i, + 'threshold-change': /\b(?:threshold|trial count|trials|test kind|pass rate|bar)\b/i, + 'close-contribution': /\b(?:close (?:their|the|a|his|her) (?:pr|pull request|contribution)|decline|reject (?:the )?(?:pr|contribution))\b/i, + destructive: /\b(?:delete|destroy|drop|wipe|force[- ]push|rotate|revoke|irreversible|purge|reset)\b/i, +}; +export const CAPS = { action: 60, target: 120, scope: 160, limits: 300, words: 2000, asked: 300, thread: 80, event: 120, rule: 20, by: 120 } as const; +const TOKEN = /^[a-z0-9][a-z0-9-]{0,59}$/; +const SCOPE = /^(?:all|repo:[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+|captain:[a-z0-9][a-z0-9-]{0,59})$/; + +export interface Source { thread: string; event: string } +export interface OwnerAnswer { + schema_version: 1; id: string; owner: string; kind: Kind; action: string; target: string; scope: string; limits: string; + words: string; words_by: string; source: Source; rule: string; asked: string; supersedes: string; recorded_by: string; recorded_at: string; +} +export interface Verification { schema_version: 1; row: string; verified_by: string; verified_at: string; words_sha256: string } +export interface Store { dir: string; owner: string; on_capy: boolean } +export interface AnswerError { code: ResultCodeName; message: string } +export interface StoreRead { + state: 'present' | 'empty' | 'unavailable' | 'uncertain'; + rows: OwnerAnswer[]; verifications: Verification[]; problems: string[]; +} + +const sha = (s: string) => createHash('sha256').update(s).digest('hex'); +const isErr = (x: unknown): x is AnswerError => !!x && typeof x === 'object' && 'code' in (x as object); +export { isErr as isAnswerError }; + +function contained(root: string, file: string): boolean { + const rel = path.relative(root, file); + return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel); +} + +/** + * The owner's store. On Capy (GSTACK_CAPY=1) it is the one mounted `user-<owner>` Drive folder (or the one + * --owner names), never an environment override and never the thrown-away state root. Off Capy it is + * GSTACK_OWNER_ANSWERS_DIR, else `<state root>/owner-answers`. + */ +export function resolveStore(env: NodeJS.ProcessEnv, owner?: string): Store | AnswerError { + if (env.GSTACK_CAPY === '1') { + const drive = path.join(env.HOME || os.homedir(), '.capy', 'drive'); + let folders: string[]; + try { folders = fs.readdirSync(drive).filter(d => d.startsWith('user-') && fs.statSync(path.join(drive, d)).isDirectory()); } catch { folders = []; } + if (owner) folders = folders.filter(d => d === `user-${owner}`); + if (!folders.length) return { code: 'OWNER_ANSWERS_NO_DRIVE', message: owner ? `no mounted Drive folder user-${owner}` : `no user-* folder under ${drive}` }; + if (folders.length > 1) return { code: 'OWNER_ANSWERS_AMBIGUOUS', message: `${folders.length} user-* folders are mounted; pass --owner <name>` }; + const folder = path.join(drive, folders[0]!); + let real: string; + try { real = fs.realpathSync(folder); } catch { return { code: 'OWNER_ANSWERS_NO_DRIVE', message: `${folder} cannot be resolved` }; } + const realDrive = fs.realpathSync(drive); + if (!contained(realDrive, real)) return { code: 'OWNER_ANSWERS_INVALID', message: `${folder} resolves outside ${drive}` }; + return { dir: path.join(real, 'owner-answers'), owner: folders[0]!.slice('user-'.length), on_capy: true }; + } + const dir = env.GSTACK_OWNER_ANSWERS_DIR || path.join(resolveStateRoot(env), 'owner-answers'); + return { dir, owner: owner || env.GSTACK_OWNER || 'owner', on_capy: false }; +} + +function field(name: keyof typeof CAPS, value: unknown, required: boolean): string | AnswerError { + const v = typeof value === 'string' ? value.trim() : ''; + if (required && !v) return { code: 'OWNER_ANSWERS_INVALID', message: `--${name} is required` }; + if (v.length > CAPS[name]) return { code: 'OWNER_ANSWERS_INVALID', message: `--${name} is ${v.length} characters (cap ${CAPS[name]})` }; + if (/[\u0000-\u0008\u000b-\u001f]/.test(v)) return { code: 'OWNER_ANSWERS_INVALID', message: `--${name} holds a control character` }; + const s = scan(v); + if (s.oversize || s.findings.some(f => f.severity === 'HIGH' || f.severity === 'MEDIUM')) return { code: 'OWNER_ANSWERS_SECRET', message: `field ${name}: ${s.oversize ? 'oversize input' : [...new Set(s.findings.map(f => f.id))].join(', ')}` }; + return v; +} + +/** The id is a hash of who said what, where, about which action: the same answer recorded twice is one row. */ +export function rowId(r: Pick<OwnerAnswer, 'owner' | 'kind' | 'action' | 'target' | 'scope' | 'source' | 'supersedes'>): string { + return 'oa-' + sha([r.owner, r.kind, r.action, r.target, r.scope, r.source.thread, r.source.event, r.supersedes].join('\u0000')).slice(0, 16); +} + +export interface NewAnswer { + kind?: string; action?: string; target?: string; scope?: string; limits?: string; words?: string; words_by?: string; + thread?: string; event?: string; rule?: string; asked?: string; supersedes?: string; by?: string; +} + +/** Validate and secret-scan one answer; the error names the field and rule, never the text. */ +export function buildAnswer(store: Store, input: NewAnswer, now = new Date()): OwnerAnswer | AnswerError { + const kind = (input.kind ?? 'standing-yes') as Kind; + if (!KINDS.includes(kind)) return { code: 'OWNER_ANSWERS_INVALID', message: `--kind must be one of ${KINDS.join('|')}` }; + const out: Record<string, string> = {}; + const need: Array<[keyof typeof CAPS, unknown, boolean]> = [ + ['action', input.action, kind !== 'revoke'], ['target', input.target, kind !== 'revoke'], ['scope', input.scope ?? 'all', true], + ['limits', input.limits, false], ['words', input.words, true], ['thread', input.thread, true], ['event', input.event, true], + ['rule', input.rule, false], ['asked', input.asked, false], ['by', input.by, true], + ]; + for (const [name, value, required] of need) { + const v = field(name, value, required); + if (isErr(v)) return v; + out[name] = v; + } + if (out.action && !TOKEN.test(out.action)) return { code: 'OWNER_ANSWERS_INVALID', message: '--action must be one lower-case token (letters, digits, hyphens)' }; + if (out.target && !TOKEN.test(out.target)) return { code: 'OWNER_ANSWERS_INVALID', message: '--target must be one lower-case token (letters, digits, hyphens)' }; + if (!SCOPE.test(out.scope!)) return { code: 'OWNER_ANSWERS_INVALID', message: '--scope must be all, repo:<owner>/<name> or captain:<name>' }; + if (out.rule && !/^R\d{1,4}$/.test(out.rule)) return { code: 'OWNER_ANSWERS_INVALID', message: '--rule must look like R6' }; + const wordsBy = (input.words_by ?? '').trim() || `agent:${out.by}`; + if (wordsBy !== 'owner') { + if (!/^agent:\S.*$/.test(wordsBy)) return { code: 'OWNER_ANSWERS_INVALID', message: '--words-by must be owner or agent:<id> on one line' }; + const agent = field('by', wordsBy.slice('agent:'.length), true); + if (isErr(agent)) return { code: agent.code, message: agent.message.replace('--by', '--words-by') }; + } + if (kind === 'revoke' && !input.supersedes?.trim()) return { code: 'OWNER_ANSWERS_INVALID', message: 'a revoke names the row it cancels with --supersedes' }; + const supersedes = (input.supersedes ?? '').trim(); + if (supersedes && !/^oa-[0-9a-f]{16}$/.test(supersedes)) return { code: 'OWNER_ANSWERS_INVALID', message: '--supersedes must be a row id (oa-…)' }; + const base = { + schema_version: 1 as const, owner: store.owner, kind, action: out.action ?? '', target: out.target ?? '', scope: out.scope!, limits: out.limits ?? '', + words: out.words!, words_by: wordsBy, source: { thread: out.thread!, event: out.event! }, rule: out.rule ?? '', asked: out.asked ?? '', + supersedes, recorded_by: out.by!, recorded_at: now.toISOString(), + }; + return { id: rowId(base), ...base }; +} + +function validRow(r: any, owner: string): string | undefined { + if (!r || r.schema_version !== 1 || typeof r.id !== 'string') return 'not a v1 row'; + if (!KINDS.includes(r.kind)) return 'unknown kind'; + for (const k of ['owner', 'action', 'target', 'scope', 'limits', 'words', 'words_by', 'rule', 'asked', 'supersedes', 'recorded_by', 'recorded_at']) if (typeof r[k] !== 'string') return `field ${k} is not a string`; + if (!r.source || typeof r.source.thread !== 'string' || typeof r.source.event !== 'string') return 'no source'; + if (r.owner !== owner) return 'another owner'; + if (rowId(r) !== r.id) return 'id does not match its fields'; + return undefined; +} + +function readJsonDir(dir: string): Array<{ name: string; value?: unknown; error?: string }> | 'unavailable' | 'missing' { + let names: string[]; + try { names = fs.readdirSync(dir); } catch (e: any) { return e?.code === 'ENOENT' ? 'missing' : 'unavailable'; } + return names.filter(n => n.endsWith('.json')).sort().map(name => { + try { + const st = fs.lstatSync(path.join(dir, name)); + if (!st.isFile()) return { name, error: 'not a regular file' }; + return { name, value: JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')) }; + } catch { return { name, error: 'unreadable or not JSON' }; } + }); +} + +/** + * The record and each of its existing directories must resolve inside the owner's folder on Capy (inside the record + * itself elsewhere): a link out of it is refused, so a planted link can neither receive rows nor feed them back. + */ +export function storeEscape(store: Store): AnswerError | undefined { + const root = store.on_capy ? path.dirname(store.dir) : store.dir; + let realRoot: string; + try { realRoot = fs.realpathSync(root); } catch { return undefined; } + for (const d of [store.dir, ...['rows', 'verifications', 'log'].map(s => path.join(store.dir, s))]) { + let real: string; + try { real = fs.realpathSync(d); } catch { + try { fs.lstatSync(d); } catch { continue; } + return { code: 'OWNER_ANSWERS_INVALID', message: `${path.relative(root, d) || '.'} is a link that cannot be resolved` }; + } + if (real !== realRoot && !contained(realRoot, real)) return { code: 'OWNER_ANSWERS_INVALID', message: `${path.relative(root, d) || '.'} resolves outside the record's folder` }; + } + return undefined; +} + +/** Every row and verification; any doubt about the whole record makes it `uncertain`, which keeps every ask. */ +export function readStore(store: Store): StoreRead { + const problems: string[] = []; + if (!fs.existsSync(store.dir)) return { state: 'empty', rows: [], verifications: [], problems }; + const escape = storeEscape(store); + if (escape) return { state: 'unavailable', rows: [], verifications: [], problems: [escape.message] }; + const rowFiles = readJsonDir(path.join(store.dir, 'rows')); + if (rowFiles === 'unavailable') return { state: 'unavailable', rows: [], verifications: [], problems: ['rows/ cannot be read'] }; + const rows: OwnerAnswer[] = []; + for (const f of rowFiles === 'missing' ? [] : rowFiles) { + const bad = f.error ?? validRow(f.value, store.owner) ?? (`${(f.value as OwnerAnswer).id}.json` === f.name ? undefined : 'file name does not match its id'); + if (bad) problems.push(`rows/${f.name}: ${bad}`); + else rows.push(f.value as OwnerAnswer); + } + const verFiles = readJsonDir(path.join(store.dir, 'verifications')); + const verifications: Verification[] = []; + if (verFiles === 'unavailable') problems.push('verifications/ cannot be read'); + for (const f of verFiles === 'missing' || verFiles === 'unavailable' ? [] : verFiles) { + const v = f.value as Verification | undefined; + if (f.error || !v || v.schema_version !== 1 || typeof v.row !== 'string' || typeof v.verified_by !== 'string' || typeof v.words_sha256 !== 'string') problems.push(`verifications/${f.name}: ${f.error ?? 'not a v1 verification'}`); + else verifications.push(v); + } + const ids = new Set(rows.map(r => r.id)); + const replacedBy = new Map<string, string[]>(); + for (const r of rows) if (r.supersedes) replacedBy.set(r.supersedes, [...(replacedBy.get(r.supersedes) ?? []), r.id]); + for (const [old, by] of replacedBy) { + if (!ids.has(old)) problems.push(`${by.join(', ')} supersede${by.length === 1 ? 's' : ''} ${old}, which is not in the record`); + if (by.length > 1) problems.push(`${old} is superseded by ${by.length} rows (${by.join(', ')})`); + } + rows.sort((a, b) => a.recorded_at.localeCompare(b.recorded_at) || a.id.localeCompare(b.id)); + return { state: problems.length ? 'uncertain' : rows.length ? 'present' : 'empty', rows, verifications, problems }; +} + +/** A row is current when no row supersedes it and it is not itself a revoke. */ +export function currentRows(read: StoreRead): OwnerAnswer[] { + const replaced = new Set(read.rows.map(r => r.supersedes).filter(Boolean)); + return read.rows.filter(r => !replaced.has(r.id) && r.kind !== 'revoke'); +} + +/** Why a row cannot be taken, or undefined when it can: the owner's own words, verified by someone else, current, unlimited. */ +export function notTakeable(row: OwnerAnswer, read: StoreRead): string | undefined { + if (read.state !== 'present') return `the record is ${read.state}`; + if (row.kind !== 'standing-yes') return `a ${row.kind} row is context only`; + if (row.words_by !== 'owner') return `the words were typed by ${row.words_by}`; + if (row.limits) return 'it carries limits the tool cannot check'; + if (!currentRows(read).some(r => r.id === row.id)) return 'it was superseded or revoked'; + const ok = read.verifications.some(v => v.row === row.id && v.verified_by !== row.recorded_by && v.words_sha256 === sha(row.words)); + return ok ? undefined : 'no second actor has verified its words at the source'; +} + +/** Create the directory for a record file, checking the record's directories before and after. */ +function prepareDir(store: Store, file: string): AnswerError | undefined { + const before = storeEscape(store); + if (before) return before; + try { fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); } catch (e: any) { + return { code: 'OWNER_ANSWERS_WRITE_FAILED', message: `${path.basename(path.dirname(file))}: ${e?.code ?? e?.message}` }; + } + return storeEscape(store); +} + +/** One file, created with O_EXCL; a write that fails after the create removes the file, so a retry starts clean. */ +export function writeExclusive(store: Store, file: string, value: unknown): 'written' | 'present' | AnswerError { + const failed = (e: any): AnswerError => ({ code: 'OWNER_ANSWERS_WRITE_FAILED', message: `${path.basename(file)}: ${e?.code ?? e?.message}` }); + const dir = prepareDir(store, file); + if (dir) return dir; + let fd: number; + try { fd = fs.openSync(file, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600); } catch (e: any) { + return e?.code === 'EEXIST' ? 'present' : failed(e); + } + try { + fs.writeSync(fd, JSON.stringify(value, null, 1) + '\n'); + fs.fsyncSync(fd); + fs.closeSync(fd); + return 'written'; + } catch (e: any) { + try { fs.closeSync(fd); } catch { /* already closed */ } + try { fs.unlinkSync(file); } catch { /* left for readStore to report */ } + return failed(e); + } +} + +export function addAnswer(store: Store, row: OwnerAnswer): 'written' | 'present' | AnswerError { + if (row.supersedes) { + const read = readStore(store); + if (!read.rows.some(r => r.id === row.supersedes)) return { code: 'OWNER_ANSWERS_NOT_FOUND', message: `no row ${row.supersedes} to supersede` }; + const other = read.rows.find(r => r.supersedes === row.supersedes && r.id !== row.id); + if (other) return { code: 'OWNER_ANSWERS_CONFLICT', message: `${row.supersedes} is already superseded by ${other.id}; supersede or revoke the current row instead` }; + } + const file = path.join(store.dir, 'rows', `${row.id}.json`); + const res = writeExclusive(store, file, row); + if (res !== 'present') return res; + let have: Partial<OwnerAnswer> = {}; + try { have = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { /* an unreadable twin is a conflict too */ } + return have.words === row.words && have.words_by === row.words_by && have.limits === row.limits + ? 'present' + : { code: 'OWNER_ANSWERS_CONFLICT', message: `${row.id} already records different words, author or limits for this source and action; supersede it instead` }; +} + +/** + * A second actor confirms the cited source holds the row's words: it reads the source event itself and names it + * (--event must equal the row's source event). The adder can never verify its own row. + */ +export function verifyAnswer(store: Store, id: string, by: string, event: string, now = new Date()): 'written' | 'present' | AnswerError { + const verifier = field('by', by, true); + if (isErr(verifier)) return verifier; + const row = readStore(store).rows.find(r => r.id === id); + if (!row) return { code: 'OWNER_ANSWERS_NOT_FOUND', message: `no row ${id}` }; + if (row.recorded_by === verifier) return { code: 'OWNER_ANSWERS_SELF_VERIFY', message: `${id} was recorded by ${verifier}` }; + if (event.trim() !== row.source.event) return { code: 'OWNER_ANSWERS_INVALID', message: `--event must name the source event the verifier read (${id} cites ${row.source.thread})` }; + const v: Verification = { schema_version: 1, row: id, verified_by: verifier, verified_at: now.toISOString(), words_sha256: sha(row.words) }; + return writeExclusive(store, path.join(store.dir, 'verifications', `${id}--${sha(verifier).slice(0, 12)}.json`), v); +} + +/** origin is "captain" for a standalone Captain ask; anything else (an autoplan gate item, an unknown draft) is never screened out. */ +export interface AskLine { line: string; text: string; origin?: string; action?: string; target?: string; scope?: string; limits?: string; classes?: string[]; compound?: boolean } + +/** An ask file: JSON `{ "asks": [AskLine, ...] }`, or plain text with one ask per non-blank line (all untyped). */ +export function parseAskFile(text: string): AskLine[] | AnswerError { + const t = text.trim(); + if (t.startsWith('{')) { + let j: any; + try { j = JSON.parse(t); } catch { return { code: 'OWNER_ANSWERS_INVALID', message: 'the ask file starts with { but is not JSON' }; } + if (!Array.isArray(j?.asks)) return { code: 'OWNER_ANSWERS_INVALID', message: 'the ask file needs an "asks" array' }; + return j.asks.map((a: any, i: number) => ({ + line: typeof a?.line === 'string' && a.line ? a.line : String(i + 1), text: typeof a?.text === 'string' ? a.text : '', origin: typeof a?.origin === 'string' ? a.origin : undefined, + action: typeof a?.action === 'string' ? a.action : undefined, target: typeof a?.target === 'string' ? a.target : undefined, + scope: typeof a?.scope === 'string' ? a.scope : undefined, limits: typeof a?.limits === 'string' ? a.limits : undefined, classes: Array.isArray(a?.classes) ? a.classes.map(String) : [], compound: a?.compound === true, + })); + } + return t.split('\n').map(l => l.trim()).filter(Boolean).map((l, i) => { + const m = /^([A-Z][0-9]*)\s*[:.)]\s*(.*)$/.exec(l); + return { line: m ? m[1]! : String(i + 1), text: m ? m[2]! : l }; + }); +} + +const STOP = new Set('the a an and or to of for in on at is it be we you your this that with as by from not no do can could should would will any all our its are was were has have if then than so but'.split(' ')); +const words = (s: string) => new Set(s.toLowerCase().split(/[^a-z0-9]+/).filter(w => w.length > 2 && !STOP.has(w))); + +/** Rows ranked by word overlap with the ask (advisory only: ranking never makes a row takeable). */ +export function rankRows(rows: OwnerAnswer[], ask: AskLine, k = 5): Array<{ row: OwnerAnswer; score: number }> { + const want = words([ask.text, ask.action ?? '', ask.target ?? ''].join(' ')); + return rows + .filter(r => !ask.scope || r.scope === 'all' || r.scope === ask.scope) + .map(row => { const have = words([row.asked, row.action, row.target, row.words].join(' ')); let score = 0; for (const w of want) if (have.has(w)) score++; return { row, score }; }) + .filter(x => x.score > 0) + .sort((a, b) => b.score - a.score || b.row.recorded_at.localeCompare(a.row.recorded_at)) + .slice(0, k); +} + +export interface Screened { line: string; text: string; verdict: 'KEEP' | 'PROPOSE_TAKE'; reason: string; take?: OwnerAnswer; related: OwnerAnswer[] } + +/** Per ask line: a proposal to take only on an exact typed match with a takeable row; otherwise keep, with related rows as context. */ +export function screenAsks(asks: AskLine[], read: StoreRead): Screened[] { + const current = currentRows(read); + return asks.map(ask => { + const related = rankRows(current, ask, 3).map(x => x.row); + const keep = (reason: string): Screened => ({ line: ask.line, text: ask.text, verdict: 'KEEP', reason, related }); + if (read.state !== 'present') return keep(`the record is ${read.state}`); + if (ask.origin !== 'captain') return keep(ask.origin === 'gate' ? 'a gate item is answered at its gate, never screened out' : 'the ask does not say it is a standalone Captain ask (origin: captain)'); + if (ask.compound) return keep('the line holds more than one decision'); + if (ask.limits?.trim()) return keep('the ask carries limits (an amount, a count, a deadline) the record cannot check'); + const tagged = (ask.classes ?? []).filter(c => (FRESH_ASK_CLASSES as readonly string[]).includes(c)); + const unknownTag = (ask.classes ?? []).find(c => !(FRESH_ASK_CLASSES as readonly string[]).includes(c)); + if (unknownTag) return keep(`unknown class ${unknownTag}`); + if (tagged.length) return keep(`always a fresh ask: ${tagged.join(', ')}`); + const netted = FRESH_ASK_CLASSES.filter(c => FRESH_ASK_WORDS[c].test(ask.text)); + if (netted.length) return keep(`its words read as a fresh-ask class: ${netted.join(', ')}`); + if (!ask.action || !ask.target || !ask.scope) return keep('the line has no typed action, target and scope'); + const exact = current.filter(r => r.action === ask.action && r.target === ask.target && (r.scope === 'all' || r.scope === ask.scope)); + const take = exact.filter(r => !notTakeable(r, read)).at(-1); + if (!take) return keep(exact.length ? `matching rows are not takeable: ${notTakeable(exact.at(-1)!, read)}` : 'no standing yes matches its action, target and scope'); + const veto = exact.find(r => r !== take && notTakeable(r, read) && (r.recorded_at > take.recorded_at || (take.scope === 'all' && r.scope !== 'all'))); + if (veto) return keep(`a newer or narrower answer for this action is not takeable: ${veto.id} (${notTakeable(veto, read)})`); + return { line: ask.line, text: ask.text, verdict: 'PROPOSE_TAKE', reason: 'a verified, current standing yes matches exactly', take, related }; + }); +} + +/** The line a Captain adds to its message for each confirmed take. */ +export function takenLine(row: OwnerAnswer): string { + const words = row.words.length > 160 ? row.words.slice(0, 159).trimEnd() + '…' : row.words; + return `Not asked, you already said: "${words.replace(/\s+/g, ' ')}" (${row.recorded_at.slice(0, 10)}, ${row.source.thread}${row.rule ? `, ${row.rule}` : ''}).`; +} + +export const LOG_DECISIONS = ['taken', 'asked'] as const; + +/** One line in the thread's own log: what the pilot did with a line, and which row it took. */ +export function logDecision(store: Store, o: { thread: string; line: string; decision: string; row?: string; by: string }, now = new Date()): string | AnswerError { + if (!/^[A-Za-z0-9_-]{1,80}$/.test(o.thread)) return { code: 'OWNER_ANSWERS_INVALID', message: '--thread must be the thread code or id (letters, digits, - and _)' }; + if (!(LOG_DECISIONS as readonly string[]).includes(o.decision)) return { code: 'OWNER_ANSWERS_INVALID', message: `--decision must be ${LOG_DECISIONS.join('|')}` }; + if (o.decision === 'taken') { + const read = readStore(store); + const row = read.rows.find(r => r.id === o.row); + if (!row) return { code: 'OWNER_ANSWERS_NOT_FOUND', message: `no row ${o.row ?? '(none given)'}` }; + const why = notTakeable(row, read); + if (why) return { code: 'OWNER_ANSWERS_NOT_TAKEABLE', message: `${row.id}: ${why}` }; + } + const file = path.join(store.dir, 'log', `${o.thread}.jsonl`); + const dir = prepareDir(store, file); + if (dir) return dir; + try { + fs.appendFileSync(file, JSON.stringify({ at: now.toISOString(), thread: o.thread, line: o.line.slice(0, 20), decision: o.decision, row: o.row ?? '', by: o.by.slice(0, CAPS.by) }) + '\n', { mode: 0o600 }); + } catch (e: any) { return { code: 'OWNER_ANSWERS_WRITE_FAILED', message: `log: ${e?.code ?? e?.message}` }; } + return file; +} diff --git a/lib/result-codes-capy.ts b/lib/result-codes-capy.ts index c3300cb359d..b6dcf3b1ca3 100644 --- a/lib/result-codes-capy.ts +++ b/lib/result-codes-capy.ts @@ -40,6 +40,51 @@ export const CAPY_RESULT_CODES = { summary: 'the autoplan run has no answered gate to import', fix: 'answer the gate first (gstack-autoplan answer ... --by human|agent:<id>), then rerun the import; it is idempotent, so a retry imports nothing twice', }, + OWNER_ANSWERS_NO_DRIVE: { + anchor: 'owner-answers-no-drive', + summary: 'no owner Drive folder (user-<owner>) is mounted on this Capy machine, so there is no record to read or write', + fix: 'run from a thread the owner owns, or pass --owner <name> for a mounted user-<name> folder; until then every ask goes to the owner', + }, + OWNER_ANSWERS_AMBIGUOUS: { + anchor: 'owner-answers-ambiguous', + summary: 'more than one user-* Drive folder is mounted, so the owner is not known', + fix: 'pass --owner <name> naming the owner whose record this is; nothing was read or written', + }, + OWNER_ANSWERS_INVALID: { + anchor: 'owner-answers-invalid', + summary: 'a row, an ask file or a flag is missing a required value, holds a value outside its format, or exceeds a length cap', + fix: 'rerun with the flags the help names (an action and target are one lower-case token each; scope is all, repo:<owner>/<name> or captain:<name>); nothing was written', + }, + OWNER_ANSWERS_SECRET: { + anchor: 'owner-answers-secret', + summary: 'a field matched the secret scanner, so the row was not written', + fix: 'remove the key, token or personal data from that field (the error names the field and rule, never the text) and rerun', + }, + OWNER_ANSWERS_WRITE_FAILED: { + anchor: 'owner-answers-write-failed', + summary: 'the record directory could not be written', + fix: 'check the path gstack-owner-answers status prints and its permissions, then rerun; a failed write removed its file, and an empty file left by a crash is named by status and must be removed', + }, + OWNER_ANSWERS_NOT_FOUND: { + anchor: 'owner-answers-not-found', + summary: 'no row with that id is in the owner record', + fix: 'gstack-owner-answers list --all shows every row id; rerun with one of them', + }, + OWNER_ANSWERS_CONFLICT: { + anchor: 'owner-answers-conflict', + summary: 'a row for the same source, action, target and scope already records different words, author or limits, or the row named to supersede is already replaced', + fix: 'check which words the owner actually said at that source; record a correction with supersede <row id> on the current row, never a second add', + }, + OWNER_ANSWERS_SELF_VERIFY: { + anchor: 'owner-answers-self-verify', + summary: 'the actor that recorded a row tried to verify it', + fix: 'a second actor reads the cited thread event and runs verify --by <its own name>; a row its recorder verified is never takeable', + }, + OWNER_ANSWERS_NOT_TAKEABLE: { + anchor: 'owner-answers-not-takeable', + summary: 'a taken decision was logged against a row that cannot be taken', + fix: 'send the ask to the owner instead (log it as asked); screen only proposes rows it can take, and the detail says why this one cannot', + }, CAPTAIN_BRIEF_INCOMPLETE: { anchor: 'captain-brief-incomplete', summary: 'the plan lacks one or more of the sections the Captain brief needs (ELI5 on a run whose gate carries it, Before → after, Why it matters, What caused this work, Big decisions), so the brief is not ready for approval', diff --git a/test/owner-answers.test.ts b/test/owner-answers.test.ts new file mode 100644 index 00000000000..398b2d269cb --- /dev/null +++ b/test/owner-answers.test.ts @@ -0,0 +1,329 @@ +/** + * The owner's answer record (lib/owner-answers.ts, bin/gstack-owner-answers, docs/owner-answers.md): + * store binding on Capy, one-file rows, second-actor verification, fail-closed reads, and the screen + * rules that decide when an ask may be left out. Every owner here is made up. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawn, spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { bunIsolationArgs } from '../lib/bun-isolation'; +import { + addAnswer, buildAnswer, currentRows, notTakeable, parseAskFile, readStore, resolveStore, screenAsks, verifyAnswer, + type AskLine, type NewAnswer, type OwnerAnswer, type Store, +} from '../lib/owner-answers'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const BIN = path.join(ROOT, 'bin', 'gstack-owner-answers'); +const dirs: string[] = []; +const tmp = (prefix: string) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); dirs.push(d); return d; }; +afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); + +/** A fake home with a mounted Drive holding the given user folders. */ +function home(...users: string[]): string { + const h = tmp('oa-home-'); + for (const u of users) fs.mkdirSync(path.join(h, '.capy', 'drive', `user-${u}`), { recursive: true }); + fs.mkdirSync(path.join(h, '.capy', 'drive'), { recursive: true }); + return h; +} +const capyEnv = (h: string) => ({ GSTACK_CAPY: '1', HOME: h, GSTACK_OWNER_ANSWERS_DIR: '' }) as NodeJS.ProcessEnv; +function store(h = home('alice')): Store { + const s = resolveStore(capyEnv(h)); + if ('code' in s) throw new Error(s.message); + return s; +} + +const MERGE: NewAnswer = { action: 'merge-when-green', target: 'pull-request', scope: 'all', words: 'yes merge when green', words_by: 'owner', thread: 'CAPT-1', event: 'evt_1', by: 'Example Captain' }; +function put(s: Store, input: NewAnswer = MERGE): OwnerAnswer { + const row = buildAnswer(s, input); + if ('code' in row) throw new Error(row.message); + expect(addAnswer(s, row)).toBe('written'); + return row; +} +function takeable(s: Store, input: NewAnswer = MERGE): OwnerAnswer { + const row = put(s, input); + expect(verifyAnswer(s, row.id, 'second reader', row.source.event)).toBe('written'); + return row; +} +const ASK: AskLine = { line: 'A', origin: 'captain', text: 'Merge #12 now that it is green?', action: 'merge-when-green', target: 'pull-request', scope: 'repo:example/widgets' }; + +function cli(args: string[], env: NodeJS.ProcessEnv) { + const r = spawnSync('bun', [...bunIsolationArgs(), BIN, ...args], { cwd: ROOT, encoding: 'utf8', timeout: 60_000, env: { ...process.env, ...env } }); + return { status: r.status ?? -1, out: r.stdout ?? '', err: r.stderr ?? '' }; +} + +describe('where the record lives', () => { + test('on Capy: the one user-* Drive folder; none, two or an unknown --owner refuse, and the env override is ignored', () => { + const h = home('alice'); + const s = resolveStore({ ...capyEnv(h), GSTACK_OWNER_ANSWERS_DIR: tmp('oa-forged-') }); + expect('code' in s ? s.code : s.dir).toBe(path.join(fs.realpathSync(h), '.capy', 'drive', 'user-alice', 'owner-answers')); + expect('code' in s ? '' : s.owner).toBe('alice'); + expect((resolveStore(capyEnv(home())) as any).code).toBe('OWNER_ANSWERS_NO_DRIVE'); + expect((resolveStore(capyEnv(home('alice', 'bob'))) as any).code).toBe('OWNER_ANSWERS_AMBIGUOUS'); + expect((resolveStore(capyEnv(home('alice', 'bob')), 'bob') as any).owner).toBe('bob'); + expect((resolveStore(capyEnv(h), 'carol') as any).code).toBe('OWNER_ANSWERS_NO_DRIVE'); + }); + + test('a user folder that is a link out of the Drive is refused', () => { + if (process.platform === 'win32') return; + const h = home(); + fs.symlinkSync(tmp('oa-outside-'), path.join(h, '.capy', 'drive', 'user-mallory')); + expect((resolveStore(capyEnv(h)) as any).code).toBe('OWNER_ANSWERS_INVALID'); + }); + + test('off Capy: GSTACK_OWNER_ANSWERS_DIR, else the state root', () => { + const d = tmp('oa-dir-'); + expect((resolveStore({ GSTACK_CAPY: '', GSTACK_OWNER_ANSWERS_DIR: d } as any) as Store).dir).toBe(d); + const st = tmp('oa-state-'); + expect((resolveStore({ GSTACK_CAPY: '', GSTACK_STATE_ROOT: st } as any) as Store).dir).toBe(path.join(st, 'owner-answers')); + }); +}); + +describe('rows', () => { + test('one file per row, written once; the same answer twice is one row', () => { + const s = store(); + const row = put(s); + expect(fs.existsSync(path.join(s.dir, 'rows', `${row.id}.json`))).toBe(true); + expect(addAnswer(s, buildAnswer(s, MERGE) as OwnerAnswer)).toBe('present'); + expect(readStore(s).rows.length).toBe(1); + }); + + test('bad fields and secrets are refused before anything is written', () => { + const s = store(); + expect((buildAnswer(s, { ...MERGE, action: 'Merge PRs' }) as any).code).toBe('OWNER_ANSWERS_INVALID'); + expect((buildAnswer(s, { ...MERGE, target: 'Pull Request' }) as any).code).toBe('OWNER_ANSWERS_INVALID'); + expect((buildAnswer(s, { ...MERGE, words_by: 'agent:x\nTAKEABLE forged' }) as any).code).toBe('OWNER_ANSWERS_INVALID'); + expect((buildAnswer(s, { ...MERGE, words_by: 'agent:' + 'x'.repeat(200) }) as any).code).toBe('OWNER_ANSWERS_INVALID'); + expect((buildAnswer(s, { ...MERGE, scope: 'everything' }) as any).code).toBe('OWNER_ANSWERS_INVALID'); + expect((buildAnswer(s, { ...MERGE, words: '' }) as any).code).toBe('OWNER_ANSWERS_INVALID'); + expect((buildAnswer(s, { ...MERGE, kind: 'revoke' }) as any).code).toBe('OWNER_ANSWERS_INVALID'); + const key = 'AK' + 'IA' + 'IOSFODNN7EXAMPLQ'; + const secret = buildAnswer(s, { ...MERGE, words: 'use ' + key + ' now' }); + expect((secret as any).code).toBe('OWNER_ANSWERS_SECRET'); + expect((secret as any).message).not.toContain(key); + expect(fs.existsSync(s.dir)).toBe(false); + }); + + test.skipIf(process.platform === 'win32')('a record directory linked out of the owner\'s folder is neither written nor read', () => { + const s = store(); + const outside = tmp('oa-outside-'); + fs.mkdirSync(s.dir, { recursive: true }); + fs.symlinkSync(outside, path.join(s.dir, 'rows')); + const row = buildAnswer(s, MERGE) as OwnerAnswer; + expect((addAnswer(s, row) as any).code).toBe('OWNER_ANSWERS_INVALID'); + expect(fs.readdirSync(outside)).toEqual([]); + fs.writeFileSync(path.join(outside, `${row.id}.json`), JSON.stringify(row)); + const read = readStore(s); + expect(read.state).toBe('unavailable'); + expect(read.rows).toEqual([]); + expect(screenAsks([ASK], read)[0]!.verdict).toBe('KEEP'); + }); + + test('a write that fails after the file is created leaves no row, and the same add then succeeds', () => { + const s = store(); + const row = buildAnswer(s, MERGE) as OwnerAnswer; + const res = addAnswer(s, { ...row, limits: 1n as unknown as string }); + expect((res as any).code).toBe('OWNER_ANSWERS_WRITE_FAILED'); + expect(fs.readdirSync(path.join(s.dir, 'rows'))).toEqual([]); + expect(addAnswer(s, row)).toBe('written'); + expect(readStore(s).state).toBe('present'); + }); + + test('two processes adding at once: one row written, one told it is present, no torn file', async () => { + const h = home('alice'); + const args = ['add', '--action', 'merge-when-green', '--target', 'pull-request', '--words', 'yes merge when green', '--words-by', 'owner', '--thread', 'CAPT-1', '--event', 'evt_1', '--by', 'Example Captain']; + const run = () => new Promise<string>(resolve => { + const c = spawn('bun', [...bunIsolationArgs(), BIN, ...args], { cwd: ROOT, env: { ...process.env, ...capyEnv(h) }, timeout: 60_000 }); + let out = ''; + c.stdout.on('data', b => { out += b; }); + c.on('close', () => resolve(out)); + }); + const outs = await Promise.all([run(), run()]); + expect(outs.filter(o => /^OWNER_ANSWER_RECORDED: oa-[0-9a-f]{16}\n$/.test(o)).length).toBe(1); + expect(outs.filter(o => o.includes('(already present)')).length).toBe(1); + const read = readStore(store(h)); + expect(read.state).toBe('present'); + expect(read.rows.length).toBe(1); + }, 120_000); +}); + +describe('what can be taken', () => { + test('the owner\'s own words, verified by a second actor, current and unlimited', () => { + const s = store(); + const row = takeable(s); + expect(notTakeable(row, readStore(s))).toBeUndefined(); + }); + + test('agent-typed words, limits, other kinds and unverified rows are context only', () => { + const s = store(); + const typed = takeable(s, { ...MERGE, words_by: undefined, event: 'evt_2' }); + const limited = takeable(s, { ...MERGE, limits: 'only under $50', event: 'evt_3' }); + const decision = takeable(s, { ...MERGE, kind: 'decision', event: 'evt_4' }); + const unverified = put(s, { ...MERGE, event: 'evt_5' }); + const read = readStore(s); + expect(notTakeable(typed, read)).toContain('typed by agent:Example Captain'); + expect(notTakeable(limited, read)).toContain('limits'); + expect(notTakeable(decision, read)).toContain('context only'); + expect(notTakeable(unverified, read)).toContain('verified'); + }); + + test('the recorder cannot verify its own row, and a verification of other words does not count', () => { + const s = store(); + const row = put(s); + expect((verifyAnswer(s, row.id, 'Example Captain', row.source.event) as any).code).toBe('OWNER_ANSWERS_SELF_VERIFY'); + expect((verifyAnswer(s, row.id, 'second reader', 'evt_other') as any).code).toBe('OWNER_ANSWERS_INVALID'); + expect(notTakeable(row, readStore(s))).toContain('verified'); + fs.mkdirSync(path.join(s.dir, 'verifications'), { recursive: true }); + fs.writeFileSync(path.join(s.dir, 'verifications', `${row.id}--forged.json`), JSON.stringify({ schema_version: 1, row: row.id, verified_by: 'x', verified_at: 'now', words_sha256: '0'.repeat(64) })); + expect(notTakeable(row, readStore(s))).toContain('verified'); + }); + + test('a superseded or revoked row stops counting; two revokes in one reply cancel both grants', () => { + const s = store(); + const merge = takeable(s); + const rerun = takeable(s, { ...MERGE, action: 'rerun-flaky-once', target: 'test', words: 'just run the failed test again', event: 'evt_9' }); + const cancel = (id: string) => put(s, { kind: 'revoke', supersedes: id, words: 'ask me again about both', words_by: 'owner', thread: 'CAPT-1', event: 'evt_10', by: 'Example Captain' }); + cancel(merge.id); cancel(rerun.id); + const read = readStore(s); + expect(read.state).toBe('present'); + expect(currentRows(read).map(r => r.id)).toEqual([]); + expect(notTakeable(merge, read)).toContain('superseded'); + expect(notTakeable(rerun, read)).toContain('superseded'); + }); +}); + +describe('fail closed', () => { + const uncertain = (mutate: (s: Store, row: OwnerAnswer) => void) => { + const s = store(); + const row = takeable(s); + mutate(s, row); + const read = readStore(s); + expect(read.state).toBe('uncertain'); + expect(read.problems.length).toBeGreaterThan(0); + expect(screenAsks([ASK], read)[0]!.verdict).toBe('KEEP'); + }; + test('a malformed row file', () => uncertain(s => fs.writeFileSync(path.join(s.dir, 'rows', 'oa-0000000000000000.json'), '{ torn'))); + test('a row whose words were edited after it was written', () => uncertain((s, row) => { + const f = path.join(s.dir, 'rows', `${row.id}.json`); + fs.writeFileSync(f, JSON.stringify({ ...row, scope: 'captain:other' })); + })); + test('a row of another owner', () => uncertain(s => { + const other = resolveStore(capyEnv(home('bob'))) as Store; + const row = buildAnswer(other, { ...MERGE, event: 'evt_7' }) as OwnerAnswer; + fs.writeFileSync(path.join(s.dir, 'rows', `${row.id}.json`), JSON.stringify(row)); + })); + test('a supersede that names a missing row', () => uncertain(s => { + const row = buildAnswer(s, { ...MERGE, event: 'evt_8', supersedes: 'oa-ffffffffffffffff' }) as OwnerAnswer; + fs.writeFileSync(path.join(s.dir, 'rows', `${row.id}.json`), JSON.stringify(row)); + })); + test('two rows that supersede the same row (two machines writing before their Drives sync)', () => uncertain((s, row) => { + put(s, { ...MERGE, words: 'merge when green, any repo', event: 'evt_11', supersedes: row.id }); + const twin = buildAnswer(s, { ...MERGE, words: 'merge when green, gstack only', event: 'evt_12', supersedes: row.id }) as OwnerAnswer; + fs.writeFileSync(path.join(s.dir, 'rows', `${twin.id}.json`), JSON.stringify(twin)); + })); + test('a second supersede or revoke of an already-replaced row is refused, not written', () => { + const s = store(); + const row = put(s); + expect(addAnswer(s, buildAnswer(s, { ...MERGE, kind: 'revoke', supersedes: row.id, event: 'evt_2' }) as OwnerAnswer)).toBe('written'); + expect(addAnswer(s, buildAnswer(s, { ...MERGE, kind: 'revoke', supersedes: row.id, event: 'evt_2' }) as OwnerAnswer)).toBe('present'); + expect((addAnswer(s, buildAnswer(s, { ...MERGE, kind: 'revoke', supersedes: row.id, event: 'evt_3' }) as OwnerAnswer) as any).code).toBe('OWNER_ANSWERS_CONFLICT'); + expect(readStore(s).state).toBe('present'); + }); + test('a second add with different words for one source and action is refused, not kept', () => { + const s = store(); + put(s); + const twin = buildAnswer(s, { ...MERGE, words: 'merge whenever' }) as OwnerAnswer; + expect((addAnswer(s, twin) as any).code).toBe('OWNER_ANSWERS_CONFLICT'); + expect(readStore(s).rows.map(r => r.words)).toEqual(['yes merge when green']); + }); + test('supersede through the API refuses a missing row', () => { + const s = store(); + const row = buildAnswer(s, { ...MERGE, supersedes: 'oa-ffffffffffffffff' }) as OwnerAnswer; + expect((addAnswer(s, row) as any).code).toBe('OWNER_ANSWERS_NOT_FOUND'); + }); +}); + +describe('screen', () => { + const verdicts = (asks: AskLine[], s: Store) => screenAsks(asks, readStore(s)).map(x => `${x.verdict}: ${x.reason}`); + test('an exact typed match with a takeable row is proposed, with the line the Captain adds', () => { + const s = store(); + const row = takeable(s, { ...MERGE, rule: 'R6' }); + const [line] = screenAsks([ASK], readStore(s)); + expect(line!.verdict).toBe('PROPOSE_TAKE'); + expect(line!.take!.id).toBe(row.id); + }); + + test('gate items, untyped, compound, fresh-ask, near-miss and wrong-scope lines are kept', () => { + const s = store(); + takeable(s, { ...MERGE, scope: 'captain:alpha' }); + const out = verdicts([ + { ...ASK, origin: 'gate', scope: 'captain:alpha' }, + { ...ASK, origin: undefined, scope: 'captain:alpha' }, + { line: 'C', origin: 'captain', text: 'Merge #12?' }, + { ...ASK, compound: true, scope: 'captain:alpha' }, + { ...ASK, limits: 'only PRs under 50 lines', scope: 'captain:alpha' }, + { ...ASK, classes: ['destructive'], scope: 'captain:alpha' }, + { ...ASK, classes: ['made-up'], scope: 'captain:alpha' }, + { ...ASK, text: 'Merge #12 and spend $400 on a rerun?', scope: 'captain:alpha' }, + { ...ASK, action: 'merge-now', scope: 'captain:alpha' }, + { ...ASK, scope: 'captain:beta' }, + { ...ASK, scope: 'repo:example/widgets' }, + ], s); + expect(out.every(v => v.startsWith('KEEP'))).toBe(true); + expect(out[0]).toContain('gate item'); + expect(out[2]).toContain('no typed action'); + expect(out[4]).toContain('limits'); + expect(out[7]).toContain('spend-over-cap'); + expect(screenAsks([{ ...ASK, scope: 'captain:alpha' }], readStore(s))[0]!.verdict).toBe('PROPOSE_TAKE'); + }); + + test('a newer or narrower matching row that cannot be taken keeps the ask', () => { + const s = store(); + takeable(s); + put(s, { ...MERGE, kind: 'decision', scope: 'repo:example/widgets', words: 'not in widgets, wait for the owners', event: 'evt_20' }); + const [line] = screenAsks([ASK], readStore(s)); + expect(line!.verdict).toBe('KEEP'); + expect(line!.reason).toContain('newer or narrower'); + expect(screenAsks([{ ...ASK, scope: 'repo:example/other' }], readStore(s))[0]!.verdict).toBe('PROPOSE_TAKE'); + }); + + test('an empty record keeps everything', () => { + expect(screenAsks([ASK], readStore(store()))[0]!.reason).toContain('empty'); + }); + + test('plain-text ask files parse as untyped lines', () => { + const asks = parseAskFile('A: Merge #12?\nB) Spend $400?\n\n') as AskLine[]; + expect(asks.map(a => a.line)).toEqual(['A', 'B']); + expect(asks.every(a => !a.action)).toBe(true); + expect((parseAskFile('{ nope') as any).code).toBe('OWNER_ANSWERS_INVALID'); + }); +}); + +describe('gstack-owner-answers', () => { + test('add, verify, screen, log and status end to end; logging a take of an untakeable row refuses', () => { + const h = home('alice'); + const env = capyEnv(h); + const add = cli(['add', '--action', 'merge-when-green', '--target', 'pull-request', '--words', 'yes merge when green', '--words-by', 'owner', '--thread', 'CAPT-1', '--event', 'evt_1', '--by', 'Example Captain', '--rule', 'R6'], env); + expect(add.status).toBe(0); + const id = /OWNER_ANSWER_RECORDED: (oa-[0-9a-f]{16})/.exec(add.out)![1]!; + expect(cli(['log', '--thread', 'CAPT-1', '--line', 'A', '--decision', 'taken', '--row', id, '--by', 'Example Captain'], env).err).toContain('(OWNER_ANSWERS_NOT_TAKEABLE)'); + expect(cli(['verify', id, '--event', 'evt_1', '--by', 'Example Captain'], env).err).toContain('(OWNER_ANSWERS_SELF_VERIFY)'); + expect(cli(['verify', id, '--event', 'evt_1', '--by', 'second reader'], env).status).toBe(0); + const askFile = path.join(tmp('oa-ask-'), 'ask.json'); + fs.writeFileSync(askFile, JSON.stringify({ asks: [ASK, { line: 'B', origin: 'captain', text: 'Close their PR?', classes: ['close-contribution'] }] })); + const screen = cli(['screen', '--ask-file', askFile], env); + expect(screen.status).toBe(0); + expect(screen.out).toContain(`PROPOSE_TAKE A ${id}: Not asked, you already said: "yes merge when green"`); + expect(screen.out).toMatch(/already said: "yes merge when green" \(\d{4}-\d{2}-\d{2}, CAPT-1, R6\)\./); + expect(screen.out).toMatch(/^KEEP B: always a fresh ask: close-contribution$/m); + expect(screen.out).not.toContain(h); + expect(fs.readFileSync(askFile, 'utf8')).toContain('"line":"B"'); + expect(cli(['log', '--thread', 'CAPT-1', '--line', 'A', '--decision', 'taken', '--row', id, '--by', 'Example Captain'], env).status).toBe(0); + expect(cli(['log', '--thread', '../x', '--line', 'A', '--decision', 'asked', '--by', 'x'], env).status).toBe(2); + const status = cli(['status'], env); + expect(status.out).toMatch(/^STATE: present$/m); + expect(status.out).toMatch(/^ROWS: 1 current=1 takeable=1 verifications=1$/m); + expect(cli(['add', '--action', 'x'], capyEnv(home())).err).toContain('(OWNER_ANSWERS_NO_DRIVE)'); + }, 120_000); +}); From dd4266dc4b5acb72772c32e4aec32835d659a094 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 07:19:24 +0800 Subject: [PATCH 55/62] Check each app build with an agent from another model family before its owner is asked to try it (GST-3025) (#4465) Adds `gstack-first-use`: before an app build reaches its owner as "ready to try", an agent from another model family plays that exact build, does the plan's first five day-one actions with a screenshot or video of each, and checks every link. Only then does it print the "try this build" message. Why: a recent app build passed every review and its owner still found the first screen broken, because nothing tried the build the way the owner would. Nothing to do now; the first real use is that app's next build. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/red-team#4 reader=red-team --- README.md | 1 + bin/gstack-doctor-components.sh | 6 + bin/gstack-first-use | 148 +++++++ capy/skill/gstack/captain.md | 8 + ...st-use-check-before-owner-tries-a-build.md | 1 + docs/first-use-check.md | 93 +++++ docs/troubleshooting.md | 30 ++ lib/first-use-message.ts | 115 ++++++ lib/first-use.ts | 324 +++++++++++++++ lib/result-codes-capy.ts | 30 ++ test/first-use.test.ts | 369 ++++++++++++++++++ test/fixtures/first-use/autoplan-plan.md | 25 ++ test/fixtures/first-use/one-page-plan.md | 17 + test/fixtures/first-use/play.json | 24 ++ test/helpers/free-fixtures-data.ts | 1 + 15 files changed, 1192 insertions(+) create mode 100755 bin/gstack-first-use create mode 100644 changelog.d/first-use-check-before-owner-tries-a-build.md create mode 100644 docs/first-use-check.md create mode 100644 lib/first-use-message.ts create mode 100644 lib/first-use.ts create mode 100644 test/first-use.test.ts create mode 100644 test/fixtures/first-use/autoplan-plan.md create mode 100644 test/fixtures/first-use/one-page-plan.md create mode 100644 test/fixtures/first-use/play.json diff --git a/README.md b/README.md index 59a4f1e74eb..d863952d286 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,7 @@ On Windows without Developer Mode (MSYS2 / Git Bash), `setup` falls back to file | [First Production Deploy](docs/howto-bring-up-a-first-deploy.md) | What to do when `/setup-deploy` says nothing is deployed yet: hosting, env and secrets, DNS, checking it works, then back to `/setup-deploy` | | [Land a fix in someone else's repo](docs/howto-land-a-fix-in-someone-elses-repo.md) | Read their rules, search for the same fix, run every guard their CI runs before opening, keep it small, answer each review point in a new commit | | [Run a human playtest](docs/howto-run-human-playtests.md) | Ask about moments and where people would stop, and why a back-to-back pick between two builds measures the order, not the build | +| [Check a build before its owner tries it](docs/first-use-check.md) | `gstack-first-use`: an agent from another model family plays the exact build cold, does the first five day-one actions with evidence, checks every link, and only then prints the "try this build" message | | [Builder Ethos](ETHOS.md) | Builder philosophy: Boil the Ocean, Search Before Building, three layers of knowledge | | [GBrain quick tour](docs/gbrain-quick-tour.md) | The four setup paths, MCP registration, the per-repo trust policy, memory sync, Conductor env vars | | [Using GBrain with GStack](USING_GBRAIN_WITH_GSTACK.md) | Every path, flag, bin helper, and troubleshooting step for `/setup-gbrain` | diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index ee78184e68f..8226db50449 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -410,6 +410,12 @@ gstack_result_anchor() { ARCHIVE_GH_READ_FAILED) printf '%s' 'archive-gh-read-failed' ;; ARCHIVE_PR_STATE_UNKNOWN) printf '%s' 'archive-pr-state-unknown' ;; ARCHIVE_POLICY_UNREADABLE) printf '%s' 'archive-policy-unreadable' ;; + FIRST_USE_PLAN_UNREADY) printf '%s' 'first-use-plan-unready' ;; + FIRST_USE_PLAY_SPEC_INCOMPLETE) printf '%s' 'first-use-play-spec-incomplete' ;; + FIRST_USE_SAME_FAMILY) printf '%s' 'first-use-same-family' ;; + FIRST_USE_NO_PRIVATE_DRIVE) printf '%s' 'first-use-no-private-drive' ;; + FIRST_USE_RECORD_INVALID) printf '%s' 'first-use-record-invalid' ;; + FIRST_USE_REFUSED) printf '%s' 'first-use-refused' ;; BUDGET_CAP_REACHED) printf '%s' 'budget-cap-reached' ;; BUDGET_READING_MISSING) printf '%s' 'budget-reading-missing' ;; METER_SCOPE_PARENT) printf '%s' 'meter-scope-parent' ;; diff --git a/bin/gstack-first-use b/bin/gstack-first-use new file mode 100755 index 00000000000..55285ada7fe --- /dev/null +++ b/bin/gstack-first-use @@ -0,0 +1,148 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * gstack-first-use — the cold first-use check for an app build (docs/first-use-check.md). + * + * gstack-first-use start --app <slug> --plan <plan.md> --play <play.json> --platform ios|android|web --commit <sha> + * (--testflight <build> | --deploy <version>) --builder <model> --checker <model> [--json] + * gstack-first-use brief --run <dir> + * gstack-first-use record --run <dir> --action <n> --verdict pass|fail --evidence <file> --device <text> --account <text> --by <model> [--note <text>] [--json] + * gstack-first-use predict --run <dir> --score <1-10> --why <text> --by <model> [--json] + * gstack-first-use links --run <dir> --account <owner-equivalent account> --device-class ios|android|web [--json] + * gstack-first-use check --run <dir> --platform … --commit … (--testflight … | --deploy …) [--json] + * gstack-first-use message --run <dir> --platform … --commit … (--testflight … | --deploy …) + * gstack-first-use score --run <dir> --score <1-10> --words "<owner's exact words>" --by <who relayed them> [--json] + * gstack-first-use show --run <dir> [--json] + * gstack-first-use root + * + * start freezes the first five rows of the plan's ### Day one table and the build fingerprint into a + * write-once manifest; brief prints what the checker from the other model family gets; record, predict + * and links write its evidence, predicted score and dated link receipts; check prints FIRST_USE: pass + * or refuses (FIRST_USE_REFUSED); message prints the "try this build" text only when check passes; + * score keeps the owner's score and words beside the prediction. Records live in the owner's private + * user-level Capy Drive folder (GSTACK_FIRST_USE_DIR overrides). Logic: lib/first-use.ts. + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; +import { buildLabel, checkLinks, decide, ownerScore, predict, readManifest, recordResult, recordRoot, startRun, type BuildId, type FirstUseError } from '../lib/first-use'; +import { renderBrief, renderPlayMessage } from '../lib/first-use-message'; +import { resultLine } from '../lib/result-codes'; + +const HELP = `gstack-first-use — a cold first-use check on an app build before its owner tries it (docs/first-use-check.md) + + start --app <slug> --plan <plan.md> --play <play.json> --platform ios|android|web --commit <sha> + (--testflight <build> | --deploy <version>) --builder <model> --checker <model> [--json] + brief --run <dir> what the checker from the other model family is given + record --run <dir> --action <n> --verdict pass|fail --evidence <file> --device <text> --account <text> --by <model> [--note <text>] + predict --run <dir> --score <1-10> --why <text> --by <model> + links --run <dir> --account <text> --device-class ios|android|web check every play link now, as the owner-equivalent audience + check --run <dir> --platform … --commit … (--testflight … | --deploy …) FIRST_USE: pass, or refused + message --run <dir> --platform … --commit … (--testflight … | --deploy …) the "try this build" text, only after a pass + score --run <dir> --score <1-10> --words "<owner's exact words>" --by <who relayed them> + show --run <dir> [--json] + root where records live + +${exitTableHelp()}`; + +const flag = (args: string[], name: string) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }; +const say = (line: string) => process.stdout.write(line + '\n'); +const refuse = (cmd: string, e: FirstUseError) => { process.stderr.write(resultLine(`gstack-first-use ${cmd}`, e.code, e.detail) + '\n'); return e.code === 'FIRST_USE_RECORD_INVALID' ? EXIT.fail : EXIT.refused; }; +const buildArgs = (a: string[]): Partial<BuildId> => ({ platform: flag(a, '--platform') as BuildId['platform'], commit: flag(a, '--commit'), testflight: flag(a, '--testflight'), deploy: flag(a, '--deploy') }); + +/** The --run directory, which must sit inside the record root so evidence and scores stay in the private record. */ +function runDir(cmd: string, a: string[]): string | number { + const run = flag(a, '--run'); + if (!run) { process.stderr.write(`gstack-first-use: ${cmd} needs --run <dir>\n`); return EXIT.usage; } + const root = recordRoot(); + if ('error' in root) return refuse(cmd, root.error); + let real: string, realRoot: string; + try { real = fs.realpathSync(run); realRoot = fs.realpathSync(root.root); } catch { return refuse(cmd, { code: 'FIRST_USE_RECORD_INVALID', detail: `no run directory at ${run}` }); } + if (!real.startsWith(realRoot + path.sep)) return refuse(cmd, { code: 'FIRST_USE_RECORD_INVALID', detail: `${run} is outside the record root ${root.root}` }); + return real; +} + +function cmdStart(a: string[], json: boolean): number { + const need = ['--app', '--plan', '--play', '--platform', '--commit', '--builder', '--checker'].filter(f => !flag(a, f)); + if (need.length) { process.stderr.write(`gstack-first-use: start needs ${need.join(', ')}\n`); return EXIT.usage; } + const root = recordRoot(); + if ('error' in root) return refuse('start', root.error); + let play: unknown; + try { play = JSON.parse(fs.readFileSync(flag(a, '--play')!, 'utf8')); } catch { return refuse('start', { code: 'FIRST_USE_PLAY_SPEC_INCOMPLETE', detail: `${flag(a, '--play')} is not a readable JSON play spec` }); } + const r = startRun({ root: root.root, app: flag(a, '--app')!, planPath: flag(a, '--plan')!, build: buildArgs(a), play, builder: flag(a, '--builder')!, checker: flag(a, '--checker')! }); + if ('error' in r) return refuse('start', r.error); + if (json) { say(JSON.stringify({ run: r.dir, actions: r.manifest.actions.length, rows_sha256: r.manifest.source.rows_sha256, build: r.manifest.build })); return EXIT.ok; } + say(`FIRST_USE_RUN: ${r.dir}`); + say(`FIRST_USE_FROZEN: ${r.manifest.actions.length} actions rows=${r.manifest.source.rows_sha256.slice(0, 12)} build=${buildLabel(r.manifest.build)} checker=${r.manifest.checker.model}`); + r.manifest.actions.forEach(x => say(` ${x.n}. ${x.action}`)); + say(`NEXT: gstack-first-use brief --run "${r.dir}" (give it to one fresh agent on ${r.manifest.checker.model}, never a ${r.manifest.builder.family} model)`); + return EXIT.ok; +} + +function cmdShow(dir: string, json: boolean): number { + const read = readManifest(dir); + if ('error' in read) return refuse('show', read.error); + const m = read.manifest; + const d = decide(dir, m.build); + const summary = { app: m.app, build: buildLabel(m.build), checker: m.checker.model, actions: m.actions.length, passed: d.passed, reasons: d.reasons, + predicted: d.prediction?.score ?? null, owner: d.owner ? { score: d.owner.score, words: d.owner.words, at: d.owner.at } : null, + gap: d.prediction && d.owner ? d.owner.score - d.prediction.score : null }; + if (json) { say(JSON.stringify(summary)); return EXIT.ok; } + say(`FIRST_USE_SHOW: app=${m.app} build=${summary.build} passed=${d.passed}/${m.actions.length} predicted=${summary.predicted ?? 'none'} owner=${summary.owner?.score ?? 'none'}${summary.gap === null ? '' : ` gap=${summary.gap > 0 ? '+' : ''}${summary.gap}`}`); + if (summary.owner) say(`OWNER_WORDS: ${summary.owner.words}`); + for (const r of d.reasons) say(`OPEN: ${r}`); + return EXIT.ok; +} + +async function main(argv: string[]): Promise<number> { + const [cmd, ...a] = argv; + if (!cmd || cmd === '--help' || cmd === '-h') { say(HELP); return cmd ? EXIT.ok : EXIT.usage; } + const json = a.includes('--json'); + if (cmd === 'root') { const r = recordRoot(); if ('error' in r) return refuse('root', r.error); say(`FIRST_USE_ROOT: ${r.root}`); return EXIT.ok; } + if (cmd === 'start') return cmdStart(a, json); + if (!['brief', 'record', 'predict', 'links', 'check', 'message', 'score', 'show'].includes(cmd)) { process.stderr.write(`gstack-first-use: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; } + const dir = runDir(cmd, a); + if (typeof dir === 'number') return dir; + if (cmd === 'show') return cmdShow(dir, json); + if (cmd === 'brief') { + const read = readManifest(dir); + if ('error' in read) return refuse(cmd, read.error); + process.stdout.write(renderBrief(read.manifest, dir)); + process.stderr.write(`DISPATCH: give this brief, and nothing else about the build, to one fresh agent on ${read.manifest.checker.model} (not a ${read.manifest.builder.family} model) on its own machine; it runs its own gstack install check first\n`); + return EXIT.ok; + } + if (cmd === 'record') { + const n = Number(flag(a, '--action')); + const r = recordResult({ dir, action: Number.isInteger(n) ? n : -1, verdict: flag(a, '--verdict') ?? '', evidence: flag(a, '--evidence') ?? '', device: flag(a, '--device') ?? '', account: flag(a, '--account') ?? '', by: flag(a, '--by') ?? '', note: flag(a, '--note') }); + if ('error' in r) return refuse(cmd, r.error); + say(json ? JSON.stringify(r.result) : `FIRST_USE_RESULT: action=${r.result.action} verdict=${r.result.verdict} evidence=${r.result.evidence.file} sha256=${r.result.evidence.sha256.slice(0, 12)}`); + return EXIT.ok; + } + if (cmd === 'predict') { + const r = predict({ dir, score: flag(a, '--score') ?? '', why: flag(a, '--why') ?? '', by: flag(a, '--by') ?? '' }); + if ('error' in r) return refuse(cmd, r.error); + say(json ? JSON.stringify(r.prediction) : `FIRST_USE_PREDICTED: ${r.prediction.score} (${r.prediction.by.model})`); + return EXIT.ok; + } + if (cmd === 'score') { + const r = ownerScore({ dir, score: flag(a, '--score') ?? '', words: flag(a, '--words') ?? '', by: flag(a, '--by') ?? '' }); + if ('error' in r) return refuse(cmd, r.error); + say(json ? JSON.stringify({ score: r.owner.score, at: r.owner.at }) : `FIRST_USE_OWNER_SCORE: ${r.owner.score} recorded in the private record`); + return EXIT.ok; + } + if (cmd === 'links') { + const r = await checkLinks(dir, { account: flag(a, '--account'), device_class: flag(a, '--device-class') as BuildId['platform'] }); + if ('error' in r) return refuse(cmd, r.error); + if (json) say(JSON.stringify(r.receipts)); + else r.receipts.forEach(x => say(`LINK: ${x.verdict} status=${x.status || x.error || 'none'} as=${x.audience.device_class} ${x.url}`)); + return r.receipts.every(x => x.verdict === 'live') ? EXIT.ok : EXIT.fail; + } + const d = decide(dir, buildArgs(a)); + if (!d.ok) return refuse(cmd, { code: 'FIRST_USE_REFUSED', detail: d.reasons.join('; ') }); + if (cmd === 'message') { process.stdout.write(renderPlayMessage(d)); return EXIT.ok; } + const m = d.manifest!; + say(json ? JSON.stringify({ ok: true, app: m.app, build: m.build, passed: d.passed, links: d.links.length, predicted: d.prediction?.score }) + : `FIRST_USE: pass app=${m.app} build=${buildLabel(m.build)} actions=${d.passed}/${m.actions.length} links=${d.links.length}/${m.play.links.length} checker=${m.checker.model} predicted=${d.prediction?.score}`); + return EXIT.ok; +} + +process.exit(await main(process.argv.slice(2))); diff --git a/capy/skill/gstack/captain.md b/capy/skill/gstack/captain.md index 0e9374902cf..6287ee0eaee 100644 --- a/capy/skill/gstack/captain.md +++ b/capy/skill/gstack/captain.md @@ -170,3 +170,11 @@ take every reading (start, notes, close) from its own row of the root thread's ` reason=budget_exhausted`, `status=incomplete`), the lane reports the BUDGET and RECOVER lines and asks the owner; it never raises the cap itself. The owner's answer runs the RECOVER line with `--approved-by <who> --words "<their words>"`, and `gstack-approvals add` records the same words. + +## 5. Asks to try a build + +An ask for the owner to try an app build, and any "v1 is ready" report, goes out only after the build clears +`gstack-first-use` (`docs/first-use-check.md` in the checkout): an agent from another model family plays that exact +build cold on the same kind of device and does the plan's first five day-one actions, with a screenshot or video of +each. Send the text `gstack-first-use message` prints, unchanged; when it refuses, fix the build and replay instead of +asking. Record the owner's score and words with `gstack-first-use score`, never in a PR or the repository. diff --git a/changelog.d/first-use-check-before-owner-tries-a-build.md b/changelog.d/first-use-check-before-owner-tries-a-build.md new file mode 100644 index 00000000000..38a83b8e155 --- /dev/null +++ b/changelog.d/first-use-check-before-owner-tries-a-build.md @@ -0,0 +1 @@ +- **A cold first-use check before an app build reaches its owner (GST-3025).** New `gstack-first-use` freezes the first five day-one actions from the plan and the exact build, has an agent from another model family play that build on the same kind of device with a screenshot or video for each action, checks every link within 15 minutes of sending, and prints the "try this build" message only when all of it passes. The owner's score and words are kept beside the checker's predicted score in the owner's private drive. See `docs/first-use-check.md`. diff --git a/docs/first-use-check.md b/docs/first-use-check.md new file mode 100644 index 00000000000..467bf40b503 --- /dev/null +++ b/docs/first-use-check.md @@ -0,0 +1,93 @@ +# Check an app build before its owner tries it + +When an agent builds an app for someone, every review can pass and the first thing the owner taps can still be broken. `gstack-first-use` closes that gap. Before a build reaches its owner as "ready to try", a fresh agent from a **different model family** than the one that built it plays that exact build cold, on the same kind of device and account the owner uses. It does the first five things the plan says the owner will do on day one, saves a screenshot or short video of each, checks that every link in the message is live, and predicts the owner's score from 1 to 10. Only when all of that passes does the tool print the "try this build" message. + +It gates two things: the message that asks the owner to try a build, and any "v1 is ready" report. It does not gate `/ship`: code review and the first-use check answer different questions. + +## The steps + +Run these from the thread that owns the build (on Capy, a Captain or the agent building the app). + +1. **Freeze the five actions and the build.** + + ```bash + gstack-first-use start --app plantpal --plan plan.md --play play.json \ + --platform ios --commit <full commit sha> --testflight 17 \ + --builder anthropic/claude-opus-5-5 --checker openai/gpt-6.2-sol + ``` + + It reads the first five rows of the plan's day-one table, records their hash, the play spec and the build fingerprint (the commit plus the TestFlight build number, or `--deploy <version>` for a web or Android build) in a write-once `manifest.json`, and prints `FIRST_USE_RUN: <dir>`. It refuses when the table is missing or malformed, has fewer than five rows, has an empty cell in its first five rows or still has a row marked `assumed` among them, when the play spec misses a part, or when the checker's model family is the builder's. + +2. **Hand the checker its brief.** `gstack-first-use brief --run <dir>` prints everything the checker gets: the device and account, the play text, and the five frozen actions with the commands to record each. Give it to one fresh agent on the `--checker` model and nothing else about the build: no plan, no code, no notes. Every value the brief puts into a command is shell-quoted, so the checker can paste the lines as they are. On Capy, start a subagent with that model on `machine: "fresh"`; it attaches a cloud phone with `tools.capy.phone` (`attach`, then `install` with the build from `tools.mobile.build`) and drives the screen with `tools.capy.computer`, or opens a web build in the browser. It runs its own gstack install check first. + +3. **The checker records each action and predicts the score.** + + ```bash + gstack-first-use record --run <dir> --action 1 --verdict pass --evidence today.png \ + --device "iPhone 17 Pro (cloud)" --account "fresh Apple ID" --by openai/gpt-6.2-sol + gstack-first-use predict --run <dir> --score 6 --why "reminders work, adding plants is slow" --by openai/gpt-6.2-sol + ``` + + The evidence file (PNG, JPEG, GIF, WebP, HEIC, MP4, MOV or WebM, up to 100 MB) is copied into the run and recorded with its hash and size. A fail needs `--note` saying what happened. Only the checker's family may record, and `--account` must be the play spec's owner-equivalent account exactly (the brief prints it), so a pass on a developer or admin account doesn't count. Replaying an action adds a new result; the newest one counts. + +4. **Check the links right before sending.** `gstack-first-use links --run <dir> --account "<the play spec's account>" --device-class ios` opens every link in the play spec and writes a dated receipt for each, bound to that audience: the owner-equivalent account and the build's device class. It refuses any other audience, and the gate counts only receipts for this one. A link passes on a 2xx or 3xx answer. A 401 or 403 passes only when the play spec marks the link `"login_gated": true`. The request itself carries no sign-in, so for a login-gated link the receipt proves the link is up and gated; the checker's played results on that account prove the sign-in works. + +5. **Print the message.** `gstack-first-use message --run <dir> --platform ios --commit <sha> --testflight 17` prints the "try this build" text only when every check below passes, and refuses otherwise, printing nothing on stdout. Send that text as it is. For a "v1 is ready" report, run `gstack-first-use check` with the same flags and paste its `FIRST_USE: pass …` line. + +6. **Save the owner's reaction.** When the owner replies, `gstack-first-use score --run <dir> --score 4 --words "4, Talk is slow" --by "<who relayed it>"`. `gstack-first-use show --run <dir>` prints the predicted score, the owner's score and words, and the gap between them. + +## What the gate refuses + +`check` and `message` pass only when all of these hold. Each failure is listed in the `FIRST_USE_REFUSED` line ([troubleshooting](troubleshooting.md#first-use-refused)). + +- The build you're about to send is the one that was checked (`build_mismatch`). +- The plan's first five day-one rows haven't changed since `start` (`source_changed`, `source_missing`). An edit elsewhere in the plan doesn't count. +- Every frozen action's newest result, from the checker's family on the owner-equivalent account, is a pass, and its evidence file still matches its hash (`action_<n>_not_played`, `action_<n>_failed`, `action_<n>_evidence_stale`). +- Every link has a live receipt from the last 15 minutes, checked as the owner-equivalent account and device class (`link_unchecked`, `link_down`, `link_stale`). +- The checker predicted a score (`no_predicted_score`). + +The message never shows the predicted score, so it can't anchor the owner's own. + +## The day-one table + +Both kinds of plan feed the check in one format: the day-one table that `/autoplan` puts on the plan-approval page, and the one-page list of the first five things the owner does on day one. Either one needs a heading named `Day one` (any level; `Day-one page` also works) followed by a table with these seven columns, in any order: + +| action | frequency | source | feature | route | first build | check | +|---|---|---|---|---|---|---| +| sees which plant needs water today | daily | owner words 1 | Today list | root screen | build 1 | the plant due today is at the top, marked due | + +The table needs at least five rows, and every cell of the first five needs a value; the check freezes those five in table order. A row whose source starts with `assumed` must be confirmed with the owner before `start` will freeze it. `test/first-use.test.ts` pins this format with one fixture of each kind, so a change to the table parser fails that test instead of quietly changing what gets checked. + +<a id="play-spec"></a> +## Play-message requirements + +Every ask to play or try a build carries full play instructions in the same message (the factory's play-instructions rule, R47). The play spec is a JSON file with one field per part, and `start` refuses one that's missing any: + +| Part | Field | Notes | +|---|---|---| +| 1. The links | `links`: `[{ "label", "url", "login_gated"? }]` | http or https; each checked live within 15 minutes of sending | +| 2. Device and setup | `device`, `setup`, `account` | the owner's device kind and account kind; the checker plays on the same kind, and results and link receipts are bound to `account` and the build's platform | +| 3. What it is, in a sentence | `what` | | +| 4. How to start | `start` | | +| 5. Controls | `controls` | | +| 6. How long to play | `minutes` | a whole number from 1 to 240 | +| 7. What we want to learn | `learn` | | +| 8. How to report back | `report` | the message adds "a score from 1 to 10 and one line" | +| 9. Known quirks | `quirks` | "none" is fine; empty isn't | +| 10. Reply word | `reply_word` | one word | + +## Where the record lives + +The record holds the owner's own scores and words, so it stays private. On Capy it lives in the owner's user-level Capy Drive folder (`~/.capy/drive/user-*/first-use/<app>/<run>/`), which every thread the owner has opened can read and nobody else's can. If none or several such folders are mounted, the tool refuses rather than fall back to the machine's throwaway folder. Off Capy it lives under the gstack state root (`first-use/`). `GSTACK_FIRST_USE_DIR` overrides both. Nothing from a run belongs in a public repository or a PR body. + +A run directory holds `manifest.json`, `results/`, `evidence/`, `links/`, `prediction.json` and `owner/`. Every file is written once; to check again (a new build, changed day-one rows, a new prediction), start a new run. + +## How we'll know it helps + +With a handful of builds, this is a case series, not an eval. For each build, keep the pass count, the owner's score and words, the predicted score, and any escape: a day-one action that failed on the owner's device after the check passed it. The targets are zero escapes and a median owner score of 7 or more across the next three app builds. `gstack-first-use show --json` prints each run's numbers. + +## What it doesn't do yet + +- It doesn't drive the owner's own phone; it plays on a cloud device of the same kind. +- It doesn't dispatch the checker by itself; the thread that owns the build starts it with the brief. +- It doesn't check the wording of other messages sent to the owner. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 3da9afc6687..ee35ecf7bd8 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2405,6 +2405,36 @@ whose Plan line differs from the PR body's current line. **Fix.** The lane fixes the PR body's Plan line if needed and reruns `gstack-ship-queue ready --pr <n>` at the pin. +<a id="first-use-plan-unready"></a> +### `gstack-first-use start: ... (FIRST_USE_PLAN_UNREADY)` + +**Meaning.** `start` could not freeze the day-one actions: the plan has no `### Day one` table, the table is missing a column or has fewer than five rows, one of its first five rows has an empty cell, or one of them is still marked `assumed`. Exit 3; nothing is written. **Fix.** Give the plan the pinned table ([first-use-check.md](first-use-check.md#the-day-one-table)) and confirm every assumed row with the owner, then rerun `start`. + +<a id="first-use-play-spec-incomplete"></a> +### `gstack-first-use start: ... (FIRST_USE_PLAY_SPEC_INCOMPLETE)` + +**Meaning.** The play spec JSON misses one of the ten parts every ask to play or try a build carries (links, device and setup, what it is, how to start, controls, how long, what we want to learn, how to report back, known quirks, reply word). The line names each missing part and field. Exit 3. **Fix.** Fill them in ([first-use-check.md](first-use-check.md#play-spec)); "none" is a fine value for known quirks. + +<a id="first-use-same-family"></a> +### `gstack-first-use start|record|predict: ... (FIRST_USE_SAME_FAMILY)` + +**Meaning.** The check needs an agent from a different model family than the one that built the app. The builder and checker are the same family, a family could not be read from the model id, or `--by` on a result or prediction is not the run's checker family. Exit 3. **Fix.** Pass full `provider/model` ids from different families, and let only the checker record results. + +<a id="first-use-no-private-drive"></a> +### `gstack-first-use: ... (FIRST_USE_NO_PRIVATE_DRIVE)` + +**Meaning.** On Capy the record holds the owner's scores and words, so it lives only in his private user-level drive folder. None or several `~/.capy/drive/user-*` folders are mounted, so the tool refuses rather than writing to the machine's throwaway folder. Exit 3. **Fix.** Run it in a thread the owner owns, or set `GSTACK_FIRST_USE_DIR` to his private folder. + +<a id="first-use-record-invalid"></a> +### `gstack-first-use: ... (FIRST_USE_RECORD_INVALID)` + +**Meaning.** A value or file is invalid: a bad `--commit`, `--action`, `--verdict` or score, an `--account` or `--device-class` that isn't the run's owner-equivalent audience, a run directory outside the record root, evidence that is not a screenshot or short video (or is empty, a link, or over 100 MB), an unreadable manifest, or a second prediction on a run. Exit 1. **Fix.** Correct the value. Run files are written once; to redo a check, start a new run. + +<a id="first-use-refused"></a> +### `gstack-first-use check|message: ... (FIRST_USE_REFUSED)` + +**Meaning.** The build has not cleared its first-use check, so `message` prints no "try this build" text and `check` prints no `FIRST_USE: pass` line. The detail lists every reason: `build_mismatch`, `source_changed`, `source_missing`, `action_<n>_not_played`, `action_<n>_failed`, `action_<n>_evidence_stale`, `link_unchecked`, `link_down`, `link_stale` (over 15 minutes old), `no_predicted_score`, `record_unreadable`. Exit 3. **Fix.** Fix the build and replay failed actions, rerun `links` right before sending, or start a new run for a new build or changed day-one rows. + ## /ship token budget and fresh-context handoffs (gstack-ship-budget) The flow, the BUDGET line field by field and the meters are in [ship-budget.md](ship-budget.md). diff --git a/lib/first-use-message.ts b/lib/first-use-message.ts new file mode 100644 index 00000000000..151d7b4c08c --- /dev/null +++ b/lib/first-use-message.ts @@ -0,0 +1,115 @@ +/** + * first-use-message — the play spec and the two texts the first-use check prints + * (docs/first-use-check.md). The play spec holds the ten parts every ask to play + * or try a build carries (the factory's R47): the links, the device and setup, + * what it is, how to start, the controls, how long, what we want to learn, how + * to report back, known quirks and the reply word. renderPlayMessage() is the + * only "try this build" text, printed after decide() passes; renderBrief() is + * what the cold checker from the other model family is given, and nothing more. + */ +import { buildLabel, type Decision, type FirstUseError, type Manifest } from './first-use'; + +export interface PlayLink { url: string; label: string; login_gated?: boolean } +export interface PlaySpec { + links: PlayLink[]; device: string; setup: string; account: string; what: string; start: string; + controls: string; minutes: number; learn: string; report: string; quirks: string; reply_word: string; +} +/** R47's ten parts in order, with the play-spec fields each one reads. */ +export const PLAY_PARTS: Array<{ part: string; fields: Array<keyof PlaySpec> }> = [ + { part: 'The links, each checked live minutes before sending', fields: ['links'] }, + { part: 'Device and setup', fields: ['device', 'setup', 'account'] }, + { part: 'What it is, in a sentence', fields: ['what'] }, + { part: 'How to start', fields: ['start'] }, + { part: 'Controls', fields: ['controls'] }, + { part: 'How long to play', fields: ['minutes'] }, + { part: 'What we want to learn', fields: ['learn'] }, + { part: 'How to report back', fields: ['report'] }, + { part: 'Known quirks', fields: ['quirks'] }, + { part: 'Reply word', fields: ['reply_word'] }, +]; +const TEXT_FIELDS = ['device', 'setup', 'account', 'what', 'start', 'controls', 'learn', 'report', 'quirks', 'reply_word'] as const; + +/** A complete play spec, or the R47 parts it is missing. "none" is a fine answer for quirks; an empty field is not. */ +export function checkPlaySpec(raw: unknown): { spec: PlaySpec } | { error: FirstUseError } { + const o = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>; + const bad = new Set<keyof PlaySpec>(); + for (const f of TEXT_FIELDS) if (typeof o[f] !== 'string' || !(o[f] as string).trim()) bad.add(f); + if (typeof o.reply_word === 'string' && !/^[A-Za-z][A-Za-z0-9-]{0,23}$/.test(o.reply_word.trim())) bad.add('reply_word'); + if (!Number.isInteger(o.minutes) || (o.minutes as number) < 1 || (o.minutes as number) > 240) bad.add('minutes'); + const links = Array.isArray(o.links) ? o.links as Array<Record<string, unknown>> : []; + const linkOk = (l: Record<string, unknown>) => typeof l?.label === 'string' && !!l.label.trim() && typeof l.url === 'string' && /^https?:\/\/[^\s]+$/.test(l.url) + && (l.login_gated === undefined || typeof l.login_gated === 'boolean'); + if (!links.length || !links.every(linkOk)) bad.add('links'); + if (bad.size) { + const parts = PLAY_PARTS.filter(p => p.fields.some(f => bad.has(f))).map(p => `${p.part} (${p.fields.filter(f => bad.has(f)).join(', ')})`); + return { error: { code: 'FIRST_USE_PLAY_SPEC_INCOMPLETE', detail: `missing or invalid: ${parts.join('; ')}` } }; + } + const spec: PlaySpec = { + links: links.map(l => ({ url: l.url as string, label: (l.label as string).trim(), ...(l.login_gated ? { login_gated: true } : {}) })), + minutes: o.minutes as number, + ...Object.fromEntries(TEXT_FIELDS.map(f => [f, (o[f] as string).trim()])) as Omit<PlaySpec, 'links' | 'minutes'>, + }; + return { spec }; +} + +const hhmm = (iso: string) => iso.slice(11, 16); +const platformName = { ios: 'iOS', android: 'Android', web: 'web' } as const; + +/** The "try this build" message: R47's ten parts, then what the cold check covered. Call only after decide() passed. */ +export function renderPlayMessage(d: Decision, now: Date = new Date()): string { + const m = d.manifest!, p = m.play; + const checked = d.links.map(l => Date.parse(l.checked_at)); + const oldest = Math.min(...checked); + const ago = Math.max(0, Math.round((now.getTime() - oldest) / 60_000)); + return [ + `**Try ${m.app}: ${buildLabel(m.build)}**`, '', + `1. **Links** (each checked live at ${new Date(oldest).toISOString().slice(11, 16)} UTC, ${ago} min before this message):`, + ...p.links.map(l => ` - [${l.label}](${l.url})${l.login_gated ? ' (asks you to sign in)' : ''}`), + `2. **Device and setup:** ${p.device}. ${p.setup} Account: ${p.account}.`, + `3. **What it is:** ${p.what}`, + `4. **How to start:** ${p.start}`, + `5. **Controls:** ${p.controls}`, + `6. **How long:** about ${p.minutes} minutes.`, + `7. **What we want to learn:** ${p.learn}`, + `8. **How to report back:** ${p.report} Give it a score from 1 to 10 and one line on what stood out.`, + `9. **Known quirks:** ${p.quirks}`, + `10. **Reply word:** ${p.reply_word}, then your score and your line, for example "${p.reply_word} 7, the first screen was slow".`, + '', + `Checked before it reached you: an agent from another model family (${m.checker.model}) played this exact build cold on a ${platformName[m.build.platform]} cloud device and did the first ${m.actions.length} things you'll do on day one. All ${d.passed} worked, with a screenshot or video of each:`, + ...m.actions.map(a => `- ${a.action}`), + '', + ].join('\n'); +} + +/** One POSIX shell word: single quotes, with each embedded single quote closed, escaped and reopened. */ +export const shellQuote = (v: string) => `'${v.replace(/'/g, `'\\''`)}'`; + +/** What the cold checker is given: the build, the device and account, the play message parts and the frozen actions, with the commands that record each. */ +export function renderBrief(m: Manifest, dir: string): string { + const p = m.play, b = m.build; + const install = b.platform === 'web' + ? 'open the first link in a browser on that device' + : `attach a ${platformName[b.platform]} phone (\`tools.capy.phone\` with action "attach", platform "${b.platform}" and the model closest to the device above), install this exact build on it (action "install"; ${b.testflight ? `TestFlight build ${b.testflight}` : `version ${b.deploy}`}), and drive its screen with \`tools.capy.computer.on({ machine_id })\``; + const by = `--by ${shellQuote(m.checker.model)}`, run = `--run ${shellQuote(dir)}`; + return [ + `# Cold first-use check: ${m.app}, ${buildLabel(b)}`, '', + `You are playing this build for the first time, as its owner will. You run on ${m.checker.model}; the team that built it runs on ${m.builder.family} models, and you have not seen its plan, code, notes or messages. Do not read them: you get only what the owner gets, below.`, '', + '## Device and account', '', + `Use the same kind of device and account as the owner: ${p.device}. ${p.setup} Account: ${p.account} (play only on this kind of account; \`record\` takes it exactly). On Capy, ${install}.`, '', + '## What the owner is told', '', + `- What it is: ${p.what}`, `- Links: ${p.links.map(l => `${l.label} ${l.url}`).join('; ')}`, `- How to start: ${p.start}`, `- Controls: ${p.controls}`, + `- How long: about ${p.minutes} minutes`, `- Known quirks: ${p.quirks}`, '', + `## The ${m.actions.length} things the owner will do on day one (frozen ${m.created_at.slice(0, 10)})`, '', + ...m.actions.map(a => `${a.n}. ${a.action} (${a.frequency || 'how often unstated'}). Way in: ${a.route || 'not stated'}. It works when: ${a.check}`), '', + '## What to do', '', + '1. Do each action as the owner would, from a cold start, with no help beyond the text above.', + '2. Capture a screenshot or a short video that shows the result, then record it. A pass means the owner would see it work on the first try; anything else is a fail, and the note says what happened:', + '', '```bash', `gstack-first-use record ${run} --action N --verdict pass --evidence FILE --device 'DEVICE YOU USED' --account ${shellQuote(p.account)} ${by}`, + `gstack-first-use record ${run} --action N --verdict fail --evidence FILE --device 'DEVICE YOU USED' --account ${shellQuote(p.account)} ${by} --note 'WHAT HAPPENED'`, '```', '', + '3. Predict the owner\'s score from 1 to 10 for this build, with one line on why:', '', + '```bash', `gstack-first-use predict ${run} --score N --why 'ONE LINE' ${by}`, '```', '', + '4. Report back: one line per action (pass or fail and why), your predicted score, and the one thing most likely to disappoint the owner.', + '', + ].join('\n'); +} + diff --git a/lib/first-use.ts b/lib/first-use.ts new file mode 100644 index 00000000000..3f7ed6a7e81 --- /dev/null +++ b/lib/first-use.ts @@ -0,0 +1,324 @@ +/** + * first-use — the cold first-use check for an app build (docs/first-use-check.md). + * Before a build reaches its owner as "ready to try", an agent from another model + * family plays that exact build on the same kind of device and account and does + * the first five things the plan's day-one table says the owner will do. This + * module keeps the record: an immutable start manifest (the frozen day-one rows + * with their hash, the play spec, the build fingerprint, the builder's and the + * checker's model families), one write-once file per action result with its + * evidence copied in and hashed, dated link receipts, the checker's predicted + * score and the owner's scores and words. decide() reads it back and refuses the + * "try it" message unless every frozen action passed on this build, every link + * was live within 15 minutes, the day-one rows are unchanged and a prediction + * exists. The record lives in the owner's private user-level Capy Drive folder + * on Capy (never the public repository), else under the gstack state root. + */ +import * as crypto from 'node:crypto'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { parseDayOne } from './autoplan-owner-text'; +import { resolveStateRoot } from './state-root'; +import { checkPlaySpec, type PlaySpec } from './first-use-message'; + +export const FIRST_USE_ACTIONS = 5; +export const LINK_FRESH_MS = 15 * 60 * 1000; +export const EVIDENCE_MAX_BYTES = 100 * 1024 * 1024; +export const EVIDENCE_KINDS: Record<string, 'screenshot' | 'video'> = { + '.png': 'screenshot', '.jpg': 'screenshot', '.jpeg': 'screenshot', '.gif': 'screenshot', '.webp': 'screenshot', '.heic': 'screenshot', + '.mp4': 'video', '.mov': 'video', '.webm': 'video', +}; +export type FirstUseCode = 'FIRST_USE_PLAN_UNREADY' | 'FIRST_USE_PLAY_SPEC_INCOMPLETE' | 'FIRST_USE_SAME_FAMILY' | 'FIRST_USE_NO_PRIVATE_DRIVE' | 'FIRST_USE_RECORD_INVALID' | 'FIRST_USE_REFUSED'; +export interface FirstUseError { code: FirstUseCode; detail: string } +type Result<T> = T | { error: FirstUseError }; +const fail = (code: FirstUseCode, detail: string) => ({ error: { code, detail } }); + +export interface FrozenAction { n: number; action: string; frequency: string; feature: string; route: string; first_build: string; check: string; source: string } +export interface BuildId { platform: 'ios' | 'android' | 'web'; commit: string; testflight?: string; deploy?: string } +export interface Manifest { + schema_version: 1; kind: 'first-use-manifest'; app: string; created_at: string; + source: { path: string; rows_sha256: string }; actions: FrozenAction[]; + build: BuildId & { fingerprint: string }; play: PlaySpec; + builder: { model: string; family: string }; checker: { model: string; family: string }; +} +export interface ActionResult { + schema_version: 1; kind: 'first-use-result'; action: number; action_text: string; build_fingerprint: string; at: string; + verdict: 'pass' | 'fail'; evidence: { file: string; sha256: string; bytes: number; kind: 'screenshot' | 'video' }; + device: string; account: string; by: { model: string; family: string }; note: string; +} +/** Who a check speaks for: the owner-equivalent account from the play spec and the build's device class. */ +export interface Audience { account: string; device_class: BuildId['platform'] } +export const audienceOf = (m: Manifest): Audience => ({ account: m.play.account, device_class: m.build.platform }); +const sameAudience = (a: Partial<Audience> | undefined, b: Audience) => a?.account === b.account && a?.device_class === b.device_class; +export interface LinkReceipt { schema_version: 1; kind: 'first-use-link'; url: string; build_fingerprint: string; audience: Audience; checked_at: string; status: number; login_gated: boolean; verdict: 'live' | 'down'; error?: string } +export interface Prediction { schema_version: 1; kind: 'first-use-prediction'; score: number; why: string; by: { model: string; family: string }; at: string; build_fingerprint: string } +export interface OwnerScore { schema_version: 1; kind: 'first-use-owner-score'; score: number; words: string; by: string; at: string; build_fingerprint: string } + +const FAMILY_WORDS: Array<[string, RegExp]> = [ + ['anthropic', /\b(claude|opus|sonnet|haiku|fable)\b/], + ['openai', /\b(gpt|codex|chatgpt)\b/], + ['google', /\bgemini\b/], + ['xai', /\bgrok\b/], + ['meta', /\b(llama|muse)\b/], + ['deepseek', /\bdeepseek\b/], + ['moonshotai', /\bkimi\b/], + ['qwen', /\bqwen\b/], +]; +/** + * A model's family: a known provider before the slash (`openai/gpt-6.2-sol` is openai), a bare family name, or a known + * model word, which also wins over a routing prefix (`openrouter/anthropic/claude-…` is anthropic); else the unknown + * provider before the slash, or undefined. + */ +export function modelFamily(model: string): string | undefined { + const s = model.trim().toLowerCase(); + if (!s) return undefined; + const slash = s.indexOf('/'); + const prefix = slash > 0 ? s.slice(0, slash) : s; + if (FAMILY_WORDS.some(([f]) => f === prefix)) return prefix; + return FAMILY_WORDS.find(([, re]) => re.test(s))?.[0] ?? (slash > 0 ? prefix : undefined); +} + +/** The first five rows of the plan's `### Day one` table (lib/autoplan-owner-text.ts parses it; the format is pinned by test/first-use.test.ts). */ +export function freezeActions(planText: string): Result<{ actions: FrozenAction[]; rows_sha256: string }> { + const day = parseDayOne(planText); + if (day.status === 'none') return fail('FIRST_USE_PLAN_UNREADY', 'the plan has no ### Day one table'); + if (day.status === 'malformed') return fail('FIRST_USE_PLAN_UNREADY', day.reason ?? 'the day-one table is malformed'); + if (day.rows.length < FIRST_USE_ACTIONS) return fail('FIRST_USE_PLAN_UNREADY', `the day-one table has ${day.rows.length} row${day.rows.length === 1 ? '' : 's'}; the check needs ${FIRST_USE_ACTIONS}`); + const rows = day.rows.slice(0, FIRST_USE_ACTIONS); + const blank = rows.map((r, i) => [r.frequency, r.source, r.feature, r.route, r.first_build, r.check].some(c => !c.trim()) ? i + 1 : 0).filter(Boolean); + if (blank.length) return fail('FIRST_USE_PLAN_UNREADY', `day-one row ${blank.join(', ')} has an empty cell; every column of the first ${FIRST_USE_ACTIONS} rows needs a value`); + const assumed = rows.map((r, i) => r.assumed ? i + 1 : 0).filter(Boolean); + if (assumed.length) return fail('FIRST_USE_PLAN_UNREADY', `day-one row ${assumed.join(', ')} is still marked assumed`); + const actions = rows.map((r, i) => ({ n: i + 1, action: r.action, frequency: r.frequency, feature: r.feature, route: r.route, first_build: r.first_build, check: r.check, source: r.source })); + return { actions, rows_sha256: sha256(JSON.stringify(actions)) }; +} + +/** Validates a build id; the fingerprint is the hash of platform, commit and the TestFlight build or deploy version. */ +export function buildFingerprint(b: Partial<BuildId>): Result<BuildId & { fingerprint: string }> { + if (b.platform !== 'ios' && b.platform !== 'android' && b.platform !== 'web') return fail('FIRST_USE_RECORD_INVALID', '--platform must be ios, android or web'); + if (!/^[0-9a-f]{40}$/.test(b.commit ?? '')) return fail('FIRST_USE_RECORD_INVALID', '--commit must be the full 40-character commit the build was made from'); + const tf = b.testflight?.trim(), dep = b.deploy?.trim(); + if (!!tf === !!dep) return fail('FIRST_USE_RECORD_INVALID', 'give exactly one of --testflight <build number> or --deploy <version>'); + const id: BuildId = { platform: b.platform, commit: b.commit!, ...(tf ? { testflight: tf } : { deploy: dep }) }; + return { ...id, fingerprint: sha256(JSON.stringify([id.platform, id.commit, id.testflight ?? '', id.deploy ?? ''])).slice(0, 16) }; +} +export const buildLabel = (b: BuildId) => `${b.commit.slice(0, 12)}, ${b.testflight ? `TestFlight build ${b.testflight}` : `deploy ${b.deploy}`}`; + +/** + * Where records live: GSTACK_FIRST_USE_DIR; on Capy (GSTACK_CAPY=1) the one `~/.capy/drive/user-*` folder's + * `first-use/` (none or several refuses, never the throwaway machine folder); elsewhere `<state root>/first-use`. + */ +export function recordRoot(env: NodeJS.ProcessEnv = process.env): Result<{ root: string }> { + if (env.GSTACK_FIRST_USE_DIR) return { root: path.resolve(env.GSTACK_FIRST_USE_DIR) }; + if (env.GSTACK_CAPY !== '1') return { root: path.join(resolveStateRoot(env), 'first-use') }; + const drive = path.join(env.HOME || os.homedir(), '.capy', 'drive'); + let found: string[] = []; + try { found = fs.readdirSync(drive).filter(d => d.startsWith('user-') && fs.statSync(path.join(drive, d)).isDirectory()); } catch { /* no drive mounted */ } + if (found.length !== 1) return fail('FIRST_USE_NO_PRIVATE_DRIVE', found.length ? `${found.length} user-level drive folders (${found.join(', ')})` : `no user-level drive folder under ${drive}`); + return { root: path.join(drive, found[0]!, 'first-use') }; +} + +const sha256 = (data: string | Buffer) => crypto.createHash('sha256').update(data).digest('hex'); +const stamp = (d: Date) => d.toISOString().replace(/[-:]/g, ''); +const writeOnce = (file: string, value: unknown) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' }); +}; +const readJson = <T>(file: string): T | undefined => { try { return JSON.parse(fs.readFileSync(file, 'utf8')) as T; } catch { return undefined; } }; + +export interface StartInput { root: string; app: string; planPath: string; build: Partial<BuildId>; play: unknown; builder: string; checker: string; now?: Date } +/** Freezes the day-one rows and writes the run's manifest once; returns the run directory. */ +export function startRun(o: StartInput): Result<{ dir: string; manifest: Manifest }> { + if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(o.app)) return fail('FIRST_USE_RECORD_INVALID', '--app must be a lowercase slug like ghome'); + let planText: string; + try { planText = fs.readFileSync(o.planPath, 'utf8'); } catch { return fail('FIRST_USE_PLAN_UNREADY', `cannot read ${o.planPath}`); } + const frozen = freezeActions(planText); + if ('error' in frozen) return frozen; + const play = checkPlaySpec(o.play); + if ('error' in play) return play; + const build = buildFingerprint(o.build); + if ('error' in build) return build; + const builder = modelFamily(o.builder), checker = modelFamily(o.checker); + if (!builder || !checker) return fail('FIRST_USE_SAME_FAMILY', `unknown model family for ${!builder ? `--builder ${o.builder}` : `--checker ${o.checker}`}`); + if (builder === checker) return fail('FIRST_USE_SAME_FAMILY', `builder and checker are both ${builder}`); + const now = o.now ?? new Date(); + const manifest: Manifest = { + schema_version: 1, kind: 'first-use-manifest', app: o.app, created_at: now.toISOString(), + source: { path: path.resolve(o.planPath), rows_sha256: frozen.rows_sha256 }, actions: frozen.actions, + build, play: play.spec, builder: { model: o.builder, family: builder }, checker: { model: o.checker, family: checker }, + }; + const dir = path.join(o.root, o.app, `${stamp(now)}-${build.fingerprint.slice(0, 8)}`); + try { writeOnce(path.join(dir, 'manifest.json'), manifest); } catch (e) { return fail('FIRST_USE_RECORD_INVALID', `cannot write ${dir}/manifest.json: ${(e as Error).message}`); } + return { dir, manifest }; +} + +export function readManifest(dir: string): Result<{ manifest: Manifest }> { + const m = readJson<Manifest>(path.join(dir, 'manifest.json')); + if (!m || m.schema_version !== 1 || m.kind !== 'first-use-manifest' || !Array.isArray(m.actions) || !m.build?.fingerprint) return fail('FIRST_USE_RECORD_INVALID', `no readable manifest.json in ${dir}`); + return { manifest: m }; +} + +/** The checker's own model, from its own family: the builder never grades its own build. */ +function checkerOf(m: Manifest, by: string): Result<{ by: { model: string; family: string } }> { + const family = modelFamily(by); + if (!family || family !== m.checker.family) return fail('FIRST_USE_SAME_FAMILY', `--by ${by} is ${family ?? 'an unknown family'}; this run's checker is ${m.checker.family} (${m.checker.model})`); + return { by: { model: by, family } }; +} + +export interface RecordInput { dir: string; action: number; verdict: string; evidence: string; device: string; account: string; by: string; note?: string; now?: Date } +/** One write-once result for one frozen action; the evidence file is copied into the run and hashed. */ +export function recordResult(o: RecordInput): Result<{ file: string; result: ActionResult }> { + const read = readManifest(o.dir); + if ('error' in read) return read; + const m = read.manifest; + const action = m.actions.find(a => a.n === o.action); + if (!action) return fail('FIRST_USE_RECORD_INVALID', `--action must be 1 to ${m.actions.length}`); + if (o.verdict !== 'pass' && o.verdict !== 'fail') return fail('FIRST_USE_RECORD_INVALID', '--verdict must be pass or fail'); + if (!o.device.trim()) return fail('FIRST_USE_RECORD_INVALID', 'name the --device you played on'); + if (o.account.trim() !== m.play.account) return fail('FIRST_USE_RECORD_INVALID', `play on the owner-equivalent account and pass it exactly: --account "${m.play.account}"`); + if (o.verdict === 'fail' && !o.note?.trim()) return fail('FIRST_USE_RECORD_INVALID', 'a fail needs --note saying what happened'); + const who = checkerOf(m, o.by); + if ('error' in who) return who; + const ev = copyEvidence(o.dir, o.action, o.evidence); + if ('error' in ev) return ev; + const now = o.now ?? new Date(); + const result: ActionResult = { + schema_version: 1, kind: 'first-use-result', action: o.action, action_text: action.action, build_fingerprint: m.build.fingerprint, at: now.toISOString(), + verdict: o.verdict, evidence: ev.evidence, device: o.device.trim(), account: o.account.trim(), by: who.by, note: o.note?.trim() ?? '', + }; + const file = path.join(o.dir, 'results', `${o.action}-${stamp(now)}-${crypto.randomBytes(3).toString('hex')}.json`); + try { writeOnce(file, result); } catch (e) { return fail('FIRST_USE_RECORD_INVALID', `cannot write ${file}: ${(e as Error).message}`); } + return { file, result }; +} + +function copyEvidence(dir: string, n: number, src: string): Result<{ evidence: ActionResult['evidence'] }> { + const kind = EVIDENCE_KINDS[path.extname(src).toLowerCase()]; + if (!kind) return fail('FIRST_USE_RECORD_INVALID', `evidence must be a screenshot or short video (${Object.keys(EVIDENCE_KINDS).join(' ')})`); + let st: fs.Stats; + try { st = fs.lstatSync(src); } catch { return fail('FIRST_USE_RECORD_INVALID', `no evidence file at ${src}`); } + if (!st.isFile()) return fail('FIRST_USE_RECORD_INVALID', 'the evidence must be a regular file, not a link or directory'); + if (st.size === 0 || st.size > EVIDENCE_MAX_BYTES) return fail('FIRST_USE_RECORD_INVALID', `the evidence is ${st.size} bytes (1 to ${EVIDENCE_MAX_BYTES})`); + const bytes = fs.readFileSync(src); + const digest = sha256(bytes); + const file = path.join('evidence', `${n}-${digest.slice(0, 16)}${path.extname(src).toLowerCase()}`); + try { + fs.mkdirSync(path.join(dir, 'evidence'), { recursive: true }); + if (!fs.existsSync(path.join(dir, file))) fs.writeFileSync(path.join(dir, file), bytes, { flag: 'wx' }); + } catch (e) { return fail('FIRST_USE_RECORD_INVALID', `cannot write ${path.join(dir, file)}: ${(e as Error).message}`); } + return { evidence: { file, sha256: digest, bytes: bytes.length, kind } }; +} + +export type Fetcher = (url: string) => Promise<{ status: number }>; +export const liveFetcher: Fetcher = async url => { + const res = await fetch(url, { method: 'GET', redirect: 'follow', signal: AbortSignal.timeout(15_000) }); + await res.body?.cancel().catch(() => undefined); + return { status: res.status }; +}; + +/** + * Checks every play link once for the run's audience (the owner-equivalent account and device class) and writes a + * dated receipt per link bound to that audience; a login-gated link passes on 401 or 403 only when the play spec marks it. + */ +export async function checkLinks(dir: string, as: Partial<Audience>, fetcher: Fetcher = liveFetcher, now: () => Date = () => new Date()): Promise<Result<{ receipts: LinkReceipt[] }>> { + const read = readManifest(dir); + if ('error' in read) return read; + const m = read.manifest, audience = audienceOf(m); + if (!sameAudience(as, audience)) return fail('FIRST_USE_RECORD_INVALID', `check links as the owner-equivalent audience: --account "${audience.account}" --device-class ${audience.device_class}`); + const receipts: LinkReceipt[] = []; + for (const [i, link] of m.play.links.entries()) { + let status = 0, error: string | undefined; + try { status = (await fetcher(link.url)).status; } catch (e) { error = (e as Error).message || String(e); } + const gated = !!link.login_gated; + const live = (status >= 200 && status < 400) || (gated && (status === 401 || status === 403)); + const at = now(); + const receipt: LinkReceipt = { schema_version: 1, kind: 'first-use-link', url: link.url, build_fingerprint: m.build.fingerprint, audience, checked_at: at.toISOString(), status, login_gated: gated, verdict: live ? 'live' : 'down', ...(error ? { error } : {}) }; + const file = path.join(dir, 'links', `${stamp(at)}-${i + 1}-${crypto.randomBytes(3).toString('hex')}.json`); + try { writeOnce(file, receipt); } catch (e) { return fail('FIRST_USE_RECORD_INVALID', `cannot write ${file}: ${(e as Error).message}`); } + receipts.push(receipt); + } + return { receipts }; +} + +const score = (s: string) => /^(10|[1-9])$/.test(s.trim()) ? Number(s.trim()) : undefined; + +/** The checker's predicted owner score, written once per run. */ +export function predict(o: { dir: string; score: string; why: string; by: string; now?: Date }): Result<{ prediction: Prediction }> { + const read = readManifest(o.dir); + if ('error' in read) return read; + const n = score(o.score); + if (n === undefined || !o.why.trim()) return fail('FIRST_USE_RECORD_INVALID', 'predict needs --score 1-10 and --why <one line>'); + const who = checkerOf(read.manifest, o.by); + if ('error' in who) return who; + const prediction: Prediction = { schema_version: 1, kind: 'first-use-prediction', score: n, why: o.why.trim(), by: who.by, at: (o.now ?? new Date()).toISOString(), build_fingerprint: read.manifest.build.fingerprint }; + try { writeOnce(path.join(o.dir, 'prediction.json'), prediction); } catch { return fail('FIRST_USE_RECORD_INVALID', 'this run already has a predicted score; start a new run to predict again'); } + return { prediction }; +} + +/** The owner's own score and exact words, appended (the newest counts); kept beside the prediction in the private record. */ +export function ownerScore(o: { dir: string; score: string; words: string; by: string; now?: Date }): Result<{ owner: OwnerScore }> { + const read = readManifest(o.dir); + if ('error' in read) return read; + const n = score(o.score); + if (n === undefined || !o.words.trim() || !o.by.trim()) return fail('FIRST_USE_RECORD_INVALID', 'score needs --score 1-10, --words "<the owner’s exact words>" and --by <who relayed them>'); + const now = o.now ?? new Date(); + const owner: OwnerScore = { schema_version: 1, kind: 'first-use-owner-score', score: n, words: o.words, by: o.by.trim(), at: now.toISOString(), build_fingerprint: read.manifest.build.fingerprint }; + const file = path.join(o.dir, 'owner', `${stamp(now)}-${crypto.randomBytes(3).toString('hex')}.json`); + try { writeOnce(file, owner); } catch (e) { return fail('FIRST_USE_RECORD_INVALID', `cannot write ${file}: ${(e as Error).message}`); } + return { owner }; +} + +function readDir<T>(dir: string): { rows: T[]; unreadable: string[] } { + const rows: T[] = [], unreadable: string[] = []; + let names: string[] = []; + try { names = fs.readdirSync(dir).filter(f => f.endsWith('.json')).sort(); } catch { /* none yet */ } + for (const f of names) { const r = readJson<T>(path.join(dir, f)); if (r) rows.push(r); else unreadable.push(f); } + return { rows, unreadable }; +} +const newest = <T extends { at?: string; checked_at?: string }>(rows: T[]) => [...rows].sort((a, b) => (a.at ?? a.checked_at ?? '').localeCompare(b.at ?? b.checked_at ?? '')).at(-1); + +export interface Decision { ok: boolean; reasons: string[]; manifest?: Manifest; passed: number; links: LinkReceipt[]; prediction?: Prediction; owner?: OwnerScore } +/** + * Whether this run clears the build about to be sent: the same build, unchanged day-one rows, a pass with intact + * evidence for every frozen action, a live receipt under 15 minutes old for every play link, and a predicted score. + */ +export function decide(dir: string, build: Partial<BuildId>, now: Date = new Date()): Decision { + const read = readManifest(dir); + if ('error' in read) return { ok: false, reasons: [read.error.detail], passed: 0, links: [] }; + const m = read.manifest, reasons: string[] = []; + const current = buildFingerprint(build); + if ('error' in current) reasons.push(current.error.detail); + else if (current.fingerprint !== m.build.fingerprint) reasons.push(`build_mismatch: this run checked ${buildLabel(m.build)}, not ${buildLabel(current)}`); + let planText: string | undefined; + try { planText = fs.readFileSync(m.source.path, 'utf8'); } catch { reasons.push(`source_missing: ${m.source.path}`); } + if (planText !== undefined) { + const again = freezeActions(planText); + if ('error' in again) reasons.push(`source_changed: ${again.error.detail}`); + else if (again.rows_sha256 !== m.source.rows_sha256) reasons.push('source_changed: the day-one rows changed since the check started; start a new run'); + } + if (m.builder.family === m.checker.family) reasons.push('same_family'); + const results = readDir<ActionResult>(path.join(dir, 'results')); + if (results.unreadable.length) reasons.push(`record_unreadable: results/${results.unreadable.join(', results/')}`); + let passed = 0; + for (const a of m.actions) { + const r = newest(results.rows.filter(x => x.action === a.n && x.build_fingerprint === m.build.fingerprint && x.by?.family === m.checker.family && x.account === m.play.account)); + if (!r) { reasons.push(`action_${a.n}_not_played`); continue; } + if (r.verdict !== 'pass') { reasons.push(`action_${a.n}_failed: ${r.note}`); continue; } + let bytes: Buffer | undefined; + try { bytes = fs.readFileSync(path.join(dir, r.evidence.file)); } catch { /* missing */ } + if (!bytes || bytes.length !== r.evidence.bytes || sha256(bytes) !== r.evidence.sha256) { reasons.push(`action_${a.n}_evidence_stale`); continue; } + passed++; + } + const receipts = readDir<LinkReceipt>(path.join(dir, 'links')); + const links: LinkReceipt[] = []; + for (const link of m.play.links) { + const r = newest(receipts.rows.filter(x => x.url === link.url && x.build_fingerprint === m.build.fingerprint && sameAudience(x.audience, audienceOf(m)))); + if (!r) { reasons.push(`link_unchecked: ${link.url} (as ${m.play.account} on ${m.build.platform})`); continue; } + links.push(r); + if (r.verdict !== 'live') reasons.push(`link_down: ${link.url} (status ${r.status || r.error || 'none'})`); + else if (now.getTime() - Date.parse(r.checked_at) > LINK_FRESH_MS) reasons.push(`link_stale: ${link.url} was checked at ${r.checked_at}, over 15 minutes ago`); + } + const prediction = readJson<Prediction>(path.join(dir, 'prediction.json')); + if (!prediction) reasons.push('no_predicted_score'); + const owner = newest(readDir<OwnerScore>(path.join(dir, 'owner')).rows); + return { ok: reasons.length === 0, reasons, manifest: m, passed, links, prediction, owner }; +} diff --git a/lib/result-codes-capy.ts b/lib/result-codes-capy.ts index b6dcf3b1ca3..d42752d6f17 100644 --- a/lib/result-codes-capy.ts +++ b/lib/result-codes-capy.ts @@ -200,4 +200,34 @@ export const CAPY_RESULT_CODES = { summary: 'gstack-archive-check landed found no usable .gstack/plain-titles.json (missing, invalid or with no codes), so it cannot tell a tracker code from any other ref and closes nothing', fix: 'run it from the repository root, where .gstack/plain-titles.json lives; if the file is missing or invalid there, fix it on main (docs/ship-policy.md#plain-titles) and rerun; close nothing until then', }, + FIRST_USE_PLAN_UNREADY: { + anchor: 'first-use-plan-unready', + summary: 'the plan has no usable ### Day one table to freeze (missing, malformed, fewer than five complete rows, or a row still marked assumed)', + fix: 'add or fix the ### Day one table (action, frequency, source, feature, route, first build, check) and confirm every assumed row with the owner, then run start again', + }, + FIRST_USE_PLAY_SPEC_INCOMPLETE: { + anchor: 'first-use-play-spec-incomplete', + summary: 'the play spec is missing one or more of the ten parts every ask to play or try a build carries', + fix: 'fill in the parts the line names in the play spec JSON (docs/first-use-check.md#play-spec), then run start again', + }, + FIRST_USE_SAME_FAMILY: { + anchor: 'first-use-same-family', + summary: 'the checker is from the builder’s model family, its family is unknown, or a result was recorded by a model other than the run’s checker family', + fix: 'name the builder and checker as provider/model ids from different families (for example anthropic/… and openai/…), and record results only from the checker', + }, + FIRST_USE_NO_PRIVATE_DRIVE: { + anchor: 'first-use-no-private-drive', + summary: 'on Capy, the first-use record needs exactly one user-level Capy Drive folder (~/.capy/drive/user-*) and found none or several', + fix: 'run it in a thread of the build’s owner, where his private user drive is mounted, or set GSTACK_FIRST_USE_DIR to his private folder; never fall back to the machine folder', + }, + FIRST_USE_RECORD_INVALID: { + anchor: 'first-use-record-invalid', + summary: 'a first-use record input or file is invalid (bad flag value, unreadable manifest, a run outside the record root, bad evidence, or a write-once file that already exists)', + fix: 'correct the value the line names; never edit or delete files in a run directory, start a new run instead', + }, + FIRST_USE_REFUSED: { + anchor: 'first-use-refused', + summary: 'the build has not cleared its first-use check, so no "try this build" message or "v1 is ready" report may go out', + fix: 'act on each reason the line lists: replay the failed or unplayed actions, rerun links within 15 minutes of sending, add the predicted score, or start a new run for a new build or changed day-one rows', + }, } satisfies Record<string, ResultCode>; diff --git a/test/first-use.test.ts b/test/first-use.test.ts new file mode 100644 index 00000000000..96b2e543dbe --- /dev/null +++ b/test/first-use.test.ts @@ -0,0 +1,369 @@ +/** + * The first-use check (lib/first-use.ts, lib/first-use-message.ts, bin/gstack-first-use; + * docs/first-use-check.md). Every owner, app, plan and build here is made up. Pins the + * day-one table format both plan sources share (autoplan's ### Day one table and the + * one-page day-one list), so a change to lib/autoplan-owner-text.ts fails here rather + * than silently changing what the check freezes. Runs under a temporary HOME, drive and + * record root, serves its links from a local server, and proves the real drive is untouched. + */ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { DAY_ONE_COLUMNS, DAY_ONE_TITLES } from '../lib/autoplan-owner-text'; +import { buildFingerprint, checkLinks, decide, freezeActions, modelFamily, ownerScore, predict, readManifest, recordResult, recordRoot, startRun, type Fetcher } from '../lib/first-use'; +import { checkPlaySpec, PLAY_PARTS, renderBrief, renderPlayMessage } from '../lib/first-use-message'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const FIX = path.join(ROOT, 'test', 'fixtures', 'first-use'); +const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'first-use-')); +afterAll(() => fs.rmSync(TMP, { recursive: true, force: true })); + +const AUTOPLAN = fs.readFileSync(path.join(FIX, 'autoplan-plan.md'), 'utf8'); +const ONE_PAGE = fs.readFileSync(path.join(FIX, 'one-page-plan.md'), 'utf8'); +const PLAY = JSON.parse(fs.readFileSync(path.join(FIX, 'play.json'), 'utf8')); +const COMMIT = 'c0ffee'.padEnd(40, '0'); +const BUILD = { platform: 'ios' as const, commit: COMMIT, testflight: '17' }; +const T0 = new Date('2026-11-18T10:00:00Z'); +const ACTIONS = [ + 'adds her first three plants by photo', 'sees which plant needs water today', 'marks a plant as watered', 'gets a reminder at 8am', "opens a plant's care card", +]; +let n = 0; +const fresh = (name: string) => { const d = path.join(TMP, `${name}-${++n}`); fs.mkdirSync(d, { recursive: true }); return d; }; +const shot = (dir: string, name = 'shot.png', body = 'png bytes') => { const f = path.join(dir, name); fs.writeFileSync(f, body); return f; }; +const playWith = (port: number) => ({ ...PLAY, links: PLAY.links.map((l: { url: string }) => ({ ...l, url: l.url.replace('PORT', String(port)) })) }); +const AS = { account: PLAY.account, device_class: 'ios' as const }; +const okFetch: Fetcher = async url => ({ status: url.endsWith('/account') ? 401 : 200 }); + +/** A run on its own plan copy and record root, with every action passed, the links checked and a prediction. */ +function passedRun(o: { plan?: string } = {}) { + const root = fresh('root'), work = fresh('work'); + const planPath = path.join(work, 'plan.md'); + fs.writeFileSync(planPath, o.plan ?? AUTOPLAN); + const r = startRun({ root, app: 'plantpal', planPath, build: BUILD, play: playWith(1), builder: 'anthropic/claude-opus-5-5', checker: 'openai/gpt-6.2-sol', now: T0 }); + if ('error' in r) throw new Error(r.error.detail); + for (let a = 1; a <= 5; a++) { + const rec = recordResult({ dir: r.dir, action: a, verdict: 'pass', evidence: shot(work, `a${a}.png`, `screen ${a}`), device: 'iPhone 17 Pro (cloud)', account: PLAY.account, by: 'openai/gpt-6.2-sol', now: T0 }); + if ('error' in rec) throw new Error(rec.error.detail); + } + const p = predict({ dir: r.dir, score: '6', why: 'the reminder works but adding plants is slow', by: 'openai/gpt-6.2-sol', now: T0 }); + if ('error' in p) throw new Error(p.error.detail); + return { ...r, planPath, work, root }; +} + +describe('the day-one table format (pinned)', () => { + test('the parser this check reads keeps its titles and columns', () => { + expect(DAY_ONE_TITLES).toEqual(['Day one', 'Day-one page', 'Day one page']); + expect([...DAY_ONE_COLUMNS]).toEqual(['action', 'frequency', 'source', 'feature', 'route', 'first build', 'check']); + }); + + test('an autoplan plan and a one-page day-one list freeze the same five actions', () => { + const a = freezeActions(AUTOPLAN), b = freezeActions(ONE_PAGE); + if ('error' in a || 'error' in b) throw new Error('fixture did not freeze'); + expect(a.actions.map(x => x.action)).toEqual(ACTIONS); + expect(b.actions).toEqual(a.actions); + expect(b.rows_sha256).toBe(a.rows_sha256); + expect(a.actions[3]).toEqual({ n: 4, action: 'gets a reminder at 8am', frequency: 'daily', feature: 'Morning reminder', route: 'notification', first_build: 'build 1', check: 'a notification arrives at 8:00 on the device', source: 'calendar habit' }); + }); + + test('a sixth row marked assumed is not frozen; an assumed row in the first five refuses', () => { + expect('error' in freezeActions(AUTOPLAN)).toBe(false); + const assumed = AUTOPLAN.replace('| gets a reminder at 8am | daily | calendar habit |', '| gets a reminder at 8am | daily | assumed |'); + const r = freezeActions(assumed); + expect('error' in r && r.error).toEqual({ code: 'FIRST_USE_PLAN_UNREADY', detail: 'day-one row 4 is still marked assumed' }); + }); + + test('fewer than five rows, or an empty cell in the first five, refuses', () => { + const four = ONE_PAGE.replace(/^\| opens a plant's care card .*\n/m, ''); + expect(freezeActions(four)).toEqual({ error: { code: 'FIRST_USE_PLAN_UNREADY', detail: 'the day-one table has 4 rows; the check needs 5' } }); + const blank = ONE_PAGE.replace('| Morning reminder | notification |', '| Morning reminder | |'); + expect(freezeActions(blank)).toEqual({ error: { code: 'FIRST_USE_PLAN_UNREADY', detail: 'day-one row 4 has an empty cell; every column of the first 5 rows needs a value' } }); + }); + + test('no table, a missing column or an empty table refuses', () => { + expect(freezeActions('# A plan\n\nNo day one here.\n')).toEqual({ error: { code: 'FIRST_USE_PLAN_UNREADY', detail: 'the plan has no ### Day one table' } }); + const noCheck = ONE_PAGE.replace('| Check |', '| Notes |'); + expect('error' in freezeActions(noCheck) && freezeActions(noCheck)).toMatchObject({ error: { detail: 'the table has no check column' } }); + const empty = '## Day one\n\n| action | frequency | source | feature | route | first build | check |\n|---|---|---|---|---|---|---|\n'; + expect(freezeActions(empty)).toMatchObject({ error: { code: 'FIRST_USE_PLAN_UNREADY' } }); + }); +}); + +describe('model families and build fingerprints', () => { + test('families come from the provider prefix, a family name or a known model word', () => { + expect(modelFamily('openai/gpt-6.2-sol')).toBe('openai'); + expect(modelFamily('anthropic/claude-opus-5-5')).toBe('anthropic'); + expect(modelFamily('claude-fable-5-2')).toBe('anthropic'); + expect(modelFamily('gpt-6-astra')).toBe('openai'); + expect(modelFamily('google')).toBe('google'); + expect(modelFamily('gemini-4-carbon')).toBe('google'); + expect(modelFamily('mystery-model')).toBeUndefined(); + expect(modelFamily('openrouter/anthropic/claude-opus-5-5')).toBe('anthropic'); + expect(modelFamily('bedrock/anthropic.claude-sonnet-5-5')).toBe('anthropic'); + expect(modelFamily('zai/glm-5.3')).toBe('zai'); + }); + + test('a same-family or unknown checker refuses at start', () => { + const work = fresh('fam'), planPath = path.join(work, 'plan.md'); + fs.writeFileSync(planPath, AUTOPLAN); + const base = { root: fresh('root'), app: 'plantpal', planPath, build: BUILD, play: PLAY }; + expect(startRun({ ...base, builder: 'anthropic/claude-opus-5-5', checker: 'claude-fable-5-2' })).toMatchObject({ error: { code: 'FIRST_USE_SAME_FAMILY', detail: 'builder and checker are both anthropic' } }); + expect(startRun({ ...base, builder: 'anthropic/claude-opus-5-5', checker: 'mystery-model' })).toMatchObject({ error: { code: 'FIRST_USE_SAME_FAMILY' } }); + }); + + test('a build needs a full commit and exactly one of TestFlight build or deploy version', () => { + expect(buildFingerprint({ ...BUILD, commit: 'abc123' })).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + expect(buildFingerprint({ ...BUILD, deploy: 'v1' })).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + expect(buildFingerprint({ platform: 'web', commit: COMMIT })).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + const a = buildFingerprint(BUILD), b = buildFingerprint({ ...BUILD, testflight: '18' }); + if ('error' in a || 'error' in b) throw new Error('valid builds refused'); + expect(a.fingerprint).not.toBe(b.fingerprint); + expect(a.fingerprint).toMatch(/^[0-9a-f]{16}$/); + }); +}); + +describe('the play spec carries the ten parts of every play ask', () => { + test('the fixture is complete and the parts are in order', () => { + expect('spec' in checkPlaySpec(PLAY)).toBe(true); + expect(PLAY_PARTS.map(p => p.part)).toEqual([ + 'The links, each checked live minutes before sending', 'Device and setup', 'What it is, in a sentence', 'How to start', 'Controls', + 'How long to play', 'What we want to learn', 'How to report back', 'Known quirks', 'Reply word', + ]); + }); + + test('missing parts are named', () => { + const { controls: _c, quirks: _q, ...rest } = PLAY; + const r = checkPlaySpec({ ...rest, links: [{ label: 'x', url: 'ftp://nope' }], minutes: 0 }); + expect(r).toEqual({ error: { code: 'FIRST_USE_PLAY_SPEC_INCOMPLETE', detail: 'missing or invalid: The links, each checked live minutes before sending (links); Controls (controls); How long to play (minutes); Known quirks (quirks)' } }); + expect(checkPlaySpec({ ...PLAY, reply_word: 'two words' })).toMatchObject({ error: { detail: 'missing or invalid: Reply word (reply_word)' } }); + }); +}); + +describe('where records live', () => { + test('override, then the one user drive on Capy, else the state root', () => { + const home = fresh('home'); + expect(recordRoot({ GSTACK_FIRST_USE_DIR: path.join(home, 'x') })).toEqual({ root: path.join(home, 'x') }); + expect(recordRoot({ HOME: home, GSTACK_CAPY: '1' })).toMatchObject({ error: { code: 'FIRST_USE_NO_PRIVATE_DRIVE' } }); + fs.mkdirSync(path.join(home, '.capy', 'drive', 'user-ada-example'), { recursive: true }); + fs.mkdirSync(path.join(home, '.capy', 'drive', 'project-plantpal'), { recursive: true }); + expect(recordRoot({ HOME: home, GSTACK_CAPY: '1' })).toEqual({ root: path.join(home, '.capy', 'drive', 'user-ada-example', 'first-use') }); + fs.mkdirSync(path.join(home, '.capy', 'drive', 'user-bo-example'), { recursive: true }); + expect(recordRoot({ HOME: home, GSTACK_CAPY: '1' })).toMatchObject({ error: { code: 'FIRST_USE_NO_PRIVATE_DRIVE', detail: '2 user-level drive folders (user-ada-example, user-bo-example)' } }); + expect(recordRoot({ HOME: home, GSTACK_STATE_ROOT: path.join(home, 'state') })).toEqual({ root: path.join(home, 'state', 'first-use') }); + }); +}); + +describe('the gate', () => { + test('five passes, live links and a prediction clear the exact build, and the message carries every part', async () => { + const r = passedRun(); + expect(decide(r.dir, BUILD, T0).reasons).toEqual(['link_unchecked: http://127.0.0.1:1/testflight (as a fresh Apple ID with notifications allowed on ios)', 'link_unchecked: http://127.0.0.1:1/account (as a fresh Apple ID with notifications allowed on ios)']); + const links = await checkLinks(r.dir, AS, okFetch, () => T0); + expect('receipts' in links && links.receipts.map(x => x.verdict)).toEqual(['live', 'live']); + const d = decide(r.dir, BUILD, new Date(T0.getTime() + 5 * 60_000)); + expect(d).toMatchObject({ ok: true, reasons: [], passed: 5 }); + const msg = renderPlayMessage(d, new Date(T0.getTime() + 5 * 60_000)); + for (const [i, label] of ['Links', 'Device and setup', 'What it is', 'How to start', 'Controls', 'How long', 'What we want to learn', 'How to report back', 'Known quirks', 'Reply word'].entries()) { + expect(msg).toContain(`${i + 1}. **${label}`); + } + expect(msg).toContain('checked live at 10:00 UTC, 5 min before this message'); + expect(msg).toContain('[TestFlight invite](http://127.0.0.1:1/testflight)'); + expect(msg).toContain('(asks you to sign in)'); + expect(msg).toContain('Try plantpal: c0ffee000000, TestFlight build 17'); + for (const a of ACTIONS) expect(msg).toContain(`- ${a}`); + expect(msg).not.toContain('predict'); + }); + + test('another build, a stale link, a changed day-one row and tampered evidence each refuse', async () => { + const r = passedRun(); + await checkLinks(r.dir, AS, okFetch, () => T0); + expect(decide(r.dir, { ...BUILD, testflight: '18' }, T0).reasons).toEqual(['build_mismatch: this run checked c0ffee000000, TestFlight build 17, not c0ffee000000, TestFlight build 18']); + expect(decide(r.dir, BUILD, new Date(T0.getTime() + 16 * 60_000)).reasons).toEqual([ + 'link_stale: http://127.0.0.1:1/testflight was checked at 2026-11-18T10:00:00.000Z, over 15 minutes ago', + 'link_stale: http://127.0.0.1:1/account was checked at 2026-11-18T10:00:00.000Z, over 15 minutes ago', + ]); + fs.writeFileSync(r.planPath, AUTOPLAN.replace('gets a reminder at 8am', 'gets a reminder at 9am')); + expect(decide(r.dir, BUILD, T0).reasons).toEqual(['source_changed: the day-one rows changed since the check started; start a new run']); + fs.writeFileSync(r.planPath, AUTOPLAN + '\nAn edit outside the table does not count.\n'); + expect(decide(r.dir, BUILD, T0).ok).toBe(true); + const ev = fs.readdirSync(path.join(r.dir, 'evidence')).find(f => f.startsWith('2-'))!; + fs.writeFileSync(path.join(r.dir, 'evidence', ev), 'edited'); + expect(decide(r.dir, BUILD, T0).reasons).toEqual(['action_2_evidence_stale']); + }); + + test('a failed action, a down link and a missing prediction refuse; the newest result for an action counts', async () => { + const root = fresh('root'), work = fresh('work'), planPath = path.join(work, 'plan.md'); + fs.writeFileSync(planPath, ONE_PAGE); + const r = startRun({ root, app: 'plantpal', planPath, build: BUILD, play: playWith(1), builder: 'anthropic/claude-opus-5-5', checker: 'gemini-4-carbon', now: T0 }); + if ('error' in r) throw new Error(r.error.detail); + const rec = (a: number, verdict: string, at: Date, note?: string) => recordResult({ dir: r.dir, action: a, verdict, evidence: shot(work, `a${a}-${verdict}.mp4`, `${a}${verdict}`), device: 'iPhone 17 Pro (cloud)', account: PLAY.account, by: 'google/gemini-4-carbon', note, now: at }); + for (let a = 1; a <= 4; a++) rec(a, 'pass', T0); + expect(rec(5, 'fail', T0)).toMatchObject({ error: { detail: 'a fail needs --note saying what happened' } }); + rec(5, 'fail', T0, 'the care card is blank'); + await checkLinks(r.dir, AS, async () => ({ status: 401 }), () => T0); + expect(decide(r.dir, BUILD, T0).reasons).toEqual([ + 'action_5_failed: the care card is blank', 'link_down: http://127.0.0.1:1/testflight (status 401)', 'no_predicted_score', + ]); + rec(5, 'pass', new Date(T0.getTime() + 60_000)); + await checkLinks(r.dir, AS, okFetch, () => new Date(T0.getTime() + 60_000)); + expect(predict({ dir: r.dir, score: '7', why: 'clean', by: 'gemini-4-carbon' })).toMatchObject({ prediction: { score: 7 } }); + expect(predict({ dir: r.dir, score: '8', why: 'again', by: 'gemini-4-carbon' })).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + expect(decide(r.dir, BUILD, T0)).toMatchObject({ ok: true, passed: 5 }); + }); + + test('link receipts and results bind the owner-equivalent account and device class', async () => { + const r = passedRun(); + expect(await checkLinks(r.dir, { account: 'any session', device_class: 'ios' }, okFetch, () => T0)).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + expect(await checkLinks(r.dir, { account: PLAY.account, device_class: 'web' }, okFetch, () => T0)).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + expect(fs.existsSync(path.join(r.dir, 'links'))).toBe(false); + const other = { schema_version: 1, kind: 'first-use-link', url: 'http://127.0.0.1:1/testflight', build_fingerprint: JSON.parse(fs.readFileSync(path.join(r.dir, 'manifest.json'), 'utf8')).build.fingerprint, audience: { account: 'a developer account', device_class: 'ios' }, checked_at: T0.toISOString(), status: 200, login_gated: false, verdict: 'live' }; + fs.mkdirSync(path.join(r.dir, 'links')); + fs.writeFileSync(path.join(r.dir, 'links', 'other.json'), JSON.stringify(other)); + expect(decide(r.dir, BUILD, T0).reasons[0]).toBe('link_unchecked: http://127.0.0.1:1/testflight (as a fresh Apple ID with notifications allowed on ios)'); + expect(recordResult({ dir: r.dir, action: 1, verdict: 'pass', evidence: shot(r.work, 'dev.png'), device: 'd', account: 'a developer account', by: 'openai/gpt-6.2-sol' })).toMatchObject({ error: { detail: 'play on the owner-equivalent account and pass it exactly: --account "a fresh Apple ID with notifications allowed"' } }); + }); + + test('the builder cannot record a result or a prediction, and evidence must be a screenshot or video', () => { + const r = passedRun(); + expect(recordResult({ dir: r.dir, action: 1, verdict: 'pass', evidence: shot(r.work, 'self.png'), device: 'd', account: PLAY.account, by: 'anthropic/claude-opus-5-5' })).toMatchObject({ error: { code: 'FIRST_USE_SAME_FAMILY' } }); + expect(recordResult({ dir: r.dir, action: 1, verdict: 'pass', evidence: shot(r.work, 'notes.txt'), device: 'd', account: PLAY.account, by: 'openai/gpt-6.2-sol' })).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + expect(recordResult({ dir: r.dir, action: 6, verdict: 'pass', evidence: shot(r.work, 'six.png'), device: 'd', account: PLAY.account, by: 'openai/gpt-6.2-sol' })).toMatchObject({ error: { detail: '--action must be 1 to 5' } }); + const link = path.join(r.work, 'link.png'); + fs.symlinkSync(shot(r.work, 'real.png'), link); + expect(recordResult({ dir: r.dir, action: 1, verdict: 'pass', evidence: link, device: 'd', account: PLAY.account, by: 'openai/gpt-6.2-sol' })).toMatchObject({ error: { detail: 'the evidence must be a regular file, not a link or directory' } }); + }); + + test('the owner score and words sit beside the prediction; the manifest is written once', () => { + const r = passedRun(); + expect(ownerScore({ dir: r.dir, score: '4', words: '', by: 'GStack Minder' })).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + ownerScore({ dir: r.dir, score: '4', words: '4, Talk is slow', by: 'GStack Minder', now: T0 }); + ownerScore({ dir: r.dir, score: '5', words: '5, better after the fix', by: 'GStack Minder', now: new Date(T0.getTime() + 60_000) }); + const d = decide(r.dir, BUILD, T0); + expect(d.prediction?.score).toBe(6); + expect(d.owner).toMatchObject({ score: 5, words: '5, better after the fix' }); + expect(fs.readdirSync(path.join(r.dir, 'owner'))).toHaveLength(2); + const again = startRun({ root: r.root, app: 'plantpal', planPath: r.planPath, build: BUILD, play: PLAY, builder: 'anthropic/claude-opus-5-5', checker: 'openai/gpt-6.2-sol', now: T0 }); + expect(again).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + }); + + test('a record write that fails refuses with FIRST_USE_RECORD_INVALID instead of throwing', async () => { + const r = passedRun(); + for (const d of ['results', 'links', 'owner']) { + fs.rmSync(path.join(r.dir, d), { recursive: true, force: true }); + fs.writeFileSync(path.join(r.dir, d), 'not a directory'); + } + expect(recordResult({ dir: r.dir, action: 1, verdict: 'pass', evidence: shot(r.work, 'again.png', 'again'), device: 'd', account: PLAY.account, by: 'openai/gpt-6.2-sol' })).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + expect(await checkLinks(r.dir, AS, okFetch)).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + expect(ownerScore({ dir: r.dir, score: '4', words: '4, fine', by: 'GStack Minder' })).toMatchObject({ error: { code: 'FIRST_USE_RECORD_INVALID' } }); + }); + + test('the brief shell-quotes every value it puts into the record and predict lines', () => { + const work = fresh('quote'), planPath = path.join(work, 'plan.md'), marker = path.join(work, 'ran'); + fs.writeFileSync(planPath, AUTOPLAN); + const account = `Ada's "test" $HOME \`touch ${marker}\` $(touch ${marker}) account`; + const r = startRun({ root: path.join(fresh('root'), 'it\'s "$x"'), app: 'plantpal', planPath, build: BUILD, play: { ...PLAY, account }, builder: 'anthropic/claude-opus-5-5', checker: 'openai/gpt-6.2-sol', now: T0 }); + if ('error' in r) throw new Error(r.error.detail); + const lines = renderBrief(r.manifest, r.dir).split('\n').filter(l => l.startsWith('gstack-first-use ')); + expect(lines).toHaveLength(3); + for (const line of lines) { + const argv = spawnSync('bash', ['-c', line.replace(/^gstack-first-use /, "printf '%s\\n' ")], { encoding: 'utf8', timeout: 10_000 }).stdout.split('\n'); + expect(argv[argv.indexOf('--run') + 1]).toBe(r.dir); + expect(argv[argv.indexOf('--by') + 1]).toBe('openai/gpt-6.2-sol'); + if (line.includes(' record ')) expect(argv[argv.indexOf('--account') + 1]).toBe(account); + } + expect(fs.existsSync(marker)).toBe(false); + }); + + test('the brief gives the checker only the play text and the frozen actions', () => { + const r = passedRun(); + const read = readManifest(r.dir); + if ('error' in read) throw new Error('no manifest'); + const brief = renderBrief(read.manifest, r.dir); + expect(brief).toContain('You run on openai/gpt-6.2-sol; the team that built it runs on anthropic models'); + expect(brief).toContain('tools.capy.phone'); + expect(brief).toContain('TestFlight build 17'); + for (const a of ACTIONS) expect(brief).toContain(a); + expect(brief).toContain(`gstack-first-use record --run '${r.dir}' --action N --verdict pass --evidence FILE --device 'DEVICE YOU USED' --account 'a fresh Apple ID with notifications allowed' --by 'openai/gpt-6.2-sol'`); + expect(brief).not.toContain('Ada Example'); + expect(brief).not.toContain(r.planPath); + }); +}); + +describe('gstack-first-use (CLI, temporary HOME and drive)', () => { + const BIN = path.join(ROOT, 'bin', 'gstack-first-use'); + const realDrive = path.join(os.homedir(), '.capy', 'drive'); + const realRecords = () => { try { return fs.readdirSync(realDrive).filter(d => fs.existsSync(path.join(realDrive, d, 'first-use'))).map(d => `${d}:${fs.readdirSync(path.join(realDrive, d, 'first-use')).join(',')}`); } catch { return []; } }; + let server: ReturnType<typeof Bun.serve>; + let home: string, env: Record<string, string>; + const before = realRecords(); + beforeAll(() => { + server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: req => new Response('ok', { status: new URL(req.url).pathname === '/account' ? 403 : 200 }) }); + home = fresh('home'); + fs.mkdirSync(path.join(home, '.capy', 'drive', 'user-ada-example'), { recursive: true }); + env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith('GSTACK_')).map(([k, v]) => [k, v ?? ''])); + Object.assign(env, { HOME: home, GSTACK_CAPY: '1', GSTACK_STATE_ROOT: path.join(home, 'state') }); + }); + afterAll(() => server?.stop(true)); + const cli = async (...args: string[]) => { + const p = Bun.spawn([process.execPath, BIN, ...args], { env, stdout: 'pipe', stderr: 'pipe', timeout: 30_000 }); + const [stdout, stderr, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]); + return { stdout, stderr, code }; + }; + + test('start, brief, record, predict, links, message, score and show in the owner\'s private drive', async () => { + const work = fresh('cli'); + const plan = path.join(work, 'plan.md'), play = path.join(work, 'play.json'); + fs.writeFileSync(plan, AUTOPLAN); + fs.writeFileSync(play, JSON.stringify(playWith(server.port!))); + const build = ['--platform', 'ios', '--commit', COMMIT, '--testflight', '17']; + const start = await cli('start', '--app', 'plantpal', '--plan', plan, '--play', play, ...build, '--builder', 'anthropic/claude-opus-5-5', '--checker', 'openai/gpt-6.2-sol'); + expect(start.code).toBe(0); + const dir = /^FIRST_USE_RUN: (.+)$/m.exec(start.stdout)![1]!; + expect(dir.startsWith(path.join(home, '.capy', 'drive', 'user-ada-example', 'first-use', 'plantpal') + path.sep)).toBe(true); + expect(start.stdout).toContain('FIRST_USE_FROZEN: 5 actions'); + + const early = await cli('message', '--run', dir, ...build); + expect(early.code).toBe(3); + expect(early.stdout).toBe(''); + expect(early.stderr).toContain('(FIRST_USE_REFUSED)'); + expect(early.stderr).toContain('action_1_not_played'); + + const brief = await cli('brief', '--run', dir); + expect(brief.stdout).toContain('# Cold first-use check: plantpal'); + expect(brief.stderr).toContain('DISPATCH: give this brief'); + + for (let a = 1; a <= 5; a++) { + const rec = await cli('record', '--run', dir, '--action', String(a), '--verdict', 'pass', '--evidence', shot(work, `a${a}.png`, `s${a}`), '--device', 'iPhone 17 Pro (cloud)', '--account', PLAY.account, '--by', 'openai/gpt-6.2-sol'); + expect(rec.code).toBe(0); + } + expect((await cli('predict', '--run', dir, '--score', '6', '--why', 'reminder works, adding is slow', '--by', 'openai/gpt-6.2-sol')).stdout).toContain('FIRST_USE_PREDICTED: 6'); + expect((await cli('links', '--run', dir)).code).toBe(1); + const links = await cli('links', '--run', dir, '--account', PLAY.account, '--device-class', 'ios'); + expect(links.code).toBe(0); + expect(links.stdout).toContain('LINK: live status=403 as=ios'); + + const check = await cli('check', '--run', dir, ...build); + expect(check.stdout).toMatch(/^FIRST_USE: pass app=plantpal build=c0ffee000000, TestFlight build 17 actions=5\/5 links=2\/2 checker=openai\/gpt-6.2-sol predicted=6$/m); + const msg = await cli('message', '--run', dir, ...build); + expect(msg.code).toBe(0); + expect(msg.stdout).toContain('10. **Reply word:** played'); + expect((await cli('check', '--run', dir, '--platform', 'ios', '--commit', COMMIT, '--testflight', '18')).code).toBe(3); + + expect((await cli('score', '--run', dir, '--score', '4', '--words', '4, Talk is slow', '--by', 'Example Captain')).code).toBe(0); + const show = await cli('show', '--run', dir, '--json'); + expect(JSON.parse(show.stdout)).toMatchObject({ passed: 5, predicted: 6, owner: { score: 4, words: '4, Talk is slow' }, gap: -2 }); + expect(realRecords()).toEqual(before); + }); + + test('a run outside the record root and a second user drive refuse', async () => { + const outside = fresh('outside'); + const r = await cli('show', '--run', outside); + expect(r.code).toBe(1); + expect(r.stderr).toContain('is outside the record root'); + fs.mkdirSync(path.join(home, '.capy', 'drive', 'user-bo-example'), { recursive: true }); + const two = await cli('root'); + expect(two.code).toBe(3); + expect(two.stderr).toContain('(FIRST_USE_NO_PRIVATE_DRIVE)'); + fs.rmSync(path.join(home, '.capy', 'drive', 'user-bo-example'), { recursive: true }); + }); +}); diff --git a/test/fixtures/first-use/autoplan-plan.md b/test/fixtures/first-use/autoplan-plan.md new file mode 100644 index 00000000000..1479e515d3f --- /dev/null +++ b/test/fixtures/first-use/autoplan-plan.md @@ -0,0 +1,25 @@ +# Plantpal: a watering coach for houseplants (synthetic fixture) + +Made-up plan for test/first-use.test.ts. The owner, the app and every row are invented. + +## Implementation plan + +### Owner's words + +- Ada Example, day 0: "I keep forgetting which plant needs water" + +### Day one + +| action | frequency | source | feature | route | first build | check | +|---|---|---|---|---|---|---| +| adds her first three plants by photo | once | owner words 1 | Add plant | home screen, plus button | build 1 | three plants show on the home screen with names | +| sees which plant needs water today | daily | owner words 1 | Today list | root screen | build 1 | the plant due today is at the top, marked due | +| marks a plant as watered | daily | owner words 1 | Watered button | Today list, tap a plant | build 1 | the plant drops off today's list | +| gets a reminder at 8am | daily | calendar habit | Morning reminder | notification | build 1 | a notification arrives at 8:00 on the device | +| opens a plant's care card | weekly | owner words 1 | Care card | home screen, tap a plant | build 1 | the card shows light, water and the last watered date | +| shares a plant with her partner | assumed | assumed | Sharing | plant card, share | build 2 | the partner's phone shows the plant | + +### What it won't do yet + +- No Android build +- No plant disease diagnosis diff --git a/test/fixtures/first-use/one-page-plan.md b/test/fixtures/first-use/one-page-plan.md new file mode 100644 index 00000000000..1bb418ecd08 --- /dev/null +++ b/test/fixtures/first-use/one-page-plan.md @@ -0,0 +1,17 @@ +# Day-one page: Plantpal (synthetic fixture, R107 style) + +The first five things the owner does on day one, each with a check that it works. Invented for tests. + +## Day one + +| Action | Feature | Route | First build | Check | Frequency | Source | +| --- | --- | --- | --- | --- | --- | --- | +| adds her first three plants by photo | Add plant | home screen, plus button | build 1 | three plants show on the home screen with names | once | owner words 1 | +| sees which plant needs water today | Today list | root screen | build 1 | the plant due today is at the top, marked due | daily | owner words 1 | +| marks a plant as watered | Watered button | Today list, tap a plant | build 1 | the plant drops off today's list | daily | owner words 1 | +| gets a reminder at 8am | Morning reminder | notification | build 1 | a notification arrives at 8:00 on the device | daily | calendar habit | +| opens a plant's care card | Care card | home screen, tap a plant | build 1 | the card shows light, water and the last watered date | weekly | owner words 1 | + +## Install + +Put build 1 on the owner's phone after the first PR. diff --git a/test/fixtures/first-use/play.json b/test/fixtures/first-use/play.json new file mode 100644 index 00000000000..d4bcba83d73 --- /dev/null +++ b/test/fixtures/first-use/play.json @@ -0,0 +1,24 @@ +{ + "links": [ + { + "label": "TestFlight invite", + "url": "http://127.0.0.1:PORT/testflight" + }, + { + "label": "Account page", + "url": "http://127.0.0.1:PORT/account", + "login_gated": true + } + ], + "device": "iPhone 17 Pro on iOS 26", + "setup": "Install TestFlight from the App Store first.", + "account": "a fresh Apple ID with notifications allowed", + "what": "Plantpal tells you which houseplant needs water today.", + "start": "Open the TestFlight invite, tap Install, then open Plantpal.", + "controls": "Tap to open, swipe left on a plant to mark it watered.", + "minutes": 10, + "learn": "Whether the Today list is the first thing you want every morning.", + "report": "Reply in this thread.", + "quirks": "The first photo can take a few seconds to upload.", + "reply_word": "played" +} diff --git a/test/helpers/free-fixtures-data.ts b/test/helpers/free-fixtures-data.ts index 726a5baf1df..e8a831859d4 100644 --- a/test/helpers/free-fixtures-data.ts +++ b/test/helpers/free-fixtures-data.ts @@ -151,6 +151,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = { 'test/fixtures/exercised-map-replay.json': ['scripts/exercised-map.ts'], 'test/fixtures/exit-propagation/**': ['test/exit-propagation.test.ts'], 'test/fixtures/factory-scorecard/**': ['test/factory-scorecard.test.ts'], + 'test/fixtures/first-use/**': ['test/first-use.test.ts'], 'test/fixtures/founder-resources-pool.txt': ['test/founder-resources-bin.test.ts'], 'test/fixtures/free-shard-capture.ts': ['test/test-free-shards-capture.test.ts'], 'test/fixtures/gh-poll/**': ['test/gh-poll.test.ts'], From cbd21f94243405223d87f64658c0deac009b7cda Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 07:38:45 +0800 Subject: [PATCH 56/62] Let the /ship conductor trial resolve case revert conflicts by hand (GST-3003) (#4460) Lets the /ship conductor trial use pull requests whose revert conflicts with later code, by resolving those conflicts by hand in docs, tests and the planted file only. Why: only 5 of the 10 needed cases (and no large one) reverted cleanly, so the trial could not start as planned. Nothing to do: no bar, arm, decision, scoring rule or stop rule changes; no paid call has run. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- changelog.d/capy-g1-cases-amend.md | 1 + docs/evals/ship-conductor-fold-prereg.md | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) create mode 100644 changelog.d/capy-g1-cases-amend.md diff --git a/changelog.d/capy-g1-cases-amend.md b/changelog.d/capy-g1-cases-amend.md new file mode 100644 index 00000000000..86151c37858 --- /dev/null +++ b/changelog.d/capy-g1-cases-amend.md @@ -0,0 +1 @@ +The /ship conductor trial plan now lets case reverts that conflict with later code be resolved by hand in docs, tests and the planted file, so large pull requests can be cases (GST-3003). diff --git a/docs/evals/ship-conductor-fold-prereg.md b/docs/evals/ship-conductor-fold-prereg.md index ad5479b529c..587f24d19ce 100644 --- a/docs/evals/ship-conductor-fold-prereg.md +++ b/docs/evals/ship-conductor-fold-prereg.md @@ -2,6 +2,10 @@ frozen: 2026-11-17 +Amended 2026-11-17, before any paid call, on the owner's grant (GSTA-36): Cases rule 1 now allows hand-resolved +revert conflicts in docs, tests and the plant's own file, because only 5 of the 10 hosts needed (and no large one) +reverted cleanly onto the frozen main commit. No bar, arm, decision, scoring rule or stop rule changed. + Status: locked at merge, before any paid call. Owner: GStack Minder (GSTA-36); runner GSTA-589. Paid runs start only after this file merges and the owner approves the budget below. @@ -74,8 +78,11 @@ Ten cases, the same ten in every arm (fully paired, the strongest form of matchi sealing subagent picks them after this file merges, by these rules: 1. **Host pull request.** A garrytan/gstack pull request merged on or after 2026-07-01 (after Opus 5.5's training - cutoff), whose revert applies cleanly to one frozen main commit, and whose reverted tree passes typecheck and the - host's own tests. Excluded: changes to docs, generated files, VERSION or CHANGELOG only, and changes to /ship or + cutoff), whose revert applies to one frozen main commit (88da124d) and whose reverted tree passes typecheck and + the host's own tests. A revert that conflicts with later main is resolved by hand, removing the host's lines as + they read at the frozen commit, only in docs, test files and the plant's own file; a conflict in any other code + file disqualifies the host. Conflicts in VERSION, CHANGELOG.md, package.json and generated files are ignored. + Every resolution is recorded in the label file. Excluded: changes to docs, generated files, VERSION or CHANGELOG only, and changes to /ship or review tooling itself (`ship/`, `lib/ship-*`, `bin/gstack-ship-*`, `bin/gstack-review-*`). 2. **Size class**, by changed lines without generated files and lockfiles: 3 small (under 150), 4 medium (150 to 600), 3 large (over 600). At least 3 of the 10 are hosts that `gstack-review-plan` sends to the full panel From 29e950227b2d6b87a0529492885f42e522483969 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 09:28:22 +0800 Subject: [PATCH 57/62] Review planner sorts Swift and Xcode files by risk instead of sending every iOS PR to the full panel (GST-3041) (#4469) /ship's review planner now sorts Swift and Xcode files by risk, so a plain iOS UI change gets the light review instead of the full five-reader panel. Why: `gstack-diff-scope` had no rule for `.swift`, so every all-Swift diff printed `SCOPE_ERROR=unmatched` and the planner failed closed. Reported from the GHome iOS app's PR review. Nothing to do: unknown file types still fail closed exactly as before. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/outside-voice#1 reader=outside-voice Review-Finding: p2/red-team#1 reader=red-team --- bin/gstack-design-detect.ts | 6 +-- bin/gstack-diff-scope | 19 ++++++++ changelog.d/review-plan-sorts-swift-paths.md | 1 + docs/review-policy.md | 2 +- docs/skills.md | 4 +- lib/frontend-scope.ts | 12 +++++ lib/review-risk.ts | 1 + test/diff-scope.test.ts | 48 +++++++++++++++++++ .../review-pins/files/lib/review-risk.ts.json | 2 +- .../review-pins/replays/GST-3041.json | 1 + test/frontend-scope.test.ts | 15 ++++++ test/gstack-design-detect.test.ts | 4 ++ test/review-plan-cli.test.ts | 17 +++++++ test/review-risk-routing.test.ts | 15 ++++++ 14 files changed, 140 insertions(+), 7 deletions(-) create mode 100644 changelog.d/review-plan-sorts-swift-paths.md create mode 100644 test/fixtures/review-pins/replays/GST-3041.json diff --git a/bin/gstack-design-detect.ts b/bin/gstack-design-detect.ts index b5ffd67cc24..addb543fe19 100755 --- a/bin/gstack-design-detect.ts +++ b/bin/gstack-design-detect.ts @@ -96,7 +96,7 @@ import { import { writeReceipt, writeOutcome } from '../lib/egress-receipt'; import { readConfigKey, resolveStateRoot } from '../lib/state-root'; import { DESIGN_SLOP_CATALOG, entryForImpeccableId } from '../lib/design-catalog'; -import { isFrontendPath } from '../lib/frontend-scope'; +import { isFrontendPath, isNativeUiPath } from '../lib/frontend-scope'; import { baseArg } from '../lib/gate-diff/git'; // ── Environment ────────────────────────────────────────────────────────────── @@ -830,8 +830,8 @@ function resolveTargets(args: ScanArgs, p: Probe): { targets: string[]; refusedB runZ(['diff', '-z', '--name-only', '--diff-filter=ACMR', 'HEAD']); runZ(['ls-files', '-z', '--others', '--exclude-standard']); for (const rel of [...files].sort()) { - // impeccable reads web sources; a Dart file is frontend scope but not a scan target. - if (!isFrontendPath(rel) || rel.endsWith('.dart')) continue; + // impeccable reads web sources; a Dart or Swift file is frontend scope but not a scan target. + if (!isFrontendPath(rel) || isNativeUiPath(rel)) continue; const abs = path.join(top, rel); try { if (fs.lstatSync(abs).isSymbolicLink()) { refuse(rel, 'symlink named by git is never scanned'); continue; } } catch { continue; } const real = realpathOrNull(abs); diff --git a/bin/gstack-diff-scope b/bin/gstack-diff-scope index 8c63dda0720..3b6d8dd10a7 100755 --- a/bin/gstack-diff-scope +++ b/bin/gstack-diff-scope @@ -246,6 +246,8 @@ for f in ${FILES_LIST[@]+"${FILES_LIST[@]}"}; do # Frontend: CSS, views, components, templates case "$f" in + # SwiftPM's manifest is a dependency file (CONFIG below), never UI. + Package.swift|*/Package.swift) ;; *.css|*.scss|*.less|*.sass|*.pcss) m_frontend=true ;; *.tsx|*.jsx|*.vue|*.svelte|*.astro) m_frontend=true ;; *.erb|*.haml|*.slim|*.hbs|*.ejs) m_frontend=true ;; @@ -255,6 +257,11 @@ for f in ${FILES_LIST[@]+"${FILES_LIST[@]}"}; do # A skipped reviewer is invisible; an extra one (design-lite included) is a # visible pass that costs a review. *.dart) m_frontend=true ;; + # Swift, the same way (GST-3041): a SwiftUI view and a network client share + # the extension. Interface Builder files, string catalogs and asset catalogs + # are UI only. + *.swift) m_frontend=true ;; + *.storyboard|*.xib|*.strings|*.stringsdict|*.xcstrings|*.xcassets/*) m_frontend=true ;; tailwind.config.*|postcss.config.*) m_frontend=true ;; app/views/*|*/components/*|styles/*|css/*|app/assets/stylesheets/*) m_frontend=true ;; esac @@ -290,6 +297,12 @@ for f in ${FILES_LIST[@]+"${FILES_LIST[@]}"}; do .gstack/*) m_config=true ;; requirements.txt|pyproject.toml|go.mod|Cargo.toml|composer.json) m_config=true ;; pubspec.lock|*/pubspec.lock) m_config=true ;; + # Apple dependencies, project file and build settings (signing included); + # Info.plist and entitlements also read as AUTH below. + Package.swift|*/Package.swift|Package.resolved|*/Package.resolved) m_config=true ;; + Podfile|*/Podfile|Podfile.lock|*/Podfile.lock|Cartfile|*/Cartfile|Cartfile.resolved|*/Cartfile.resolved) m_config=true ;; + *.pbxproj|*.xcconfig|*.xcscheme|*.xcworkspacedata|*.xctestplan) m_config=true ;; + *.plist|*.entitlements|*.xcprivacy) m_config=true ;; esac # Migrations: database migration files. Bare migrations/* covers a @@ -316,6 +329,10 @@ for f in ${FILES_LIST[@]+"${FILES_LIST[@]}"}; do case "$f" in *jwt*|*permission*|*role*) m_auth=true ;; *session*) _session_data "$f" || m_auth=true ;; + # Apple permissions (GST-3041): Info.plist holds URL schemes, App Transport + # Security exceptions and usage strings; entitlements grant capabilities + # (keychain groups, push, HealthKit); the privacy manifest declares data use. + Info.plist|*/Info.plist|*-Info.plist|*.entitlements|*.xcprivacy) m_auth=true ;; esac _auth_path "$f" && m_auth=true @@ -330,6 +347,8 @@ for f in ${FILES_LIST[@]+"${FILES_LIST[@]}"}; do fi case "$f" in *.dart) m_backend=true ;; + Package.swift|*/Package.swift) ;; + *.swift) m_backend=true ;; esac [ "$m_frontend" = true ] && FRONTEND=true diff --git a/changelog.d/review-plan-sorts-swift-paths.md b/changelog.d/review-plan-sorts-swift-paths.md new file mode 100644 index 00000000000..64a158ba710 --- /dev/null +++ b/changelog.d/review-plan-sorts-swift-paths.md @@ -0,0 +1 @@ +- **/ship's review plan now sorts Swift and Xcode files by risk instead of sending every iOS PR to the full review panel (GST-3041).** `gstack-diff-scope` had no rule for `.swift`, so an all-Swift diff printed `SCOPE_ERROR=unmatched` and the planner failed closed to five readers plus a coverage audit; a 55-line SwiftUI copy change got the whole panel. Swift source now reads as UI and app code (like Dart), as do storyboards, XIBs, string catalogs and asset catalogs. `Info.plist`, entitlements and the privacy manifest read as permissions (auth), and `Package.swift`, `Package.resolved`, `Podfile`(`.lock`), `project.pbxproj`, `.xcconfig` and schemes read as config, never as UI. Swift networking code (`URLSession`, `URLRequest`, `NWConnection`, Alamofire) still raises the review to full depth, the same as `fetch` in TypeScript. A file type no rule knows, such as a Metal shader, still fails closed. Reported from the GHome iOS app's PR review. diff --git a/docs/review-policy.md b/docs/review-policy.md index 4c1a321f8d5..f483e3e5452 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -416,7 +416,7 @@ redaction call, an import of a redaction or outside-voice module, a `SECRET` or constant set to a regex, since that code decides what reaches an outside model, GST-1177; `shell: true`, `exec(` and `execSync(`, `eval`, `new Function(`, raw HTML sinks, a shell run through argv, recursive deletes), any call to an outbound HTTP client (`fetch`, `http(s).get` or `.request`, axios, got, undici, -`requests`, `httpx`, urllib, with no exemption for a literal URL), `new URL` from +`requests`, `httpx`, urllib, Swift's `URLSession`, `URLRequest(`, `NWConnection` and Alamofire, with no exemption for a literal URL), `new URL` from input, redirect toggles, proxy settings and host allowlists, archive extraction and path traversal (`tar.x`, adm-zip, yauzl, extract-zip, `extractall`, `tar -x`, `unzip`, `path.join` or `resolve` on request or entry input, a `'..'` check added diff --git a/docs/skills.md b/docs/skills.md index dd53ccf96c8..14f1f399b57 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -421,7 +421,7 @@ It runs an 80-item visual audit on your live site — in your Aside browser, so The self-regulation heuristic is tuned for design work — CSS-only changes get a free pass (they are inherently safe and reversible), but changes to component JSX/TSX files count against the risk budget. Hard cap at 30 fixes. If the risk score exceeds 20%, it stops and asks. -**Design detector.** When you have [impeccable](https://impeccable.style) installed, its engine runs first: on a URL the page's rendered DOM is dumped (linked styles inlined) and scanned; on a feature branch with no URL the changed frontend files are scanned (`.dart` files excepted: they count as frontend scope, but the engine reads web sources). Every mechanical finding arrives as a `FINDING-NNN` tagged with its rule id (`[nested-cards]`, `[low-contrast]`), and the report closes with `Detector: N → M`. gstack never runs impeccable's installer; when no engine is present it offers, once, to download the engine binary (checksum-pinned, logged in the egress ledger) and remembers the answer; without it the audit is unchanged. `gstack-config set design_detector off` disables the pre-pass. +**Design detector.** When you have [impeccable](https://impeccable.style) installed, its engine runs first: on a URL the page's rendered DOM is dumped (linked styles inlined) and scanned; on a feature branch with no URL the changed frontend files are scanned (Dart, Swift, Interface Builder, string-catalog and asset-catalog files excepted: they count as frontend scope, but the engine reads web sources). Every mechanical finding arrives as a `FINDING-NNN` tagged with its rule id (`[nested-cards]`, `[low-contrast]`), and the report closes with `Detector: N → M`. gstack never runs impeccable's installer; when no engine is present it offers, once, to download the engine binary (checksum-pinned, logged in the egress ledger) and remembers the answer; without it the audit is unchanged. `gstack-config set design_detector off` disables the pre-pass. ### Example @@ -631,7 +631,7 @@ Findings get action, not just listed. Obvious mechanical fixes (dead code, stale One exception: a shortcut you took deliberately and logged. A `gstack-shortcut(dec-<id>)` marker whose decision id resolves in the decision ledger downgrades the finding to acknowledged debt. An orphan marker — one with no ledger entry behind it — doesn't suppress anything; the gap is reported normally and the marker itself gets flagged. -**Design pass.** When the diff touches frontend files, the Design specialist reads `review/design-checklist.md`, which is generated from `lib/design-catalog.ts`, so `/review`, `/ship`, and `/design-review` flag the same patterns under the same rule ids. If you have [impeccable](https://impeccable.style) installed, its engine scans the changed frontend files first (`.dart` files get the checklist pass only): its rows bucket by tier (auto-fix, ask, possible), a detector hit and a checklist hit at the same file:line collapse into one row, and your repo's `.impeccable/config*.json` ignores are read as settled decisions. Without it, the checklist pass runs alone. +**Design pass.** When the diff touches frontend files, the Design specialist reads `review/design-checklist.md`, which is generated from `lib/design-catalog.ts`, so `/review`, `/ship`, and `/design-review` flag the same patterns under the same rule ids. If you have [impeccable](https://impeccable.style) installed, its engine scans the changed frontend files first (Dart, Swift, Interface Builder, string-catalog and asset-catalog files get the checklist pass only): its rows bucket by tier (auto-fix, ask, possible), a detector hit and a checklist hit at the same file:line collapse into one row, and your repo's `.impeccable/config*.json` ignores are read as settled decisions. Without it, the checklist pass runs alone. **PR type.** The checklist starts by naming the kind of PR from the changed paths: docs-only, CI/infra, scripts/tooling, application or mixed, and the review's first line says which (`PR type: <type>`). Application and mixed diffs run every category as before. A CI/infra, scripts/tooling or docs-only diff always gets Gate Integrity, Shell Injection, Completeness Gaps, Distribution & CI/CD Pipeline and Repo Conventions & Platform Fit; every other category with nothing to check is listed once, in one line, as not applicable, and never counts as passed. Repo Conventions & Platform Fit flags new files that don't match the languages and tools the repo already uses or the platforms its CI runs on, such as a `.bat` build script in a bash-and-Makefile repo. diff --git a/lib/frontend-scope.ts b/lib/frontend-scope.ts index 96c90806c66..f0a5e4ec6d1 100644 --- a/lib/frontend-scope.ts +++ b/lib/frontend-scope.ts @@ -19,8 +19,13 @@ const EXTENSIONS = new Set([ // Dart: a Flutter widget and a repository share the extension, so the bash // script counts .dart as frontend AND backend; only the frontend half lives here. '.dart', + // Swift and Apple UI files (GST-3041): .swift is frontend and backend like .dart. + '.swift', '.storyboard', '.xib', '.strings', '.stringsdict', '.xcstrings', ]); +/** Native UI sources impeccable cannot read: frontend scope, never a design-scan target. */ +const NATIVE_UI = /\.(dart|swift|storyboard|xib|strings|stringsdict|xcstrings)$|\.xcassets\//; + // Root-level only: the bash arm's glob (`tailwind.config.*`) is matched against the // whole repo-relative path, so a nested `apps/web/tailwind.config.js` is not frontend there. const ROOT_CONFIG_PREFIXES = ['tailwind.config.', 'postcss.config.']; @@ -41,13 +46,20 @@ export function isTemplateCandidate(relPath: string): boolean { return TEMPLATE_EXT.test(rel) && !TEMPLATE_SKIP.test(rel) && !TEST_PATH.test(rel); } +/** A frontend path in a native UI format (Dart, Swift, Interface Builder, string and asset catalogs) rather than a web source. */ +export function isNativeUiPath(relPath: string): boolean { + return NATIVE_UI.test(relPath.replace(/\\/g, '/')); +} + /** Repo-relative path (forward slashes) → is it a frontend file per gstack-diff-scope? */ export function isFrontendPath(relPath: string): boolean { const rel = relPath.replace(/\\/g, '/').replace(/^\.\//, ''); const base = rel.slice(rel.lastIndexOf('/') + 1); const dot = base.lastIndexOf('.'); const ext = dot >= 0 ? base.slice(dot) : ''; // case-sensitive, exactly like gstack-diff-scope's globs + if (base === 'Package.swift') return false; // SwiftPM's manifest: config, never UI if (EXTENSIONS.has(ext)) return true; + if (rel.includes('.xcassets/')) return true; if (!rel.includes('/') && ROOT_CONFIG_PREFIXES.some(p => base.startsWith(p))) return true; if (rel.startsWith('app/views/')) return true; if (rel.includes('/components/')) return true; diff --git a/lib/review-risk.ts b/lib/review-risk.ts index 1403961d311..f413feaedb0 100644 --- a/lib/review-risk.ts +++ b/lib/review-risk.ts @@ -90,6 +90,7 @@ export const SECURITY_LINE = [ /['"`](?:node:)?child_process['"`]/, /(?:(?<![.\w$])|\b(?:globalThis|window|self)\.)fetch\s{0,20}\(/, /\bhttps?\.(?:request|get)\s{0,20}\(/, /\baxios\b/, /(?<![.\w$])got(?:\.[a-z]{1,10})?\s{0,20}\(/, /\bundici\b/, /\b(?:requests|httpx)\.[a-z]{1,10}\s{0,20}\(/, /\burllib(?:3|\.request)?\b|\burlopen\s{0,20}\(/, /\bnew\s{1,20}URL\s{0,20}\(\s{0,20}(?!['"][^'"\\]{0,2000}['"]\s{0,20}\)|import\.meta\.url\s{0,20}\))/, /\b(?:urljoin|url\.resolve)\s{0,20}\(/, + /\bURLSession\b|\bURLRequest\s{0,20}\(|\bNWConnection\b|\bAlamofire\b|\bAF\.(?:request|download|upload|streamRequest)\s{0,20}\(/, /\bredirect\s*:\s*['"](?:follow|manual)['"]|\b(?:maxRedirects|followRedirects?|follow_redirects|allow_redirects)\s*[:=]/, /\b(?:HTTPS?_PROXY|NO_PROXY|ALL_PROXY|https?_proxy|no_proxy)\b|\b(?:Https?)?ProxyAgent\b|\bproxy\s*(?::|=(?![=>]))/, /\b(?:allowed|trusted|blocked|denied)[_-]?(?:hosts?|domains?|origins?|urls?)|\b(?:hosts?|domains?|origins?|urls?)[_-]?(?:allow|deny|block)[_-]?list/i, /\btar\.(?:x|extract)\s*\(|\.(?:extractall|extractAllTo|extractEntryTo)\s*\(|\b(?:tar|tf|zf|zip|archive)\.extract\s*\(|\bshutil\.unpack_archive\s*\(|\b(?:adm-zip|AdmZip|yauzl|extract-zip|unzipper|node-stream-zip)\b/, diff --git a/test/diff-scope.test.ts b/test/diff-scope.test.ts index b8fb6aa5b5e..2db37b8733c 100644 --- a/test/diff-scope.test.ts +++ b/test/diff-scope.test.ts @@ -161,6 +161,19 @@ describe('gstack-diff-scope', () => { expect(runScope(createRepo(['packages/cache/pubspec.lock'])).SCOPE_CONFIG).toBe('true'); }); + // Value: protects=an iOS UI change plans its review instead of failing closed; fails_when=.swift matches no arm and the + // diff prints SCOPE_ERROR=unmatched (review-depth then forces the full panel); why_new=GST-3041: ghome#32, a 55-line + // SwiftUI copy change, got 5 readers and a coverage audit; seam=none; no_claim=which readers that plan dispatches + test('a ghome#32-like SwiftUI change is frontend and backend, not unmatched (GST-3041)', () => { + const { vars, status, stdout } = runScopeFull(createRepo([ + 'App/AppModel.swift', 'App/Watch/PhoneWatchLink.swift', 'App/Review/ReviewView.swift', 'App/Health/HealthSync.swift', + 'App/Home/SettingsView.swift', 'App/Meeting/InSessionView.swift', 'App/Meeting/MeetingRecorder.swift', 'App/Brief/YourDayViews.swift', + ])); + expect(stdout).not.toContain('SCOPE_ERROR'); + expect(status).toBe(0); + expect(vars).toMatchObject({ SCOPE_FRONTEND: 'true', SCOPE_BACKEND: 'true', SCOPE_AUTH: 'false', SCOPE_CONFIG: 'false', SCOPE_API: 'false' }); + }); + test('detects test files', () => { const dir = createRepo(['test/app.test.ts']); const scope = runScope(dir); @@ -342,6 +355,32 @@ describe('glob classes (table-driven, #2526 + #2455)', () => { { name: 'contest_rules.py is not a test', file: 'pkg/contest_rules.py', expects: ['SCOPE_BACKEND'], alsoFalse: ['SCOPE_TESTS'] }, { name: 'testing/ dir is not a test dir', file: 'pkg/testing/fixtures_loader.py', expects: ['SCOPE_BACKEND'], alsoFalse: ['SCOPE_TESTS'] }, { name: 'attest_*.py is not a test', file: 'pkg/attest_signer.py', expects: ['SCOPE_BACKEND'], alsoFalse: ['SCOPE_TESTS'] }, + // Swift and Xcode (GST-3041). Source, Interface Builder files, string catalogs and asset catalogs read as UI and app + // code, the way .dart and .tsx do. Files that carry real risk never read as UI: permissions (Info.plist, entitlements, + // the privacy manifest) are AUTH like any *permission* path; dependency manifests and locks, the project file and build + // settings are CONFIG like package.json and Gemfile.lock; Swift under an auth or api path keeps AUTH or API. + { name: 'SwiftUI view', file: 'App/Review/ReviewView.swift', expects: ['SCOPE_FRONTEND', 'SCOPE_BACKEND'], alsoFalse: ['SCOPE_AUTH', 'SCOPE_CONFIG'] }, + { name: 'storyboard', file: 'App/Base.lproj/Main.storyboard', expects: ['SCOPE_FRONTEND'], alsoFalse: ['SCOPE_BACKEND', 'SCOPE_AUTH'] }, + { name: 'xib', file: 'App/Cells/ItemCell.xib', expects: ['SCOPE_FRONTEND'], alsoFalse: ['SCOPE_BACKEND'] }, + { name: 'legacy .strings', file: 'App/en.lproj/Localizable.strings', expects: ['SCOPE_FRONTEND'], alsoFalse: ['SCOPE_BACKEND'] }, + { name: '.stringsdict plurals', file: 'App/en.lproj/Localizable.stringsdict', expects: ['SCOPE_FRONTEND'], alsoFalse: ['SCOPE_BACKEND'] }, + { name: 'string catalog', file: 'App/Localizable.xcstrings', expects: ['SCOPE_FRONTEND'], alsoFalse: ['SCOPE_BACKEND'] }, + { name: 'asset catalog', file: 'App/Assets.xcassets/AccentColor.colorset/Contents.json', expects: ['SCOPE_FRONTEND'], alsoFalse: ['SCOPE_BACKEND'] }, + { name: 'Info.plist is permissions (URL schemes, ATS, usage strings)', file: 'App/Info.plist', expects: ['SCOPE_AUTH', 'SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'GoogleService-Info.plist reads as Info.plist', file: 'App/GoogleService-Info.plist', expects: ['SCOPE_AUTH', 'SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'entitlements are permissions', file: 'App/GHome.entitlements', expects: ['SCOPE_AUTH', 'SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'privacy manifest is permissions', file: 'App/PrivacyInfo.xcprivacy', expects: ['SCOPE_AUTH', 'SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'other plist is config', file: 'App/Defaults.plist', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND', 'SCOPE_AUTH'] }, + { name: 'Package.swift is a dependency manifest, never UI', file: 'Package.swift', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND', 'SCOPE_BACKEND'] }, + { name: 'nested Package.swift', file: 'Packages/GHomeCore/Package.swift', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND', 'SCOPE_BACKEND'] }, + { name: 'Package.resolved in the project', file: 'GHome.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'Podfile', file: 'Podfile', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'Podfile.lock', file: 'ios/Podfile.lock', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'project.pbxproj is build settings and signing', file: 'GHome.xcodeproj/project.pbxproj', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND', 'SCOPE_BACKEND'] }, + { name: 'xcconfig is build settings', file: 'Config/Release.xcconfig', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'shared scheme', file: 'GHome.xcodeproj/xcshareddata/xcschemes/GHome.xcscheme', expects: ['SCOPE_CONFIG'], alsoFalse: ['SCOPE_FRONTEND'] }, + { name: 'Swift under an auth path keeps AUTH', file: 'App/Auth/SignInView.swift', expects: ['SCOPE_AUTH', 'SCOPE_FRONTEND', 'SCOPE_BACKEND'] }, + { name: 'Swift under an api path keeps API', file: 'Sources/GHomeCore/api/GatewayClient.swift', expects: ['SCOPE_API', 'SCOPE_BACKEND'] }, ]; for (const row of TABLE) { @@ -391,6 +430,15 @@ describe('exit-code contract (#2526)', () => { expect(vars.SCOPE_API).toBe('false'); }); + // Value: protects=an Apple file type no arm knows still fails closed after Swift and Xcode got arms; fails_when=a broad + // *.swift-style or catch-all arm swallows unknown extensions; why_new=GST-3041 added Apple arms; seam=none; no_claim=none + test('an unknown Apple file type (a Metal shader) still fails closed (GST-3041)', () => { + const { vars, status, stdout } = runScopeFull(createRepo(['App/Shaders/Glow.metal'])); + expect(status).toBe(2); + expect(vars.SCOPE_ERROR).toBe('unmatched'); + expect(stdout).toContain('# unmatched: App/Shaders/Glow.metal'); + }); + test('unresolvable base → SCOPE_ERROR=no_base + exit 2 (a green would mean "could not look")', () => { const dir = createRepo(['app.ts']); const result = spawnSync('bash', [SCRIPT, 'no-such-branch'], { cwd: dir, stdio: 'pipe', timeout: 5000 }); diff --git a/test/fixtures/review-pins/files/lib/review-risk.ts.json b/test/fixtures/review-pins/files/lib/review-risk.ts.json index 1ee80cb2e39..61b0e5c8539 100644 --- a/test/fixtures/review-pins/files/lib/review-risk.ts.json +++ b/test/fixtures/review-pins/files/lib/review-risk.ts.json @@ -1 +1 @@ -{"sha":"25a7de61580398df96dca3651b10b2494825047e0898980406928b931b5f90af","replay":"GST-1350"} +{"sha":"2dbe134d502279da7a5f27e5370bb45a9658f01322030b1e27180d0e9e11285d","replay":"GST-3041"} diff --git a/test/fixtures/review-pins/replays/GST-3041.json b/test/fixtures/review-pins/replays/GST-3041.json new file mode 100644 index 00000000000..dc2626ef7da --- /dev/null +++ b/test/fixtures/review-pins/replays/GST-3041.json @@ -0,0 +1 @@ +{"replay":"GST-3041","justification":"GST-3041 no-loss replay: the review-risk.ts SECURITY_LINE alternative for Swift networking (URLSession, URLRequest, NWConnection, Alamofire) only adds security hits. Planner depth from 2081e670 (old) and a936221e (new) on the last 200 first-parent main commits (64862e41..cbd21f94): 200 identical (126 full, 74 light), 0 raised, 0 lowered, no risk class lost. Controls: a URLSession client fixture raises light to full with risk security; a SwiftUI-only fixture stays light. Reviewer text is unchanged."} diff --git a/test/frontend-scope.test.ts b/test/frontend-scope.test.ts index 147e7d42075..0cd036fd049 100644 --- a/test/frontend-scope.test.ts +++ b/test/frontend-scope.test.ts @@ -47,6 +47,21 @@ const SAMPLES: Array<[string, boolean]> = [ ['lib/widgets/bbtm_drawer/view/bbtm_drawer.dart', true], ['packages/cache/lib/cache.dart', true], ['test/ui/drawer_widget_test.dart', true], + ['App/Review/ReviewView.swift', true], + ['App/Base.lproj/Main.storyboard', true], + ['App/Cells/ItemCell.xib', true], + ['App/en.lproj/Localizable.strings', true], + ['App/en.lproj/Localizable.stringsdict', true], + ['App/Localizable.xcstrings', true], + ['App/Assets.xcassets/AppIcon.appiconset/Contents.json', true], + ['Package.swift', false], + ['Packages/GHomeCore/Package.swift', false], + ['Packages/components/Package.swift', false], // the manifest arm wins over */components/*, as it does in the script + ['App/Info.plist', false], + ['App/GHome.entitlements', false], + ['GHome.xcodeproj/project.pbxproj', false], + ['Config/Release.xcconfig', false], + ['App/Shaders/Glow.metal', false], ]; describe('isFrontendPath', () => { diff --git a/test/gstack-design-detect.test.ts b/test/gstack-design-detect.test.ts index 84a4e4e62e7..a76e6008083 100644 --- a/test/gstack-design-detect.test.ts +++ b/test/gstack-design-detect.test.ts @@ -911,6 +911,9 @@ describe('scan', () => { // fails_when=the .dart exclusion in resolveTargets is dropped; why_new=no --changed case had a Dart file; seam=none; // no_claim=the real impeccable engine (fake engine logs argv) fs.writeFileSync(path.join(REPO, 'drawer.dart'), 'class Drawer {}\n'); // untracked Dart: frontend scope, not a scan target + // Value: protects=a SwiftUI file (frontend scope since GST-3041) never reaches the web-source engine either; fails_when=the + // native-UI exclusion covers .dart only; why_new=GST-3041 made .swift frontend; seam=none; no_claim=the real engine + fs.writeFileSync(path.join(REPO, 'ReviewView.swift'), 'struct ReviewView {}\n'); const log = path.join(SANDBOX, 'argv4.log'); fs.rmSync(log, { force: true }); try { @@ -923,6 +926,7 @@ describe('scan', () => { fs.rmSync(path.join(REPO, 'styles'), { recursive: true, force: true }); fs.rmSync(path.join(REPO, 'notes.md'), { force: true }); fs.rmSync(path.join(REPO, 'drawer.dart'), { force: true }); + fs.rmSync(path.join(REPO, 'ReviewView.swift'), { force: true }); git(REPO, 'checkout', '-q', 'main'); git(REPO, 'branch', '-q', '-D', 'feature'); } diff --git a/test/review-plan-cli.test.ts b/test/review-plan-cli.test.ts index b4836f30f2d..ceadee1f2cd 100644 --- a/test/review-plan-cli.test.ts +++ b/test/review-plan-cli.test.ts @@ -60,6 +60,23 @@ describe('gstack-review-plan', () => { expect(r.stdout).toContain('REVIEW_PLAN: class=tests pass=1 next=full dispatches=1 numbers=no'); expect(r.stdout.split('\n').filter(l => l.startsWith('DISPATCH: '))).toEqual(['DISPATCH: specialist batched effort=medium checklists=testing']); }); + // Value: protects=an iOS UI change plans by risk instead of failing closed to the full panel, while Apple permissions still plan + // full; fails_when=gstack-diff-scope prints SCOPE_ERROR=unmatched for .swift, or Info.plist reads as plain UI; why_new=GST-3041: + // ghome#32, a 55-line SwiftUI copy change, got 5 readers and a coverage audit; seam=gstack-review-plan on a real repo; + // no_claim=what the readers find + test('a SwiftUI change plans light, not the fail-closed panel; an Info.plist edit plans gate (GST-3041)', () => { + const view = 'import SwiftUI\nstruct ReviewView: View {\n var body: some View { Text("Saved") }\n}\n'; + const ui = { 'App/Review/ReviewView.swift': view, 'App/Home/SettingsView.swift': view, 'App/AppModel.swift': 'final class AppModel {}\n', 'Tests/GHomeTests/HealthSyncTests.swift': 'import XCTest\n' }; + const light = run(repo(ui), []); + expect(light.stdout).not.toContain('DEPTH_ERROR'); + expect(light.stdout).toMatch(/^REVIEW_DEPTH: light /m); + expect(light.stdout).toMatch(/^REVIEW_PLAN: class=code /m); + const plist = run(repo({ ...ui, 'App/Info.plist': '<plist><dict><key>NSAllowsArbitraryLoads</key><true/></dict></plist>\n' }), []); + expect(plist.stdout).toMatch(/^REVIEW_CLASS: gate .*auth paths/m); + expect(plist.stdout).toMatch(/^REVIEW_DEPTH: full /m); + const client = run(repo({ ...ui, 'App/Client.swift': 'final class Client {\n func load(_ r: URLRequest) async throws -> Data { try await URLSession.shared.data(for: r).0 }\n}\n' }), []); + expect(client.stdout).toMatch(/^REVIEW_DEPTH: full .*risk:security/m); + }); test('a docs diff that publishes numbers keeps the outside voice', () => { const r = run(repo({ 'docs/bench.md': 'Median latency fell 42% to 180 ms.\n' }), []); expect(r.stdout).toContain('DISPATCH: outside-voice outside-voice effort=host'); diff --git a/test/review-risk-routing.test.ts b/test/review-risk-routing.test.ts index 66f3d8fa99f..5f05c886753 100644 --- a/test/review-risk-routing.test.ts +++ b/test/review-risk-routing.test.ts @@ -277,6 +277,21 @@ describe('GST-850: security reaches outbound URLs, archives, path traversal and }); }); +describe('GST-3041: Swift networking is security, SwiftUI is not', () => { + // Value: protects=a Swift diff that adds an outbound HTTP client still reaches the full panel now that .swift no longer fails closed; + // fails_when=URLSession, URLRequest, NWConnection or Alamofire reads light, or an ordinary SwiftUI view raises a class; seam=matchRisk + test.each([ + 'let (data, _) = try await URLSession.shared.data(for: request)', 'let session = URLSession(configuration: .ephemeral)', + 'var request = URLRequest(url: endpoint)', 'let conn = NWConnection(host: host, port: 443, using: .tls)', 'import Alamofire', 'AF.request(url).responseDecodable(of: Item.self) { _ in }', + ])('%s is security', line => { + expect(risk(['App/Client.swift'], { 'App/Client.swift': [line] })).toEqual(['security']); + }); + test('an ordinary SwiftUI view is not security', () => { + for (const line of ['struct ReviewView: View {', ' var body: some View { Text("Saved") }', 'let url = URL(string: "https://example.com")!', '@State private var request = ""']) + expect(risk(['App/ReviewView.swift'], { 'App/ReviewView.swift': [line] })).toEqual([]); + }); +}); + describe('GST-850: money reaches metering, charge and credit code', () => { // Value: protects=a billing-client or metering diff gets the money reader; fails_when=gbrain-evals #289 reads required=none again, // or costume, a CLI usage line or a proxy with no billing names money; seam=matchRisk and targetedClasses From c9b6fe0ab36220858cb20287cf9cc9bfd18d9ea6 Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 10:12:43 +0800 Subject: [PATCH 58/62] Second-model plan reviews in autoplan stop being reported unavailable; --help stops printing a fake refusal (GST-3051) (#4471) A second-model plan review in `/autoplan` is no longer reported as unavailable when it actually ran, and `gstack-outside-voice --help` no longer prints a line that reads like a real consent refusal. Why: sessions believed the false label and paid to re-run the review, or closed the plan phase without its second-model review. Nothing to do: the command autoplan already runs now picks the right check by itself. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-outside-voice | 21 ++-- ...lan-second-model-review-not-unavailable.md | 1 + docs/troubleshooting.md | 7 +- lib/autoplan-prompts.ts | 3 +- lib/autoplan-reconcile.ts | 11 +- lib/claude-code-migration.ts | 2 +- lib/outside-review-result.ts | 13 +- test/outside-consent.test.ts | 2 +- test/outside-voice-autoplan-gate.test.ts | 117 ++++++++++++++++++ 9 files changed, 159 insertions(+), 18 deletions(-) create mode 100644 changelog.d/capy-autoplan-second-model-review-not-unavailable.md create mode 100644 test/outside-voice-autoplan-gate.test.ts diff --git a/bin/gstack-outside-voice b/bin/gstack-outside-voice index 381fbcd0ac6..68af3a6cba6 100755 --- a/bin/gstack-outside-voice +++ b/bin/gstack-outside-voice @@ -4,7 +4,7 @@ * * gstack-outside-voice run --runner codex-cli|api|host-subagent --prompt <file> --out <file> * [--model <id>] [--result <file>] [--native-model <id>] [--fallback <runner>] - * [--gate review|structured|spec|proposal] [--timeout-ms N] [--max-tokens N] [--cwd <dir>] [--json] + * [--gate review|structured|spec|proposal|autoplan] [--timeout-ms N] [--max-tokens N] [--cwd <dir>] [--json] * gstack-outside-voice runners [--model <id>] [--json] the runner table: capabilities and availability here * gstack-outside-voice family <model-id> the model's family (same-family rule) * @@ -17,6 +17,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; +import { RESULT_FORMAT_HEADER } from '../lib/autoplan-reconcile'; import { findingsLabel, type OutsideGate } from '../lib/outside-review-result'; import { RUNNER_IDS, createRunner, familyConflict, modelFamily, outsideStatusLine, runnerTable, selectRunner, type RunnerId } from '../lib/outside-voice-runner'; import { outsideConsent } from '../lib/outside-consent'; @@ -26,7 +27,7 @@ import { resultLine } from '../lib/result-codes'; const HELP = `gstack-outside-voice — one outside voice, three runners (docs/unattended.md) run --runner <r> --prompt <file> --out <file> [--model <id>] [--result <file>] [--native-model <id>] - [--fallback <r>] [--gate review|structured|spec|proposal] [--timeout-ms N] [--max-tokens N] [--cwd <dir>] [--json] + [--fallback <r>] [--gate review|structured|spec|proposal|autoplan] [--timeout-ms N] [--max-tokens N] [--cwd <dir>] [--json] runners [--model <id>] [--json] the runner table: id, capabilities, available here family <model-id> print the model family (anthropic, openai, google, ...) @@ -35,10 +36,14 @@ OPENAI_API_KEY/ANTHROPIC_API_KEY; needs --model), host-subagent (binds --result cross-family subagent the host ran; needs --model). --max-tokens caps the api runner's output (Anthropic default 16384; its default time limit grows with it); a response cut off at the limit is unavailable (truncated). --native-model enforces the same-family -rule. GSTACK_OUTSIDE_RUNNER names the fallback when --fallback is absent. -Prints OUTSIDE_STATUS: <status> provider=<runner> model=<id> family=<f> and writes <out>.meta.json. -codex_reviews=disabled (or an unreadable config) refuses every runner before it starts: -OUTSIDE_STATUS: not_run reason=consent_missing, exit 3. Enable: gstack-config set codex_reviews enabled. +rule. GSTACK_OUTSIDE_RUNNER names the fallback when --fallback is absent. --gate defaults to +autoplan (its INPUT receipt and gstack-findings fence) when the prompt carries gstack-autoplan's +RESULT FORMAT, else review. Writes <out>.meta.json and prints a status line, for example + OUTSIDE_STATUS: <status> provider=<runner> model=<id> family=<f> +codex_reviews=disabled (or an unreadable config) refuses every runner before it starts, exit 3, +with the status line + OUTSIDE_STATUS: not_run reason=consent_missing +Enable: gstack-config set codex_reviews enabled. ${exitTableHelp()}`; function flag(args: string[], name: string): string | undefined { @@ -76,8 +81,8 @@ async function main(argv: string[]): Promise<number> { if (!isRunner(requested)) return usage(`--runner must be one of ${RUNNER_IDS.join(', ')}`); if (!promptFile || !outFile) return usage('run needs --prompt <file> --out <file>'); if (!fs.existsSync(promptFile)) return usage(`prompt file not found: ${promptFile}`); - const gate = (flag(rest, '--gate') ?? 'review') as OutsideGate; - if (!['review', 'structured', 'spec', 'proposal'].includes(gate)) return usage('--gate must be review, structured, spec or proposal'); + const gate = (flag(rest, '--gate') ?? (fs.readFileSync(promptFile, 'utf8').includes(RESULT_FORMAT_HEADER) ? 'autoplan' : 'review')) as OutsideGate; + if (!['review', 'structured', 'spec', 'proposal', 'autoplan'].includes(gate)) return usage('--gate must be review, structured, spec, proposal or autoplan'); const maxTokensText = flag(rest, '--max-tokens'); const maxTokens = maxTokensText === undefined ? undefined : Number(maxTokensText); if (maxTokens !== undefined && (!Number.isInteger(maxTokens) || maxTokens <= 0)) return usage('--max-tokens needs a positive integer'); diff --git a/changelog.d/capy-autoplan-second-model-review-not-unavailable.md b/changelog.d/capy-autoplan-second-model-review-not-unavailable.md new file mode 100644 index 00000000000..3bc3e442b78 --- /dev/null +++ b/changelog.d/capy-autoplan-second-model-review-not-unavailable.md @@ -0,0 +1 @@ +- **A second-model plan review in `/autoplan` is no longer reported as unavailable when it actually ran (GST-3051).** `gstack-outside-voice run` judged autoplan's reviews by `/review`'s rule, which wants a `Recommendation: ... because ...` line autoplan never asks for, so a finished review printed `VERDICT: unavailable` (`missing_markers`) and sessions paid to re-run it or dropped it. A prompt that carries autoplan's result format is now checked against that format (its `INPUT:` line and `gstack-findings` fence; `--gate autoplan` asks for it explicitly), and a reply without them, or an empty one, is still unavailable. `gstack-outside-voice --help` also no longer prints a line that starts with `OUTSIDE_STATUS:`, which logs and models read as a real consent refusal. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ee35ecf7bd8..c58bf256420 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -386,7 +386,12 @@ it; `gstack-outside-voice run` sends that default to Anthropic only. **Meaning.** The answer did not contain what the gate checks: a `Recommendation: ... because ...` line (or a `## Recommendation` heading whose next non-blank line is a plain sentence with a `because` reason), a -`SCORE:`/`AMBIGUITIES:` pair, or severity tags. +`SCORE:`/`AMBIGUITIES:` pair, autoplan's `INPUT: <phase> <sha256>` line and +`gstack-findings` fence, or severity tags. `gstack-outside-voice run` judges a +prompt that carries autoplan's RESULT FORMAT by that format (`--gate autoplan`), +so an autoplan second-model review that reports `missing review completion +recommendation` came from a gstack older than that fix: read its result file +before re-running it. **Fix.** Re-run the review. diff --git a/lib/autoplan-prompts.ts b/lib/autoplan-prompts.ts index fc136627f13..1abd7e09e74 100644 --- a/lib/autoplan-prompts.ts +++ b/lib/autoplan-prompts.ts @@ -13,6 +13,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { bunIsolationArgs } from './bun-isolation'; import { detectDocsOnly, readScopeMarker, scopeMarker, scopeTokens, type ScopeFlags, type UiEvidence } from './autoplan-scope'; +import { RESULT_FORMAT_HEADER } from './autoplan-reconcile'; import { COORDINATOR_CONTRACT } from './coordinator-contract'; import { capyBootstrapCommand } from './doctor-components'; import { DX_ERROR_COMPACT } from './dx-error-contract'; @@ -117,7 +118,7 @@ export function extractHeading(text: string, heading: string): string | undefine export const RESULT_FORMAT = (phase: string, sha256: string, resultPath: string) => ` --- -RESULT FORMAT (required by gstack-autoplan; the parent binds your file by this contract): +${RESULT_FORMAT_HEADER} 1. The first line of your result is exactly: INPUT: ${phase} ${sha256} 2. Write the complete review as prose, then END with one fenced block of canonical findings, one JSON object per line: \`\`\`gstack-findings diff --git a/lib/autoplan-reconcile.ts b/lib/autoplan-reconcile.ts index 9a7ed459d79..45044e7d3f1 100644 --- a/lib/autoplan-reconcile.ts +++ b/lib/autoplan-reconcile.ts @@ -15,6 +15,8 @@ import type { FindingRow, Severity, Voice } from './headless-artifacts'; export const SEVERITIES: readonly Severity[] = ['Critical', 'High', 'Medium', 'Low', 'Informational']; +/** The RESULT FORMAT block's opening words (lib/autoplan-prompts.ts); a prompt that carries them asks for this contract. */ +export const RESULT_FORMAT_HEADER = 'RESULT FORMAT (required by gstack-autoplan; the parent binds your file by this contract):'; const SEVERITY_ALIASES: Record<string, Severity> = { critical: 'Critical', p0: 'Critical', blocker: 'Critical', high: 'High', p1: 'High', major: 'High', @@ -49,8 +51,8 @@ export function severityOf(value: unknown): Severity | undefined { return SEVERITY_ALIASES[value.trim().toLowerCase()]; } -/** Parse a reviewer's result: the INPUT receipt for this phase and snapshot, then the canonical findings fence(s). */ -export function parseReviewResult(text: string, expected: { phase: string; sha256: string }): ParsedReviewResult { +/** Parse a reviewer's result: the INPUT receipt for this phase and snapshot (any, without expected), then the canonical findings fence(s). */ +export function parseReviewResult(text: string, expected?: { phase: string; sha256: string }): ParsedReviewResult { const errors: string[] = []; const receipt = parseReceipt(text, expected); if (!receipt.ok) errors.push(receipt.error!); @@ -59,12 +61,13 @@ export function parseReviewResult(text: string, expected: { phase: string; sha25 return { receipt, findings, fenceFound, errors }; } -/** The full-read receipt: `INPUT: <phase> <sha256>` in the first five non-empty lines, matching this phase and snapshot. */ -export function parseReceipt(text: string, expected: { phase: string; sha256: string }): ParsedReviewResult['receipt'] & { present: boolean; error?: string } { +/** The full-read receipt: `INPUT: <phase> <sha256>` in the first five non-empty lines, matching this phase and snapshot when expected is given. */ +export function parseReceipt(text: string, expected?: { phase: string; sha256: string }): ParsedReviewResult['receipt'] & { present: boolean; error?: string } { const head = text.split('\n').map(l => l.trim()).filter(Boolean).slice(0, 5); const receiptLine = head.find(l => /^INPUT:\s*\S+\s+[0-9a-f]{64}\b/i.test(l)); const m = receiptLine ? /^INPUT:\s*(\S+)\s+([0-9a-f]{64})/i.exec(receiptLine) : null; if (!m) return { ok: false, present: false, error: 'no INPUT: <phase> <sha256> line in the first five lines' }; + if (!expected) return { ok: true, present: true, phase: m[1]!.toLowerCase(), sha256: m[2]!.toLowerCase(), line: receiptLine }; const ok = m[1]!.toLowerCase() === expected.phase && m[2]!.toLowerCase() === expected.sha256.toLowerCase(); return { ok, present: true, phase: m[1]!.toLowerCase(), sha256: m[2]!.toLowerCase(), line: receiptLine, ...(ok ? {} : { error: `receipt names ${m[1]} ${m[2]!.slice(0, 12)}…, expected ${expected.phase} ${expected.sha256.slice(0, 12)}…` }) }; diff --git a/lib/claude-code-migration.ts b/lib/claude-code-migration.ts index 31c7da30fee..1c04fd4de2d 100644 --- a/lib/claude-code-migration.ts +++ b/lib/claude-code-migration.ts @@ -11,7 +11,7 @@ const BANNER = '<!-- AUTO-GENERATED from'; export const CLAUDE_CODE_RUNTIME_FILES = [ 'bin/gstack-claude-code', 'bin/gstack-models', 'bin/gstack-config', 'bin/gstack-lock.sh', 'bin/gstack-state-root.sh', 'lib/claude-code.ts', 'lib/claude-code-windows-job.ts', 'lib/claude-bin.ts', - 'lib/outside-review-result.ts', 'lib/gate-outcomes.ts', 'lib/outside-consent.ts', 'lib/state-root.ts', + 'lib/outside-review-result.ts', 'lib/autoplan-reconcile.ts', 'lib/gate-outcomes.ts', 'lib/outside-consent.ts', 'lib/state-root.ts', 'lib/model-catalog.ts', 'lib/model-policy.ts', 'lib/model-policy-cli.ts', 'lib/model-policy-notice.ts', 'lib/agent-model.ts', ]; diff --git a/lib/outside-review-result.ts b/lib/outside-review-result.ts index 079cfda047f..6824a9acbfc 100644 --- a/lib/outside-review-result.ts +++ b/lib/outside-review-result.ts @@ -7,9 +7,11 @@ * the highest finding severity, and the verdict. validateOutsideReview() is the * older text-only shape, kept for direct importers and stale rendered skills. */ +import { parseReviewResult } from './autoplan-reconcile'; import { GATE_OUTCOMES, gateOutcomeLine, type GateReason } from './gate-outcomes'; -export type OutsideGate = 'review' | 'structured' | 'spec' | 'execution' | 'proposal'; +/** autoplan: the INPUT receipt and gstack-findings fence that lib/autoplan-prompts.ts RESULT_FORMAT asks every plan reviewer for. */ +export type OutsideGate = 'review' | 'structured' | 'spec' | 'execution' | 'proposal' | 'autoplan'; export type OutsideVerdict = 'clean' | 'findings' | 'unverified' | 'unavailable'; export type Severity = 'P0' | 'P1' | 'P2' | 'P3'; @@ -132,6 +134,7 @@ function execution(input: OutsideReviewInput): OutsideReviewClassification['exec * Critical and high block like P0/P1; medium and low are advisory like P2/P3. */ const SEVERITY_WORDS: Record<string, Severity> = { critical: 'P0', high: 'P1', medium: 'P2', low: 'P3' }; +const AUTOPLAN_LEVEL: Record<string, Severity | undefined> = { Critical: 'P0', High: 'P1', Medium: 'P2', Low: 'P3' }; const WORD = '(critical|high|medium|low)'; const SEVERITY_LABELS = [ new RegExp(`\\b(?:severity|priority)\\b[\\t ]*[:=][\\t ]*(?:\\*\\*|__|\\[|\`)*${WORD}\\b`, 'gim'), @@ -264,6 +267,12 @@ export function classifyOutsideReview(input: OutsideReviewInput): OutsideReviewC const blocking = findings.highest === 'P0' || findings.highest === 'P1'; const result = (verdict: OutsideVerdict, reason?: GateReason, detail?: string): OutsideReviewClassification => ({ execution: ran, findings, verdict, ...(reason ? { reason } : {}), ...(detail ? { detail } : {}) }); + if (input.gate === 'autoplan') { + const parsed = parseReviewResult(input.text); + if (parsed.errors.length) return result('unavailable', 'missing_markers', `autoplan result: ${parsed.errors.join('; ')}`.slice(0, 240)); + const highest = parsed.findings.map(f => AUTOPLAN_LEVEL[f.severity]).filter((s): s is Severity => !!s).sort()[0] ?? null; + return { execution: ran, findings: { highest }, verdict: highest === 'P0' || highest === 'P1' ? 'findings' : 'clean' }; + } if (input.gate === 'spec') { const scores = [...input.text.matchAll(/^SCORE:[\t ]*(10|[0-9])[\t ]*\r?$/gm)]; const ambiguities = [...input.text.matchAll(/^AMBIGUITIES:[\t ]*(\S[^\r\n]*)\r?$/gm)]; @@ -350,7 +359,7 @@ export function validateOutsideReview(text: string, gate: OutsideGate): { comple } const VERDICT_EXIT: Record<OutsideVerdict, number> = { clean: 0, findings: 3, unverified: 4, unavailable: 1 }; -const GATES = ['review', 'structured', 'spec', 'execution', 'proposal']; +const GATES = ['review', 'structured', 'spec', 'execution', 'proposal', 'autoplan']; const USAGE = `Usage: outside-review-result.ts <gate> <response-file> outside-review-result.ts --verdict [--stderr <file>] [--exit <code>] [--events <file>] [--provider-error <file>] [--label <name>] <gate> <response-file> Gates: ${GATES.join('|')}. Two-argument form exits 0 completed, 1 unavailable, 2 usage. diff --git a/test/outside-consent.test.ts b/test/outside-consent.test.ts index 239a57fc33a..872badc8fa2 100644 --- a/test/outside-consent.test.ts +++ b/test/outside-consent.test.ts @@ -150,7 +150,7 @@ describe('gstack-claude-code', () => { describe('API sends: gstack-outside-voice and the unattended runner', () => { let server: ReturnType<typeof Bun.serve>; let requests = 0; - const REVIEW = '[P2] A finding.\n\nRecommendation: revise because the premise is unmeasured.\n'; + const REVIEW = `INPUT: ceo ${'a'.repeat(64)}\n\n[P2] A finding.\n\nRecommendation: revise because the premise is unmeasured.\n\n\`\`\`gstack-findings\n\`\`\`\n`; beforeAll(() => { server = Bun.serve({ port: 0, fetch() { requests++; return Response.json({ model: 'gpt-6-astra', choices: [{ message: { content: REVIEW } }], usage: {} }); } }); }); diff --git a/test/outside-voice-autoplan-gate.test.ts b/test/outside-voice-autoplan-gate.test.ts new file mode 100644 index 00000000000..4741396f7e0 --- /dev/null +++ b/test/outside-voice-autoplan-gate.test.ts @@ -0,0 +1,117 @@ +/** + * GST-3051: an autoplan outside review run the DRIVER.md way (no --gate) is + * judged by autoplan's own result contract, the INPUT receipt and the + * gstack-findings fence (lib/autoplan-prompts.ts RESULT_FORMAT), never by the + * /review gate's Recommendation line, so a review that ran is not labeled + * unavailable (missing_markers). A reply without that contract, or an empty + * one, still is. And --help never prints a line that starts like a real + * OUTSIDE_STATUS or VERDICT result. + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { writePrompts } from '../lib/autoplan-prompts'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const BIN = path.join(ROOT, 'bin', 'gstack-outside-voice'); +const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'ov-autoplan-')); +afterAll(() => fs.rmSync(TMP, { recursive: true, force: true })); + +const SHA = 'a'.repeat(64); +const snapshotPath = path.join(TMP, 'snapshot.md'); +fs.writeFileSync(snapshotPath, '# Plan\n\n## Implementation plan\n\n- Add a flag.\n'); +const prompts = writePrompts({ phase: 'ceo', snapshot: { nativePrompt: 'native\n', snapshotPath, sha256: SHA }, outDir: TMP, priorConsensus: [] }); + +const env: Record<string, string> = {}; +for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !/^(OPENAI|ANTHROPIC)_/.test(k) && k !== 'GSTACK_OUTSIDE_RUNNER') env[k] = v; +env.GSTACK_STATE_ROOT = path.join(TMP, 'state'); + +function run(args: string[]) { + return spawnSync('bun', [BIN, ...args], { cwd: ROOT, env, encoding: 'utf8', timeout: 60_000 }); +} +/** The DRIVER.md:29 form: host-subagent binding the reviewer's file, no --gate. */ +function review(name: string, text: string, extra: string[] = [], prompt = prompts.outside) { + const result = path.join(TMP, name + '.result.md'); + fs.writeFileSync(result, text); + const out = path.join(TMP, name + '.out.md'); + const r = run(['run', '--runner', 'host-subagent', '--prompt', prompt, '--out', out, '--result', result, '--model', 'openai/gpt-6-astra', '--native-model', 'claude-opus-5-5', ...extra]); + const meta = JSON.parse(fs.readFileSync(out + '.meta.json', 'utf8')); + return { ...r, meta }; +} +const fence = (rows: string[]) => '\x60\x60\x60gstack-findings\n' + rows.join('\n') + (rows.length ? '\n' : '') + '\x60\x60\x60\n'; +const HIGH = '{"id":"F1","severity":"High","title":"The premise is unmeasured","fix":"Measure it first"}'; +const MEDIUM = '{"id":"F2","severity":"Medium","title":"Name the flag plainly"}'; +const receipt = 'INPUT: ceo ' + SHA + '\n\n'; + +describe('autoplan outside review without --gate', () => { + test('a review that follows the RESULT FORMAT is completed with its findings, not missing_markers', () => { + const r = review('high', receipt + 'The plan assumes demand it never measured.\n\n' + fence([HIGH, MEDIUM])); + expect(r.status, r.stderr).toBe(0); + expect(r.stdout).toContain('VERDICT: findings\nFINDINGS: P1\n'); + expect(r.stdout).toMatch(/^OUTSIDE_STATUS: completed provider=host-subagent model=openai\/gpt-6-astra family=openai/m); + expect(r.meta.status).toBe('completed'); + expect(r.meta.verdict).toMatchObject({ execution: { state: 'ran' }, verdict: 'findings', findings: { highest: 'P1' } }); + expect(r.meta.reason).toBeUndefined(); + }); + + test('an empty fence is a clean review; advisory-only findings are clean with their severity', () => { + const none = review('none', receipt + 'Nothing to add.\n\n' + fence([])); + expect(none.status, none.stderr).toBe(0); + expect(none.stdout).toContain('VERDICT: clean\nFINDINGS: none\n'); + const medium = review('medium', receipt + 'One naming nit.\n\n' + fence([MEDIUM])); + expect(medium.status, medium.stderr).toBe(0); + expect(medium.stdout).toContain('VERDICT: clean\nFINDINGS: P2\n'); + }); + + test('a reply without the fence or the INPUT receipt is still unavailable (missing_markers)', () => { + for (const [name, text] of [['no-fence', receipt + 'High: the premise is unmeasured.\n'], ['no-receipt', 'Review follows.\n\n' + fence([HIGH])]] as const) { + const r = review(name, text); + expect(r.status).toBe(1); + expect(r.stdout).toContain('VERDICT: unavailable\n'); + expect(r.meta).toMatchObject({ status: 'unavailable', reason: 'missing_markers' }); + } + }); + + test('an empty reply is still unavailable', () => { + const r = review('empty', ''); + expect(r.status).toBe(1); + expect(r.meta).toMatchObject({ status: 'unavailable', reason: 'empty_response' }); + }); + + test('a malformed findings row is unavailable and names the row', () => { + const r = review('bad-row', receipt + fence(['{"severity":"Huge","title":"x"}'])); + expect(r.status).toBe(1); + expect(r.meta).toMatchObject({ status: 'unavailable', reason: 'missing_markers' }); + expect(r.meta.detail).toContain('findings row 1'); + }); +}); + +describe('gate selection', () => { + test('--gate autoplan applies the same contract to any prompt', () => { + const plain = path.join(TMP, 'plain-prompt.md'); + fs.writeFileSync(plain, 'Review this plan.\n'); + const r = review('explicit', receipt + fence([HIGH]), ['--gate', 'autoplan'], plain); + expect(r.status, r.stderr).toBe(0); + expect(r.stdout).toContain('VERDICT: findings\nFINDINGS: P1\n'); + }); + + test("a prompt without autoplan's RESULT FORMAT keeps the review gate", () => { + const plain = path.join(TMP, 'review-prompt.md'); + fs.writeFileSync(plain, 'Review this diff.\n'); + const r = review('review-default', receipt + fence([HIGH]), [], plain); + expect(r.status).toBe(1); + expect(r.meta).toMatchObject({ status: 'unavailable', reason: 'missing_markers', detail: 'missing review completion recommendation' }); + }); +}); + +describe('--help', () => { + test('no help line starts like a real result line', () => { + for (const r of [run(['--help']), run([]), run(['run'])]) { + const text = r.stdout + r.stderr; + expect(text).toContain('consent_missing'); + expect(text.split('\n').filter(line => /^(?:OUTSIDE_STATUS|VERDICT):/.test(line))).toEqual([]); + } + }); +}); From 237371474bda407ccd2344f696b9508c55006c2d Mon Sep 17 00:00:00 2001 From: Garry Tan <garrytan@gmail.com> Date: Wed, 18 Nov 2026 10:21:31 +0800 Subject: [PATCH 59/62] Let autoplan revise accept a plan without section headings, as next does (GST-3050) (#4470) `gstack-autoplan revise` now accepts a revised plan whenever the first `next` accepted its shape, so a run no longer pays for a full review round and then refuses the owner's edit. Why: a plan with no section headings is reviewed whole by `next`, but once the owner added one heading, `revise` stopped with `PLAN_SECTIONS_INVALID`. Nothing to do: runs already in progress pick this up too. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- ...oplan-revise-accepts-heading-less-plans.md | 2 + docs/troubleshooting.md | 5 ++- docs/unattended.md | 4 +- lib/autoplan-revise.ts | 28 +++++++++--- test/autoplan-revise.test.ts | 44 +++++++++++++++++++ 5 files changed, 74 insertions(+), 9 deletions(-) create mode 100644 changelog.d/autoplan-revise-accepts-heading-less-plans.md diff --git a/changelog.d/autoplan-revise-accepts-heading-less-plans.md b/changelog.d/autoplan-revise-accepts-heading-less-plans.md new file mode 100644 index 00000000000..12decab39c5 --- /dev/null +++ b/changelog.d/autoplan-revise-accepts-heading-less-plans.md @@ -0,0 +1,2 @@ +- **`gstack-autoplan revise` no longer refuses a plan that the first `next` accepted.** A plan with no `## Implementation plan` or `## Review record` heading is reviewed whole by `next`, but once the owner added one of those headings while editing (for example a `## Review record` noting the accepted changes), `revise` stopped with `PLAN_SECTIONS_INVALID` after a full paid review round, and its fix pointed at a `--scaffold` flag the first `next` never asked for. `revise` now adds the missing heading to its own copy of the plan and prints `SCAFFOLDED:`, the way `next --scaffold` does; the owner's file is never edited. A run whose first plan already had both headings still refuses a revision that drops one, and now says why. +- **`revise --plan` with a different file now says the run follows that file.** It prints `PLAN_INPUT: <old> -> <new>` and records the move, so drift checks no longer switch to another file silently. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index c58bf256420..27b7bf46fe9 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5354,7 +5354,10 @@ section is refused before anything is written. The error names the problem. **Fix.** Add the missing heading, or rerun the first `next` with `--scaffold`: it writes `<out>/plan-source.md` with the missing heading added, reviews that copy and prints `SCAFFOLDED:`. Your plan file is never edited. Duplicate, -reversed or empty sections are ambiguous and must be fixed by hand. +reversed or empty sections are ambiguous and must be fixed by hand. On +`revise`, a run whose first plan was scaffolded or had no headings at all gets +the one missing heading added to its own copy (`SCAFFOLDED:`); a run whose first +plan had both headings refuses a revision that drops one, and says so. <a id="plan-amend-pending"></a> ### `PLAN_AMEND_PENDING` diff --git a/docs/unattended.md b/docs/unattended.md index d9b41014b43..68c4da48dd2 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -690,7 +690,9 @@ by its runner. Result codes: `EXECUTION_UNKNOWN`, `RUN_LOCKED`, `answer` prints `PLAN_SOURCE_CHANGED` when the source plan moved since the snapshot. A plan without both `## Implementation plan` and `## Review record` refuses with `PLAN_SECTIONS_INVALID`; `next --scaffold` reviews a copy with - the missing heading added. `resume` completes an interrupted revise. + the missing heading added, and `revise` does the same (`SCAFFOLDED:`) when + the run's first plan was scaffolded or had no headings. A revise from a + different file prints `PLAN_INPUT: <old> -> <new>`. `resume` completes an interrupted revise. - **Admission and upgrades.** `next`, `submit`, `answer`, `revise`, `export` and `run` refuse on a Capy host (`GSTACK_CAPY=1`) without an ok install verdict for this checkout, HEAD and workflow at `$GSTACK_INSTALL_VERDICT` diff --git a/lib/autoplan-revise.ts b/lib/autoplan-revise.ts index 5d884614869..beaa95151a2 100644 --- a/lib/autoplan-revise.ts +++ b/lib/autoplan-revise.ts @@ -26,6 +26,7 @@ import { carryLines, keepPlanFile, voidPendingCheck } from './autoplan-carry'; import { atCap, pendingDeltas, roundCap, roundOf } from './autoplan-budget'; import { diffStat, earlierRows, lineDiff } from './autoplan-confirm'; import { SETTLEABLE_CHANGES } from './autoplan-reconcile'; +import { sectionHeadings } from '../bin/gstack-autoplan-snapshot'; import { normalizeRevision, reviewHash, scaffold } from './autoplan-plan-text'; import { parseScopeTokens } from './autoplan-scope'; import { PHASES, detectScope, extractHeading, phaseOrder, type Phase, type ScopeFlags } from './autoplan-prompts'; @@ -36,8 +37,17 @@ export interface ReviseResult { state: RunState; reopened: Phase[]; lines: strin const amendmentLine = (state: RunState) => `AMENDMENTS: pending=${pendingAmendments(state).map(a => a.decision).join(',') || 'none'}`; -/** The revised plan's text as the run reviews it (cut to the run's heading; scaffolded when the run was). */ -function revisionText(state: RunState, file: string): string { +/** Whether the run's first plan had no section headings, so init reviewed it whole: the restore point holds its exact bytes. */ +function firstPlanBare(state: RunState): boolean { + try { return !sectionHeadings(fs.readFileSync(state.restore, 'utf8')).length; } catch { return false; } +} + +/** + * The revised plan's text as the run reviews it (cut to the run's heading). One missing heading is scaffolded + * when the first `next` accepted a plan without both (a scaffolded run, or a plan with no headings at all); + * a run that started with both headings keeps refusing a revision that drops one, as `next` does. + */ +function revisionText(state: RunState, file: string): { text: string; added?: string } { if (!fs.existsSync(file)) throw new RunError('PLAN_SECTIONS_INVALID', `${file}: not found`, 3); let text = fs.readFileSync(file, 'utf8'); if (state.plan_heading) { @@ -46,8 +56,9 @@ function revisionText(state: RunState, file: string): string { text = section; } const diag = scaffold(text); - if (diag.problem && !(state.scaffolded && diag.text)) throw new RunError('PLAN_SECTIONS_INVALID', `${file}: ${diag.problem}`, 3); - return diag.text ?? text; + if (diag.problem && !diag.text) throw new RunError('PLAN_SECTIONS_INVALID', `${file}: ${diag.problem}`, 3); + if (diag.problem && !state.scaffolded && !firstPlanBare(state)) throw new RunError('PLAN_SECTIONS_INVALID', `${file}: ${diag.problem}; this run's first plan had both headings, so its revisions keep both`, 3); + return { text: diag.text ?? text, added: diag.added }; } function settleAmendments(state: RunState, ids: string[], status: 'incorporated' | 'withdrawn' | 'settled', at: string, extra: Record<string, unknown> = {}): Array<Record<string, unknown>> { @@ -83,7 +94,7 @@ function settleEvidence(state: RunState, ids: string[], revised?: string): { pla } if (revised) return { plan_sha256: revised, changes }; let input = ''; - try { input = state.plan_input && fs.existsSync(state.plan_input) ? reviewHash(revisionText(state, state.plan_input)) : active; } catch { /* unreadable: refused below */ } + try { input = state.plan_input && fs.existsSync(state.plan_input) ? reviewHash(revisionText(state, state.plan_input).text) : active; } catch { /* unreadable: refused below */ } if (input !== active) throw new RunError('AMENDMENT_NOT_SETTLEABLE', `the plan file has edits the run has not reviewed (active ${active.slice(0, 12)}, plan file ${input.slice(0, 12) || 'unreadable'}); revise --plan <file> --incorporates <ids> --settle ${ids.join(',')} instead`, 3); return { plan_sha256: active, changes }; } @@ -147,7 +158,7 @@ export function reviseRun(o: ReviseOptions): ReviseResult { return { state, reopened: [], lines }; } const file = path.resolve(o.plan); - const text = revisionText(state, file); + const { text, added: scaffoldedHeading } = revisionText(state, file); let newHash: string; try { newHash = reviewHash(text); } catch (e: any) { throw new RunError('PLAN_SECTIONS_INVALID', `${file}: ${e.message}`, 3); } const oldHash = reviewHash(fs.readFileSync(state.active_plan, 'utf8')); @@ -198,6 +209,7 @@ export function reviseRun(o: ReviseOptions): ReviseResult { state.phase_order = order; state.required_phases = order; state.scope = { ...detected, ui: detected.ui || state.scope.ui, dx: detected.dx || state.scope.dx }; if (reopen.length || added.length) state.status = 'running'; + const inputFrom = state.plan_input !== file ? state.plan_input : undefined; state.plan_input = file; state.plan_source = path.join(out, `plan-source.v${k}.md`); state.plan_revision = k; delete state.plan_reality; const settled = [...settleAmendments(state, incorporates, 'incorporated', at, { old_plan_sha256: oldHash, new_plan_sha256: newHash }), ...settleAmendments(state, withdraw, 'withdrawn', at, { by: 'owner' }), @@ -206,11 +218,13 @@ export function reviseRun(o: ReviseOptions): ReviseResult { if (amending) state.status = pendingAmendments(state).length ? 'amend_pending' : state.phase_order.some(p => !state.phases[p]?.closed_at) ? 'running' : pendingDeltas(state).length ? 'gate_pending' : 'complete'; // A quiet revise that ends at gate_pending still has an earlier capped delta waiting: the owner gets a new gate for it. const regate = (capped.length > 0 || quiet) && state.status === 'gate_pending'; - const committed = { event: 'plan_revised', k, plan: file, old_plan_sha256: oldHash, new_plan_sha256: newHash, source_file_sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), reopened: reopen, added, at_gate_rev: atGate ?? null }; + const committed = { event: 'plan_revised', k, plan: file, old_plan_sha256: oldHash, new_plan_sha256: newHash, source_file_sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), reopened: reopen, added, at_gate_rev: atGate ?? null, ...(inputFrom ? { plan_input_from: inputFrom } : {}) }; fs.writeFileSync(path.join(staging, FILES.run), JSON.stringify({ state, renames, committed, settled }, null, 2) + '\n'); publish(state, staging, renames, committed, settled); keepPlanFile(state.out, file); const lines = [`REVISED: plan=${newHash.slice(0, 12)} reopened=${reopen.join(',') || 'none'}${added.length ? ` added=${added.join(',')}` : ''}${capped.length ? ` capped=${capped.join(',')}` : ''}`, + ...(scaffoldedHeading ? [`SCAFFOLDED: added "${scaffoldedHeading}" (${state.scaffolded ? 'the run was scaffolded' : "the run's first plan had no section headings"}; copy at ${state.plan_source}; ${file} unchanged)`] : []), + ...(inputFrom ? [`PLAN_INPUT: ${inputFrom} -> ${file} (drift checks and later revises read ${file}; pass --plan ${inputFrom} to go back)`] : []), ...(quiet ? [`APPLIED: ${incorporates.join(',')} without re-review (${state.lean ? 'lean run: one gate revision' : 'below High'}; plan +${delta.added} -${delta.removed} lines)`] : []), amendmentLine(state)]; for (const phase of capped) lines.push(`CAPPED: ${phase} used round ${roundOf(state, phase)} of ${roundCap(state, phase)}: not reopened; the gate asks the owner about the unreviewed delta (+${delta.added} -${delta.removed} lines)`); if (regate) { diff --git a/test/autoplan-revise.test.ts b/test/autoplan-revise.test.ts index e58dbbdb309..8733b9e3167 100644 --- a/test/autoplan-revise.test.ts +++ b/test/autoplan-revise.test.ts @@ -189,4 +189,48 @@ describe('plan sections', () => { expect(res.status).toBe(3); expect(res.stderr).toMatch(/Implementation plan is empty.*\(PLAN_SECTIONS_INVALID\)$/m); }); + const BARE = '# Retry backoff\n\nAdd exponential backoff to lib/worker.ts: base 500 ms, cap 30 s.\n'; + test('a run whose first plan had no headings revises a plan that gained one heading, scaffolding the other', () => { + for (const [name, v2, added] of [ + ['record', BARE.replace('30 s', '60 s') + '\n## Review record\n\nIncorporated the cap change.\n', '## Implementation plan'], + ['impl', '# Retry backoff\n\n## Implementation plan\n\nAdd exponential backoff, cap 60 s.\n', '## Review record'], + ] as const) { + const dir = path.join(r.host.base, `bare-${name}`); + const plan = writePlan(dir, BARE); + const out = path.join(dir, 'run'); + expect(r.ap(['next', '--out', out, '--plan', plan, '--no-ui']).status).toBe(0); + fs.writeFileSync(plan, v2); + const rev = r.ap(['revise', '--out', out, '--plan', plan]); + expect(rev.status, rev.stderr).toBe(0); + expect(rev.stdout).toMatch(new RegExp(`^SCAFFOLDED: added "${added}" \\(the run's first plan had no section headings; .*plan-source\\.v1\\.md`, 'm')); + expect(rev.stdout).toMatch(/^REVISED: plan=[0-9a-f]{12} reopened=ceo$/m); + expect(fs.readFileSync(plan, 'utf8')).toBe(v2); + const active = fs.readFileSync(path.join(out, 'plan-active.md'), 'utf8'); + expect(active).toContain('cap 60 s'); + expect(active.slice(0, active.indexOf('## Review record'))).not.toContain('Incorporated'); + } + }); + test('a run that started with both headings still refuses a revision missing one, and says why', () => { + const s = start(); + fs.writeFileSync(s.plan, V2.replace('## Review record\n', '')); + const res = r.ap(['revise', '--out', s.out, '--plan', s.plan]); + expect(res.status).toBe(3); + expect(res.stderr).toMatch(/no "## Review record"; this run's first plan had both headings, so its revisions keep both.*\(PLAN_SECTIONS_INVALID\)$/m); + }); +}); + +describe('plan path', () => { + test('revise from another plan file says the run now follows it; the same file prints nothing', () => { + const s = start(); + fs.writeFileSync(s.plan, V2); + const same = r.ap(['revise', '--out', s.out, '--plan', s.plan]); + expect(same.status, same.stderr).toBe(0); + expect(same.stdout).not.toContain('PLAN_INPUT:'); + const v2 = v2File(s.dir, V2.replace('jitter 10%', 'jitter 20%')); + const moved = r.ap(['revise', '--out', s.out, '--plan', v2]); + expect(moved.status, moved.stderr).toBe(0); + expect(moved.stdout).toContain(`PLAN_INPUT: ${s.plan} -> ${v2} (drift checks and later revises read ${v2}; pass --plan ${s.plan} to go back)`); + expect(readRunJson(s.out).plan_input).toBe(v2); + expect(readJsonl(path.join(s.out, 'attempts.jsonl')).filter(e => e.event === 'plan_revised').map(e => e.plan_input_from ?? null)).toEqual([null, s.plan]); + }); }); From f3e31a722b4fc47a7bae8eb7b16ba193be2a81e7 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:42:17 +0700 Subject: [PATCH 60/62] chore(sync): keep hono override at 4.13.16 so bun.lock stays frozen-valid --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4a13870c3de..f3873098377 100644 --- a/package.json +++ b/package.json @@ -107,7 +107,7 @@ "@modelcontextprotocol/sdk": "1.32.0", "adm-zip": "^0.6.1", "fast-uri": "3.1.9", - "hono": "4.13.13", + "hono": "4.13.16", "image-size": "2.0.4", "ip-address": "10.7.4", "proxy-addr": "2.0.8", From da3d41308de3e8384c293b61931ba9aaa7685f21 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:49:51 +0700 Subject: [PATCH 61/62] chore(sync): lower skill-md size pins to the fork's VERSION string length --- test/fixtures/skill-md-size-allowlist.json | 102 ++++++++++----------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/test/fixtures/skill-md-size-allowlist.json b/test/fixtures/skill-md-size-allowlist.json index 1935d573db3..5ac91fac6f6 100644 --- a/test/fixtures/skill-md-size-allowlist.json +++ b/test/fixtures/skill-md-size-allowlist.json @@ -2,56 +2,56 @@ "_comment": "Generated SKILL.md files over the limit, pinned at their exact character count (#3199). test/skill-md-size-guard.test.ts fails when a pinned skill grows past its pin or shrinks below it: lower the pin when a skill shrinks and delete it once the skill is within the limit. Raising a pin is an owner decision. The shared-preamble hoist (GSTA-96) moved every tier 2+ skill's shared preamble into sections/preamble.md; the pins below are what remains.", "limit": 100000, "pins": { - "agy/gstack-autoplan": 109449, - "agy/gstack-plan-design-review": 109103, - "agy/gstack-plan-devex-review": 114944, - "agy/gstack-plan-eng-review": 143530, - "agy/gstack-review": 104723, - "codex/gstack-autoplan": 108192, - "codex/gstack-plan-design-review": 110460, - "codex/gstack-plan-devex-review": 116452, - "codex/gstack-plan-eng-review": 144695, - "codex/gstack-review": 104107, - "copilot/gstack-autoplan": 108892, - "copilot/gstack-plan-design-review": 109369, - "copilot/gstack-plan-devex-review": 114406, - "copilot/gstack-plan-eng-review": 143695, - "copilot/gstack-review": 104304, - "cursor/gstack-autoplan": 108124, - "cursor/gstack-plan-design-review": 107911, - "cursor/gstack-plan-devex-review": 113676, - "cursor/gstack-plan-eng-review": 142285, - "cursor/gstack-review": 122776, - "factory/gstack-autoplan": 110402, - "factory/gstack-plan-design-review": 111009, - "factory/gstack-plan-devex-review": 117039, - "factory/gstack-plan-eng-review": 145393, - "factory/gstack-review": 126549, - "gbrain/gstack-autoplan": 108531, - "gbrain/gstack-plan-eng-review": 124932, - "gemini/gstack-autoplan": 108682, - "gemini/gstack-plan-design-review": 109197, - "gemini/gstack-plan-devex-review": 114234, - "gemini/gstack-plan-eng-review": 143528, - "gemini/gstack-review": 104126, - "hermes/gstack-autoplan": 108536, - "hermes/gstack-plan-eng-review": 124885, - "kiro/gstack-autoplan": 107898, - "kiro/gstack-plan-design-review": 107757, - "kiro/gstack-plan-devex-review": 113528, - "kiro/gstack-plan-eng-review": 142147, - "kiro/gstack-review": 122600, - "openclaw/gstack-autoplan": 108354, - "openclaw/gstack-plan-eng-review": 123428, - "opencode/gstack-autoplan": 108873, - "opencode/gstack-plan-design-review": 109225, - "opencode/gstack-plan-devex-review": 114284, - "opencode/gstack-plan-eng-review": 143554, - "opencode/gstack-review": 123398, - "slate/gstack-autoplan": 108011, - "slate/gstack-plan-design-review": 107834, - "slate/gstack-plan-devex-review": 113602, - "slate/gstack-plan-eng-review": 142216, - "slate/gstack-review": 122688 + "agy/gstack-autoplan": 109389, + "agy/gstack-plan-design-review": 109043, + "agy/gstack-plan-devex-review": 114884, + "agy/gstack-plan-eng-review": 143470, + "agy/gstack-review": 104663, + "codex/gstack-autoplan": 108132, + "codex/gstack-plan-design-review": 110400, + "codex/gstack-plan-devex-review": 116392, + "codex/gstack-plan-eng-review": 144635, + "codex/gstack-review": 104047, + "copilot/gstack-autoplan": 108832, + "copilot/gstack-plan-design-review": 109309, + "copilot/gstack-plan-devex-review": 114346, + "copilot/gstack-plan-eng-review": 143635, + "copilot/gstack-review": 104244, + "cursor/gstack-autoplan": 108064, + "cursor/gstack-plan-design-review": 107851, + "cursor/gstack-plan-devex-review": 113616, + "cursor/gstack-plan-eng-review": 142225, + "cursor/gstack-review": 122716, + "factory/gstack-autoplan": 110342, + "factory/gstack-plan-design-review": 110949, + "factory/gstack-plan-devex-review": 116979, + "factory/gstack-plan-eng-review": 145333, + "factory/gstack-review": 126489, + "gbrain/gstack-autoplan": 108471, + "gbrain/gstack-plan-eng-review": 124872, + "gemini/gstack-autoplan": 108622, + "gemini/gstack-plan-design-review": 109137, + "gemini/gstack-plan-devex-review": 114174, + "gemini/gstack-plan-eng-review": 143468, + "gemini/gstack-review": 104066, + "hermes/gstack-autoplan": 108476, + "hermes/gstack-plan-eng-review": 124825, + "kiro/gstack-autoplan": 107838, + "kiro/gstack-plan-design-review": 107697, + "kiro/gstack-plan-devex-review": 113468, + "kiro/gstack-plan-eng-review": 142087, + "kiro/gstack-review": 122540, + "openclaw/gstack-autoplan": 108294, + "openclaw/gstack-plan-eng-review": 123368, + "opencode/gstack-autoplan": 108813, + "opencode/gstack-plan-design-review": 109165, + "opencode/gstack-plan-devex-review": 114224, + "opencode/gstack-plan-eng-review": 143494, + "opencode/gstack-review": 123338, + "slate/gstack-autoplan": 107951, + "slate/gstack-plan-design-review": 107774, + "slate/gstack-plan-devex-review": 113542, + "slate/gstack-plan-eng-review": 142156, + "slate/gstack-review": 122628 } } From 52af83451d665ad484d4ed143f458e761923febc Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:10:05 +0700 Subject: [PATCH 62/62] chore(sync): record the merged scripts/test-pr-profile.ts as non-behavioral at HARNESS_VERSION 6 --- scripts/harness-pins/scripts/test-pr-profile.ts.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/harness-pins/scripts/test-pr-profile.ts.json b/scripts/harness-pins/scripts/test-pr-profile.ts.json index 1c96603f13f..f7490879642 100644 --- a/scripts/harness-pins/scripts/test-pr-profile.ts.json +++ b/scripts/harness-pins/scripts/test-pr-profile.ts.json @@ -1 +1 @@ -{"blob":"6f9f93ff672653c72d9e0d97ff9499b6062890a3","since":6,"nonBehavioral":"adds crew/scripts/release-notes.ts to the free-only list beside release-cut.ts"} +{"blob":"27142f6c634a51f91e11c122c9b5d23f4398b21f","since":6,"nonBehavioral":"adds crew/scripts/release-notes.ts to the free-only list beside release-cut.ts (upstream), plus the fork-only FREE_ONLY_PR_FILES entry classifying the fork's free-suite workflow; no eval case or verdict reads either"}