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/.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/.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/.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/.github/workflows/windows-setup-e2e.yml b/.github/workflows/windows-setup-e2e.yml index c281edcce9c..3da65103e4e 100644 --- a/.github/workflows/windows-setup-e2e.yml +++ b/.github/workflows/windows-setup-e2e.yml @@ -75,6 +75,7 @@ on: - 'bin/gstack-config' - 'bin/gstack-patch-names' - 'bin/gstack-state-root.sh' + - 'bin/gstack-lock.sh' - 'bin/gstack-skill-name.sh' - 'bin/gstack-install-registry.sh' - 'bin/gstack-render-claude.sh' @@ -194,6 +195,7 @@ jobs: bin/gstack-config bin/gstack-patch-names bin/gstack-state-root.sh + bin/gstack-lock.sh bin/gstack-skill-name.sh bin/gstack-install-registry.sh bin/gstack-render-claude.sh 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/.gstack/pregate.json b/.gstack/pregate.json index 04502a58f51..2fc8cc546f5 100644 --- a/.gstack/pregate.json +++ b/.gstack/pregate.json @@ -15,7 +15,8 @@ "licenses/**": [], "contrib/**": [], "supabase/**": [], - "qm/sandbox/skills/gstack-review/scripts/diff-base.sh": ["test/qm-edition.test.ts"] + "qm/sandbox/skills/gstack-review/scripts/diff-base.sh": ["test/qm-edition.test.ts"], + "lib/shell-writes.ts": ["test/skill-contract.test.ts"] }, "selection": { "free-tests.yml/free-suite": "bun run scripts/test-free-shards.ts --list" 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 42db0bdc3dd..409090f4bc4 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 | @@ -429,10 +429,10 @@ 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 ` 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 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 `; 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` @@ -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/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/README.md b/README.md index e7d04738bc9..d863952d286 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 @@ -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. | @@ -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 | @@ -270,6 +270,9 @@ 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 | +| [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/SKILL.md b/SKILL.md index 40d70531492..d3ae8f153c9 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, docs, security or design. Use for: gstack, which gstack skill, route this with gstack. (gstack)" allowed-tools: - Bash - Read @@ -94,6 +94,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: @@ -191,7 +198,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` @@ -252,11 +258,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 371e5683817..b46e8858b0e 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, + 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: @@ -67,7 +67,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` @@ -107,11 +106,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/TODOS.md b/TODOS.md index e47fc855e15..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. @@ -46,7 +50,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 ` 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/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/autoplan/DRIVER.md b/autoplan/DRIVER.md index 81d661433ab..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: phase=

voice=native|outside prompt= result=` 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: 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 ""` 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: ." 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=`); render it with `gstack-gate render

/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. @@ -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/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: phase=

voice=native|outside prompt= result=` 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=`); render it with `gstack-gate render

/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/SKILL.md b/autoplan/SKILL.md index 796c5b9f459..60c1498aa5b 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/autoplan/sections/preamble.md +++ b/autoplan/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: 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 /run.json` is the completion check. End with `GSTACK_RESULT: skill=autoplan status= run=`. 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 /run.json` is the completion check. End with `GSTACK_RESULT: skill=autoplan status= run=`. diff --git a/benchmark-models/SKILL.md b/benchmark-models/SKILL.md index 612b9df38ce..b0773605f81 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 @@ -94,6 +94,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/benchmark/SKILL.md b/benchmark/SKILL.md index a27c8459587..f888ae0e513 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 @@ -95,6 +95,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: 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-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) # - matches a line in ~/.gstack/.brain-skip.txt # +# Refuses (exit 1, nothing queued) a 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-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-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-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-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 (exit 0) or CI_CARRY: none () (exit 1). + * --allow-repo-commands). Prints CI_CARRY: accepted (exit 0) or CI_CARRY: none () (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 ] [--profile ]... [--command --allow-repo-commands] [--json] - CI_CARRY: accepted (exit 0) or CI_CARRY: none () (exit 1) + CI_CARRY: accepted (exit 0) or CI_CARRY: none () (exit 1); a run at an earlier commit with + HEAD's exact tree (git rev-parse ^{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 ] [--profile ] [--timeout ] [--interval ] - 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/'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, { 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-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 240d9e85b23..4a35d020c00 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 } @@ -1278,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-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-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-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/bin/gstack-docs-candidate b/bin/gstack-docs-candidate index de205969625..b354b33a1a8 100755 --- a/bin/gstack-docs-candidate +++ b/bin/gstack-docs-candidate @@ -54,11 +54,12 @@ * -result.json and the section, unchanged, as -documentation.md * in --out-dir and prints DOCS_RESULT: ok. Otherwise it writes nothing, prints a * DOCS_RESULT_INVALID line naming each bad key and a RETRY_NOTE: for the re-audit's - * prompt, and exits 1 (GST-1843). When the line's only fault is its shape it prints - * FORMAT_REPAIR: instead of RETRY_NOTE:, and the step re-asks for the line once without - * spending an attempt: repair-prompt prints that re-ask (the schema, the problems and the - * child's own output), and result --repair-of checks the reply, refusing a - * second repair of the same audit and any change to a value the first line gave correctly. + * prompt, and exits 1 (GST-1843). When the line's only fault is its shape, or text follows + * a JSON line carrying the audit id, it prints FORMAT_REPAIR: instead of RETRY_NOTE:, and the + * step re-asks for the line once without spending an attempt: repair-prompt prints that re-ask + * (the schema, the problems and the child's own output), and result --repair-of + * checks the reply, refusing a second repair of the same audit and any change to a value the + * first line gave correctly; after trailing text only a blocked status and its blockers carry over. */ import { spawnSync } from 'child_process'; import * as fs from 'fs'; @@ -358,7 +359,7 @@ function main(argv: string[]): void { else console.log(`RETRY_NOTE: ${docsRetryNote(check.problems)}`); process.exit(1); } - if (repairOf) console.log('FORMAT_REPAIR: applied (the reply kept every value the first line gave correctly)'); + if (repairOf) console.log('FORMAT_REPAIR: applied (the reply kept every value the repair had to keep)'); fs.mkdirSync(outDir, { recursive: true, mode: 0o700 }); const resultFile = path.join(outDir, `${auditId}-result.json`); const sectionFile = path.join(outDir, `${auditId}-documentation.md`); @@ -377,7 +378,7 @@ function main(argv: string[]): void { const output = fs.readFileSync(file, 'utf8'); const check = checkDocsResult(output, auditId, repoFile()); if (check.ok || !check.repairable) throw new Error(`${file} is not a format-only failure of the last line, so it has no format repair: ${check.ok ? 'it is a valid result' : 'a content failure counts as an attempt (Blocked recovery, RETRY_NOTE:)'}`); - process.stdout.write(docsRepairPrompt(output, auditId, check.problems)); + process.stdout.write(docsRepairPrompt(output, auditId, check.problems, check.whole, check.kept)); return; } throw new Error(USAGE); diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index 4a810df8abc..8226db50449 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' ;; @@ -401,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' ;; @@ -413,6 +428,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' ;; @@ -437,6 +455,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-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/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 { 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 { 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/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-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 --plan --play --platform ios|android|web --commit + * (--testflight | --deploy ) --builder --checker [--json] + * gstack-first-use brief --run + * gstack-first-use record --run --action --verdict pass|fail --evidence --device --account --by [--note ] [--json] + * gstack-first-use predict --run --score <1-10> --why --by [--json] + * gstack-first-use links --run --account --device-class ios|android|web [--json] + * gstack-first-use check --run --platform … --commit … (--testflight … | --deploy …) [--json] + * gstack-first-use message --run --platform … --commit … (--testflight … | --deploy …) + * gstack-first-use score --run --score <1-10> --words "" --by [--json] + * gstack-first-use show --run [--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 --plan --play --platform ios|android|web --commit + (--testflight | --deploy ) --builder --checker [--json] + brief --run what the checker from the other model family is given + record --run --action --verdict pass|fail --evidence --device --account --by [--note ] + predict --run --score <1-10> --why --by + links --run --account --device-class ios|android|web check every play link now, as the owner-equivalent audience + check --run --platform … --commit … (--testflight … | --deploy …) FIRST_USE: pass, or refused + message --run --platform … --commit … (--testflight … | --deploy …) the "try this build" text, only after a pass + score --run --score <1-10> --words "" --by + show --run [--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 => ({ 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 \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 { + 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/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 ] + * + * 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 ]\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/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-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-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-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-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 { 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/bin/gstack-no-stop b/bin/gstack-no-stop index 9477de83925..35491f2dc9c 100755 --- a/bin/gstack-no-stop +++ b/bin/gstack-no-stop @@ -1,6 +1,6 @@ #!/usr/bin/env -S bun --no-env-file --config=/dev/null /** - * gstack-no-stop — record one of the five no-stop defaults and go on (GSTA-258 K1, docs/review-policy.md#no-stop). + * gstack-no-stop — record one of the four no-stop defaults and go on (GSTA-258 K1, docs/review-policy.md#no-stop). * * gstack-no-stop record --class --reason --evidence [--range-base ] [--json] * gstack-no-stop import --from /no-stop.json [--json] @@ -19,7 +19,7 @@ import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { appendLedger, checkNoStop, ledgerPath, readLedger } from '../lib/no-stop'; import { runScriptSync } from '../lib/script-invocation'; -const HELP = `gstack-no-stop — record one of the five no-stop defaults (docs/review-policy.md#no-stop) +const HELP = `gstack-no-stop — record one of the four no-stop defaults (docs/review-policy.md#no-stop) record --class --reason --evidence [--range-base ] [--json] NO_STOP: recorded: go on. NO_STOP: refused (exit 3): the stop stands. Anything else still stops. @@ -28,15 +28,11 @@ const HELP = `gstack-no-stop — record one of the five no-stop defaults (docs/r test-timeout-fix a fix that only raises a test's timeout (--range-base the commit before it): its gate 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 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 the newest review-log pass row's commit, - the commit before the fix for test-timeout-fix, the receipt head for stamp-only-carry); required for those three - --base (stamp-only-carry): compare HEAD with the receipt head merged into (base side on conflict), - so a base merge plus a stamp qualifies and a product conflict resolution does not + the commit before the fix for test-timeout-fix); required for those two import --from [--json] add an autoplan run's no-stop.json records to the branch's ledger list [--json] the branch's ledger and its path @@ -44,7 +40,7 @@ ${exitTableHelp()}`; const flag = (args: string[], name: string) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }; const git = (args: string[]) => spawnSync('git', args, { cwd: process.cwd(), encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); -const NEEDS_RANGE = ['scoped-fix-check', 'test-timeout-fix', 'stamp-only-carry']; +const NEEDS_RANGE = ['scoped-fix-check', 'test-timeout-fix']; const K1_BY = 'gstack no-stop default (K1)'; const AUTOPLAN_EVIDENCE = /^autoplan:\S+@gate_rev=\d+$/; @@ -74,8 +70,7 @@ function record(args: string[], json: boolean): number { const cls = flag(args, '--class') ?? ''; const commit = (ref: string | undefined) => { if (!ref) return undefined; const r = git(['rev-parse', '--verify', '--quiet', '--end-of-options', `${ref}^{commit}`]); return r.status === 0 ? r.stdout.trim() : null; }; const rangeBase = commit(flag(args, '--range-base')); - const base = cls === 'stamp-only-carry' ? commit(flag(args, '--base')) : undefined; - if (rangeBase === null || base === null) { process.stderr.write(`gstack-no-stop record: --range-base and --base must name commits\n`); return EXIT.usage; } + if (rangeBase === null) { process.stderr.write(`gstack-no-stop record: --range-base must name a commit\n`); return EXIT.usage; } if (!cls) { process.stderr.write(`gstack-no-stop record: --class is required\n${HELP}\n`); return EXIT.usage; } if (NEEDS_RANGE.includes(cls) && !rangeBase) { process.stderr.write(`gstack-no-stop record: --class ${cls} needs --range-base \n`); return EXIT.usage; } const file = ledgerPath(process.cwd()); @@ -94,13 +89,7 @@ function record(args: string[], json: boolean): number { } let diff: string | undefined; if (rangeBase) { - let from = rangeBase; - if (base) { - const merged = git(['merge-tree', '--write-tree', '-X', 'ours', base, rangeBase]); - if (merged.status !== 0) { process.stderr.write(`NO_STOP: refused ${cls} (git merge-tree ${base} ${rangeBase} failed: ${merged.stderr.trim() || 'conflict'}); stop for the owner\n`); return EXIT.refused; } - from = merged.stdout.split('\n')[0]!.trim(); - } - const d = git(['diff', '--no-color', '--no-ext-diff', '--no-renames', from, 'HEAD']); + const d = git(['diff', '--no-color', '--no-ext-diff', '--no-renames', rangeBase, 'HEAD']); if (d.status !== 0) { process.stderr.write(`gstack-no-stop record: git diff ${rangeBase} HEAD failed: ${d.stderr.trim()}\n`); return EXIT.fail; } diff = d.stdout; } 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 --out * [--model ] [--result ] [--native-model ] [--fallback ] - * [--gate review|structured|spec|proposal] [--timeout-ms N] [--max-tokens N] [--cwd ] [--json] + * [--gate review|structured|spec|proposal|autoplan] [--timeout-ms N] [--max-tokens N] [--cwd ] [--json] * gstack-outside-voice runners [--model ] [--json] the runner table: capabilities and availability here * gstack-outside-voice family 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 --prompt --out [--model ] [--result ] [--native-model ] - [--fallback ] [--gate review|structured|spec|proposal] [--timeout-ms N] [--max-tokens N] [--cwd ] [--json] + [--fallback ] [--gate review|structured|spec|proposal|autoplan] [--timeout-ms N] [--max-tokens N] [--cwd ] [--json] runners [--model ] [--json] the runner table: id, capabilities, available here family 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: provider= model= family= and writes .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 .meta.json and prints a status line, for example + OUTSIDE_STATUS: provider= model= family= +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 { if (!isRunner(requested)) return usage(`--runner must be one of ${RUNNER_IDS.join(', ')}`); if (!promptFile || !outFile) return usage('run needs --prompt --out '); 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/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 --target --words --thread --event + * --by [--kind standing-yes|decision|preference|ruling-ref] [--scope all|repo:|captain:] + * [--limits ] [--words-by owner|agent:] [--rule R] [--asked ] [--json] + * gstack-owner-answers supersede (the add flags) | revoke --words <…> --thread --event --by + * gstack-owner-answers verify --event --by + * gstack-owner-answers check --ask-file [--all] [--json] related answers per ask line (advisory) + * gstack-owner-answers screen --ask-file [--json] KEEP or PROPOSE_TAKE per line; never edits the ask + * gstack-owner-answers log --thread --line --decision taken|asked [--row ] --by + * gstack-owner-answers list [--all] [--json] | status + * Every command takes [--owner ] (on Capy: which user- 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 --target --words --thread --event --by + [--kind standing-yes|decision|preference|ruling-ref] [--scope all|repo:/|captain:] [--limits ] + [--words-by owner|agent:] [--rule R] [--asked ] + one row, written once; --words-by defaults to agent:, and only owner rows can ever be taken + supersede (add's flags) a new row that replaces + revoke --words --thread --event --by the row stops counting + verify --event --by a second actor reads the cited source event, names it, and confirms it + holds the row's words; the recorder cannot + check --ask-file [--all] related answers per ask line, ranked by shared words (advisory; never a take) + screen --ask-file per line: KEEP or PROPOSE_TAKE , 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 --line --decision taken|asked [--row ] --by 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 ] 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; bools: Set; error?: string } { + const pos: string[] = []; const flags: Record = {}; const bools = new Set(); + 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, extra: Partial = {}): 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 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 ' }); + case 'revoke': return pos[0] ? write(cmd, store, newAnswer(flags, { kind: 'revoke', supersedes: pos[0] }), json) : fail(cmd, { code: 'OWNER_ANSWERS_INVALID', message: 'revoke ' }); + case 'verify': { + if (!pos[0]) return fail(cmd, { code: 'OWNER_ANSWERS_INVALID', message: 'verify --event --by ' }); + 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/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 | --title-file ] [--branch ] [--body-file ] [--changelog ] + check [--title | --title-file ] [--branch ] [--body-file [--head-branch ]] [--changelog ] [--commits-file ] [--created-at ] [--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 = []) => { + 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-render-claude.sh b/bin/gstack-render-claude.sh index c7b06c4cd14..3353f074a22 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" @@ -126,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/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-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-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 --phase [--record ] [--wait-s ] -- '' ['' ...] + * Runs the phase's commands in order, each in the background (output in /phases//.log), and prints + * only result lines: RAN: / exit= with each command's CODE: lines, then PHASE: 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 /stop.json. + * gstack-ship-phase program + * Prints the checked-in Capy phase program (lib/capy-ship-phase.js): PROGRAM: v sha256= bytes=, 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 '); +if (!phase || !/^[A-Za-z0-9._-]+$/.test(phase)) usage('run needs --phase (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-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 = { 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/ 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/ 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/ 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 --screen (train policy) the PR head's screen verdict read from its run (SCREEN_VERDICT) verify --post-merge [--timeout ] 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 --pin [--accept-gate-disposition ]... [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] + land --pr --pin [--accept-gate-disposition ]... [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] [--body-file ] 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 (docs/ship-policy.md#gate-dispositions) - land --pr [--dry-run] [--no-wait] [--timeout ] [--break-lock [--break-train-lock]] [--allow-repo-commands] + land --pr [--dry-run] [--no-wait] [--timeout ] [--break-lock [--break-train-lock]] [--allow-repo-commands] [--body-file ] 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 " (#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 --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 --pin .\n` + : `\nThis repository (merge: ${loaded.policy.merge}): land with gstack-ship-queue land --pr ${loaded.policy.train ? ', or train land for a built train' : ''}; --pin is the merge: direct form.\n`; +} + async function main(argv: string[]): Promise { 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 { 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 (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 `); const gateExit = flag(args, '--gate-exit'); diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 5709d718e39..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 ] [--head ] [--base ] [--version ] [--gated-tree ] - * [--predecessor ] [--gate ] [--ci ] [--spend-usd ] + * [--predecessor ] [--gate ] [--ci ] [--spend-usd ] [--calls | --budget-record ] * [--session-kind ] [--artifacts-consumed /] [--run ] [--thread ] * [--receipt ] [--policy ]... @@ -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, @@ -35,7 +37,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { ghSpawnSync } from '../lib/gh-poll'; -import { EXIT, exitTableHelp, type ShipReceipt } from '../lib/headless-artifacts'; +import { EXIT, exitTableHelp, NO_STOP_CLASSES, type ShipReceipt } from '../lib/headless-artifacts'; import { resultLine, resultLineWithDocs } from '../lib/result-codes'; import { versionAtRef } from '../lib/restamp'; import { branchSides, stampOnlyLine, type BranchSide } from '../lib/stamp-only'; @@ -46,12 +48,12 @@ import { installedGstackVersion, isUnavailable, loadPolicyFromBase, matchesAny, import { approvalForReceipt } from '../lib/approval-citations'; import { CARRY_METADATA_GLOBS, CARRY_NAMED_PATHS, CARRY_TEST_GLOBS, - bindReceipt, carryReceipt, classifyCarryPath, computeCensus, extractReceipt, landedStackParent, missingIssueLines, orderReceipt, parseReviewLoop, placeReceipt, planCarry, planTreeCarry, + bindReceipt, carryReceipt, recheckCarried, classifyCarryPath, computeCensus, extractReceipt, landedStackParent, missingIssueLines, orderReceipt, parseReviewLoop, placeReceipt, planCarry, planTreeCarry, receiptIssuesFrom, receiptSummaryLine, renderCensus, renderReceiptBlock, validateReceipt, type CensusPr, } 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,8 +62,11 @@ 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'; +import { runCalls } from '../lib/ship-clock'; const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt) @@ -86,13 +91,25 @@ 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) write flags: --pr --head --base --version --gated-tree --predecessor --gate --ci --spend-usd + --calls | --budget-record (calls=: the run's calls from the call log since gstack-ship-budget start; lib/ship-clock.ts) --session-kind --artifacts-consumed / --run --thread --receipt --policy --preregistration --history --queue-mode --pregate (C8: refused unless current, green and every requires-remote obligation carries a receipt: PREGATE_STALE / PREGATE_LANE_FAILED / PREGATE_INCOMPLETE / PREGATE_REMOTE_UNCLEARED) --issues @@ -124,7 +141,7 @@ write flags: --pr --head --base --version --gated-tree --predecessor --gate (a JSON array of {class, reason, evidence}: each routine stop the run recorded and went on past, class one of - scoped-fix-check, test-timeout-fix, pregate-flake-rerun, stamp-only-carry, autoplan-regate); recorded as no_stop. + scoped-fix-check, test-timeout-fix, pregate-flake-rerun, autoplan-regate); recorded as no_stop. --declare-risk (the same list gstack-review-plan --declare-risk took): joins review_depth's risk and only raises its depth; review_depth.declared and .detected record both lists (GST-1129). An unknown class is RECEIPT_INVALID. --platform-review (NEXT: platform's PLATFORM_REVIEW: id): records review_depth platform with capy-ai[bot]'s review at HEAD; @@ -162,7 +179,8 @@ function noStopArg(raw: string | undefined): ShipReceipt['no_stop'] { if (raw === undefined) return undefined; const parsed = JSON.parse(raw.startsWith('@') ? fs.readFileSync(raw.slice(1), 'utf8') : raw); if (!Array.isArray(parsed)) throw new Error('--no-stop expects a JSON array of {class, reason, evidence}'); - return parsed.length ? parsed : undefined; + const kept = parsed.filter(r => (NO_STOP_CLASSES as readonly string[]).includes(r?.class) || void process.stderr.write(`NO_STOP: dropped ${JSON.stringify(r?.class)} from --no-stop: not a current no-stop class (${NO_STOP_CLASSES.join(', ')}), so the receipt leaves it out (GST-2706)\n`)); + return kept.length ? kept : undefined; } function git(args: string[], cwd?: string): string | undefined { const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000, maxBuffer: 256 * 1024 * 1024 }); @@ -216,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 , 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); @@ -334,11 +361,12 @@ 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, 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 +685,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) => { @@ -694,6 +723,7 @@ function cmdCarry(rest: string[], json: boolean): number { if (receipt.base_red) return refused('QUEUE_RECEIPT_CONDITIONAL', 'the receipt is paused on a red base, so there is nothing passing to carry; /ship --resume re-runs Step 5 and writes a full receipt'); const from = receipt.head.toLowerCase(); if (!/^[0-9a-f]{40,64}$/.test(from)) return refused('RECEIPT_CARRY_REFUSED', `the receipt's head ${receipt.head.slice(0, 12)} is not a full commit id`); + if (recheckCarried(receipt)) return refused('RECEIPT_CARRY_REFUSED', `the receipt reached ${from.slice(0, 12)} through a scoped re-check (carry: ${receipt.carry!.reason.slice(0, 160)}), which is advice only (GST-2673), so the product code it covered never got a full review; the receipt is unchanged: run /ship on ${head.slice(0, 12)} for the merge head's full review (docs/review-policy.md#rounds-per-pull-request)`); if (from === head) { process.stderr.write(receiptSummaryLine(receipt) + '\n'); process.stdout.write(json ? JSON.stringify({ skill: 'ship', status: 'current', head, carry: null }) + '\n' : `CARRY: current (the receipt already names ${head.slice(0, 12)})\n`); @@ -724,7 +754,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 +881,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 +892,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 +932,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 +1030,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 +1110,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/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/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/browse/SKILL.md b/browse/SKILL.md index 77c35e38735..1b43edfaace 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 @@ -94,6 +94,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: 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/canary/SKILL.md b/canary/SKILL.md index 8ffc95b3447..10c466fe09b 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/canary/sections/preamble.md +++ b/canary/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/captain/SKILL.md b/captain/SKILL.md index f8b0d6b5a9f..0dcee5e0bc0 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 @@ -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 `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) @@ -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/.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/.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/sections/preamble.md b/captain/sections/preamble.md index 79e0a158c80..f753a5e1b1c 100644 --- a/captain/sections/preamble.md +++ b/captain/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: 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 --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 …`); 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/.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/captain/templates/READY.md b/captain/templates/READY.md index ff4f5002fb7..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: ) @@ -51,6 +53,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/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/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 `. /ship reads `cost.tokens` and `cost.credits` from `tools.thread.get({ thread_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 --credits `, 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: ". '' && 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: "", cwd: "", base: "", out: "/p", pass: "-p", laneModel: "", planFlags: [], logStart: ["review"], jam: "", record: "", 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: ""`. 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 `. 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: ". '' && 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: "", cwd: "", base: "", out: "/p", pass: "-p", laneModel: "", planFlags: [], logStart: ["review"], jam: "", record: "", 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: ""`. 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: "", phase: , commands: [" …"], record, jam, 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 `. A small waiting child saves nothing. ## Plan, approve, ship diff --git a/capy/skill/gstack/captain.md b/capy/skill/gstack/captain.md index d4227c769b8..6287ee0eaee 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 @@ -149,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. @@ -168,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 --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/capy/skill/gstack/factory.md b/capy/skill/gstack/factory.md index fa10da5d101..cb6aba07200 100644 --- a/capy/skill/gstack/factory.md +++ b/capy/skill/gstack/factory.md @@ -11,8 +11,8 @@ 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. -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] +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** (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: 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/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/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/.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/.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/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/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: -> ` and records the move, so drift checks no longer switch to another file silently. 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/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/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/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 ` 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/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/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 ` 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/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/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/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/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/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/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/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/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/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/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/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 ` 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/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/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/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/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/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/codex/SKILL.md b/codex/SKILL.md index 4433a09d84e..818553da47c 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/codex/sections/preamble.md +++ b/codex/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## 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 26eb4baee32..7def9e45f48 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/context-restore/sections/preamble.md +++ b/context-restore/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## 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 ed8179a08ed..01d5b6efbfe 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/context-save/sections/preamble.md +++ b/context-save/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/crew/docs/captain.md b/crew/docs/captain.md index 64ff032b308..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//SKILL.md` | the controller | crew procedures the lanes load (the runbooks) | -| `reports/.md` | each lane, once | Outcome with its Unverified line, PR, Needs, Cost, Lesson, Approvals ([template](../../captain/templates/report.md)) | +| `reports/.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-.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 @@ -668,6 +672,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/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`, 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 `, held by the same floor. Details, the floor's refusal codes and the "nothing green in the window" failure mode: 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 { 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/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/scripts/release-cut.ts b/crew/scripts/release-cut.ts index 167b7b3fa1f..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, 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 @@ -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. @@ -67,8 +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 }; @@ -77,11 +83,12 @@ 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; export const WINDOW_COMMITS = 200; -export const NOTES_CAP = 60_000; const HOUR = 3_600_000; export const runGh: Gh = (args) => { @@ -98,16 +105,6 @@ function parseJson(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 `. 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 } @@ -116,7 +113,11 @@ interface CheckRun { id?: number; name: string; status: string; conclusion: stri export interface TrainEvidence { bySha: Map; byTree: Map; release?: Map } export interface GateOptions { requiredCheck?: string; backstopCheck?: string; evidence?: TrainEvidence; treeOf?: (sha: string) => string | null } -/** Why a commit is not releasable, or green and through which evidence. */ +/** + * Why a commit is not releasable, or green and through which evidence. Red and running checks also come from CI at the commit as the + * merge queue reads it (lib/ci-head-checks.ts), so a failed check whose rerun attempt created no jobs, or a workflow run that failed + * before any job, is red here too (GST-2252). + */ export function gateVerdict(gh: Gh, repo: string, sha: string, o: GateOptions = {}): Verdict { const required = o.requiredCheck ?? REQUIRED_CHECK; const backstop = o.backstopCheck ?? BACKSTOP_CHECK; @@ -124,16 +125,21 @@ export function gateVerdict(gh: Gh, repo: string, sha: string, o: GateOptions = if (!paged) return { green: false, why: 'cannot read its check runs', pending: false }; const pages = (Array.isArray(paged) ? paged : [paged]) as Array<{ check_runs?: CheckRun[] }>; let runs = pages.flatMap(p => p.check_runs ?? []); - if (runs.some(c => c.status !== 'completed' || RED.has(c.conclusion ?? ''))) { + const setAside = (): AsideRuns => { 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 checkRunIds = new Set(); + const workflowRunIds = new Set(); + for (const w of wfRuns.flatMap(p => p.workflow_runs ?? []).filter(w => asideWorkflows.has(w.path ?? '') && typeof w.id === 'number')) { + workflowRunIds.add(w.id!); 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') checkRunIds.add(j.id); } - runs = runs.filter(c => !(typeof c.id === 'number' && own.has(c.id))); - } + return { checkRunIds, workflowRunIds }; + }; + let aside = runs.some(c => c.status !== 'completed' || RED.has(c.conclusion ?? '')) ? setAside() : undefined; + if (aside) runs = runs.filter(c => !(typeof c.id === 'number' && aside!.checkRunIds.has(c.id))); let via = backstop; for (const name of [required, backstop]) { const named = runs.filter(c => c.name === name); @@ -146,10 +152,13 @@ export function gateVerdict(gh: Gh, repo: string, sha: string, o: GateOptions = if (named.length === 0) return { green: false, why: `no ${name} check run`, pending: false }; return { green: false, why: `${name} concluded ${named.map(c => c.conclusion).join(',')}`, pending: false }; } - const red = runs.filter(c => c.status === 'completed' && RED.has(c.conclusion ?? '')); - if (red.length > 0) return { green: false, why: `red check runs: ${[...new Set(red.map(c => c.name))].join(', ')}`, pending: false }; - const running = runs.filter(c => c.status !== 'completed'); - if (running.length > 0) return { green: false, why: `check runs still going: ${[...new Set(running.map(c => c.name))].join(', ')}`, pending: true }; + let head = headCheckRows(gh, repo, sha, aside); + if (!aside && 'rows' in head && head.rows.some(r => bucketClass(r.bucket) !== 'pass')) head = headCheckRows(gh, repo, sha, aside = setAside()); + if ('error' in head) return { green: false, why: 'cannot read its check runs', pending: false }; + const red = [...runs.filter(c => c.status === 'completed' && RED.has(c.conclusion ?? '')).map(c => c.name), ...head.rows.filter(r => bucketClass(r.bucket) === 'fail').map(r => r.name)]; + if (red.length > 0) return { green: false, why: `red check runs: ${[...new Set(red)].join(', ')}`, pending: false }; + const running = [...runs.filter(c => c.status !== 'completed').map(c => c.name), ...head.rows.filter(r => r.bucket === 'pending').map(r => r.name)]; + if (running.length > 0) return { green: false, why: `check runs still going: ${[...new Set(running)].join(', ')}`, pending: true }; return { green: true, via }; } @@ -213,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'); /** @@ -430,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 { @@ -549,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 }; @@ -603,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'); @@ -620,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. @@ -634,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 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 } +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(); + 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 = { 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 b415cfc2913..e05cb850df8 100644 --- a/crew/test/release-cadence.test.ts +++ b/crew/test/release-cadence.test.ts @@ -11,6 +11,7 @@ import * as path from 'node:path'; import { bunIsolationArgs } from '../../lib/bun-isolation'; import { FLOOR_HOURS, FORCED_AFTER_HOURS, IMPORTANT_FLOOR_HOURS, SCHEDULED_GRACE_HOURS, decideDaily, importantChanges, type DailyInput, type ImportantChange } from '../scripts/release-cadence'; import { gitIn, planDaily, type Gh } from '../scripts/release-cut'; +import { ciRest, ciShimCases } from '../../test/helpers/ci-attempts-fixture'; const H = 3_600_000; // Tuesday 2026-11-10 14:00 UTC: not a regular day. @@ -138,8 +139,9 @@ const GREEN = [{ name: 'free-tests', status: 'completed', conclusion: 'success' function fakeGh(pending: Set = new Set()): Gh { return (args) => { const api = args[0] === 'api' ? args[args.length - 1]! : ''; - const m = /commits\/([0-9a-f]+)\/check-runs/.exec(api); - if (m) return { status: 0, stdout: JSON.stringify([{ check_runs: pending.has(m[1]!) ? [{ name: 'main-backstop', status: 'in_progress', conclusion: null }] : GREEN }]), stderr: '' }; + const m = /commits\/([0-9a-f]+)\/|head_sha=([0-9a-f]+)/.exec(api); + const rest = m && ciRest(args, { check_runs: pending.has(m[1] ?? m[2]!) ? [{ name: 'main-backstop', status: 'in_progress', conclusion: null }] : GREEN }); + if (rest) return rest; if (args[0] === 'release' && args[1] === 'view' && args[2] === 'v1.0.0') return { status: 0, stdout: '{}', stderr: '' }; return { status: 1, stdout: '', stderr: 'gh: Not Found (HTTP 404)' }; }; @@ -183,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' }); @@ -215,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(); @@ -245,7 +247,7 @@ describe.skipIf(process.platform === 'win32')('release-cut --daily (the workflow 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 *check-runs*) echo \'' + JSON.stringify([{ check_runs: GREEN }]) + '\' ;;\n "release view v1.0.0 "*) echo \'{}\' ;;\n *) exit 1 ;;\nesac\n', { mode: 0o755 }); + 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 = { ...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 = (...args: string[]) => spawnSync(process.execPath, [...bunIsolationArgs(), 'run', path.join(path.resolve(import.meta.dir, '..', '..'), 'crew', 'scripts', 'release-cut.ts'), '--repo', 'o/r', ...args], @@ -276,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); @@ -297,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 = { ...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 7abf1470957..d809e48f94e 100644 --- a/crew/test/release-cut.test.ts +++ b/crew/test/release-cut.test.ts @@ -11,11 +11,13 @@ import { execFileSync, spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { bunIsolationArgs } from '../../lib/bun-isolation'; +import { PR303, PR303_RERUN_PASSED, ciRest, ciShimCases, type CiAtCommit } from '../../test/helpers/ci-attempts-fixture'; 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'; +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. @@ -42,8 +44,12 @@ function fakeGh(state: State): Gh { return (args) => { state.calls.push(args); const api = args[0] === 'api' ? args[args.length - 1]! : ''; - const m = /commits\/([0-9a-f]+)\/check-runs/.exec(api); - if (m) return { status: 0, stdout: JSON.stringify([{ check_runs: state.checks[m[1]!] ?? GREEN }]), stderr: '' }; + if (api && state.api && api in state.api) return { status: 0, stdout: JSON.stringify(state.api[api]), stderr: '' }; + const m = /commits\/([0-9a-f]+)\/|head_sha=([0-9a-f]+)/.exec(api); + const sha = m?.[1] ?? m?.[2]; + const listed = sha ? state.api?.['repos/o/r/actions/runs?head_sha=' + sha + '&per_page=100'] as Array<{ workflow_runs?: Array> }> | undefined : undefined; + const rest = sha && ciRest(args, { check_runs: state.checks[sha] ?? GREEN, workflow_runs: listed?.flatMap(p => p.workflow_runs ?? []) }); + if (rest) return rest; if (api && state.api && api in state.api) return { status: 0, stdout: JSON.stringify(state.api[api]), stderr: '' }; if (api) return { status: 1, stdout: '', stderr: 'gh: Not Found (HTTP 404)' }; if (args[0] === 'release' && args[1] === 'view') return state.released.has(args[2]!) ? { status: 0, stdout: '{}', stderr: '' } : { status: 1, stdout: '', stderr: 'release not found' }; @@ -123,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'); @@ -171,9 +178,8 @@ describe('release-cut: planning', () => { // never a failed required run, a gh error, an unrelated running check or a second page; seam=none; no_claim=GitHub's real check-runs payload shape (a fake gh answers; unit only) test('gateVerdict: a failed free-tests run, an unreadable check-runs API, an unrelated running check and a paginated check list', () => { const checks = (runs: unknown[]): Gh => (args) => { - const api = args[args.length - 1]!; - if (/check-runs/.test(api)) return { status: 0, stdout: JSON.stringify(runs), stderr: '' }; - return { status: 1, stdout: '', stderr: 'unexpected gh ' + args.join(' ') }; + if (args.includes('--slurp')) return { status: 0, stdout: JSON.stringify(runs), stderr: '' }; + return ciRest(args, { check_runs: (runs as Array<{ check_runs: Array> }>).flatMap(p => p.check_runs) }) ?? { status: 1, stdout: '', stderr: 'unexpected gh ' + args.join(' ') }; }; const failed = checks([{ check_runs: [{ name: REQUIRED_CHECK, status: 'completed', conclusion: 'failure' }] }]); expect(gateVerdict(failed, 'o/r', 'a'.repeat(40))).toEqual({ green: false, why: REQUIRED_CHECK + ' concluded failure', pending: false }); @@ -193,6 +199,16 @@ describe('release-cut: planning', () => { expect(gateVerdict(skipped, 'o/r', 'a'.repeat(40))).toEqual({ green: true, via: BACKSTOP_CHECK }); }); + // Value: protects=the release cut counts a failed check whose rerun attempt created no jobs and a workflow run that failed before any job, as the merge + // queue does, while a rerun that passed stays releasable; fails_when=gateVerdict reads only GitHub's default (latest-attempt) check-runs list and calls a + // main commit carrying gstack-evals#303's failures releasable; seam=lib/ci-head-checks.ts (ciAtHead) in gateVerdict, through ciRest's filter=latest/all + // split; no_claim=GitHub's attempt grouping (the fixture is #4235's recording) + test('gateVerdict: a failed check hidden behind a rerun attempt with no jobs, and a workflow run that failed with no jobs, are red (gstack-evals#303, GST-2252)', () => { + const at = (data: CiAtCommit): Gh => args => ciRest(args, { ...data, check_runs: [...GREEN, ...data.check_runs] }) ?? { status: 1, stdout: '', stderr: 'unexpected gh ' + args.join(' ') }; + expect(gateVerdict(at(PR303), 'o/r', 'a'.repeat(40))).toEqual({ green: false, why: 'red check runs: checks, sealed (run 42671854799, no jobs)', pending: false }); + expect(gateVerdict(at(PR303_RERUN_PASSED), 'o/r', 'a'.repeat(40))).toEqual({ green: true, via: BACKSTOP_CHECK }); + }); + test('an active freeze in refs/notes/gstack-trains refuses the cut; a cleared one does not', () => { const f = fixture(); const freeze = { schema: 1, kind: 'freeze', repo_key: 'k', train: 'abc', reason: 'backstop red on 2 cases', created_at: 'x', cleared_at: null }; @@ -346,6 +362,59 @@ 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=the every-attempt read (lib/ci-head-checks.ts) sets the cut's own runs aside by job id and workflow run id, the way the default list + // does, so a failed attempt of the cut's own job or a cut run that failed with no jobs never keeps a gated commit out, while another workflow's jobless + // failure still does; fails_when=headCheckRows rows skip GST-2463's exclusion and the cut deadlocks on its own "Cut the release" run (GST-2252 after + // #4297); seam=gh is faked with check-runs (filter=latest/all), actions/runs and jobs payloads; no_claim=a live workflow run + test('gateVerdict: the every-attempt read sets the cut\'s own earlier attempt and its jobless run aside by id, never by name (GST-2252, GST-2463)', () => { + const evidence = gatedBy(sha, '43072520821'); + const wf = (id: number, path: string, conclusion: string) => ({ id, path, check_suite_id: id, workflow_id: id, name: path, status: 'completed', conclusion, created_at: '2026-11-11T00:00:00Z' }); + const api = (runs: Array>, jobs: Record) => Object.assign( + { ['repos/o/r/actions/runs?head_sha=' + sha + '&per_page=100']: [{ total_count: runs.length, workflow_runs: runs }] }, + ...Object.entries(jobs).map(([id, ids]) => ({ ['repos/o/r/actions/runs/' + id + '/jobs?filter=all&per_page=100']: [{ total_count: ids.length, jobs: ids.map(j => ({ id: j })) }] }))); + const earlier = { ...ownRun('completed', 'failure'), earlier_attempt: true } as CheckRun; + expect(gateVerdict(ghFor([...unbacked, earlier], api([wf(9001, CUT_WORKFLOW, 'success')], { 9001: [OWN_JOB] })), 'o/r', sha, { evidence })) + .toEqual({ green: true, via: 'release gate run 43072520821' }); + expect(gateVerdict(ghFor(unbacked, api([wf(9001, CUT_WORKFLOW, 'failure')], { 9001: [] })), 'o/r', sha, { evidence })) + .toEqual({ green: true, via: 'release gate run 43072520821' }); + expect(gateVerdict(ghFor(unbacked, api([wf(9001, CUT_WORKFLOW, 'failure'), wf(555, '.github/workflows/evals.yml', 'failure')], { 9001: [] })), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'red check runs: .github/workflows/evals.yml (run 555, no jobs)', pending: false }); + expect(gateVerdict(ghFor([...unbacked, { ...earlier, id: 70555 } as CheckRun], api([wf(9001, CUT_WORKFLOW, 'success')], { 9001: [OWN_JOB] })), 'o/r', sha, { evidence })) + .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); @@ -495,7 +564,7 @@ describe('release-cut: train evidence gates a commit whose backstop never settle if (process.platform === 'win32') return; const shim = path.join(f.base, 'shim'); fs.mkdirSync(shim); - fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\ncase "$*" in\n *check-runs*) echo \'' + JSON.stringify([{ check_runs: f.state.checks[head] }]) + '\' ;;\n *) exit 1 ;;\nesac\n', { mode: 0o755 }); + fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\ncase "$*" in\n' + ciShimCases(f.state.checks[head]) + ' *) exit 1 ;;\nesac\n', { mode: 0o755 }); const run = (...args: string[]) => spawnSync(process.execPath, [...bunIsolationArgs(), 'run', path.join(path.resolve(import.meta.dir, '..', '..'), 'crew', 'scripts', 'release-cut.ts'), ...args], { cwd: f.work, encoding: 'utf8', timeout: 60_000, env: cliEnv(shim) }); const cli = run('--repo', f.repo, '--dry-run', '--ref', head, '--required-check', 'ci', '--backstop-check', 'nightly-backstop', '--notes-ref', 'refs/notes/other-trains'); @@ -538,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); @@ -576,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 }); @@ -598,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); @@ -658,7 +727,7 @@ describe.skipIf(process.platform === 'win32')('release-cut: the workflow entry p const f = fixture(); const shim = path.join(f.base, 'shim'); fs.mkdirSync(shim); - fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\necho "gh $*" >> "' + path.join(f.base, 'gh.log') + '"\ncase "$*" in\n *check-runs*) echo \'' + JSON.stringify([{ check_runs: GREEN }]) + '\' ;;\n "release view v1.0.3 "*) echo \'{\"tagName\":\"v1.0.3\"}\' ;;\n *) exit 1 ;;\nesac\n', { mode: 0o755 }); + fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\necho "gh $*" >> "' + path.join(f.base, 'gh.log') + '"\ncase "$*" in\n' + ciShimCases(GREEN) + ' "release view v1.0.3 "*) echo \'{\"tagName\":\"v1.0.3\"}\' ;;\n *) exit 1 ;;\nesac\n', { mode: 0o755 }); const run = (...args: string[]) => spawnSync(process.execPath, [...bunIsolationArgs(), 'run', path.join(path.resolve(import.meta.dir, '..', '..'), 'crew', 'scripts', 'release-cut.ts'), ...args], { cwd: f.work, encoding: 'utf8', timeout: 60_000, env: cliEnv(shim) }); @@ -672,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('
Release notes'); - 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'); @@ -692,7 +761,7 @@ describe.skipIf(process.platform === 'win32')('release-cut: the workflow entry p expect(refused.stdout).toContain('REFUSED: non-fast-forward'); // Nothing green: the real cut goes red (exit 1), a dry run has answered (exit 0) and names every skip. - fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\ncase "$*" in\n *check-runs*) echo \'' + JSON.stringify([{ check_runs: GREEN.filter(c => c.name !== BACKSTOP_CHECK) }]) + '\' ;;\n *) exit 1 ;;\nesac\n', { mode: 0o755 }); + fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\ncase "$*" in\n' + ciShimCases(GREEN.filter(c => c.name !== BACKSTOP_CHECK)) + ' *) exit 1 ;;\nesac\n', { mode: 0o755 }); git(f.seed, 'push', '-q', '--delete', 'origin', 'stable', 'refs/tags/v1.0.3'); f.refresh(); git(f.work, 'tag', '-d', 'v1.0.3'); const noneDry = run('--repo', f.repo, '--dry-run'); @@ -751,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'); @@ -985,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); @@ -1154,7 +1224,7 @@ describe.skipIf(process.platform === 'win32')('release-cut: refusals at the work f.refresh(); const shim = path.join(f.base, 'shim'); fs.mkdirSync(shim); - fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\ncase "$*" in\n *check-runs*) echo \'' + JSON.stringify([{ check_runs: GREEN }]) + '\' ;;\n "release view v1.0.3 "*) echo \'{"publishedAt":"' + isoZ(at) + '"}\' ;;\n *) echo "release not found" >&2; exit 1 ;;\nesac\n', { mode: 0o755 }); + fs.writeFileSync(path.join(shim, 'gh'), '#!/usr/bin/env bash\ncase "$*" in\n' + ciShimCases(GREEN) + ' "release view v1.0.3 "*) echo \'{"publishedAt":"' + isoZ(at) + '"}\' ;;\n *) echo "release not found" >&2; exit 1 ;;\nesac\n', { mode: 0o755 }); const run = (env: Record, ...args: string[]) => spawnSync(process.execPath, [...bunIsolationArgs(), 'run', path.join(path.resolve(import.meta.dir, '..', '..'), 'crew', 'scripts', 'release-cut.ts'), '--repo', f.repo, ...args], { cwd: f.work, encoding: 'utf8', timeout: 60_000, env: cliEnv(shim, env) }); const stable = () => git(f.origin, 'rev-parse', 'refs/heads/stable'); @@ -1207,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) => { + 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/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/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/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-consultation/SKILL.md b/design-consultation/SKILL.md index 4681f821783..61e27b0ba49 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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/design-consultation/sections/preamble.md +++ b/design-consultation/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## 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 81511c24a4f..535b31c22d4 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/design-html/sections/preamble.md +++ b/design-html/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## 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 c6ffa486469..90551122625 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/design-motion/sections/preamble.md +++ b/design-motion/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## 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 aaaf3ab2bb7..67becac6ca1 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/design-review/sections/preamble.md +++ b/design-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## 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 7fd4411c8ed..30f7f1a9d46 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/design-shotgun/sections/preamble.md +++ b/design-shotgun/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: 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 22e940c332b..4da92aabe17 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 @@ -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 `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 79e0a158c80..f753a5e1b1c 100644 --- a/devex-review/sections/preamble.md +++ b/devex-review/sections/preamble.md @@ -1,6 +1,6 @@ -# gstack shared preamble 4e82fa4c839f +# gstack shared preamble d8804c5ab6bf ## 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 @@ -225,6 +224,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: diff --git a/diagram/SKILL.md b/diagram/SKILL.md index b56f771d317..5842ecfd634 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 @@ -97,6 +97,13 @@ 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`. +- 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, ``, lorem ipsum, broken links and images. + ## Completion Status Protocol When completing a skill workflow, report status using one of: 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/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/TESTING_INTERNALS.md b/docs/TESTING_INTERNALS.md index c4abc8f9fca..317cfd7fda1 100644 --- a/docs/TESTING_INTERNALS.md +++ b/docs/TESTING_INTERNALS.md @@ -1036,8 +1036,10 @@ namespaces Chromium's sandbox needs, and `python3-venv` is absent (required by the Python runner tests). VMs are named `ubirun---`, plus a `-t` TTL suffix -(below); `` is `UBI_OWNER` (the thread id on a Capy machine; lowercase -letters and digits, at most 12), which `up`, `run` and `verify` require. Every exit +(below); `` is `UBI_OWNER` in full (the thread id on a Capy machine; lowercase +letters and digits, at most 31, longer is refused with `UBI_OWNER_TOO_LONG`), which `up`, `run` and `verify` require. Older runner copies cut the owner to 12 +characters, so owners sharing that prefix reaped each other's VMs (#3748); a VM named under the cut form +counts as a longer owner's only when this machine's VM record lists it under that form. Every exit path destroys the client's own VM (`trap` on EXIT, INT, TERM, HUP and QUIT), and `down` fails loudly (`FAILED to destroy / (HTTP )`) unless the VM is confirmed gone. `list --mine` shows this owner's VMs, `usage` the @@ -1069,7 +1071,14 @@ before the create request when that exceeds the known ceiling (`UBI_QUOTA_VCPUS`, or the maximum the last refusal printed, remembered in the state root; `UBI_QUOTA_WAIT=` waits for room instead). When the usage read fails (`usage` exits 1 on an unreadable VM list or size and skips a VM that 404s), the preflight retries -within `UBI_QUOTA_WAIT`, then logs and leaves the decision to the API. `run`, `verify` +within `UBI_QUOTA_WAIT`, then refuses under a `UBI_QUOTA_VCPUS` ceiling +(`UBI_QUOTA_UNREADABLE`, nothing launched) and leaves the decision to the API under a +cached refusal maximum, which is the API's own ceiling. The usage read and the +booking of the new VM's vCPUs run under one lock per machine (`UBI_QUOTA_LOCK`), and a +booking counts until its create is answered, so shards a fan-out starts together +on one machine cannot all pass on the same reading; `room [-s SIZE]` prints how many +VMs fit now (`UBICLOUD_ROOM: room= ...`) for a fan-out to size each batch. Callers +on different machines still race, which the project's 48 spare vCPUs absorb. `run`, `verify` and `ssh NAME COMMAND` stream the remote output through a watchdog: a heartbeat line every `UBI_HEARTBEAT` seconds (300), and a command silent for `UBI_IDLE_TIMEOUT` seconds (1800) or older than `UBI_RUN_TIMEOUT` (0, unlimited) @@ -1808,7 +1817,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 @@ -2003,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 @@ -2037,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 @@ -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/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/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/evals/ship-conductor-fold-prereg.md b/docs/evals/ship-conductor-fold-prereg.md new file mode 100644 index 00000000000..587f24d19ce --- /dev/null +++ b/docs/evals/ship-conductor-fold-prereg.md @@ -0,0 +1,197 @@ +# Prereg: does /ship need its conductor subagent? (GST-3003) + +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. + +## 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 `` on garrytan/gstack; its base is ``. Install gstack for +ship, then run /ship at the branch head against ``. 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 `` against ``, 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 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 + (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. 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 --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 ` for a web or Android build) in a write-once `manifest.json`, and prints `FIRST_USE_RUN: `. 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 ` 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 --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 --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 --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 --platform ios --commit --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 --score 4 --words "4, Talk is slow" --by ""`. `gstack-first-use show --run ` 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__not_played`, `action__failed`, `action__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. + + +## 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///`), 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/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 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 : path unavailable (); gstack skips it.` **Problem.** A gbrain code source points at a directory that no longer 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/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. 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/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/loadouts.md b/docs/loadouts.md index 50d4a24aa10..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:` 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; 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`). | @@ -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/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-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 `/owner-answers/` | + +On Capy the record is bound to the one mounted `user-*` folder, or to the one +`--owner ` 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/.json one answer, created once with O_EXCL, never edited + verifications/--.json a second actor's confirmation of a row's words + log/.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:/` or `captain:`. 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:` (the default) | +| `source` | `{ "thread": , "event": }`: 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 `) 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 ` 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: ` ()`; +- 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/pregate.md b/docs/pregate.md index 892af1ecfbb..b37dec29fc7 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 ` (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)) | @@ -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` @@ -428,7 +437,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 `), @@ -559,7 +572,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/` (gstack's `scripts/ubicloud/ubi-runner.sh run --src - -- ' '`). Without either, the tier runs locally under + --setup -- ''`, where the setup script, kept under +`/projects//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 @@ -996,7 +1013,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` @@ -1067,6 +1084,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. +- HEAD's runs include those of its newest + ancestors (up to 20 back) whose tree `git rev-parse ^{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 / at + commit , not HEAD ; git rev-parse reads the same tree for + both`, a Step 5 lane reads `LANE: