diff --git a/.github/workflows/evals.yml b/.github/workflows/evals.yml index a908fdb40..e7b81e55b 100644 --- a/.github/workflows/evals.yml +++ b/.github/workflows/evals.yml @@ -479,6 +479,7 @@ jobs: - name: Print the screening selection and its estimated cost (no paid case runs) env: PR_NUMBER: ${{ github.event.pull_request.number }} + EVALS_SCREEN_POLICY: narrow run: | EVALS_TIER=gate bun --no-install run scripts/test-paid-shards.ts --tier gate --emit-plan /tmp/paid-plan/manifest.json --slices 1 bun --no-env-file --config=/dev/null --no-install run scripts/train-gate.ts screen-summary /tmp/paid-plan/manifest.json --pr "$PR_NUMBER" >> "$GITHUB_STEP_SUMMARY" @@ -573,6 +574,9 @@ jobs: EVALS_CACHE_DIR: ${{ steps.reuse.outputs.reuse == 'on' && '/tmp/gstack-eval-input-cache' || '' }} # Dispatch diff base (CEO-17): a screen's merge-commit first parent, else the exact merge-base, else the named base branch, else detection. EVALS_BASE: ${{ needs.route.outputs.screen_base || inputs.base_sha || (inputs.base_ref != '' && format('origin/{0}', inputs.base_ref)) || '' }} + # Dispatched screens and eval:bg:pr default to narrow; a broad screen (`ready --screen --broad`) and a + # pull_request run (the merge gate when no train block exists) keep every derived dependent. + EVALS_SCREEN_POLICY: ${{ inputs.screen_policy || (github.event_name == 'workflow_dispatch' && 'narrow') || 'broad' }} run: EVALS_TIER=gate bun --no-install run scripts/test-paid-shards.ts --tier gate --emit-plan /tmp/paid-plan/manifest.json --slice-budget 420 --jobs 2 --max-parallel 20 # R2a/R2: reuse holds only when this head's own plan selects exactly the diff --git a/.github/workflows/free-tests.yml b/.github/workflows/free-tests.yml index 948b597ee..443888a40 100644 --- a/.github/workflows/free-tests.yml +++ b/.github/workflows/free-tests.yml @@ -23,6 +23,22 @@ on: push: branches: [main] workflow_dispatch: + inputs: + free_runner: + description: 'Runner-sizing experiments only: Ubicloud runner for the free-suite shards (ubicloud-standard-2, -4 or -8; empty keeps FREE_SUITE_RUNNER). Never cite such a run as a PR or train Free Tests result.' + type: string + default: '' + free_shards: + description: 'Runner-sizing experiments only: shard count, 1-40 (empty keeps FREE_SUITE_SHARDS)' + type: string + default: '' + +# The one source of the free-suite runner and shard count. pull_request and +# push runs never see workflow_dispatch inputs, so free-plan resolves these +# (or a dispatch override) into outputs that free-suite reads. +env: + FREE_SUITE_RUNNER: ubicloud-standard-2 + FREE_SUITE_SHARDS: '20' # Keyed on the PR number, not head_ref: a bare branch name carries no fork # prefix, so same-name branches from two forks would share one group and a @@ -43,6 +59,7 @@ jobs: timeout-minutes: 5 outputs: matrix: ${{ steps.plan.outputs.matrix }} + runner: ${{ steps.plan.outputs.runner }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -56,9 +73,27 @@ jobs: - id: plan name: Inventory and balance the complete free suite # Warns in the job summary when more than 5 files are unseeded. + env: + RUNNER_OVERRIDE: ${{ inputs.free_runner }} + SHARDS_OVERRIDE: ${{ inputs.free_shards }} run: | - matrix=$(bun run scripts/test-free-shards.ts --ci-plan "$RUNNER_TEMP/free-plan.json" --shards 20) + set -euo pipefail + runner="${RUNNER_OVERRIDE:-$FREE_SUITE_RUNNER}" + shards="${SHARDS_OVERRIDE:-$FREE_SUITE_SHARDS}" + case "$runner" in + ubicloud-standard-2|ubicloud-standard-4|ubicloud-standard-8) ;; + *) echo "::error::free_runner '$runner' is not ubicloud-standard-2, -4 or -8"; exit 1 ;; + esac + case "$shards" in + ''|*[!0-9]*) echo "::error::free_shards '$shards' is not a whole number"; exit 1 ;; + esac + if [ "$shards" -lt 1 ] || [ "$shards" -gt 40 ]; then echo "::error::free_shards $shards is outside 1-40"; exit 1; fi + if [ "$runner" != "$FREE_SUITE_RUNNER" ] || [ "$shards" != "$FREE_SUITE_SHARDS" ]; then + echo "- Runner-sizing experiment: $shards shards on $runner (defaults $FREE_SUITE_SHARDS on $FREE_SUITE_RUNNER); not a PR or train Free Tests result" >> "$GITHUB_STEP_SUMMARY" + fi + matrix=$(bun run scripts/test-free-shards.ts --ci-plan "$RUNNER_TEMP/free-plan.json" --shards "$shards") echo "matrix=$matrix" >> "$GITHUB_OUTPUT" + echo "runner=$runner" >> "$GITHUB_OUTPUT" - name: Seed growth ratchet (60 s ceiling, shrink-only allowlist) run: | GSTACK_FREE_SEED_BASE="$(git merge-base HEAD origin/main)" bun test test/free-seed-ratchet.test.ts @@ -288,6 +323,21 @@ jobs: installed="${chrome%/*}/chrome-sandbox" test -f "$helper" && test ! -L "$helper" sudo install -T -o root -g root -m 4755 "$helper" "$installed" + # Runner image 20261026.1.0 keeps kernel.apparmor_restrict_unprivileged_userns=1 + # but loads no AppArmor profiles, so Chromium's namespace sandbox aborts with + # "credentials.cc: Permission denied". Grant user namespaces to this one + # resolved binary, the way Ubuntu's own chrome profile does. + - name: Let the bundled Chromium create its sandbox namespaces + run: | + set -euo pipefail + chrome=$(bun -e 'import { chromium } from "playwright"; import { realpathSync } from "node:fs"; console.log(realpathSync(chromium.executablePath()))') + case "$chrome" in + "$HOME"/.cache/ms-playwright/chromium-*/chrome-linux*/chrome) ;; + *) echo "Unexpected Chromium installation path" >&2; exit 1 ;; + esac + profile=/etc/apparmor.d/gstack-playwright-chromium + printf 'abi ,\ninclude \nprofile gstack-playwright-chromium %s flags=(unconfined) {\n userns,\n}\n' "$chrome" | sudo tee "$profile" > /dev/null + sudo apparmor_parser -r "$profile" - name: Install Xvfb + X11 utilities + gate tools run: sudo apt-get install -y --no-install-recommends xvfb x11-utils poppler-utils fonts-noto-color-emoji zsh - name: Configure git identity (tests init temp repos) @@ -314,7 +364,7 @@ jobs: free-suite: needs: free-plan - runs-on: ubicloud-standard-8 + runs-on: ${{ needs.free-plan.outputs.runner }} timeout-minutes: 20 strategy: fail-fast: false @@ -397,6 +447,21 @@ jobs: sudo install -T -o root -g root -m 4755 "$helper" "$installed" test "$(stat -c '%u:%a' "$installed")" = '0:4755' cmp -s "$helper" "$installed" + # Runner image 20261026.1.0 keeps kernel.apparmor_restrict_unprivileged_userns=1 + # but loads no AppArmor profiles, so Chromium's namespace sandbox aborts with + # "credentials.cc: Permission denied". Grant user namespaces to this one + # resolved binary, the way Ubuntu's own chrome profile does. + - name: Let the bundled Chromium create its sandbox namespaces + run: | + set -euo pipefail + chrome=$(bun -e 'import { chromium } from "playwright"; import { realpathSync } from "node:fs"; console.log(realpathSync(chromium.executablePath()))') + case "$chrome" in + "$HOME"/.cache/ms-playwright/chromium-*/chrome-linux*/chrome) ;; + *) echo "Unexpected Chromium installation path" >&2; exit 1 ;; + esac + profile=/etc/apparmor.d/gstack-playwright-chromium + printf 'abi ,\ninclude \nprofile gstack-playwright-chromium %s flags=(unconfined) {\n userns,\n}\n' "$chrome" | sudo tee "$profile" > /dev/null + sudo apparmor_parser -r "$profile" # Headed-browser tests (handoff, extension sidepanel DOM) need a real # DISPLAY — first Linux run failed with Playwright's "launched a headed @@ -446,6 +511,18 @@ jobs: - name: Build trusted CSO helper used by free contract tests run: bun run build:cso + # Runner sizing: the suite runs one test at a time, so a shard needs RAM + # and disk more than cores. Sample both while it runs and report the peak. + - name: Start the memory and disk sampler + run: | + cat > "$RUNNER_TEMP/sample-resources.sh" <<'EOF' + while :; do + printf '%s %s %s\n' "$(date +%s)" "$(free -k | awk 'NR == 2 { print $3 }')" "$(df -Pk / | awk 'NR == 2 { print $4 }')" + sleep 2 + done + EOF + nohup sh "$RUNNER_TEMP/sample-resources.sh" > "$RUNNER_TEMP/resources.log" 2>&1 & + # GSTACK_EXPECT_BINARIES=1 arms make-pdf/test/e2e/ci-prereqs.test.ts: # if a future edit drops the gate build (or poppler), the lane FAILS # instead of the gates silently self-skipping back to false green. @@ -464,6 +541,12 @@ jobs: GSTACK_FREE_RETRY_FLAKY: "1" GSTACK_FLAKE_LEDGER: ${{ runner.temp }}/flake-ledger.jsonl + - name: Report peak memory and minimum free disk + if: always() + run: | + if [ ! -s "$RUNNER_TEMP/resources.log" ]; then echo "RESOURCES: no samples"; exit 0; fi + awk '{ if ($2 > used) used = $2; if (free == "" || $3 < free) free = $3 } END { printf "RESOURCES: peak_used_mib=%d min_free_disk_mib=%d samples=%d\n", used / 1024, free / 1024, NR }' "$RUNNER_TEMP/resources.log" | tee -a "$GITHUB_STEP_SUMMARY" + - name: Upload strict shard result if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 diff --git a/.github/workflows/version-gate.yml b/.github/workflows/version-gate.yml index 32b36a04f..1be24d4e6 100644 --- a/.github/workflows/version-gate.yml +++ b/.github/workflows/version-gate.yml @@ -1,12 +1,10 @@ name: Version Gate +# Every PR: under changelog_fragments a PR that touches no release file must +# still prove it carries a fragment (docs/ship-policy.md#changelog-fragments). on: pull_request: branches: [main] - paths: - - 'VERSION' - - 'CHANGELOG.md' - - 'package.json' concurrency: group: version-gate-${{ github.event.pull_request.number }} diff --git a/.gstack/always-run.json b/.gstack/always-run.json new file mode 100644 index 000000000..f6c36742f --- /dev/null +++ b/.gstack/always-run.json @@ -0,0 +1,11 @@ +{ + "tests": [ + "test/*tripwire*.test.ts", + "test/*ratchet*.test.ts", + "test/env-host-fence-conformance.test.ts", + "test/free-fixtures.test.ts", + "test/bun-entry-isolation.test.ts", + "test/egress-receipt-wiring.test.ts", + "test/review-packets-removed.test.ts" + ] +} diff --git a/.gstack/ship-policy.json b/.gstack/ship-policy.json index d50acbc38..ad1b381fd 100644 --- a/.gstack/ship-policy.json +++ b/.gstack/ship-policy.json @@ -14,5 +14,6 @@ "pr_count": { "default_pr_count": 1, "split_requires_owner": true }, "maintainers": ["garrytan"], "train": { "gate_workflow": "evals.yml", "free_workflow": "free-tests.yml", "full_gate_check": "gstack/full-gate", "record_artifact": "gstack-train-record", "max_size": 3, "fill_hours": 1, "screen_selection": "gstack-paid", "trial_reservation_usd": 1.5 }, - "min_gstack_version": "1.91.299.0" + "changelog_fragments": { "dir": "changelog.d", "required_checks": ["free-tests", "windows-free-tests", "Check VERSION is not stale vs queue", "quality", "check-freshness", "actionlint"] }, + "min_gstack_version": "1.91.340.0" } diff --git a/AGENTS.md b/AGENTS.md index 4232c097b..abe32fea9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ Invoke them by name (e.g., `/office-hours`). | `/codex` | Second opinion via OpenAI Codex. Review, challenge, or consult modes. Available outside the Codex harness. | | `/claude-code` | Second opinion via Claude Code. Review, challenge, or consult modes. Available outside the Claude Code harness. | | `/investigate` | Systematic root-cause debugging. No fixes without investigation. | +| `/verify` | Build-and-verify loop while you code: the repo's checks plus the tests pregate selects, fix, repeat, then hand off to `/ship`. Never green on an unmapped change. | | `/design-review` | Live-site visual audit + fix loop with atomic commits. | | `/design-shotgun` | Generate multiple AI design variants, comparison board, iterate. | | `/design-html` | Generate production-quality Pretext-native HTML/CSS. | @@ -70,7 +71,7 @@ Invoke them by name (e.g., `/office-hours`). | `/captain` | Run a crew from one controller: READY contract, merge trains, digest, approvals shapes, daily flaky pass. Also `/crew`. Templates in `captain/templates/`, team guide in `docs/captain.md`. | | `/benchmark` | Performance regression detection (page load, Core Web Vitals). | | `/ubicloud` | Run a heavy suite, build or eval on an ephemeral 16-vCPU Ubicloud VM: TTL-named VMs with a reaper, quota preflight, hang watchdog, one committed verify per repository. | -| `/benchmark-models` | Cross-model benchmark for skills (Claude, GPT, Gemini side-by-side). | +| `/benchmark-models` | Cross-model benchmark for skills (Claude, GPT, Gemini, plus particle-1 and DeepSeek V4.1 Flash through OpenRouter, side-by-side). | | `/eval-plan` | Preregister a paid eval (bars, arms, decoys, stop rules), dry-run it for $0, pilot three priced items, then approve the spend. | | `/cso` | Supported security findings with explicit coverage. Static assessment remains available without catalog profiles. Contained runtime and scanner execution needs Docker and a matching qualified profile. The runtime catalog qualifies ten images: Node 24.4.0, Bun 1.3.10, Python 3.13.4 with uv 0.8.0, Rails on Ruby 3.4.4, and PostgreSQL 17.2, each for linux/amd64 and linux/arm64. The scanner catalog qualifies twelve: gitleaks, OSV-Scanner, Schemathesis, Semgrep, Trivy and zizmor on both platforms. Without Docker, or where no profile matches (native Windows Docker, for example), `/cso` runs 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. | | `/setup-gbrain` | Set up gbrain for cross-machine session memory sync. | diff --git a/CHANGELOG.md b/CHANGELOG.md index f6e40735e..845e26fed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,697 @@ # Changelog +## [1.91.371.0] - 2026-10-31 + +**A PR push in a repository with a merge train no longer waits ten minutes for a check that does no work.** Under a train policy every PR push runs E2E Evals in `pr-summary` mode, which plans no paid slices, yet its `readiness` job still waited out the 600-second quiet window and green Free Tests before the run could finish. Now `readiness` waits for `route` and skips in `pr-summary` mode, so E2E Evals on a PR push finishes in about a minute (58 s on #3609) instead of after the 10-minute wait. + +### Changed +- **`.github/workflows/evals.yml`**: `readiness` needs `route` and runs only when the mode is not `pr-summary`. In `pr` mode (a repository without a train) it still gates recovery and planning as before. In `pr-summary` mode a red Free Tests now shows on Free Tests alone, which stays the required free check; the train gate and the dispatched screen still carry the paid work. +- **`bun run test:health`**: the "PR lane push-to-verdict" rule text says `pr-summary` runs skip the wait since GSTA-149, so its p50 drops by about 10 minutes from this change on. +- **docs/TESTING_INTERNALS.md** describes the skip. + +### Tests +- `test/evals-pr-lane-workflow.test.ts` pins `readiness.needs` and the full `if`. `test/evals-train-workflow.test.ts` checks that a `pr-summary` push runs only `build-image`, `route` and `screen-summary`, and that `pr` mode still runs `readiness`. + +## [1.91.370.0] - 2026-10-31 + +**The free suite now runs on `ubicloud-standard-2` instead of `ubicloud-standard-8`, at the same 20 shards, for about a quarter of the runner cost.** Each shard runs its files one at a time, so it waits on disk and processes rather than CPU. In three paired rounds at one commit, the median per-shard time rose by 3 to 8 s, inside the round-to-round spread of −90 to +65 s, while runner-minutes stayed about equal (464 vs 475). Peak memory stayed under 2.5 GiB and free disk above 15 GiB. A 16-shard arm was slower beyond that spread, so the shard count stays at 20. + +### Changed +- **`.github/workflows/free-tests.yml`**: one workflow-level `FREE_SUITE_RUNNER` (`ubicloud-standard-2`) and `FREE_SUITE_SHARDS` (`20`) set the free-suite size for pull_request, push and dispatch runs alike. `free-plan` resolves them into its `runner` output and the plan's shard count, and `free-suite` reads `runs-on` from that output. The duration-seed recorder stays on `ubicloud-standard-8`. +- **Sizing experiments without a workflow edit**: `workflow_dispatch` takes `free_runner` (`ubicloud-standard-2`, `-4` or `-8` only) and `free_shards` (1–40). `free-plan` refuses any other value before planning, and a run that overrides either one says in its job summary that it is a sizing experiment, not a PR or train Free Tests result. +- **Every free-suite shard prints `RESOURCES: peak_used_mib=… min_free_disk_mib=… samples=…`** from a memory and disk sample every 2 s, even when the suite fails. If a shard shows OOM, ENOSPC or an unexplained Chromium launch failure, move `FREE_SUITE_RUNNER` to `ubicloud-standard-4`. + +### Tests +- `test/free-tests-workflow-wiring.test.ts`: runs the real `free-plan` step with a stubbed `bun`. It checks that the constant passes through when no override is given, that a valid override is honored, and that `ubuntu-24.04`, `ubicloud-standard-8 x`, `0`, `41` and `16; true` are refused before planning. It also checks that the sampler starts before the suite and that the report step runs `always()`. +- `test/free-durations-record-workflow.test.ts`: the recorder and `FREE_SUITE_RUNNER` must both be Ubicloud standard runners. They no longer have to be the same size, because the recorder stays on standard-8. + +## [1.91.369.0] - 2026-10-31 + +**`gstack-wtree` works again in a repository that gitignores `.bun/`.** Since GST-421, its `git add -A` carried an exclude pathspec naming `.bun`, and git refuses a pathspec naming an ignored path with exit 1. Every fingerprint call then failed, which broke `gstack-review-log --start`, the evidence checks and /ship in harness-evals (HARN-1, HARN-7, harness-evals#148; GST-449). + +### Fixed +- **The `.bun/` exclude applies only when the root `.bun/` exists and is not ignored.** The check reads the ignore rules alone (`git check-ignore --no-index`), so a file still tracked under an ignored `.bun/` doesn't bring the failure back. An ignored `.bun/` already stays out of `git add -A`, so the fingerprint is the same either way. + +### Tests +- `test/evidence.test.ts`: with `.bun/` or `/.bun` in `.gitignore`, `gstack-wtree` prints a tree and a lane that writes `.bun/` grades FRESH. With a file tracked under an ignored `.bun/`, the tree matches a plain `git add -A`, and editing or deleting that file changes it. The existing unignored `.bun/` cases still pass. + +## [1.91.368.0] - 2026-10-31 + +**`gstack-pregate --remote` no longer dies at 300 s while its gate waits on CI.** CAPY-1 (qm#2837) had a remote gate that waits for a CI run and prints nothing while it waits, so pregate killed it as stalled after 300 s, whatever `--timeout` said, and the heartbeat gave no hint of what the gate was doing (GST-431). + +### Fixed +- **The remote gate is bounded by its timeout only** (`--timeout`, else `timeout_s`, else 600 s; the gate also gets it as `PREGATE_TIMEOUT_S`). The stall timer still applies to the lanes runner and guards. +- **The remote gate's heartbeat names its last output line**, so a gate that prints the CI run it is waiting on shows it every 60 s. + +### Tests +- `test/pregate-remote.test.ts`: a gate quiet past `--stall-timeout` but inside `--timeout` clears its obligation; a gate past `--timeout` stays uncleared with `PREGATE_INCOMPLETE`. +- `test/pregate-supervise.test.ts`: a heartbeat with `lastLine` names the command's last output line. + +## [1.91.367.0] - 2026-10-31 + +**/ship's review collection no longer counts a reviewer that says it could not review as clean.** In the GSTA-196 replay a specialist replied in prose that the diff base did not exist and it was not returning NO FINDINGS. `collect` parsed that reply to zero findings, and `verify` marked the brief collected, so the review would have read clean from a reader that never saw the diff. What reviewers see is unchanged: every brief renders byte for byte as before. + +### Fixed +- **`gstack-review-dispatch collect` needs the clean marker a reader's own brief asks for before it counts a reply with no findings.** That is `NO FINDINGS` alone on a line for the specialists, the batched specialist, the targeted reader, the Red Team and fix-check; the `Recommendation:` line for the outside voice; and either one for the native adversarial voice. A reply with no finding and no marker (a refusal, an empty reply, a reader that never got the diff) is recorded with `review: false`, prints `COLLECT_NOT_REVIEWED` and exits 1. Re-sending the brief and collecting a real review voids it, and the outside voice, whose failure never blocks, is collected with `--unavailable ''` and verifies as `UNAVAILABLE`, never as a review. A failure text that still holds findings is refused there and collected normally, so nothing is lost. +- **`gstack-review-dispatch verify` reports that reader's brief `NOT_COLLECTED` and its output `NOT_REVIEWED`, so VERIFY reads dirty.** When the output file is still there and unchanged, verify checks the marker in it again, so a ledger written before this change is judged by the same rule. The GSTA-189 replay's combined ledger still verifies clean, with five `NO FINDINGS` specialists and one outside voice ending in `Recommendation:`. +- **A paragraph finding keeps its detail bullets.** The GSTA-196 native adversarial voice wrote four findings, each with unlabeled bullets and then a `Severity:` line. Every bullet closed the open finding, so each `Severity:` line opened a new one: 4 findings collected as 8. They now collect as 4, each at the stronger of its two labels. Only an unnumbered bullet with no file and line of its own counts as detail; a numbered item is still its own finding. +- **Every other finding collects exactly as before.** Main's parser and this one were run over every recorded reader output: 25 raw outputs from the GSTA-189 and GSTA-196 replays and 2,172 finding records from arms C6, L6, A3668 (both suites), G1 and L. 2,196 of the 2,197 collect the same findings with the same labels. The one difference is the GSTA-196 native sample, where 8 fragments join into 4 findings, each at its strongest fragment's label. + +## [1.91.366.0] - 2026-10-31 + +**A partial `gstack-post pr-body` post keeps the PR's intro.** Since GST-412, any body file with a `## ` section replaced the text above the PR's first heading, so a lane that posted only `## Screenshots` deleted a human intro or a `Review-loop exception:` line under the receipt (GStack Minder: "a partial pr-body post must keep the human intro"). + +### Fixed +- **Only a full post owns the text above the first heading.** A file with a receipt block above its first `## ` section, as /ship composes it, still replaces stale lead text and stale notes under the receipt. Any other file keeps them; its own lead text still replaces the PR's lead text. + +### Tests +- `test/gstack-post.test.ts`: a partial post keeps the intro and the note under the receipt, even with a caption of its own or a receipt further down; the full-post cases now carry a receipt, as /ship's body does. + +## [1.91.365.0] - 2026-10-31 + +**An unclosed code fence in an outside review no longer hides a later `[P1]` or not-ready verdict (GST-436).** Before, an outside-voice reply that said no issues were found, opened a code fence it never closed, and then listed a `[P1]` finding or ended with `Verdict: not ready` was classified clean, because everything after the fence was treated as quoted code. Now a P0 or P1 severity or a last `Verdict: not ready` after an unclosed fence still blocks. Text inside that fence still can't make a reply clean, so a quoted `Verdict: ready`, `[P3]` or `No issues found.` there is ignored, as before. + +### Fixed +- `lib/outside-review-result.ts` reads the reply after an unclosed fence's opening line for severities (P0 and P1, or Critical and High words, block), an unparsed label (which makes the review `unverified`) and a last `Verdict: not ready`. The evidence for clean (a parsed severity, the last verdict line, the no-findings conclusion) keeps that text blanked. Closed fences still hide quoted severities. +- Fence matching is one pass, and an opener counts only when a later marker of its kind is at least as long. A reply with thousands of unmatched fences classifies in milliseconds instead of rescanning the rest once per fence. + +### Tests +- `test/outside-review-unclosed-fence.test.ts` covers: + - a `[P1]` and a `Verdict: not ready` after an unclosed fence + - a closed fence that still hides a quoted `[P1]` + - a quoted `Verdict: ready`, `[P3]` or `No issues found.` inside an unclosed fence, which stays findings or unverified + - 3,000 unmatched fences + +## [1.91.364.0] - 2026-10-31 + +**`--policy-from head` now only adds test lanes, and the repo can set pregate's per-process timeout.** Two /ship tooling gaps cost other crews a rerun each. GEVA-2 (gstack-evals#93) had a PR that added its own pregate lane, but `gstack-ship-preflight` could not pass `--policy-from head`, so Step 5 failed with `PREGATE_NO_LANE` and the lane called runLanes by hand (GST-419). HARN-1 (HARN-12) had lanes of about 780 s, while preflight and the `finish` fallback ran pregate at its 600 s default, so the result was always `PREGATE: incomplete` (GST-420). There was also a hole behind the first gap: `--policy-from head` took the branch's whole `.gstack/pregate.json`, so a branch could delete its own lanes. + +### Added +- **`timeout_s` in `.gstack/pregate.json`** (1 to 3600 s): gstack-pregate's per-process timeout when `--timeout` is not passed, so preflight, `finish` and plain runs all pick it up. The remote gate gets the same value as `PREGATE_TIMEOUT_S`. A timed-out lane names where its timeout came from (`--timeout`, `timeout_s from ` or the 600 s default). +- **`gstack-ship-preflight --policy-from head`** forwards to Step 5's pregate. When pregate does not pass, preflight prints up to three `PREGATE_DETAIL:` lines with pregate's own reasons, and a refusal reads `PREGATE: refused ()` instead of `unreadable`. + +### Changed +- **A head policy may only add test lanes** (`PREGATE_HEAD_POLICY_LOOSENS`). It may add a `dependencies` glob with at least one test, or add tests to a glob the trusted policy already maps. Anything else that differs from the trusted policy refuses the run and names each difference. The trusted policy is the base copy, or the user-owned file when the base has none. A branch behind its base is measured from the copy at its merge base and runs the base tip's policy plus its additions. A head file with no trusted policy anywhere is still a bootstrap. +- **`--remote` works with `--policy-from head`** once that check passes, so a lane on a machine with under 8 cores can clear its obligation. It still runs the trusted copy's `remote_gate`. With no trusted policy at all, `--remote` under head is refused, because a bootstrap head file's own `remote_gate` would be clearing its own obligation. +- **Under `--policy-from head`, an invalid user-owned policy now refuses** (`PREGATE_CONFIG_INVALID`) instead of being ignored, because it is the policy the head file is compared with. +- **A `[]` declaration added only on the branch is refused under `--policy-from head`**, the Dart device-test workaround included: declare `"**/integration_test/**": []` on the base branch first. The `PREGATE_NO_LANE` fix line and docs say so. + +### Tests +- `test/pregate-head-policy.test.ts`: a head policy that adds a lane passes; one that removes or swaps a lane, adds `[]`, changes the runner, downgrades a check, allowlists a finding or deletes the file is refused; reorders are not changes; a stale branch keeps the base's newer lanes; the user-owned policy is compared when the base has none; a bootstrap still runs; `timeout_s` bounds each runner process, `--timeout` overrides it, and out-of-range values are invalid. +- `test/ship-preflight.test.ts`: `--policy-from head` reaches pregate, a removed lane stops with `PREGATE_HEAD_POLICY_LOOSENS`, and `timeout_s` reaches preflight's pregate with the cause printed. +- `test/pregate-remote.test.ts`: `--remote` under head runs the base gate with the `timeout_s` deadline (or `--timeout`), and a head policy that changes the gate is refused. `test/pregate-dart.test.ts` and `test/pregate-user-policy.test.ts` follow the two behavior changes above. + +## [1.91.363.0] - 2026-10-31 + +**A passing test lane that leaves Bun's `.bun/` folder behind now grades FRESH, `--check-prose` no longer reads the Approvals table as a claim, and `gstack-post pr-body` drops a stale intro.** Three /ship false alarms from GST-421 and GST-412 (HARN-1, HARN-12, GSTA-2, GEVA-69, gstack-evals#90). + +### Fixed +- **GST-421: `gstack-wtree` leaves an untracked `.bun/` folder at the repo root out of the fingerprint.** A test that created it made `gstack-evidence` treat the run as a mid-run edit, so `check` graded the lane STALE with "record has no content fingerprint" and named no file. Tracked files under `.bun/` still count, and a tree without that folder hashes exactly as before. +- **GST-421: `gstack-evidence` names what changed during a run.** When the fingerprint before and after a run differ, the record stores up to five changed paths as `wtree_changed`, the stderr warning lists them, and `check` grades STALE with `content changed during the run: `. A record without them (or with entries that are not plain paths) still says "record has no content fingerprint". +- **GST-412: `gstack-ship-receipt read --check-prose` skips the `## Approvals` block `gstack-approvals` renders** (the heading, the table and its `Source: gstack-approvals record` line), so "one Step 11 pass" in the owner's quoted words is no longer read as `gate..pass body=11`. Text after that block, a row the renderer would not write, a hand-written Approvals list and an example inside a code fence are still checked, the text on either side of the block never joins into a new claim, and CRLF bodies work. + +### Changed +- **GST-412: `gstack-post pr-body` manages the text above the first heading when the file has a `## ` section.** The current body's opening text, any text between the receipt and the first heading, or a whole body with no `## ` heading, is replaced by the file's own text above its first heading, or dropped when the file has none. The stderr line names each dropped piece with its first line (`; dropped leading text ("…")`), or withholds that line when the redaction scan flags it, so a removed secret never reaches the terminal. A receipt-only or text-only file merges as before, and reposting the same body gives the same bytes. + +### Tests +- `test/evidence.test.ts`: a lane that writes `.bun/x` grades FRESH; one that writes `src/new.ts` grades STALE naming it; a tracked file under `.bun/` still moves the fingerprint; a tree without `.bun/` hashes like a plain `git add -A`. +- `test/ship-receipt-prose.test.ts`: the rendered Approvals table, text after its footer, a fenced example, a hand-written list and a CRLF body. +- `test/gstack-post.test.ts`: stale lead text and stale text under the receipt are dropped and named; receipt-only and text-only files keep the old merge; reposts are byte-identical; an attribution callout is never doubled. + +## [1.91.362.0] - 2026-10-31 + +**A /ship review pass on Capy is one call to a checked-in program, and reviewer briefs no longer pass through the model.** In the GSTA-189 replay one pass took about 10 parent calls to plan, render, create, check and poll its readers, and the Red Team brief went out wrong twice because a file read cut its long lines. What reviewers see, which reviewers run, their depth and the blocking floor are unchanged, and the new path renders all 16 briefs of that replay byte for byte. + +### Added +- **`gstack-review-dispatch pass`** plans a pass and writes a staged manifest: audits marked first, then specialists with QA and the other audits, then the Red Team, then Step 11's voices. Each brief is rendered once its inputs exist, and the Red Team's findings file is the specialists' collected lines byte for byte. +- **Briefs travel in chunks** (`gstack-review-dispatch chunk`) of at most 65,536 characters, so a brief over 1 MB, or one whose diff has invalid UTF-8, reaches the reader whole and is checked by `sent` before the reader starts. +- **The Capy pass program** (`lib/capy-review-pass.js`, served by `gstack-review-dispatch program`) runs plan, review-log start, dispatch, poll, collect, the Red Team and the budget note in one call, returning within 200 s; the gstack Capy skill carries the loader. Each reader's intent is saved before its subagent is created, so a rerun after a lost create result finds the reader by title instead of starting it twice, and an unclear outcome stops the pass. A failed reader stops every rerun instead of leaving it polling, and a review-log start that failed is retried before any reader goes out. + +### Fixed +- **The pass program takes its input as the Capy skill writes it.** `extras` may be JSON in the input, not only a file path, and `cwd` names the checkout its commands run in. A reader that reports done a moment before its summary arrives is collected on a later poll instead of stopping the pass. Replay C2-34 (GSTA-193) lost 7 of its 15 calls to these three issues. +- **The targeted reader runs in the pass.** When the plan dispatches it for money, gate, auth or secret code, it is staged with Step 11's voices on the merge base. Its brief matches `gstack-review-dispatch render --role targeted` byte for byte, and its ledger row carries the classes, rules, brief and patch the receipt's targeted record reads. + +## [1.91.361.0] - 2026-10-31 + +**A reviewer's install no longer rewrites the lane's launch environment, and a hand-run `gstack-upgrade` on Capy no longer moves a checkout under another session.** These are follow-ups to the v1.91.356.0 fix that stopped reviewer installs from upgrading the shared checkout. + +### Fixed +- **A `--for review-voice` install that keeps the lane's fuller install verdict now borrows that install's launch environment.** It writes no launch file and announces the lane's own `GSTACK_LAUNCH_FILE` and `GSTACK_LAUNCH_PATH`. Before, it rewrote the lane's `.env` and could repoint `.launch/bun` at gstack's minimum Bun instead of the project's pinned Bun. A reviewer's own launch directory now lives under `.profile/review-voice.launch` (mode 0700), and a failing review-voice check removes `.profile/`. +- **`bin/gstack-upgrade` on Capy counts a fresh `capy-server` lease as another session's.** Every session on a Capy machine runs under one `capy-server` process, so its own-session exclusion used to drop a sibling's lease and move the checkout at once. It now refuses with `a shared harness (capy-server, pid

) holds a lease m old; … (UPGRADE_BUSY)` until that lease is 120 minutes old. `GSTACK_UPGRADE_FORCE=1` still overrides. `gstack-lease live` keeps its meaning for the session start and the team-mode hook; only `gstack-upgrade` passes the new `--count-shared-harness` flag. +- **Fix hints after a skipped upgrade name the 120-minute wait or `GSTACK_UPGRADE_FORCE=1`** instead of a bare `bin/gstack-upgrade`, which on Capy now refuses while a lease is fresh. +- **The /autoplan reviewer prompt no longer says its install fast-forwards the checkout.** It clones when absent and otherwise uses the checkout as it is. + +### Changed +- **Documented: the bootstrapper still fast-forwards a checkout below the supported minimum, for a reviewer too.** Below it, every session's trailer on that checkout fails, and the minimum rises only for install-honesty or security fixes. A test locks this rule. + +## [1.91.360.0] - 2026-10-31 + +**A PR's changelog.d fragment no longer brings back every paid gate case.** Since fragments became the way every PR records its CHANGELOG entry (v1.91.342.0), the PR eval selector read each `changelog.d/.md` as an unknown dependency and restored the full gate, so it saved nothing on any PR (GST-400, found on #3668). + +### Fixed +- **`scripts/test-pr-profile.ts`** treats a `.md` file directly in the ship policy's `changelog_fragments.dir` as having no eval dependents. Other files in that folder, nested files, and a touchfile that names a fragment still select as before. +- **`test/helpers/test-selection.ts`** lists both paths of a renamed file, so moving a file into `changelog.d/` or `docs/` still selects the cases its old path fed. + +### Tests +- `test/test-pr-profile.test.ts` covers a fragment-only PR (no full fallback, no cases), other files in the folder, and a touchfile that names a fragment; `test/changed-files-union.test.ts` covers a rename. + +## [1.91.359.0] - 2026-10-31 + +**New `/verify` skill: run the repo's own checks and the tests `/ship`'s pre-gate would pick, fix what breaks, and repeat until green, then hand off to `/ship`.** `/verify` is the loop an agent runs while building. It never calls a change green when it cannot tell which tests cover it, and it asks once before running any repo command. It never reviews, bumps a version, pushes or opens a PR. GST-116, PR 1 of 2; moving `/health` onto the same detector is PR 2. + +### Added +- **`gstack-checks`** (`bin/gstack-checks`, `lib/checks.ts`) with four verbs. `detect` lists the checks the repo declares (a `gstack:verify:` line, then a `## Health Stack` section in CLAUDE.md, then package.json scripts, tsconfig, eslint or biome, pyproject, Cargo.toml and go.mod) and never makes one up. `run` runs them plus the tests pregate's own selector picks, under pregate's supervision, and prints one `CHECK ` line each with at most 40 failing lines. `trust` records consent. `status` prints `READY_FOR_SHIP tree=` from the last run and reruns nothing. +- **No false green.** A touched file with no test (`UNMAPPED`), a selection that ran zero tests (`ZERO_RUN`), more than 300 selected test files (`TOO_BROAD`), a timeout and a missing tool or service (`ENV`) are all not green. A tree that changes during a run reads `INCOMPLETE`. `status` is `NOT_READY` once the tree, the trusted commands, the base commit or the pregate policy moves. Platform lanes pregate owes remotely are listed as `not_covered`. +- **Consent covers every command a run could execute:** the checks, every package.json script, the pregate runner (or what it would detect) and each selection manifest command. Any change asks again, and nothing runs before consent. +- **`/verify` skill** (lightest preamble): `detect`, ask before `trust`, `run` after each change, fix reds in the code under test, stop after 5 runs, a repeated failure or an environment failure, send a stubborn red to `/investigate`, and finish on `READY_FOR_SHIP`. + +### Tests +- `test/gstack-checks.test.ts` covers detection, the verify-gate parity of the `gstack:verify:` parser, consent (including a changed selection command, refused before it runs), reds, unmapped and zero-run selections, partial runs, a tree moved mid-run and argument errors. +- `test/fixtures/skill-evals/verify/` adds six eval tasks (build error, failing test, lint only, a test that needs a missing service, a repo with no checks, a green tree) with shell postconditions. `test/verify-skill-eval.test.ts` checks for free that each seed gives the expected verdict, that a real fix passes, and that two decoys (a disabled check, a claim of green with no fix) fail. +- Catalog budget ceiling raised from 1,393 to 1,423 for the new skill row, by the new-skill ratchet in `test/catalog-budget.test.ts`. + +## [1.91.358.0] - 2026-10-31 + +**Diffs that touch money, gate, auth or secret code now get one more reviewer, a targeted reader with a short brief for that kind of code, and the /ship receipt records whether it ran (GST-257, part 1 of 2).** The merge queue reports the result and refuses nothing yet; enforcement comes in a later release. + +### Added +- **`lib/review-targeted.ts` names the classes a diff touches.** It reads added and deleted lines, so removing a spend cap, a check or a redaction counts. Money is a cost, spend, budget, ledger, billing, price, fee or invoice path, an identifier ending in `_usd` or `Usd`, any `spend_cap` spelling, or a call to a paid model provider. Gate is a hunk the gate scan tagged. Auth is `SCOPE_AUTH` on an auth, session, jwt, permission or role path. Secret is a secrets, credentials, keychain or token path, or a line that reads a key-named environment variable or a credential store. Matching is token-bounded, paths review depth counts as docs or tests never count (agent prose such as skill sections and docs/review-policy.md counts as code there, so it counts here too), and an input the classifier cannot read gives all four classes. +- **`gstack-review-plan` prints `TARGETED: classes=… rules=… brief=… targeted_patch_id=…`** and, when a class hit, `DISPATCH: targeted targeted effort=full` at every depth, light included. `--targeted-ran ` skips the reader only when the whole committed diff, tests included, is the one it already read. +- **`review/specialists/targeted.md` is the reader's brief:** one block per class, the blocking floor in one sentence, and the checklist's Forced-CRITICAL rule on uncapped spend in the money block. The reader is read-only, and `NO FINDINGS` is a result. +- **`gstack-review-dispatch render --role targeted --classes …`** renders the brief with only the blocks that hit; `verify --targeted-out ` writes the record (done only when the reader's output was collected and the committed diff it was rendered on is unchanged) `gstack-ship-receipt write --review-targeted @` stores as `review_targeted`, bound to the receipt's `product_patch_id`. A carry keeps it while the product patch is unchanged. +- **`gstack-ship-queue ready` and `train build` print `REVIEW_TARGETED: required=… receipt=… verdict=ok|missing`.** Nothing is refused on it in this release. + +### Precision +- Over the last 100 non-release commits on main (8663c3d2..8be7f213), money hit 21, gate 18, auth 3 and secret 8. The gate class first used the gate paths, which hit 43 of 100, so it was narrowed to the gate scan's tagged hunks; those paths already get full review depth. + +### Tests +- `test/review-targeted.test.ts` covers each class with deleted lines, token boundaries, the docs and tests exclusions, failing closed, the dispatch at light, standard and full depth, `--targeted-ran`, the path from `render` through the receipt, the review-loop summary and the queue line. Its dispatch-superset check runs `gstack-review-plan` on 18 fixture diffs and requires every reviewer main dispatched at 8be7f21, unchanged, plus only the targeted reader. `test/review-packets-removed.test.ts` repins `lib/review-depth.ts` and `ship/sections/adversarial.md` and pins the new brief to that check. + +## [1.91.357.0] - 2026-10-31 + +**pregate `literals` no longer flags a version-history table that the branch extended.** A test that keeps one row per past version of a constant (`[45, ""]`, then `[46, ""]`) used to fail `literals` on every bump, because the old row still holds the old value. Truther turned the check down to a warning over it, which also hid real stale tests. + +### Fixed +- `lib/pregate/checks/literals.ts`: a row that starts with the old value is skipped when the same table holds a new-value row the branch added (the file at the merge base lacks it). Only the row itself is exempt (the old value after its closing bracket on the same line still fails), and the scan continues to the next line holding the old value, so `expect(PROOF_CHECKS).toBe(45)` below an extended table still fails. A table the branch did not extend, a file that already held a new-value row at the merge base (read through a rename git detects), and a merge base that cannot be read still fail. +- docs/pregate.md describes the history-row rule and the table shapes it recognizes. + +### Tests +- `test/pregate-selection.test.ts`: an extended table, a newest-first table and a new file pass; an unextended table, a stale assertion below an extended table, an unextended table beside an extended one, and a table that already held the new row fail at the right line; string-valued and quoted semver histories pass; a stale assertion on the same line as a history row fails; a 20,000-row table is checked in linear time; and an end-to-end `gstack-pregate --only literals` run fails before the table is extended, passes after, and still fails for a renamed file whose table already held the new row. + +## [1.91.356.0] - 2026-10-31 + +**A reviewer's install no longer upgrades the gstack checkout a lane shares.** On a Capy machine, an /autoplan reviewer runs `install.sh --for review-voice` against the same checkout as the lane that dispatched it. Once the lane's workflow lease was more than 120 minutes old, that install fast-forwarded the checkout and rewrote the install verdict as `for=review-voice`. The lane's next workflow was then refused with `INSTALL_UNVERIFIED`. + +### Fixed +- **`--for review-voice` never self-upgrades the checkout.** When origin is ahead, the session prints `SELF_UPGRADE: skipped (review-voice never self-upgrades a shared checkout; fix: /bin/gstack-upgrade when no other session uses this checkout (UPGRADE_SKIPPED))`, leaves HEAD where it was, and the trailer stays ok with a `behind=` note. This holds with or without a lease, and `GSTACK_UPGRADE_FORCE=1` does not override it. If `bin/gstack-doctor-components.sh` cannot be read, the check still treats `review-voice` as a reviewer install. The bootstrapper still fast-forwards a checkout below the supported minimum. +- **`--check --for review-voice` names `bin/gstack-upgrade` as the fix** instead of the install rerun, which would not move a reviewer checkout. + +### Changed +- **The Captain's digest drops an archived thread from In progress in the same turn** (docs/captain.md, the DIGEST.md template and /captain). + +## [1.91.355.0] - 2026-10-31 + +**A driven `/ship` on Capy no longer pays one agent turn per finished reviewer, and it can count its own calls.** Replays of gstack-evals #34 and #36 (GSTA-167) made 30 to about 92 parent calls against a target of 12. In the 9-reviewer replay, 23 of 25 waits were the parent waking once per finished reviewer, because the driver told it to end its turn on `wait` while reviewers ran. What reviewers see, which reviewers run, their depth and the blocking floor are unchanged. + +### Changed +- **Readers are polled inside the program** (`ship/DRIVER.md`, Capy skill). A program returns 200 s after its first line and the next call resumes the poll; the parent never ends its turn while readers run. Capy polls with one `tools.subagent.list` per tick, starts readers a create call rejected once slots free, and reports a reader stuck for 20 minutes instead of dropping it. `wait` (now 200 s) is only for tests, pregate and CI when no reader runs. Lanes, pregate and `finish` run in the background. +- **A program returns at most 32 KB**; longer reads such as `review-army.md` split at headings, each byte once, before first use. Phase 2 used to return about 98 KB of sections at once, and truncated reads cost extra calls. +- **A fix runs as one gated program**: the failing test, the fix, `--tests-only` and the next pass, each only if the last step passed. Step 7's audit, which may write tests, settles before the review pass reads the tree. +- **An unattended `push` defers the one-time pre-push guard offer** (`REDACT_PREPUSH: … deferred=unattended`) instead of stopping. It writes no marker and installs no hook, so the next interactive session still gets the offer. + +### Added +- **`gstack-ship-budget calls --events `** counts a run's parent calls from the host's transcript items: `CALLS: total= decision= keepalive= idle_gaps_over_300s= max_gap_s=`. A wait, or a program that only reads status (plus at most one bash for its note), counts as a keep-alive. + +### Fixed +- **`gstack-ship-budget note --step 9.1`** records under step 9 with the sub-step as its label. Before, it was refused, and replays lost two notes to that error. +- **`gstack-review-scope render`** accepts `{"deferred": [...]}` as well as the bare array. +- **`gstack-review-dispatch judge`** treats a judged line with no severity, or `"severity": null`, as invalid and prints `JUDGMENT_REJECTED`. Before, it crashed with a TypeError, and a replay spent three calls recovering. +- **The Capy skill passes a rendered brief as bash `cat` prints it.** A file read cut the long lines of a 231,589-byte outside-voice brief, so `sent` reported `BRIEF_MISMATCH` and the reader had to be sent again. + +## [1.91.354.0] - 2026-10-31 + +**On Claude Code, `/land-and-deploy` loads about 15 KB less skill text per session.** Step 7's canary instructions (the canary script, third-party dashboard actions, Aside setup and the browser fallback) moved out of `land-and-deploy/SKILL.md` into an on-demand `sections/canary.md`, which the skill reads only when it reaches the canary step or a browser or third-party site action. `SKILL.md` drops from 51,992 to 32,216 bytes. Codex and Factory renders inline every section, so they stay about the same size. In a paid before/after run (Opus 5.5, 10 tasks, 3 trials per arm; GSTA-161), mean loaded skill bytes fell from 109,334 to 93,828 (-14%), the pass rate held (after 97%, before 80%, a second before panel 87%), and mean cost per session stayed flat. Pass rates are graded on the transcript. These numbers are exploratory, from one eval suite. + +### Changed +- **`land-and-deploy/sections/canary.md`** holds the post-deploy canary procedure; the routing paragraph stays in `SKILL.md`. Shared resolvers are unchanged. + +### Tests +- `test/fixtures/skill-evals/land-and-deploy/` adds a 10-task eval suite (happy path, CI-red override, conflicts, already merged, dirty checkout, first run, deploy success and failure, canary without a browser, Render hook) with a `gh` stub and a state check per task. +- Size, parity and section-loading guards re-pinned for the smaller skeleton and the new section. + +## [1.91.353.0] - 2026-10-31 + +**`/ship` Step 12 now has a way through for repos whose unit PRs never change VERSION, and an unattended `/ship` no longer writes a version bump nobody approved.** On gstack-evals (no policy file, so `bump: ask`), `--keep-current`, `--version 0.0.1` and `--accept-incomplete` all stopped with `BUMP_LEVEL needed` (gstack-evals#85), and on gstack-evals#89 an unattended run took the recommended level and wrote 0.0.2 before anyone was asked (GST-380). + +### Added +- **`"bump": "never"` in `.gstack/ship-policy.json`** for a repo whose unit PRs never version. Step 12 prints `VERSION: kept (policy: bump never; no write)`, asks nothing and refuses `--bump`; a branch that moved VERSION stops until it is put back. `gstack-restamp --next` then needs an explicit `--bump` or `--version`. The value needs `min_gstack_version` at its introducing release and cannot be combined with `queue_mode: stamp-at-merge`, `train` or `changelog_fragments`, which stamp a version at every merge. + +### Fixed +- **`gstack-ship-release version`**: on a branch whose VERSION still equals the base, `--keep-current` and `--version ` print `VERSION: kept`, write nothing and read no queue. Passing `--bump` with either stops and names the conflict. The `BUMP_LEVEL needed` stop now names `--keep-current` too. +- **No version write before the owner answers.** Under `bump: ask`, when `gstack-session-kind` reports anything but `interactive` (unattended, spawned, OpenClaw, headless or CI), a Step 12 call that would write a version stops with `BUMP_ANSWER_REQUIRED` and writes nothing until it is rerun with `--answer ""` (one line, at most 200 characters). This covers a FRESH `--bump` and a `--version` rewrite of an already bumped branch. `bump: patch` is a standing answer and needs no `--answer`. `ship/DRIVER.md` lists the stop as an approval, so a brief's "take the recommended option" no longer answers it. + +## [1.91.352.0] - 2026-10-31 + +**gstack now knows particle-1 and has measured it on its own tasks.** particle-1 (Particle AI, October 28, 2026) passed 15/15 cells on a preregistered five-task panel, the same as Sonnet 5.5 and Opus 5.5, at $0.007 per task against Sonnet 5.5's $0.037 (run `2026-10-30-0105`, Claude Code through OpenRouter). The panel is easy, so it shows no measured difference between the models, not that they are equal. Results and every cell are in [docs/evals/particle-1-2026-10.md](docs/evals/particle-1-2026-10.md). + +### Added +- **particle-1 and DeepSeek V4.1 Flash in the price table.** `lib/pricing.ts` prices `particle-1` ($0.25 input, $0.03 cached, $1.00 output per million tokens) and `deepseek-v4.1-flash-1017`; provider-prefixed ids such as `particle-ai/particle-1` resolve to them. +- **`gstack-model-benchmark --models particle,deepseek`** runs those models in Claude Code through OpenRouter (`OPENROUTER_API_KEY`). The child process gets no Anthropic credential, every Claude Code model alias is pinned to the arm's model, and a run that billed any other model is an error. `/benchmark-models` lists both and says what they send to OpenRouter. +- **A preregistered model panel** (`test/skill-e2e-model-panel.test.ts`): five gstack-shaped tasks, four models, three trials, each cell scored by a hidden check and priced from its own tokens. It runs on demand, not in the weekly eval run, because CI has no OpenRouter key. + +### Changed +- **particle-1 counts as the DeepSeek family** for outside-voice independence, because Particle built it on DeepSeek V4.1 Flash. A particle-1 voice is never treated as independent of a DeepSeek one. +- **One provider registry** feeds the benchmark CLI, its dry run and the runner. + +### Fixed +- **`--models` with no valid provider now exits 1** instead of quietly running claude. + +## [1.91.351.0] - 2026-10-31 + +**Four skill-eval check commands that gstack-evals' Lane A vendors as graders no longer pass runs that break their rule.** gstack-evals' grader audit (GST-374) showed that one agent-written `.gitignore` could hide new code from the /office-hours no-code check, and that three smaller gaps let other checks pass on the wrong files. + +### Fixed +- **office-hours/no-code-session** lists untracked files with `--exclude-from=.git/info/exclude` instead of `--exclude-standard`, so a `.gitignore` the agent writes no longer hides anything. Only the seed's own exclude entry (`.gstack-home/`) still applies. +- **learn/no-code-change** also fails on a new untracked file under `app/`. Before, `git diff --quiet HEAD -- app` saw only tracked files. +- **learn/add, prune-stale and prune-conflict** read the seeded project's `learnings.jsonl` (the slug `seed.sh` derives from the work dir) instead of `projects/*`, so an extra project folder can no longer satisfy them. +- **The eight office-hours design-doc checks and backend-skips-visual** first require `.gstack-home` to be a real directory and not a symlink. `find` does not descend into a symlinked start point, so a swapped state root used to hide every design doc and mockup. + +### Gate integrity +- These are grader edits that only tighten. Each check now fails runs it passed before, and no threshold, trial count or task was removed. The new `test/skill-eval-checks.test.ts` seeds each task with its own `seed.sh`, then runs the committed check after an honest action (it must pass) and after each hole (it must fail). On the old checks, all 15 hole cases passed the check and all 15 honest cases passed too. gstack-evals relocks its vendored copies from this commit. +- `test/skill-eval-checks.test.ts` joins the `BASELINE` in `test/test-of-test-ratchet.test.ts`. It imports no product module because no gstack module runs these check commands; the commands themselves are what it tests. + +## [1.91.350.0] - 2026-10-31 + +**`/ship` review costs less and catches more: one batched specialist, a blocking floor in both prose voices, and data files that no code reads review as docs (GSTA-167 variant G).** The no-loss replay certified the stack before merge. Round 5 replayed 14 PRs with 29 known blockers, and the new reviewers found 24 against the control's 21, non-inferior at p=0.035. Round 6 pooled 41 blockers (the 29 plus 12 confirmed units from GSTA-2): 33 against 27, non-inferior at p=0.0055. The free re-score for the classifier and state-matrix change lost 0 blockers. + +### Changed +- **One batched specialist reads every checklist at each depth.** It always reads Testing and Security on code and gate diffs, and adds State-machines, Data-migration, API-contract and Design when scope asks for them. Maintainability, Performance and Simplification run only when forced, and `gstack-review-plan` names them on a `SKIP:` line. The Red Team reads the batched reader's merged findings. +- **Specialists run at medium reasoning effort.** The Red Team, the native adversarial pass and the fix-check stay at full effort. `--no-tiers` (or `review_effort_tiers off`) runs specialists at the host default. +- **Both prose voices carry the blocking floor.** The native adversarial and outside-voice prompts say a finding blocks only if it would fail a test, break production, or lose data or secrets, and end each finding with `Severity:` and `Blocks: yes|no`. A finding is CRITICAL when its old label rule says so or it says `Blocks: yes`, and `Blocks: no` never lowers one. `gstack-review-dispatch collect` records a `Blocks: yes` finding as CRITICAL, so `judge` refuses a lead judgment that keeps it below the floor. +- **A JSON, CSV, TSV or raster data file that no code names counts as docs, not runtime lines.** `classifyDiff` finds code consumers with `git grep`; YAML, TOML, SVG and config files stay code, and path-only callers (the receipt's gate scan, the release route) keep data files code. `gstack-ship-preflight`'s `RUNTIME_LINES` now comes from the same function. +- **An untested state-matrix cell is a test gap below the floor.** A wrong row or collapsed kinds stays CRITICAL, and the state-machines checklist itself is unchanged. + +### Fixed +- **`gstack-review-dispatch render --checklists` takes the plan's checklist names** as well as paths, and refuses an unknown one. The outside-voice brief no longer adds a separate severity line, since the prompt now asks for Severity and Blocks itself. +- **`collect` keeps one finding per id in the layout the prompts ask for.** A `Severity:` or `Blocks:` line below a finding joins that finding, an inline `Blocks: yes` with no label still collects as CRITICAL, and the native voice's FIXABLE collects as CRITICAL even beside a lower `Severity:`. When the layout is unclear, `collect` merges findings rather than dropping one. +- **The data-file consumer scan reads `git grep` the same way under any git config.** `grep.lineNumber`, `grep.column` and `color.grep` no longer hide a consumer, and a failed scan keeps every data file code with `consumer_scan_failed`. + +### Tests +- `test/prose-voice-floor.test.ts` renders both prose prompts for the claude and codex hosts and checks the floor sentence and the Blocks line. `test/review-depth.test.ts` covers the batched reader on the captured fixtures, effort per role and the data-file rule. `test/review-dispatch.test.ts` covers `Blocks: yes` collection and batched checklist names. `test/review-packets-removed.test.ts` repins the changed briefs to their no-loss replays (PR-a, G1, L). + +## [1.91.349.0] - 2026-10-31 + +**Nine flaky tests from the 2026-10-30 flaky pass stop failing correct runs.** Two paid detectors missed correct replies, one paid case lost the evidence of its own failure, five free tests raced their own fixtures or paid a cold start inside a timed call, and two Windows failures came from real defects: a lost IPC receipt in the QA deadline worker and a Chromium feature that fails loopback connections. + +### Fixed +- **`lib/qa-deadline.ts`**: the receipt worker waits for the parent to acknowledge each receipt before it exits. Bun can drop an IPC message the parent has not read yet when the child exits, so on Windows `gstack-qa-deadline run` and `gstack-qa-evidence` could return the exit code without the `finished` receipt (Windows Free Tests 40991662945, `test/qa-deadline.test.ts:431` received one of two receipts). A receipt still unacknowledged after the existing 5 s write wait makes the worker exit 2, as an unwritten receipt did before. +- **`patches/playwright-core@1.62.1.patch`**: backports microsoft/playwright#43605, which disables Chromium's `TcpPortRandomizationWin`. On Windows it fails loopback page loads with `net::ERR_NO_BUFFER_SPACE` even when ports are free (`browse/test/cookie-picker-ui.test.ts`, Windows Free Tests 40656299153 and 41056150287). gstack's own browser launches on Windows had the same exposure. +- **`test/helpers/qa-only-cleanup.ts`**: the cleanup check reads the daemon state file once and treats a file deleted during shutdown as absent, instead of checking that it exists and then reading it (Free Tests 40964422549: ENOENT on `browse.json`). +- **`test/claude-code-runner.test.ts`**: the liveness helper counts a process in the `X` (being reaped) state as dead, like `Z`, and the cleanup no longer kills a pid that is already gone (Free Tests 41034844588: ESRCH). +- **`test/helpers/free-owned-browser-settlement.ts`**: in the `cancel-vanishing-record` case the fake daemon waits for the observer to remove its record before it exits, so the race the case injects always happens (Free Tests 40924799742). +- **`test/investigate-freeze-path.test.ts`**: the E1 cases pay the first bash and JSON interpreter start once, in an unasserted warm-up, before the timed hook calls. In four Windows runs (40824965988, 40917695070, 40985163846, 40996480693) only the file's first hook call hit the 15 s kill, the second took 1.9 to 7.9 s and the rest 0.3 to 1 s. Each timed call keeps its 15 s kill. + +### Gate integrity +- **ship-unmanaged-hook-consent** (`test/helpers/ship-hook-actor.ts`): the decline check also credits "no hook/change/file was installed, changed, modified, overwritten or replaced". Gate 41005113772 said "No hook was installed or changed" and "nothing was overwritten" after a correct decline; its installs, hook bytes and question checks all passed. The four negative controls still fail. +- **tpa-absent-darwin** (`test/helpers/third-party-actions.ts`): the Aside download pitch also counts in the passive voice at a clause start ("Aside ... can be downloaded at aside.com", gate 40987391676). Reported and mid-clause forms still count zero, and so does a clause with "not", "no", "never" or "n't" before the phrase. + +### Changed +- **autoplan-guard-pty** (`test/helpers/autoplan-guard-pty.ts`, `test/skill-e2e-autoplan-guard-pty.test.ts`): a `dispatch_prompt` deny prints each Agent dispatch's length, first differing offset and context next to the prompt the actor had to copy, read before cleanup deletes it. Gate 40992022983 lost those bytes because the journal summary cuts inputs at 160 characters. + +### Tests +- New captures: `test/fixtures/ship-hook-consent-2026-10-30.json` and a passive-voice capture in `test/fixtures/third-party-actions-pitch-captures.json`; both tests fail with their detector change reverted. `browse/test/playwright-core-patch.test.ts` checks the backport in the patch and the installed tree, and fails without it. `test/autoplan-guard-pty-fixture.test.ts` checks the dispatch delta on a synthetic journal. `test/qa-deadline.test.ts` plays the parent, so it now acknowledges each receipt; its assertions are unchanged, and a new case shows a worker whose parent never acknowledges exits 2 after sending both receipts. + +## [1.91.348.0] - 2026-10-31 + +- **Pregate now maps tests to dotfiles they name.** A test that reads `../.gitleaks.toml`, `.gitleaks.toml` or `join('.github', 'workflows', 'ci.yml')` used to get no edge to that file, so a branch touching only the dotfile ended in `PREGATE_NO_LANE`. Quoted literals may now start with a dot, and a dot-led literal that isn't `./` or `../` resolves from both the repository root and the folder of the file that names it, so a fixture's own `.github/` keeps its edge. A literal still forms an edge only when it names a file in the repo, so strings like `'.ts'` add nothing. On gstack this adds 179 edges (`buildGraph` over this repository: 16,934 on main 2127729, 17,113 with this change, none removed), all to real dotfiles such as `.github/workflows/*.yml` and `.gstack/*.json`. (GST-246, reported from garrytan/truther#956.) + +## [1.91.347.0] - 2026-10-31 + +**A Captain archives only its own crew's threads (R39, amended). A thread outside every crew belongs to the owner and stays as it is, even when the Captain's own automation created it.** + +### Changed +- **docs/captain.md and the Capy factory context (`factory.md` point 12)** now say a Captain archives only the threads in its own crew, each when its plan for that thread says the work is done. No Captain archives, flags or lists a thread outside every crew for archiving unless the owner asks. The earlier wording also let a Captain archive threads its automations started outside the crew, and that emptied the owner's unattached threads. + +## [1.91.346.0] - 2026-10-31 + +**`sealed.local_path` now flags a home path inside a shell default, `${UBI_RUNNER:-/home/…}`, as it already flagged the same path after `?? "/home/…"` in TypeScript.** gstack-evals `quick/laneb/runner/launch.sh:9` passed the scan because the `-` before the path counted as part of a word (#3568). + +### Fixed +- **`sealed.local_path`** (`lib/sealed-guard.ts`): a home path directly after a `${…:-` or `${…-` default now matches, for a name, an array element (`${arr[0]:-`, a subscript of up to 64 characters, so a long line of unclosed `${a[` cannot make the scan quadratic), an indirect name (`${!ref:-`), a positional number or a special parameter (`${@:-`). `:=`, `:+` and `:?` already matched, because `=`, `+` and `?` were never word characters. A hyphen anywhere else still excludes the match, so a path glued to a word (`docs-…`, `$VAR-…`, `${VAR}-…`) stays unflagged; docs/pregate.md lists that as a known limit. + +### Gate integrity +- This is a gate edit that only tightens. The guard now refuses lines it passed before. No existing test, threshold or allowlist changed. A new case in `test/sealed-guard.test.ts` covers all five operators, a positional parameter, `${@`, an array element, an indirect name, a Windows path and the TypeScript `??` form. It also checks six negative controls, which are two hyphenated paths, a hyphenated sentence, `$VAR-`, `${VAR}-` and a relative default. Without the fix it misses every `-` form. + +## [1.91.345.0] - 2026-10-31 + +**A capped `/ship` on Capy now spends fewer agent turns and counts only its own tokens, while every reviewer still gets exactly the brief 1.91.331.0 gives it.** Two new commands do `/ship`'s fixed shell work, a short driver file replaces reading the whole skill when a parent agent runs `/ship`, and the budget measures each reviewer batch on its own instead of across the parent's work. Replays of gstack-evals #34 and #36 (GSTA-167) spent 12.19M tokens on Steps 12-17 and 0.25-0.4M on each parent turn; these changes cut turns, not reviewer context. + +### Added +- **`gstack-ship-preflight`** runs Steps 1-3 (branch guard, status, fetch, diff stat, PR and receipt carry, scope, base merge, distribution, policy, runtime lines) and Step 5 (pregate, then the test lanes in parallel) in one call. **`gstack-ship-release`** runs Step 12's version, Steps 15-16's release commit and verification, and Step 17's push. Each prints at most 30 lines; `STOP:` names the decision left to the agent and `NEXT:` the step to run. Under `queue_mode stamp-at-merge` or `changelog_fragments` the version step prints `VERSION: skipped (policy: ...)` and writes nothing; under `changelog_fragments` its `NEXT:` line names the branch's own fragment, and `finish` commits that fragment as release metadata. +- **`ship/DRIVER.md`**, a compact host-neutral driver for a parent agent running `/ship` unattended: one or two calls per phase, and the section each STOP needs. Its audit, review, adversarial and documentation phases run their sections as written, so it never restates or shortens a reviewer's brief. +- **`gstack-review-dispatch`** gates every `/ship` reviewer brief and finding. `render` builds a reader's brief from its section with only declared slots filled, `sent` checks the prompt a dispatch passed against that brief by sha256 (`BRIEF_MISMATCH` voids the review), `collect` is the only way findings reach `merged.jsonl` (each with its label as written), and `judge` refuses a judged set that drops or downgrades a collected finding. `verify --ledger` replays all of it per pass from the run's ledger and prints `VERIFY: clean` only when nothing was lost; a mismatched send that was re-sent exact before anything was collected shows as `voided=N`. +- **Small runs keep their segment.** `check --runtime-lines ` continues at the Step 9 and Step 12 boundaries with a `SMALL_RUN:` line when the diff has at most 50 runtime lines and the segment would cost less than a child's fixed startup. + +### Changed +- **The Capy meter reads the agent's own thread**, its subagents included, inside the same program as the budget command, never in a call of its own. A handoff child counts from its own `verify-handoff` reading, and `reconcile` charges the `used=` its return prints. +- **Steps are priced at the run's own per-call charge** once three calls are measured; a prior reading older than the run's last reading is ignored (`CALL_UNKNOWN:`). +- **A reviewer batch is measured only by its own program's reading pair** (`settle --dispatched-at --reading --readers `); anything else prints `UNMEASURED:` and leaves the factor alone. `check` prints the reservation id alone on a `RESERVATION_ID:` line, a multi-role reservation admits one review start per role, and `--finish` settles a later Red Team batch of the same pass. +- **A handoff brief lists the child's `READ:` line ranges**: its own steps of `ship/SKILL.md` and each of its sections whole, and names the last step it returns at. +- **The Capy launch file appends the checkout's `bin/` to PATH**, so a bare `gstack-ship-budget` resolves. + +### Fixed +- **A failed child stops its parent** until a regenerated child reconciles complete or the owner resumes, and `reconcile --record` finds the parent run after a `--continue` child. +- **`close` counts review starts reserved in handoff children**, so a dispatch reserved inside a child is no longer flagged as unreserved at the root. +- **A dependency or script change after review is re-reviewed.** `gstack-ship-release finish` counts package.json and package-lock.json as release metadata only when the version alone changed, never counts bun.lock, and decides after any `--build` runs. TODOS.md edits rerun the test lanes. +- **`push` stops when the sealed-output guard could not run**, not only when it refuses. + +### Tests +- `test/review-packets-removed.test.ts` now also pins the reviewer briefs, checklists, fix-check prompt and depth rules by content, so a change to what a reviewer sees fails until its no-loss replay is recorded. + +## [1.91.344.0] - 2026-10-31 + +**A PR that moves its CHANGELOG entry into `changelog.d/` keeps its /ship receipt (GST-343).** Since #3654 turned on changelog fragments for gstack, a base merge that moved a PR's `[Unreleased]` entry into `changelog.d/.md` made `gstack-ship-receipt carry` refuse with RECEIPT_CARRY_PRODUCT_CHANGED. The PR then needed a new review pass for a changelog edit. + +### Fixed +- **Carry counts a changelog fragment as release metadata** (`lib/ship-receipt.ts`, `bin/gstack-ship-receipt`). When the base policy sets `changelog_fragments`, each `

/.md` directly under the directory is metadata, as `CHANGELOG.md` is. The directory's README.md, a nested path, a non-Markdown file and a fragment under a policy without `changelog_fragments` stay product. docs/ship-policy.md lists the fragment under release metadata. + +### Tests +- `test/gstack-ship-receipt.test.ts`: a merge-only head that moves the entry into `changelog.d/feat.md` carries as "base merge + release metadata". A README edit in the same merge is refused and named, and so is the same move when the base policy has no `changelog_fragments`. + +## [1.91.343.0] - 2026-10-31 + +**Every ask to the owner now uses one lettered format (R41): the Captain's name, then one line per decision with the problem, the options and the recommendation, so the owner can answer "do it" or a letter like "B2" from a phone. When the owner has to do something, the ask links the exact page and lists the steps (R43).** + +### Changed +- **The plan ask lists each gate choice as a lettered line** (`lib/captain-brief.ts`, `gstack-owner-brief render --captain`): "What we need from you" prints one line per choice with the recommended option first and the plan approval as the last letter. The header and the closing line invite **do it** or a named option, and a new `--captain-name ` heads the list. The relaying agent's last line maps every letter to its gate token next to `rec resolves to …` and says a named option answers as `rec except `, so a reply like "B2" translates exactly. A plan that is missing a section still invites no reply. +- **An ask that needs the owner to do something carries the exact link and simple steps (R43).** The ask format says so: the full URL of the page where it happens (never a menu path like "Settings → Tokens"; a Capy app page gets its exact path and field), numbered steps saying what to click and type, and the one word to reply when done. `docs/captain.md`, `plan-ask.md`, `merge-ask.md`, `captain/SKILL.md` and `factory.md` point 11 carry it. +- **docs/captain.md has a new section, The ask format**, and the plan ask, the controller's relay and the digest's Needs you point to it. The captain templates (`plan-ask.md`, `DIGEST.md`, `merge-ask.md`, `AGENTS.md`, `report.md`), `captain/SKILL.md`, the Capy gstack skill (`SKILL.md`, `captain.md`, `factory.md`) and `docs/recommended-harness.md` state the same format. + +### Tests +- `test/captain-brief.test.ts`: lettered lines with the recommendation first and "A1 to take recommendation", the letter-to-token map, the `--captain-name` heading, carried answers in the lettered lines, and no reply invitation on a plan that is missing a section. + +## [1.91.342.0] - 2026-10-30 + +**gstack now versions its own PRs at merge time: a PR adds `changelog.d/.md` instead of a version, and trains merge through `train land` instead of slot calls.** `.gstack/ship-policy.json` turns `changelog_fragments` on with the checks every PR runs as `required_checks`, and `min_gstack_version` moves to 1.91.340.0, the first release that reads `required_checks` and counts a stamped slot as merged only when GitHub reports it MERGED, so an older gstack refuses the file by name. + +### Changed +- **`changelog_fragments` is on for gstack** (`.gstack/ship-policy.json`, `changelog.d/README.md`): `required_checks` lists `free-tests`, `windows-free-tests`, `Check VERSION is not stale vs queue`, `quality`, `check-freshness` and `actionlint`. Path-filtered workflows stay out of the list, because a stamp commit of a PR outside their paths never gets those checks. +- **`CHANGELOG_FRAGMENTS_KEY_VERSION` is 1.91.336.0**, the version #3594 landed at, in place of the placeholder 1.92.0.0. +- **/captain teaches `train land`**: under `changelog_fragments` there is no slot call; the controller runs `gstack-ship-queue train land` per slot in order (`captain/SKILL.md.tmpl`, `docs/skills.md`). + +### Fixed +- **A stacked PR whose only own line sits inside its released parent's list merges its CHANGELOG instead of refusing** (`lib/changelog-check.ts`): `mergeChangelogs` filed the line as an addition to the parent's released entry and returned null, so #3613's slot needed a hand resolve. When that would leave the child nothing of its own, the inserted lines are now the child's entry; on #3613's real CHANGELOGs the result equals the resolve that shipped. + +### Tests +- `test/changelog-merge-damage.test.ts`: a child whose only own bullet sits at the top of the released parent's `### Changed` list keeps it as its entry and passes `ownEntryAboveMain`; a child with no line of its own, a reordered parent bullet and a duplicated one stay null. +- `test/gstack-ship-policy.test.ts`: every `required_checks` name is a check a pull_request workflow without a path filter reports (a job's `name:`, or its id when it has none), and `min_gstack_version` is at least the key's introducing version. + +## [1.91.341.0] - 2026-10-30 + +**gstack no longer leaves Ubicloud VMs running after a lane dies (GST-118).** A runner killed mid-run, a copy of the runner without a TTL, or a VM with no owner could keep billing until someone noticed. Now every VM names its owner and its lifetime, the next `up` anywhere destroys anything past its lifetime, and every run says in one line whether its VM is gone. + +### Fixed +- **`scripts/ubicloud/ubi-runner.sh`**: `up`, `run` and `verify` refuse without `UBI_OWNER` (`UBI_OWNER_REQUIRED`), so no VM is created that nobody can name. The default TTL drops from 4 hours to 3 (`UBI_TTL_HOURS`, 1-999), checked only when a VM is created, so an old setting never blocks `down` or `reap`. `reap`, which every `up` runs first, now also destroys the caller's own `ubirun--*` VMs that carry no TTL (made by older runner copies) once they are 4 hours old (`UBI_LEGACY_HOURS`). Another owner's TTL-less VM, an untagged one and names outside the `ubirun-` prefix are never touched, because only a TTL lets reap judge another lane's VM. +- **`UBICLOUD: left=<0|1|unknown> owner= vm= others=`**: `run` and `verify` end with this line, checked against the project's VM list after teardown. Anything but `left=0` turns a passing command into exit 1 and prints the `down` command to run; `run --keep` prints `left=1 ... kept=1` and keeps its exit status. +- **`scripts/ubicloud/pregate-remote.sh`**: the remote pregate refuses without `UBI_OWNER` (`PREGATE_REMOTE_OWNER_REQUIRED`), names its VM with a TTL taken from its own stop deadline plus 15 minutes (`-t1` at today's 2,700-second timeout), and fails with `PREGATE_REMOTE_INFRA` unless the runner reports `left=0`. It reads that line from the file named by `UBI_LEFT_FILE`, never from the remote command's output. +- docs/TESTING_INTERNALS.md, docs/pregate.md, docs/skills.md and the `/ubicloud` skill describe the owner rule, the new TTL default, the legacy sweep and the `left=` line. + +### Tests +- `test/ubicloud-runner.test.ts`: refusal without an owner, the TTL bounds, the legacy sweep at the default and at `UBI_LEGACY_HOURS=2` (never another owner's, an untagged or an owner-less caller's), `left=0`, `left=1` on a failed destroy (with a failing command keeping exit 7), `run --keep`, and read-only commands accepting an old `UBI_TTL_HOURS=0`. +- `test/ubicloud-pregate-remote.test.ts`: the owner refusal, the `-t1` TTL at today's timeout, and `left=1`, `left=unknown` and a missing line each failing closed with the `down` hint. + +## [1.91.340.0] - 2026-10-30 + +### Changed +- **A stamped train counts a slot as merged only when GitHub reports its PR MERGED** (`lib/ship-queue-train-verify.ts`, #3603): for a stamped train, `train land` refuses to confirm a PR GitHub reports open even when main's tree is its S_i (`QUEUE_PROOF_MISSING`), and the merged count, the freeze decision and the freeze record read every slot's GitHub state instead of trusting the record's `merged` entries. Plain trains are unchanged. + +## [1.91.339.0] - 2026-10-30 + +**Merge trains can stamp every slot themselves under `changelog_fragments`: `train build` builds a stamped prefix for each slot and `train land` publishes it, so no lane stamps a PR by hand.** gstack's own policy still leaves the key off (docs/ship-policy.md#changelog-fragments). + +### Added +- **Stamped merge trains** (`lib/ship-queue-train-stamp.ts`, `lib/ship-queue-train-land.ts`): under `changelog_fragments`, `train build` also builds S_i = stamp(merge(S_(i-1), pin_i)) for every slot, checks each is the merge modulo stamps, keeps every earlier release entry byte for byte and equals the plain prefix outside release paths (`QUEUE_TRAIN_STAMP_MISMATCH`), refuses a symlinked release file before stamping, and gates S_k. `train land --train --pr ` publishes slot i's S_i exactly. It makes a deterministic stamp commit on [pin, main], journals it before it is pushed under the pin's lease with the `evals-no-debounce` label, waits for checks, merges with `--match-head-commit` and confirms main's tree; a rerun adopts its own stamp head, a PR retargeted off the base refuses, and any other main freezes the queue as before. It first verifies the whole record against git (T0 and S_1..S_k must be the gated head's first-parent chain, each S_i's second parent slot i's pin) and uses only that chain, and it merges only when every name in the new `changelog_fragments.required_checks` is present and green on the stamp commit. `verify --train` refuses a stamped train and names `train land`; `train bisect` of a stamped train tests T0 and S_1..S_k. + +### Changed +- **The main backstop covers a stamped train's merges by exact tree** (`scripts/train-backstop.ts`, `scripts/train-gate.ts`): a record's S_i prefixes cover main only when its tree is exactly S_i; plain T_i prefixes still cover modulo stamps. +- **A train merge keeps a pin's manifest edits** (`lib/ship-queue-train.ts`): a `package.json` or lockfile conflict against the previous prefix merges three-way with the prefix's version (the same `mergeManifest` land uses) instead of taking the prefix's whole file; anything else that conflicts is a train conflict. +- **Version Gate reads a stacked child's stamp commit by its own fragments**: a parent's fragment the base has already released is skipped rather than counted again. + +### Tests +- `test/ship-queue-train-stamp.test.ts`: S2 keeps S1's release and runs the versions in order with each slot's bump; a stacked child folds only its own fragment; a four-part package.json base keeps four parts in every S_i, read from S_(i-1); a pin's manifest edit beside the version line survives the previous slot's bump; a symlinked CHANGELOG refuses before anything is written outside; a tampered earlier version or a product change is refused. +- `test/ship-queue-train-land.test.ts`: build records S1 and S2 and gates S2; land publishes each slot exactly with the label; a foreign push is never overwritten; a merge outside the train freezes the queue; a failed stamp commit pushes nothing; a rerun after the push or after the journal resumes; a retargeted PR refuses; a red stamped train bisects its stamped chain; a plain train refuses `train land`. +- `test/train-backstop.test.ts`: main equal to S1 is covered; the same tree with another VERSION is gated; a chain mixing stamped and plain prefixes is refused. +- `test/version-gate-fragments.test.ts`: a stacked child's stamp counts only its own fragment once its parent has landed. + +## [1.91.338.0] - 2026-10-30 + +**A sealed-guard waiver now counts only when it names the full commit sha.** A `.gstack/sealed-allow.tsv` line used to accept a sha as short as 7 hex characters and waive any commit whose sha started with it. A PR author could generate a commit with the same first 7 characters in minutes and publish different content at the same path under an old, reviewed waiver. A waiver now matches only the finding's full commit sha (40 hex characters, 64 in a SHA-256 repository). A shortened, uppercase or mistyped sha is ignored, so the finding still refuses, and stderr says which line was ignored and which commit the finding is in, to review before anyone waives it. + +### Changed +- `lib/sealed-guard.ts`: waivers compare the whole commit sha; `gstack-pregate sealed --json` adds `ignoredWaivers` (rule, path, the sha as written, the finding's commit) for waiver lines that name a finding's rule and path but not its commit, once per line and commit. Lines that match no finding, and waivers that applied to another commit in the push, stay silent. +- The refusal hint, the `SEALED_OUTPUT_REFUSED` fix text, docs/pregate.md and docs/troubleshooting.md say the sha must be the full commit sha. + +### Tests +- `test/sealed-guard.test.ts`: 7-, 12- and 39-character prefixes, an uppercase sha and one extra character do not waive and are named; the full sha waives, trailing whitespace included; another commit's full sha does not waive; a short line with no matching finding prints nothing; a waiver applied to one commit is not reported for a later one; a text rule with two matching lines names a short waiver once; a SHA-256 repository accepts 64 characters and rejects 40, 63 and 65; error reports carry an empty list. The two existing waiver tests now write the full sha. + +## [1.91.337.0] - 2026-10-30 + +### Changed +- **Plan first has two narrow fix exemptions.** An S1 emergency (a broken install or upgrade, a red main, a security bug) and a fix from a problem list that was already diagnosed and audited can be built without an `/autoplan` run. Every other fix, a one-line bug fix included, gets a one-round, eng-only plan. `docs/captain.md` § Plan before build says how, and `captain/SKILL.md`, `captain/templates/CREW.md` rule 24 and the Capy skill's SKILL.md list the same exemptions. + +## [1.91.336.0] - 2026-10-30 + +**A repository can now assign its version when a PR merges instead of inside the PR: PRs carry unversioned CHANGELOG fragments and `gstack-ship-queue land` stamps, pushes and merges.** Today every PR picks a version before it merges, so each merge makes the next PR's version stale and its lane redoes the stamp (a median 14.5 minutes from stamp commit to merge over 30 slots, Oct 27-29; the queue froze on hand-made stamps in #3422 and #3487). With `changelog_fragments` on, two PRs cut from one base cannot collide, and nobody stamps by hand. gstack's own policy does not turn it on in this release (docs/ship-policy.md#changelog-fragments). + +### Added +- **`changelog_fragments: { dir }`** (`lib/ship-policy.ts`, `lib/changelog-fragments.ts`): a PR adds `/.md` with its entry text and optional `bump: minor|major` front matter. Fragments are read as Git blobs only; a symlink, gitlink, nested path, empty or oversized fragment, one with a release heading, a reused name, or one whose text is already released on the base (a parent PR's fragment carried in by stacked history) is `CHANGELOG_FRAGMENT_INVALID` before any version is allocated. +- **`gstack-restamp` folds fragments**: their bodies go above any legacy `[Unreleased]` section under one new heading, the files are deleted, and the highest declared bump wins over the policy's. The tree receipt's `changelog-fragments` rule accepts exactly that fold and nothing else. +- **`gstack-ship-queue land --pr `** (`lib/ship-queue-land.ts`): the per-PR merge step. It takes the land lock (`refs/notes/gstack-land`), checks the /ship receipt, the READY receipt and checks at the pin, merges the base resolving release fields only (a clean dependency edit survives; a product conflict refuses), stamps, pushes a commit with parents [pin, base] under an exact lease, waits for checks, restamps if the base moved (at most twice), squashes with `--match-head-commit` (merges with `--merge` under `history: merge-only`) and confirms the base tree. A PR whose base is another branch refuses before the lock; a refusal before the push releases the lock. Every step is journaled and resumable, also from the stamp commit's pin when the local journal is gone. `--repair` opens the follow-up PR after `QUEUE_LAND_DRIFT`; `--census` prints what land would do with every open PR, writing nothing. +- **/ship writes the fragment** (`lib/ship-policy.ts`, `ship/SKILL.md.tmpl`): under the key, `show-effective` prints a `ship: changelog_fragments` line, so Step 12 writes no version and Step 13 writes `/.md` (linted with `gstack-prose-lint --gate`) instead of an `[Unreleased]` section; the skill's policy paragraph now says its `ship:` lines bind Steps 12–16. +- **`restamp_command` gets `GSTACK_RESTAMP_BASE_SHA`**, the release predecessor, so a repo counter such as a SAVE_VERSION computes predecessor + 1 from the base and never from the branch. +- New result codes with troubleshooting anchors: `CHANGELOG_FRAGMENT_INVALID`, `QUEUE_LAND_LOCKED`, `QUEUE_LAND_CONFLICT`, `QUEUE_LAND_DRIFT`, `QUEUE_LAND_BASE_BUSY`. + +### Changed +- **Version Gate runs on every PR** (the path filter is gone), so under `changelog_fragments` a PR that touches no release file still proves it carries a fragment. An unstamped head keeps its release fields at its merge base and adds a valid fragment (legacy `[Unreleased]` passes; a `[bot]` author needs none); a merge-step stamp commit must have parents [pin, base] and carry the base plus its fragments' effective bump, so a lane that stamps its own head fails. Without the key nothing changes. + +### Tests +- `test/changelog-fragments.test.ts`: blob-only reads and refusals, a carried-back fragment refused on whole released lines only, bump precedence, fold order with a legacy section, the restamp fold and its tree receipt, an edited fold refused. +- `test/ship-queue-land.test.ts` (bare origin and a gh shim): happy path; two PRs from one base without a collision; a legacy stamp plus a dependency edit; a title-derived entry; a product conflict; the lock and `--break-lock`; the base moving during CI; a foreign push never overwritten; a missing receipt; drift, `--repair` and the lock release; the census; a receipt that fails #3567's depth check refuses; a base with a four-part package.json in `stamp_files` lands four parts (#3557), gstack's own shape stays three; one run without `--no-wait` merges; a PR on another base refuses; `--break-lock` refuses a drift lock; a conflict releases the lock; a stacked parent's fragment refuses; a lost journal resumes; `merge-only` merges with `--merge`; a merge GitHub completed behind an error reply reconciles; `--break-lock` refuses a holder mid-merge; `--repair` resumes after a failed PR create and its PR takes over from a clean checkout; a symlinked legacy VERSION refuses in `--dry-run`; a `package.json` version source keeps its dependency edits. +- `test/version-gate-fragments.test.ts`: fragment heads, premature version changes, a bot author, an advanced base, an invalid fragment, the stamp commit's effective bump (open version claims do not apply to it), and the workflow's missing path filter. +- `test/restamp-command-boundary.test.ts`: the hook reads its counter from `GSTACK_RESTAMP_BASE_SHA`, not the branch. + +## [1.91.335.0] - 2026-10-30 + +### Fixed +- **Captains now read factory.md and the owner's model preference.** A Capy session with no gstack checkout (every Captain and coordinator, which run `install.sh --check --for none`) used to skip factory.md without a word and never applied `agent_model`, because both were read only from the checkout. The skill now tells it to read the `factory.md` beside SKILL.md, to say `factory.md: none` on its own line when there isn't one, and to read the `agent_model` line of `preferences.yaml` itself. Owners get the fix by copying `capy/skill/gstack/` into the Drive skill folder. + +## [1.91.334.0] - 2026-10-30 + +**OpenClaw opens gstack's large task skills again (GST-110).** #3555 made `hybrid` OpenClaw's default and registered review, investigate, qa, ship and plan-eng-review as skills of their own. OpenClaw 2026.10.6 serves a registered skill's `SKILL.md` whole or refuses it, with a 32,768-byte limit when its model catalog has no context window for the model. In HARN-5's panel the agent's first read of the 77,691-byte `gstack-review` file was refused in 4 of 5 trials, and opens fell from 5/5 to 0/5. Under the router layout the same file had been read as a plain file inside the router's folder, which OpenClaw pages. + +### Fixed +- **`gstack-harness register openclaw`** (`lib/harness-register.ts`): a skill whose rendered `SKILL.md` is over 32,000 bytes (`OPENCLAW_INSTRUCTION_MAX`, under both OpenClaw's 32,768-byte limit and the 32,000-character budget it applies with a 100K-200K-token context window, with the OpenClaw source lines it comes from) is registered as a short entry with the same frontmatter whose body says to read the skill's full `SKILL.md` in a plain copy of every skill and follow it. In hybrid that copy is the router's `gstack/skills/`, where the router layout read the same file, now including the five task skills; under `--skills all` it is `.gstack-skills/`, a folder OpenClaw's skill scan skips. Because the copy holds every skill, `sections/` paths and sibling paths such as `../gstack-qa/` and autoplan's `../gstack-plan-eng-review/SKILL.md` resolve to full texts. That covers four of hybrid's five direct skills and 26 of 63 skills in `--skills all` today. OpenClaw treats only a registered skill folder's `SKILL.md` as an instruction file. The ledger records the copies, so refresh, mode switches, upgrades from a #3555 registration and uninstall handle them. Skill bodies are unchanged, and Hermes, dots and `generic` registrations are byte-identical. +- docs/hosts.md and docs/OPENCLAW.md describe the entry and the limit, and docs/uninstall.md's manual OpenClaw removal command also removes `.gstack-skills/`. + +### Tests +- `test/harness-register.test.ts`: in hybrid and all, every `SKILL.md` OpenClaw would register is within the limit, each entry names a full `SKILL.md` that exists, has the same frontmatter, is outside OpenClaw's registered set and is in the ledger, every `../gstack-*` path in the copied texts resolves to a full text, re-registering over a #3555 registration converts it cleanly, and uninstall leaves nothing. Hermes's registration equals its render byte for byte. With `GSTACK_OPENCLAW_BIN` or `openclaw` on PATH, a real `openclaw skills list --json` and `skills info` show exactly `gstack` and the five task skills, each served from an entry within the limit. + +## [1.91.333.0] - 2026-10-30 + +**`gstack-factory-scorecard --now` now ends the window, so a past week no longer counts what happened after it.** Every line counts only items whose timestamps fall in `[now - since-days, now)`. Before, `--now` moved only the start, so `--now 2026-10-15T00:00:00Z --since-days 14` counted 290 merged PRs (every merge from 2026-10-01 through the day of the run) where the window holds 65, and the gate-run and release lines also counted through the day of the run. Rerun with the fix, the two weeks before 2026-10-15 show 65 merged PRs and the two weeks before 2026-10-29 show 197, matching GitHub search for both windows. + +### Fixed +- **`lib/factory-scorecard.ts`**: one window (`scoreWindow`, `inWindow`) bounds merged PRs and their lead times, gate runs and their cost, the red-train rate, flaky events, free-suite retries, issues and releases. The workflow-runs query asks GitHub for the window's days (`created=..`), and the issue searches use a closed time range instead of `>=start`. Releases are read to the last page, because GitHub orders them by creation and a draft can be published long after it was created, and a PR, gate-run or release read that runs past 20 pages now marks its line unavailable instead of printing a partial count. +- **`scripts/lib/ci-history.ts`**: `listWorkflowRuns` takes an optional `until` (exclusive), compares both ends of the window as instants and skips a run whose `created_at` does not parse; `createdFilter` builds the runs API's `created` query for both callers. +- **`docs/recommended-harness.md`**: "Where gstack's own numbers stand" is remeasured for the exact week of 2026-10-19 through 2026-10-25 UTC: 83 merged PRs (not 103), median lead time 6.5h, 54 gate runs (52 green, 2 red), $1,361.94 of known gate cost, 17 paid flake records across 11 cases, 0 releases. The earlier figures came from a run before this fix, so they counted past the end of the week. + +### Tests +- `test/factory-scorecard.test.ts`: a PR merged exactly at `--now`, and a gate run, free run and release after it, are left out; the runs and issue queries carry the window's end. A sub-second `--now` keeps the issue search range inside the window, releases behind a full page of newer ones are found, a release published late is found on a later page, and a PR, gate-run or release read past the page cap is unavailable. + +## [1.91.332.0] - 2026-10-30 + +**gstack can remember which model you want your agents on, and every Capy session now reads a one-page summary of how crews work.** Set `agent_model` once (`opus`, another family, or an exact `provider/model`) and `gstack-models resolve --role agent` returns it whenever an agent picks a model for a lane, subagent or reviewer. Unset, every agent keeps its own model, and gstack takes no position for or against any model. A cross-family outside voice and a model under test in an eval ignore the preference on purpose. On Capy the preference lives in `preferences.yaml` beside the gstack skill in your Drive, so it survives fresh machines without being copied anywhere. + +### Added +- **`gstack-models resolve --role agent [--request ]`**: the agent role. A one-job request wins and is never saved, then `agent_model` in this machine's config.yaml, then the preferences file, then `host`. Output names the winner, both stored values and the exemptions; `list` gains an agent block and `list --json` a top-level `agent` key, with `selections` unchanged. +- **`agent_model`** in `gstack-config`, checked with the same grammar as the resolver: `host`, a family (`opus`, `fable`, `sonnet`, `haiku`, `astra`, `sol`, `luna`, `terra`) or `/`. A bad value stops only the agent role, naming the file and the fix; plan-review, implementation and eval-arms keep resolving. +- **`capy/skill/gstack/factory.md`**: thirteen practices the Captain crews converged on, each pointing at the rule it summarizes, at most 3,300 bytes. SKILL.md's session start tells every session to read it once. + +### Changed +- The Capy session start (`bin/gstack-capy-session`, which updates with the checkout) points `GSTACK_PREFERENCES_FILE` at `preferences.yaml` next to the Drive skill's SKILL.md, and the installer writes it into the launch file. `--check` never writes the skill folder, and the frozen Drive bootstrapper is unchanged. +- SKILL.md allows exactly one write in the skill folder: `preferences.yaml`, when the owner asks an agent to remember a preference. +- `docs/model-policy.md` gains "Your model preference". `docs/captain.md` links factory.md, says to forward an owner's rule for every Captain, in the same turn, to the thread that keeps the account's shared rules, and says the Captain archives its own child threads by its plan for each, including ones its crew or automations started. + +## [1.91.331.0] - 2026-10-30 + +**`/ship` and `/review` go back to the reviewers they used in 1.91.325.0, because the newer reviewers missed real blockers.** In 1.91.326.0 (#3621) each reviewer started reading one prepared packet of the diff instead of reading the diff and the code around it, and the parent read a short findings record. 1.91.330.0 (#3636) let packet reviewers read a little beyond their hunks. A replay of 14 merged PRs (GSTA-167 no-loss round 3) then showed that the old reviewers find 19 of the 30 known blockers, and the packet reviewers, even with the looser reading rule, found only 10 of those 19 (the replay's counting rule favored the old review, and the packet reviewers also found 2 blockers it missed, but the preregistered bar allowed 1 miss and they had 9). So reviews run with gstack 1.91.326.0 through 1.91.330.0 are not as thorough as the review before them, and a PR reviewed on one of those versions may still hide a blocker the old review would have caught. + +If you use gstack through Capy, copy `capy/skill/gstack/` over your Drive skill folder again after upgrading, because the copy from 1.91.326.0 tells `/ship` to run `gstack-review-packet`, which this release removes. A `/ship` run that started on 1.91.326.0 through 1.91.330.0 should be restarted after the upgrade for the same reason. + +### Removed +- The packet reviewers: `bin/gstack-review-packet`, `lib/review-packet.ts`, `lib/review-packet-collect.ts`, `lib/review-plan-live.ts`, `lib/review-prompts.ts`, their tests, the reading rule #3636 added for packets, and the two size-ledger entries that paid for them. + +### Changed +- The specialist dispatch, reviewer prompts and findings collect in `ship/sections/`, `scripts/resolvers/`, `bin/gstack-review-plan`, `lib/review-collect.ts`, `docs/review-policy.md`, `docs/ship-budget.md` and `docs/troubleshooting.md` are back to what 1.91.325.0 shipped, byte for byte. Everything else that landed since then stays, including the Capy README, the ship-queue screen change and the pregate always-run list. + +### Tests +- The reviewer briefs rendered for one sample diff at 21ad261 and at 1.91.325.0 (dcd62c3) were identical when checked once by hand; no test repeats that comparison. `test/review-packet.test.ts` goes away with the code it tested, and the tests #3621 edited return to their 1.91.325.0 text. +- `test/review-packets-removed.test.ts` (new) fails if any removed packet file comes back or any tracked file other than this CHANGELOG still names one or the packet-only anchors and codes, so a branch cut before this revert cannot merge a dangling call to them. It is on `.gstack/always-run.json`, so the selected pregate runs it on every code branch. + +## [1.91.330.0] - 2026-10-30 + +**/ship reviewers now check a suspected defect against the code it depends on before they report it or let it go.** A reviewer packet used to allow at most two more ranges of up to 200 lines, from files in the diff, in one turn. In GSTA-167's no-loss replay, 7 recorded blockers needed context outside those ranges, and no reviewer found them. Each reviewer now confirms or rules out a suspected defect by reading the callers and callees of changed functions, the tests that cover them, and the config and contracts they read. It uses grep and the read tool, at most 8 reads in at most 2 turns of parallel calls. The coverage audit keeps its own budget. + +### Changed +- **Reviewer read rule** (`lib/review-prompts.ts`): `READ_BUDGET`, which every specialist, Red Team, adversarial, outside-voice and fix-check packet carries, and the packet brief (`packetBrief`), which now allows two read turns before the write. +- `docs/review-policy.md` (reviewer packets), `capy/skill/gstack/SKILL.md` (/ship reviewers on Capy) and the generated ship sections (review-army, adversarial, test-coverage) say the same. + +### Tests +- `test/review-packet.test.ts`: the batched specialist, Red Team, adversarial and fix-check packets carry the rule; the coverage audit keeps its own budget; the rule names callers, callees, tests and contracts with its read and turn bound; the Capy skill and the policy match it. +- `test/size-ledger/ship/gsta-167-review-reads.json`: 108 bytes for the longer brief, rendered three times in the ship sections. + +## [1.91.329.0] - 2026-10-30 + +**A selected pregate now runs the whole-tree tripwires and ratchets on every code branch, so they fail before review instead of in CI.** #3592 and #3593 passed their selected gate and then failed CI on exactly these scanners, because no touched file maps to a test that reads the whole tree. + +### Added +- **`.gstack/always-run.json`** (`{ "tests": [globs] }`): whole-tree tests that join the `lanes` selection whenever a branch selects any test, owes a lane, or edits the list. `--explain` prints each as ` (always_run, .gstack/always-run.json)` and a glob that matches nothing as ` matches no test file`. A docs-only branch adds nothing. A missing file means an empty list; a malformed one stops the check with a message naming the file. gstack's list names 15 tests (tripwires, ratchets, env-host fence conformance, free-fixtures, bun-entry-isolation, egress wiring); `host-conformance`, which runs `./setup`, stays off it. +- docs/pregate.md has a section on the file and why it is separate from `pregate.json` (older readers reject unknown keys there). + +### Tests +- `test/pregate-always-run.test.ts`: a code change adds the scanner the import graph never selects, and not without the file; a docs-only branch adds nothing; an edit to the list runs it and owes no lane; malformed lists stop; gstack's own list names only tracked tests and includes the GST-98 scanners. + +## [1.91.328.0] - 2026-10-30 + +**Most PRs no longer pay for a solo paid screen before the merge train runs the same cases.** `gstack-ship-queue ready` used to recommend `--screen` whenever a diff touched a skill's own cases, which is almost every PR, and the screens (16 to 19 a day at about $32 each) cost more than the train gates that rerun all 137 cases a few hours later. Of 41 full screens between Oct 20 and 29, the 3 that caught a real bug all came from diffs the selector can't narrow (an unknown dependency or a shared runtime input). The recommendation is now `--screen` only in that case; every other PR rides unscreened and the train gate's full census covers it. Because most PRs now ride unscreened, a train also stopped holding them back, so unscreened PRs fill the seats a screened PR leaves. + +### Changed +- **Screen recommendation** (`lib/ship-queue-train-ready.ts`): `--screen` when the paid selector's mode is `full-fallback` or the selector cannot select; otherwise `--no-screen`. The `SCREEN:` lines name the selector's mode and reason. +- **Slot order** (`lib/ship-queue-train.ts` `orderSlots`): screened PRs first, then unscreened PRs fill the remaining seats in READY order. The rule that built a screened-only train and held every unscreened PR once `max_size` of them waited is gone, along with its `HELD: … (unscreened PRs form their own train)` line. `--order` still overrides. +- **Train replay model** (`lib/gate-cost-history.ts` `pickTrain`) seats trains the same way. +- **Not in this change:** a focused paid run of a no-screen PR's own cases, bound to its READY receipt, needs a new `screen_policy: own` route in evals.yml (GSTA-165 1b, deferred). The matching rule 22 text in `captain/templates/CREW.md` is also deferred, as is a train-record field that attributes a red train to the PR that caused it, which the trigger for reverting this default needs (GSTA-165 v2 item 6). + +### Tests +- `test/ship-queue-train-logic.test.ts`: one screened plus five unscreened at size 5 seats five; a full unscreened pool at size 3 seats three; a skill-template diff recommends `--no-screen`; a `bun.lock` diff recommends `--screen` with its full-fallback reason. These tests failed before the change. Two more pin the diffs that still screen. A diff that mixes a skill template with `bun.lock` recommends `--screen`, and a diff the selector cannot select recommends `--screen` with the full gate selection. `test/ship-queue-train.test.ts` and `test/gate-cost.test.ts` change their ordering expectations on purpose. + +## [1.91.327.0] - 2026-10-30 + +**A new page shows how gstack and Capy run as a software factory, with measured numbers.** `capy/README.md` explains how Capy Captains, their crews and gstack's skills fit together, from the plan-first approval loop and `/ship` before READY to merge trains, fix waves, the daily flaky pass and peer Captains. It compares the 14 days after 2026-10-15 with the 14 days before: 197 PRs merged to gstack's main against 65, and 194 versions shipped against 62. It also says what those numbers leave out. The median PR shrank from 1,292 changed lines to 422, and the median time from opening a PR to merging it grew from 1.1 hours to 5.6, because trains batch merges. A footnote gives the windows and the method behind every figure, and the page ends with tips and how Garry uses the setup day to day. + +### Docs +- **`capy/README.md`**: the new page (how the pieces fit, the measured before/after, why we think it works, tips, and how Garry uses it). +- The documentation table in `README.md` and the introduction of `docs/captain.md` link to it. + +## [1.91.326.0] - 2026-10-30 + +**/ship reviewers now read one packet file each, and the parent reads a findings record of at most 60 lines instead of every reviewer's transcript.** On this PR's own /ship, pass 2's eight reviewers cost 8.6M tokens on the root counter, against 52.6M for pass 1's eleven (pass 2 read the fix range, pass 1 the whole diff, so the two are not directly comparable). + +### Added +- **`gstack-review-packet build`** writes one packet per `DISPATCH:` line of the review plan: the role's instructions and findings contract, its checklists, that reviewer's diff, a plan excerpt, a read budget and the output path. Steps 7 and 8 audits, the specialists, the Red Team, the fix-check and Step 11's adversarial pass and outside voice all dispatch this way. A packet over 200 KB is split by path; no hunk is cut and no path is dropped. Audits are never split. +- Each `PACKET:` line names its `budget_role` and `read=` line ranges of at most 30,000 bytes, and build prints `BUDGET_NEXT: dispatch:` for `gstack-ship-budget check --next`. A reviewer reads its packet with parallel range reads and finishes in about three calls. +- **`gstack-review-packet collect`** parses, validates and dedupes every reviewer's output, prints one line per reviewer plus each CRITICAL, and writes `merged.jsonl` and `informational.md` for the PR body. Missing or unusable output exits 3 with `REVIEW_COVERAGE_INCOMPLETE`. + +### Changed +- Every reviewer prompt lives in `lib/review-prompts.ts`; the resolvers import it, so a packet and the generated SKILL.md prose cannot drift. /review's generated output is unchanged. +- Large `.json`, `.jsonl`, `.ndjson`, `.csv` and `.tsv` changes (over 400 changed lines, not package or config manifests) reach reviewers as a summary built from the diff alone. The testing reviewer and the coverage audit still read data under `test/` or `fixtures/` in full. +- The Capy dispatch paragraph in `capy/skill/gstack/SKILL.md` builds packets, starts reviewers on the shared machine, polls with `transcript: "none"` and returns only collect's output. + +### Fixed +- `--base origin/main` no longer becomes `origin/origin/main` in audit prompts. +- A partial build keeps other reviewers' results only at the same head, diff base and diff content; a Red Team build against a changed tree refuses with `STALE_MANIFEST`. +- Collect counts a state-machines matrix record only from the state-machines reviewer, and a CRITICAL line that fails to parse or validate makes its reviewer invalid instead of disappearing. + +### Tests +- `test/review-packet.test.ts`: 41 tests covering packet contents, sharding, audits, budget roles, read ranges, data summaries (including a symlinked CSV that must not leak its target), stale manifests and collect's validation. Each fix in this entry has a test that failed before it. + +## [1.91.325.0] - 2026-10-30 + +**A capped /ship on Capy no longer delegates or stops just because the host's own prompt is big, and a delegated child hands off instead of stopping.** A fresh Capy call costs 150-230k before any /ship work, so the 100k start and 150k segment thresholds fired on every capped Capy start and stopped two gstack-evals #36 children at their first boundary. The thresholds now measure context above a calibrated per-host call floor. + +### Fixed +- **Thresholds sit above the host call floor.** `lib/ship-budget-calibration.json` gives each meter a `call_floor` (Capy 150k, Claude Code 40k, estimate 0); `start --call-floor ` overrides it and children inherit it. `BUDGET:` and `STOP:` lines print `call_floor=` and `above_floor=`. +- **A child never stops on the context rule.** After a completed step it hands its remaining steps to a grandchild through the same handoff, verify, return and reconcile commands (chain depth 3 at most). Before its first completed step, at the maximum depth, or past its segment it continues with one `CONTEXT_HIGH:` line. The admission cap still stops it. +- **A delegated child cannot return complete with work left over.** `return` reports `status=incomplete` with `UNRECONCILED:` or `DROPPED:` lines while one of its own grandchildren is unreconciled or a batch remainder was never re-checked. + +### Changed +- **Parallel reviewer batches near the cap admit the largest prefix that fits** (`ADMIT: k of n (remaining=)`) instead of refusing the whole batch; each reader is priced at the larger of its projection and the run's measured mean for that role. `close` flags remaining roles nobody re-checked (`DROPPED:`, `status=incomplete` until the owner accepts). + +### Tests +- `test/ship-budget-chain.test.ts` replays #36 (a child at its first boundary continues) and covers the Capy floor, grandchild handoff at depth 2, the depth-3 cap, charging a chained return once on all three meters, and the incomplete return. `test/ship-budget-batch.test.ts` replays #35's 7-reader batch near the cap. + +## [1.91.324.0] - 2026-10-29 + +**A /ship token cap now projects each step and reviewer from what the run has actually spent, so real caps stop refusing work that costs a fraction of the old guess.** On GSTA-152 a 29.28M cap refused its third reviewer because every dispatch was projected at 7.43M while real ones cost 0.23 to 1.02M; on GSTA-2 an 8M cap stopped before Step 6 after Steps 1 to 5 cost about 0.27M each, because every step was projected at 2.25M. + +### Fixed +- **`gstack-ship-budget check`** projects steps and dispatches with the run's own factor once it has measured one: the largest actual/prior ratio of its last three measurements, times 1.5. Before the first measurement the calibrated prior applies, as before. The default tail reserve scales with the step factor; the stop overhead and an explicit `--reserve` do not. +- **Reviewers admitted one at a time no longer stay reserved.** `check --returned ` settles the reviewers that came back, `gstack-review-log --finish` settles every dispatch reservation of its step, and a check that moves to the next step settles the dispatches of the step before. `settle` takes `--reading`. +- Charges the meter cannot see (`settle --unknown`, a Claude-metered outside voice) are booked at their reservation and never measured, so they cannot shrink the dispatch factor. +- `gstack-ship-budget handoff` holds back the same calibrated reserve as `check`, so a `verdict=delegate` is always one the handoff admits. + +### Changed +- The `BUDGET:` line adds `calibration=step:,dispatch:`. Each measured reservation prints `DRIFT: … projected= actual= ratio=`, and `close` prints `BUDGET_DRIFT:` totals. docs/ship-budget.md has a Calibration section. + +### Tests +- `test/ship-budget-projection.test.ts` replays GSTA-2 (an 8M cap now reaches Step 6.5 and still stops with room to stop) and GSTA-152 PR B (the 29.28M refusal is admitted and the run stops before the cap), and covers the settle points, unseen charges and the delegate/handoff boundary. The first 8 tests failed at ad8e12d; the 3 review-fix tests failed at f30c33f. + +## [1.91.323.0] - 2026-10-29 + +### Tests +- `test/review-depth.test.ts`: the #19 shape plans fix-check, Red Team and native adversarial; full depth, a fail-closed classification, `--depth-floor full`, a 151-line, missing or unread range and a gate-touching fix keep the full pass; a forced specialist and changed numbers keep their reviewers; 150, 151 and a docs-only range; the scoped pass counts toward the cap and a blocker it leaves stops; `DEPTH_RULES` moves with the constant. +- `test/review-plan-cli.test.ts`: `--range-base` plans `NEXT: scoped`; a 151-line range, no range, an unknown base and uncommitted fixes plan full. +- `test/review-scope.test.ts`: `raised_by` from the explicit field, the specialist tag or `unknown`. +- `test/ship-receipt-depth.test.ts`: the queue binds a receipt whose pass 2 was scoped. + +### Gate integrity +- Addition to the 1.91.316.0 entry below: **Pass 2 after a blocking fix now reviews the fix in proportion to its size.** When pass 1 fixed a blocking finding on a diff below full depth and the fix range has at most 150 runtime lines, /ship runs a scoped pass: one fix-check, the Red Team and the native adversarial pass on the range, instead of the specialist army. On gstack-evals#19 a 3-file fix range (+18/-6) was planned for nine reviewers. Full depth, `--depth-floor full`, a fix that touched a gate path, a larger range, or a range it cannot read keeps the full pass 2. The two-pass cap and the stop for the owner are unchanged. +- Addition to the 1.91.316.0 entry below: **`gstack-review-plan --range-base `** (`lib/review-depth.ts`): counts the committed fix range `..HEAD` the way the depth counts runtime lines, prints `FIX_RANGE: runtime_lines=|unread () base=` (`fix_range` in `--json`), and `NEXT: scoped` when the scoped pass applies. `nextStep` takes the depth and `History.rangeRuntimeLines`; `SCOPED_RANGE_LINES` (150) joins `DEPTH_RULES`, so `rules=` changes. `REVIEW_PLAN:` ends with the step's `reason="…"`. Uncommitted or untracked edits, a range base that is not an ancestor of HEAD, an empty range, and a range the classifier cannot count all plan the full pass. A full pass 1 always gets a full pass 2: `--pass1-depth` carries pass 1's `REVIEW_DEPTH` (absent counts as full), so a fix that reverts a gate, auth, migration or gate-tagged edit cannot lower pass 2. The fix range is classified with its own `gstack-diff-scope` and `gstack-gate-diff` input, and a gate-class range plans the full pass and sets `fix_range.touched_gate`. +- Addition to the 1.91.316.0 entry below: **Scoped dispatches**: the fix-check, every force-included specialist, the Red Team, the native adversarial pass when the range changes runtime lines, and the outside voice when published numbers changed. Step 11's voices that have not run yet stay listed. A light diff's raise to standard applies to the scoped set only. +- Addition to the 1.91.316.0 entry below: **Step 9** (`ship/sections/review-army.md`): the repeat decision passes `--range-base $PASS_HEAD` and maps `NEXT: scoped` to decision 3; a scoped pass logs a full-pass `review` row with `"scope":"scoped"`, so it counts toward the cap and its roles land in `review_loop.dispatches` with no receipt schema change. +- Addition to the 1.91.316.0 entry below: **`raised_by` on classified findings** (`gstack-review-scope classify`, `lib/review-scope.ts`): the reviewer that raised each finding (`core`, `qa`, a specialist, `red-team`, `adversarial-native`, `outside-voice`, `fix-check`), from the finding's `raised_by` or `specialist` tag, else `unknown`. Step 9 copies it into the review-log row. Older rows without it still summarize. +- Addition to the 1.91.316.0 entry below: **Docs**: docs/review-policy.md (rule 3, the transitions table, a scoped-pass section and Behavior changes) and docs/ship-policy.md rule 3. + +## [1.91.322.0] - 2026-10-29 + +**A PR screen no longer runs the whole paid gate just because a changed file sits on every case's import path.** Editing a file like `lib/restamp.ts` reached all 113 gate cases through the derived-reference closure, so 19 of the 41 full screens between Oct 20 and 29 ran the full $33 gate for that reason alone. A narrow screen (`gstack-ship-queue ready --screen`, and `bun run eval:bg:pr`) now leaves such a file's cases to the train gate's full census, which runs every case before anything merges. Replayed on those 41 screens with today's maps, this saves about $457 a week, and the screens that caught real PR-caused reds (#3434, #3453) still run the full gate. + +### Changed +- **Narrow screens** (`scripts/test-pr-profile.ts`, `scripts/lib/paid-select.ts`): a changed file whose derived references reach every gate case and that nothing narrower selects is a hub file. On a narrow screen it selects no case or judge; the paid plan's reason and the coverage summary name it and say the train gate runs those cases. Full-gate files, shared runtime and build inputs, paid-runner inputs, files the derivation cannot place and files deleted by the PR select exactly what they did before. `ready --screen --broad`, `pull_request` runs (the merge gate when the base has no `train` block), the train gate, `eval:bg:gate`, periodic and release runs are unchanged. +- **The READY screen preview** (`lib/ship-queue-train-ready.ts`) and the per-push screening summary now show the narrow screen's selection. +- **`test/size-ledger/**`** is a touchfile of the 20 cases that read `test/helpers/size-ledger.ts` (all periodic or marathon), so a size-ledger baseline change no longer restores the full gate. `careful/bin/mask-commit-message.awk`, loaded only by the free-tested `check-careful.sh` hook, is free-only. + +### Tests +- `test/pr-dependencies.test.ts`: a hub-only diff selects nothing on a narrow screen and every gate case on a broad one or with no policy set; a hub beside a shared runtime input, an unknown file or a full-gate file still runs the full gate; a hub beside a direct edit keeps that edit's cases; a deleted file is never a hub; the PR workflow plans narrow only for dispatches; size-ledger baselines select no gate case. + +## [1.91.321.0] - 2026-10-29 + +**Free Tests passes again on Ubicloud runner image 20261026.1.0.** Every Linux job that landed on that image failed the cookie-import Playwright pipe smoke, in-shard and again on the serial retry, and a rerun passed only when it happened to land on the older 20261021.1.0 image. Both images keep `kernel.apparmor_restrict_unprivileged_userns=1`, but 20261026 loads three AppArmor profiles instead of 123, so nothing grants the bundled Chromium a user namespace and its sandbox aborts with `credentials.cc:131 ... Permission denied`. The two Linux jobs that launch Chromium now grant user namespaces to that one binary, the way Ubuntu's own `chrome` profile does. + +### Fixed +- **`.github/workflows/free-tests.yml`**: `free-suite` and `quick-bun-default` gain a step after the SUID sandbox helper step. It resolves Playwright's Chromium, refuses any path outside `~/.cache/ms-playwright/chromium-*/chrome-linux*/chrome`, and loads an AppArmor profile that grants `userns` to that path alone. The kernel restriction stays on for every other binary. The SUID helper step is unchanged, and no step passes `--no-sandbox` or runs `sysctl`. Diagnostic dispatch 40921806393 ran 17 jobs: all 9 on 20261026 failed the smoke without the profile and passed with it, and all 8 on 20261021 passed throughout. + +### Tests +- `test/chromium-sandbox-ci.test.ts`: four cases, two per job, run the real step with stubbed `bun` and `sudo`. They check that the step sits after the helper and before the suite, the exact profile bytes and the `apparmor_parser -r` call, that no protection-lowering flag appears, and that an unexpected Chromium path is refused before any privileged call. They fail against main's workflow. + +## [1.91.320.0] - 2026-10-29 + +**A branch that adds its own pregate lane now learns why it still fails, and `gstack-post pr-body` no longer keeps a stale copy of a section.** Pregate reads its policy from the base branch so a branch cannot loosen its own gate. A branch that had already declared a lane in its own `.gstack/pregate.json` was still told to declare it, and went round in a circle. Separately, a PR body that held `## What changed` twice (an old description pasted under the /ship body) kept the old copy every time /ship reposted. + +### Fixed +- **`PREGATE_NO_LANE`**: when the branch edits `.gstack/pregate.json` and the policy comes from the base copy or the user-owned file, the fix line names that policy, says a lane the branch adds counts only once it is on the base, and offers both routes: land the policy change in its own PR first, or rerun with `--policy-from head --allow-repo-commands`, which records the run as unreviewed. Pregate still never reads the branch's policy on its own. (#3574) +- **`gstack-post pr-body`**: when the PR's current body holds a title from the file more than once, it posts nothing, exits 64 and says to rerun with `--replace` and the whole body. /ship's PR-body step stops on that refusal and reports the duplicated titles instead of reposting with `--replace` itself, since a person chooses which copy stays. (#3575) + +### Docs +- `docs/troubleshooting.md#pregate-no-lane-own-policy` explains the own-policy case and its two routes; `docs/pregate.md`'s trust boundary links it. The `gstack-post-pr-body-merge` entry covers the duplicate-title refusal. + +### Tests +- `test/pregate-selection.test.ts`: the own-policy fix line under the base policy; a head-policy run and a branch that deletes `pregate.json` get the plain fix. +- `test/pregate-user-policy.test.ts`: the own-policy line names the user file as the policy source. +- `test/gstack-post.test.ts`: a doubled title refuses and posts nothing, `--replace` posts the file, and a body with two receipt blocks refuses too. + +### Gate integrity +- `test/gstack-post.test.ts`: the duplicate-titles assertion that expected the first copy replaced and the second kept now expects the refusal, plus a case where duplicates the file does not touch are still kept. + ## [1.91.319.0] - 2026-10-29 **`gstack-pregate sealed` no longer prints a line that reads like a push confirmation.** On gstack-evals#29 the lane read `pushed aeb2413` in the `SEALED:` line as the push landing, while the remote stayed at 9036ab1 (#3565). `sealed` never pushes: it checks the commits a push would publish. `pushed ` was its label for the commit whose `sealed` policy it read beside the base branch's. diff --git a/CLAUDE.md b/CLAUDE.md index d896a3064..d425dc6e7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -148,7 +148,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,393 today; each new skill ratchets it); and +`CATALOG_BUDGET_TOKEN_EQUIVALENTS` (1,423 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 d2c84855a..715592905 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -190,8 +190,8 @@ the new defaults. | Check an ordinary edit quickly | `bun run test:quick` | Free, about a minute | Bun 1.4.2 | | Run one free test file while repairing | `bun test ` | Free, seconds | Never bare `bun test` for the suite | | Run full free acceptance before publishing | `bun run test` | Free, a few minutes | Bun 1.4.2 | -| 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` | -| Clear pregate's test tier on a machine under 8 cores ([remote gate](docs/pregate.md#remote-gate)) | `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`; keyless: nothing | +| 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 ([remote gate](docs/pregate.md#remote-gate)) | `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) | Free | Windows, Git Bash | | 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 | @@ -428,7 +428,7 @@ eval files, and misses the strict classifier. No API keys needed. - **Generator tests** (`test/gen-skill-docs.test.ts`) — Tests the template system: verifies placeholders resolve correctly, output includes value hints for flags (e.g. `-d ` 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,393 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 1,423 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` and `adm-zip` version floors, load Sharp, verify ordinary ZIP extraction, and reject extraction through destination-file and destination-directory symlinks. The symlink cases skip Windows. These checks complement the OSV scan; they do not change its existing exceptions. diff --git a/README.md b/README.md index 222b96893..f140ad1c6 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ Each skill feeds into the next. `/office-hours` writes a design doc that `/plan- | `/write-skill` | **Skill Editor** | Write a new agent skill or improve one without bloat. A five-step edit ladder (fix the tool first, add nothing the model already does, edit the line instead of appending, lowest level that reaches the agent, rule not story), `gstack-skill-bill` for size per level and growth since the last diet, a drift check that every gstack command and flag a skill names still exists, and full diets proven by a before/after/no-skill test. | | `/test-audit` | **Test Auditor** | Sweep existing tests for ones that cost more than they protect: source greps, duplicates, assertion-free probes, test-only exports. Every candidate carries an evidence card; report-only unless you approve a batch. | | `/investigate` | **Debugger** | Systematic root-cause debugging. Iron Law: no fixes without investigation. Traces data flow, tests hypotheses, stops after 3 failed fixes. | +| `/verify` | **Build Loop** | Run the repo's own checks (typecheck, lint, build) and the tests `/ship`'s pre-gate would pick for your change, fix what breaks, repeat until green, then hand off to `/ship`. Asks once before running repo commands; never calls a change green when no test covers it. | | `/design-review` | **Designer Who Codes** | Same audit as /plan-design-review, then fixes what it finds. Atomic commits, before/after screenshots. If you have impeccable installed, its engine runs first and every mechanical finding arrives tagged with its rule id. | | `/devex-review` | **DX Tester** | Live developer experience audit. Actually tests your onboarding: navigates docs, tries the getting started flow, times TTHW, triggers CLI errors the way an agent meets them (`gstack-error-capture`: no terminal, contained, redacted). Compares against `/plan-devex-review` scores — the boomerang that shows if your plan matched reality. | | `/design-shotgun` | **Design Explorer** | "Show me options." Generates 4-6 AI mockup variants, opens a comparison board in your browser, collects your feedback, and iterates. Taste memory learns what you like. Repeat until you love something, then hand it to `/design-html`. | @@ -242,6 +243,7 @@ On Windows without Developer Mode (MSYS2 / Git Bash), `setup` falls back to file |-----|---------------| | [Skill Deep Dives](docs/skills.md) | Philosophy, examples, and workflow for every skill (includes Greptile integration) | | [The recommended harness](docs/recommended-harness.md) | gstack + Capy from zero to the first merged train: install, the Captain and its Drive, trains, the daily flaky pass, the twice-weekly release, the factory scorecard, what is Capy-specific, known Capy limits | +| [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 | diff --git a/SKILL.md b/SKILL.md index feafb991e..fbacafb55 100644 --- a/SKILL.md +++ b/SKILL.md @@ -208,6 +208,7 @@ quality gates that produce better results than answering inline. - User asks to write a skill, improve or slim a skill, or add a lesson to a named skill → invoke `/write-skill` - User asks about visual polish, design audit of a live site, "this looks off" → invoke `/design-review` - User asks to audit the live developer experience, time-to-hello-world → invoke `/devex-review` +- User asks to run the checks, make the tests pass, "verify my change", "check my work" while building → invoke `/verify` - User asks to ship, deploy, push, create a PR, "let's land this", "send it" → invoke `/ship` - User asks to merge + deploy + verify as one flow → invoke `/land-and-deploy` - User asks to rebase or revive an old PR, "modernize this PR", whether a stale PR is still worth landing → invoke `/modernize` diff --git a/SKILL.md.tmpl b/SKILL.md.tmpl index 3ffde47ae..aa95dfe75 100644 --- a/SKILL.md.tmpl +++ b/SKILL.md.tmpl @@ -84,6 +84,7 @@ quality gates that produce better results than answering inline. - User asks to write a skill, improve or slim a skill, or add a lesson to a named skill → invoke `/write-skill` - User asks about visual polish, design audit of a live site, "this looks off" → invoke `/design-review` - User asks to audit the live developer experience, time-to-hello-world → invoke `/devex-review` +- User asks to run the checks, make the tests pass, "verify my change", "check my work" while building → invoke `/verify` - User asks to ship, deploy, push, create a PR, "let's land this", "send it" → invoke `/ship` - User asks to merge + deploy + verify as one flow → invoke `/land-and-deploy` - User asks to rebase or revive an old PR, "modernize this PR", whether a stale PR is still worth landing → invoke `/modernize` diff --git a/TODOS.md b/TODOS.md index 7d7aa202d..89b7d0396 100644 --- a/TODOS.md +++ b/TODOS.md @@ -2,11 +2,21 @@ ## NEXT PRIORITY +### P3: GST-421 and GST-412 follow-ups (filed 2026-10-31, from the PR B /ship review) + +- **Check the Approvals table's own cells.** `--check-prose` skips the whole rendered Approvals block, including the Asked, Covers and Still pending cells the lane types. Narrow the skip to the Exact words column. **Priority:** P3. +- **The root `.bun/` blind spot.** `gstack-wtree` leaves every untracked file under a root `.bun/` out of the fingerprint, so an edit there never makes evidence STALE. Narrow the exclusion to Bun's cache subfolder if anything starts loading code from it. **Priority:** P3. + ### P1: review-depth receipt follow-ups (filed 2026-10-28, from the #3567 /ship plan audit) - **Derive `carry.covers` from depth.** A carried receipt's `covers` is the fixed `CARRY_COVERS` list (lib/ship-receipt.ts); derive it from the recorded `review_depth` so a light review's carry does not claim the checks a full review ran (plan item 5, deferred at /ship). **Effort:** S. **Priority:** P1. - **Bound the queue's recompute time.** `gstack-ship-queue` recomputes each receipt's needed depth at READY and at train build; add a test that a five-PR train recomputes within a fixed budget, so a large diff cannot stall the train. **Effort:** S. **Priority:** P1. +### 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. +- **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) - **Show the effort that ran.** Step 0.5 prints `CODEX_EFFORT: (source: /codex --effort)` once, but the result footers do not repeat the effort, so it scrolls away. Add an `Effort:` line to the review, challenge and consult result footers. Blocked on skeleton bytes in `codex/SKILL.md` (cap 60,200). **Effort:** S. **Priority:** P3. @@ -1716,6 +1726,14 @@ run locally on a machine that has the CLI or device. **Re-entry:** the device or Aside is available to a CI runner. Remove each file's exclude entry when its prerequisite exists. +**Model panel (GSTA-173):** `skill-e2e-model-panel` is excluded too: it needs +`OPENROUTER_API_KEY`, which no CI workflow carries, and it is a research +instrument run on demand. Before its next preregistered run, fix three harness +gaps the October 2026 review found: score a timed-out cell's working tree +instead of calling it INFRA (`classifyCell`), summarize only the current run's +rows (`afterAll` reads every row in the output directory), and drain the worker +pool on the first error so no cell starts after a failure (`pool`). + **Review by:** 2026-12-28. **Effort:** S per file. **Priority:** P3. ### ✅ DONE (2026-10-02, parallel-waves fix wave): Install the Codex CLI in the CI image @@ -3587,6 +3605,34 @@ Linux cookie import shipped in v0.11.11.0 (Wave 3). Supports Chrome, Chromium, B ## Ship +### Crew template rule 22: say when a lane picks `--screen` (GSTA-165 1a follow-up) + +**What:** Update the rule 22 text in `captain/templates/CREW.md` (and its `docs/captain.md` home if it repeats the rule) so a lane picks `--screen` only when `gstack-ship-queue ready` recommends it: the paid selector's mode is `full-fallback` or it cannot select. + +**Why:** `gstack-ship-queue ready` now recommends `--no-screen` for every diff the selector can narrow, and unscreened PRs fill train seats. A crew instantiated from the template still reads the older screen guidance, so lanes can keep paying for screens the recommendation no longer asks for. + +**Context:** The GSTA-165 plan's PR 1 (D1) listed this doc change beside the code; PR #3619 shipped the code, `docs/ship-policy.md` and tests and left the template text out. Template rule 22 ("/ship before every READY") names the receipt and its homes but not the screen choice, and rule 6 names `--screen|--no-screen` without saying which to pick. + +Deferred from plan: /home/user/.capy/drive/captain-gstack-minder/plans/GSTA-165.md + +**Effort:** S +**Priority:** P1 +**Depends on:** PR #3619 + +### Train records: attribute a red train to the PR that caused it (GSTA-165 v2 item 6) + +**What:** Add an attribution field to the merge-train record so each red train names the PR (or none, or infra) that caused it. + +**Why:** The trigger for reverting GSTA-165 D1 (screen only full-fallback diffs) is "PR-attributed red trains exceed the forecast (about 10% at size 3, 16% at size 5) by 2x over 20 trains". Without an attribution field nobody can measure it, so the default cannot be revisited on evidence. + +**Context:** Restated in handoffs/GSTA-165/v2-additions.md item 6 and unassigned to a PR. Start from the train record in `lib/ship-queue-train-record.ts` and what `train bisect` writes back to it. + +Deferred from plan: /home/user/.capy/drive/captain-gstack-minder/plans/GSTA-165.md + +**Effort:** M +**Priority:** P1 +**Depends on:** PR #3619 + ### Runtime enforcement of foreground dispatch (PreToolUse hook) **What:** A PreToolUse hook (settings.json) that forces or verifies `run_in_background: false` on Agent tool calls made inside gstack workflows, making the #497/#2440 bug class structurally impossible on Claude Code instead of prose-pinned. diff --git a/VERSION b/VERSION index c6d249a3f..74cc5d7cc 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.91.319.0 +1.91.371.0 diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.md index 3a2793d5c..1cfbabfca 100644 --- a/agents-digest/gstack-AGENTS.md +++ b/agents-digest/gstack-AGENTS.md @@ -1,4 +1,4 @@ -# gstack digest v1.91.319.0 — regenerate/re-copy after upgrading gstack +# gstack digest v1.91.371.0 — regenerate/re-copy after upgrading gstack Behavioral rules from gstack (https://github.com/garrytan/gstack), compressed for agent hosts without a full skill install. The full skills add workflows, diff --git a/benchmark-models/SKILL.md b/benchmark-models/SKILL.md index 06410fc4d..0f3444718 100644 --- a/benchmark-models/SKILL.md +++ b/benchmark-models/SKILL.md @@ -196,12 +196,14 @@ If C: ask for the path. Verify it exists. Use as positional argument. ## Step 2: Choose providers ```bash -"$BIN" --prompt "unused, dry-run" --models claude,gpt,gemini --dry-run +"$BIN" --prompt "unused, dry-run" --models claude,gpt,gemini,particle,deepseek --dry-run ``` Show the dry-run output. The "Adapter availability" section tells the user which providers will actually run (OK) vs skip (NOT READY — remediation hint included). -If ALL three show NOT READY: stop with a clear message — benchmark can't run without at least one authed provider. Suggest `claude login`, `codex login`, or `gemini login` / `export GOOGLE_API_KEY`. +If every provider shows NOT READY: stop with a clear message — benchmark can't run without at least one authed provider. Suggest `claude login`, `codex login`, `gemini login` / `export GOOGLE_API_KEY`, or `export OPENROUTER_API_KEY` for particle and deepseek (they run in Claude Code, so they also need the `claude` CLI). + +particle and deepseek send the prompt and the working directory's files the model reads to OpenRouter and the model vendor. They load no Claude Code settings files (so a key in a settings.json `env` block is never sent) and run with the user's environment minus Anthropic credentials. Say so before including them. If at least one is OK: AskUserQuestion: - **Simplify:** "Which models should we include? The dry-run above showed which are authed. Unauthed ones will be skipped cleanly — they won't abort the batch." diff --git a/benchmark-models/SKILL.md.tmpl b/benchmark-models/SKILL.md.tmpl index 7360183c7..dbc447bb5 100644 --- a/benchmark-models/SKILL.md.tmpl +++ b/benchmark-models/SKILL.md.tmpl @@ -4,7 +4,8 @@ preamble-tier: 1 version: 1.0.0 description: | Cross-model benchmark for gstack skills. Runs the same prompt through Claude, - GPT (via Codex CLI), and Gemini side-by-side — compares latency, tokens, cost, + GPT (via Codex CLI), Gemini, and (through OpenRouter in Claude Code) particle-1 + and DeepSeek V4.1 Flash side-by-side — compares latency, tokens, cost, and optionally quality via LLM judge. Answers "which model is actually best for this skill?" with data instead of vibes. Separate from /benchmark, which measures web page performance. Use when: "benchmark models", "compare models", @@ -71,12 +72,14 @@ If C: ask for the path. Verify it exists. Use as positional argument. ## Step 2: Choose providers ```bash -"$BIN" --prompt "unused, dry-run" --models claude,gpt,gemini --dry-run +"$BIN" --prompt "unused, dry-run" --models claude,gpt,gemini,particle,deepseek --dry-run ``` Show the dry-run output. The "Adapter availability" section tells the user which providers will actually run (OK) vs skip (NOT READY — remediation hint included). -If ALL three show NOT READY: stop with a clear message — benchmark can't run without at least one authed provider. Suggest `claude login`, `codex login`, or `gemini login` / `export GOOGLE_API_KEY`. +If every provider shows NOT READY: stop with a clear message — benchmark can't run without at least one authed provider. Suggest `claude login`, `codex login`, `gemini login` / `export GOOGLE_API_KEY`, or `export OPENROUTER_API_KEY` for particle and deepseek (they run in Claude Code, so they also need the `claude` CLI). + +particle and deepseek send the prompt and the working directory's files the model reads to OpenRouter and the model vendor. They load no Claude Code settings files (so a key in a settings.json `env` block is never sent) and run with the user's environment minus Anthropic credentials. Say so before including them. If at least one is OK: AskUserQuestion: - **Simplify:** "Which models should we include? The dry-run above showed which are authed. Unauthed ones will be skipped cleanly — they won't abort the batch." diff --git a/bin/gstack-capy-install b/bin/gstack-capy-install index 93b51b75c..4afc9a153 100755 --- a/bin/gstack-capy-install +++ b/bin/gstack-capy-install @@ -29,7 +29,10 @@ # reuse, Bun at gstack's own supported minimum with the project's pins never # applied, no ./setup, no host profiles, no shim; the doctor certifies only the # read-only helpers, and an ok verdict a fuller install wrote for this HEAD is -# kept. Without the Drive skill, gstack_capy_bootstrap_cmd prints the command +# kept: the profile then writes no launch file and announces that install's +# own launch file and path, so the lane's environment is never rewritten +# (GST-401). A profile's own launch directory lives under .profile/, +# never .launch. Without the Drive skill, gstack_capy_bootstrap_cmd prints the command # that clones into an explicit root and runs the checkout's own bootstrapper. # Chromium is lazy by default (bin/gstack-browser-ensure # installs it on first use); --with-browser installs it now. The last lines @@ -382,6 +385,11 @@ if [ -n "$RES_BIN" ]; then esac if [ -z "$LAUNCH_DIR" ]; then LAUNCH_DIR="${VERDICT%.json}.launch" + if [ "$PROFILE" -eq 1 ]; then + LAUNCH_DIR="${VERDICT%.json}.profile/$FOR.launch" + (umask 077 && mkdir -p "${VERDICT%.json}.profile") \ + || stop INSTALL_PREFLIGHT_FAILED "could not create ${VERDICT%.json}.profile" "make $(dirname "$VERDICT") writable, then re-run" + fi gstack_launch_dir "$LAUNCH_DIR" "$RES_BIN" "$_launch_node" \ || stop INSTALL_PREFLIGHT_FAILED "could not publish the launch directory $LAUNCH_DIR" "make $(dirname "$LAUNCH_DIR") writable, then re-run" fi @@ -656,13 +664,16 @@ WARN behind — installed $INSTALLED is ${GSTACK_CAPY_BEHIND:-?} commits behind [ -n "$NOTES" ] && TRAILER="$TRAILER ($NOTES)" ;; esac # The launch file: the same assignments as a sourceable script, mode 0600, -# beside the verdict. `. ` applies them without ever printing them; the +# beside the verdict. It also appends the checkout's bin directory to PATH +# (after everything already there, so it shadows nothing): a skill's bare +# `gstack-ship-budget` resolves in a shell that sourced only this file. `. ` applies them without ever printing them; the # line carries no secret, but a caller that re-typed it as `export $(...)` # ran a bare `export` when the substitution came back empty and dumped the # whole environment, API keys included, into its tool output (GSTA-96). The # file is part of the ok verdict: a passing run that cannot write it fails, # so no caller is left with only the line and the re-typing path. LAUNCH_FILE="${VERDICT%.json}.env" +BIN_DIR=$(cd "$ROOT/bin" 2>/dev/null && pwd -P) write_launch_file() { local tmp mkdir -p "$(dirname "$LAUNCH_FILE")" || return 1 @@ -672,21 +683,34 @@ write_launch_file() { echo "# Apply it with: . " echo "# Never print it or the environment: no \`export \$(...)\`, \`env\`, \`printenv\` or bare \`set\` in a tool fence." [ -n "$LAUNCH_DIR" ] && echo "case \":\$PATH:\" in *:$(shq "$LAUNCH_DIR"):*) ;; *) PATH=$(shq "$LAUNCH_DIR"):\"\$PATH\" ;; esac; export PATH" + [ -n "$BIN_DIR" ] && echo "case \":\$PATH:\" in *:$(shq "$BIN_DIR"):*) ;; *) PATH=\"\${PATH:+\$PATH:}\"$(shq "$BIN_DIR") ;; esac; export PATH" echo "export GSTACK_SESSION_KIND=unattended" echo "export GSTACK_STATE_ROOT=$(shq "$GSTACK_STATE_ROOT")" echo "export GSTACK_EPHEMERAL=$(shq "${GSTACK_EPHEMERAL:-1}")" echo "export GSTACK_CAPY=1" echo "export GSTACK_INSTALL_VERDICT=$(shq "$VERDICT")" + if [ -n "${GSTACK_PREFERENCES_FILE:-}" ]; then echo "export GSTACK_PREFERENCES_FILE=$(shq "$GSTACK_PREFERENCES_FILE")"; fi } > "$tmp" && chmod 0600 "$tmp" && mv -f "$tmp" "$LAUNCH_FILE" || { rm -f "$tmp"; return 1; } } -if [ "$RC" -eq 0 ] && ! write_launch_file; then +# A profile check that keeps a fuller ok verdict borrows that install's launch +# file and path instead of writing over them (GST-401), unless that install +# recorded no launch path while this shell needs one to reach its Bun. +BORROWED=0 _kept_launch="" +verdict_kept && _kept_launch=$(gstack_install_verdict_field "$VERDICT" launch_path) +if [ "$RC" -eq 0 ] && verdict_kept && [ -f "$LAUNCH_FILE" ] && { [ -n "$_kept_launch" ] || [ -z "$LAUNCH_DIR" ]; }; then + BORROWED=1 LAUNCH_DIR=$_kept_launch +elif [ "$RC" -eq 0 ] && verdict_kept; then + LAUNCH_FILE="${VERDICT%.json}.profile/$FOR.env" + (umask 077 && mkdir -p "${VERDICT%.json}.profile") || true +fi +if [ "$RC" -eq 0 ] && [ "$BORROWED" -eq 0 ] && ! write_launch_file; then TRAILER="gstack: fail launch-file — could not write the launch file $LAUNCH_FILE; fix: make $(dirname "$LAUNCH_FILE") writable, or set GSTACK_STATE_ROOT to a writable directory (LAUNCH_FILE_UNWRITABLE)" RC=1 fi # A failing run announces no launch file and removes the one its verdict owned # (where the directory lets it); a profile check that keeps a fuller ok verdict # leaves that verdict's file in place. -[ "$RC" -eq 0 ] || { verdict_kept || rm -f "$LAUNCH_FILE" 2>/dev/null; LAUNCH_FILE=""; } +[ "$RC" -eq 0 ] || { [ "$PROFILE" -eq 1 ] && rm -rf "${VERDICT%.json}.profile" 2>/dev/null; verdict_kept || rm -f "$LAUNCH_FILE" 2>/dev/null; LAUNCH_FILE=""; } record_verdict "$TRAILER" "$([ "$RC" -eq 0 ] && echo 1 || echo 0)" [ "$CHECK_ONLY" -eq 1 ] || [ "$PROFILE" -eq 1 ] || write_shim printf '%s\n' "$OUT" | grep -v '^gstack: ' diff --git a/bin/gstack-capy-session b/bin/gstack-capy-session index 3df25b12e..3050b63a3 100755 --- a/bin/gstack-capy-session +++ b/bin/gstack-capy-session @@ -29,7 +29,10 @@ # inside a workflow (/ship's docs step) must not change gstack under it. The age # bound matters on Capy, where the leased harness pid is the machine's # long-lived capy-server and a live lease alone would never end the deferral; -# each gstack-skill-start renews it (UPGRADE_BUSY; GSTACK_UPGRADE_FORCE=1 overrides). Lines: `SELF_UPGRADE: done -> ` | `skipped ()` +# each gstack-skill-start renews it (UPGRADE_BUSY; GSTACK_UPGRADE_FORCE=1 overrides). +# An install profile (`--for review-voice`, a dispatched reviewer on a machine +# whose checkout a lane shares) never self-upgrades, lease or not, and +# GSTACK_UPGRADE_FORCE does not override it (UPGRADE_SKIPPED, GST-290). Lines: `SELF_UPGRADE: done -> ` | `skipped ()` # | `none (current)` | `disabled ()`. # --check never moves the checkout; behind origin it prints @@ -70,6 +73,8 @@ fi [ "${GSTACK_CAPY_REMOTE_MIN:-}" = unknown ] && echo "gstack-capy-session: remote minimum unknown (fetch failed); the revision row is local only" # shellcheck source=bin/gstack-install-verdict.sh . "$ROOT/bin/gstack-install-verdict.sh" +# shellcheck source=bin/gstack-doctor-components.sh +. "$ROOT/bin/gstack-doctor-components.sh" 2>/dev/null || gstack_doctor_install_profile() { [ "$1" = review-voice ]; } MIN_WRAPPER=$(gstack_support_env_get "$(gstack_source_root "$ROOT/bin")" GSTACK_CAPY_MIN_WRAPPER) if [ -n "$MIN_WRAPPER" ] && [ "${GSTACK_CAPY_WRAPPER_REV:-0}" -lt "$MIN_WRAPPER" ] 2>/dev/null; then echo "gstack-capy-skill: owner action — Drive copy is wrapper ${GSTACK_CAPY_WRAPPER_REV:-0}, minimum $MIN_WRAPPER; copy $ROOT/capy/skill/gstack/ (CAPY_WRAPPER_STALE)" @@ -91,12 +96,25 @@ report_behind() { GSTACK_CAPY_BEHIND_TO="$(git -C "$ROOT" show FETCH_HEAD:VERSION 2>/dev/null | head -1)" GSTACK_CAPY_BEHIND_FIX="$1" } unset GSTACK_CAPY_BEHIND GSTACK_CAPY_BEHIND_TO GSTACK_CAPY_BEHIND_FIX GSTACK_CAPY_BEHIND_BLOCKED +# The owner's preferences.yaml sits beside the Drive skill's SKILL.md and is +# read where it lies (never copied), so --check never writes the skill folder +# and a newer file is seen by the next command. The installer writes the path +# into the launch file; gstack-models resolve --role agent reads it. A wrapper +# inside this checkout is no Drive skill, so it names no preferences file. +if [ -n "${GSTACK_CAPY_WRAPPER_PATH:-}" ]; then + _prefs_dir="$(dirname "$(dirname "$GSTACK_CAPY_WRAPPER_PATH")")" + case "$_prefs_dir/" in + "$ROOT"/*) ;; + *) export GSTACK_PREFERENCES_FILE="$_prefs_dir/preferences.yaml" ;; + esac +fi RERUN="bash ${GSTACK_CAPY_WRAPPER_PATH:-/scripts/install.sh}${SKILL:+ --for $SKILL}" if [ "$CHECK" -eq 1 ]; then if behind; then # The rerun fast-forwards only what gstack-upgrade would move; otherwise # gstack-upgrade itself names the refusal and its fix. - if [ "${GSTACK_CAPY_SELF_UPGRADE:-}" = off ]; then report_behind "unset GSTACK_CAPY_SELF_UPGRADE, then $RERUN" + if gstack_doctor_install_profile "$SKILL"; then report_behind "$ROOT/bin/gstack-upgrade" + elif [ "${GSTACK_CAPY_SELF_UPGRADE:-}" = off ]; then report_behind "unset GSTACK_CAPY_SELF_UPGRADE, then $RERUN" elif [ "${GSTACK_CAPY_AUTO_UPGRADE:-1}" = 0 ]; then report_behind "unset GSTACK_CAPY_AUTO_UPGRADE, then $RERUN" elif [ "$(git -C "$ROOT" symbolic-ref -q --short HEAD 2>/dev/null)" != "$(sed -n "1s/.*branch '\([^']*\)' of .*/\1/p" "$(git -C "$ROOT" rev-parse --absolute-git-dir 2>/dev/null)/FETCH_HEAD" 2>/dev/null)" ] \ || [ -n "$(git -C "$ROOT" status --porcelain --untracked-files=no 2>/dev/null)" ] \ @@ -111,6 +129,11 @@ elif [ "${GSTACK_CAPY_SELF_UPGRADED:-}" != 1 ]; then elif [ "${GSTACK_CAPY_AUTO_UPGRADE:-1}" = 0 ]; then disabled GSTACK_CAPY_AUTO_UPGRADE elif [ -z "${GSTACK_CAPY_REMOTE_MIN:-}" ] || [ "$GSTACK_CAPY_REMOTE_MIN" = unknown ]; then echo "SELF_UPGRADE: none (remote minimum unknown)" elif ! behind; then echo "SELF_UPGRADE: none (current)" + elif gstack_doctor_install_profile "$SKILL"; then + REASON="$SKILL never self-upgrades a shared checkout; fix: GSTACK_UPGRADE_FORCE=1 $ROOT/bin/gstack-upgrade when no other session uses this checkout (UPGRADE_SKIPPED)" + echo "SELF_UPGRADE: skipped ($REASON)" + report_behind "$ROOT/bin/gstack-upgrade" + export GSTACK_CAPY_BEHIND_BLOCKED="$REASON" elif [ ! -x "$ROOT/bin/gstack-upgrade" ]; then echo "SELF_UPGRADE: skipped ($ROOT/bin/gstack-upgrade is missing)"; report_behind "$RERUN" export GSTACK_CAPY_BEHIND_BLOCKED="$ROOT/bin/gstack-upgrade is missing; fix: $RERUN (UPGRADE_REFUSED)" elif [ "${GSTACK_UPGRADE_FORCE:-}" != 1 ] && [ -x "$ROOT/bin/gstack-lease" ] \ @@ -121,7 +144,7 @@ elif [ "${GSTACK_CAPY_SELF_UPGRADED:-}" != 1 ]; then while read -r _pid _age; do HOLDERS="$HOLDERS${HOLDERS:+, }pid $_pid ($_age)"; done < [options] + + detect list the checks run would execute and whether they are trusted (reads files only) + trust trust the current command set for this repo (checks, the pregate runner and its + selection manifest commands); any change to one of them needs trust again + run [--only a,b] [--allow-repo-commands] [--timeout ] + run the checks and the tests pregate selects for the change; one line per check: + CHECK PASS|FAIL|ZERO_RUN|UNMAPPED|TOO_BROAD|ENV|TIMEOUT|INCOMPLETE + status READY_FOR_SHIP when the last run passed every check at this tree, else NOT_READY; + runs nothing + + --base the branch pregate selects against (default: origin/HEAD's branch, else main) + +Exit codes: 0 green or ready · 1 a red check or not ready · 2 an environment failure or timeout · +3 consent required, no checks, or no pregate context · 64 usage +`; + +function flag(args: string[], name: string): string | undefined { + const i = args.indexOf(name); + return i >= 0 ? args[i + 1] : undefined; +} + +function repoRoot(): string | null { + const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 }); + return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null; +} + +function loadOrRefuse(root: string, args: string[], timeoutMs: number): Loaded | null { + const l = load(root, flag(args, '--base'), timeoutMs); + if ('refused' in l) { process.stderr.write(`gstack-checks: no pregate context, so tests cannot be selected: ${l.refused}\n`); return null; } + return l; +} + +async function main(argv: string[]): Promise { + const [verb, ...args] = argv; + if (!verb || verb === '--help' || verb === '-h') { process.stdout.write(USAGE); return verb ? 0 : 64; } + if (!['detect', 'trust', 'run', 'status'].includes(verb)) { process.stderr.write(USAGE); return 64; } + const root = repoRoot(); + if (!root) { process.stderr.write('gstack-checks: not inside a git repository\n'); return 3; } + const timeoutS = Number(flag(args, '--timeout') ?? 600); + if (!Number.isFinite(timeoutS) || timeoutS <= 0) { process.stderr.write('gstack-checks: --timeout needs a positive number of seconds\n'); return 64; } + const l = loadOrRefuse(root, args, timeoutS * 1000); + if (!l) return 3; + const trusted = isTrusted(root, l.set); + const NONE = 'CHECKS: none (no gstack:verify: line, Health Stack section, manifest check, pregate policy or test file); nothing to run\n'; + if (nothingToRun(l) && (verb === 'run' || verb === 'detect')) { process.stdout.write(NONE); return verb === 'run' ? 3 : 0; } + if (verb === 'detect') { + for (const c of l.checks) process.stdout.write(`CHECK ${c.name} ${c.command}${c.body ? ` (runs: ${c.body})` : ''} (${c.source})\n`); + if (!l.checks.length) process.stdout.write('CHECKS: tests only (no gstack:verify: line, Health Stack section or manifest check)\n'); + const selection = Object.values(l.ctx.config.selection ?? {}); + process.stdout.write(`TESTS pregate selection against ${l.ctx.baseRef} (policy ${l.ctx.configLabel}; runner ${l.ctx.config.runner ?? 'detected per file'}${selection.length ? `; selection commands: ${selection.join(' | ')}` : ''})\n`); + process.stdout.write(`TRUST ${trusted ? 'trusted' : 'untrusted (run gstack-checks trust after the user agrees, or pass --allow-repo-commands)'}\n`); + return 0; + } + if (verb === 'trust') { + recordTrust(root, l.set, l.checks, l.ctx.config); + process.stdout.write(`gstack-checks: trusted ${l.checks.length} check(s) and the pregate test commands for ${root}\n`); + return 0; + } + if (verb === 'status') { + const s = status(l, readLedger(ledgerPath(root))); + process.stdout.write(s.line + '\n'); + return s.ready ? 0 : 1; + } + if (!trusted && !args.includes('--allow-repo-commands')) { + process.stderr.write(`gstack-checks: these commands are not trusted for ${root}; nothing was run (CHECKS_CONSENT_REQUIRED)\n`); + for (const c of l.checks) process.stderr.write(` ${c.name}: ${c.command}\n`); + process.stderr.write(` tests: ${l.ctx.config.runner ?? 'the runner pregate detects'} on the files pregate selects${Object.keys(l.ctx.config.selection ?? {}).length ? ' (and its selection manifest commands)' : ''}\n`); + process.stderr.write('fix: ask the user, then gstack-checks trust; or pass --allow-repo-commands when the session was launched to run them\n'); + return 3; + } + const only = flag(args, '--only')?.split(',').map(s => s.trim()).filter(Boolean); + const unknown = (only ?? []).filter(n => n !== TESTS && !l.checks.some(c => c.name === n)); + if (unknown.length) { process.stderr.write(`gstack-checks: unknown check(s) ${unknown.join(', ')}; known: ${[...l.checks.map(c => c.name), TESTS].join(', ')}\n`); return 64; } + for (const signal of ['SIGINT', 'SIGTERM'] as const) process.once(signal, () => { cancelActive(); process.exit(signal === 'SIGINT' ? 130 : 143); }); + const { outcomes, ledger } = await runChecks(l, { root, only, timeoutMs: timeoutS * 1000 }); + for (const o of outcomes) { + process.stdout.write(`CHECK ${o.name} ${o.verdict} ${(o.ms / 1000).toFixed(1)}s${o.verdict === 'PASS' ? '' : ` ${o.detail}`}\n`); + if (o.verdict !== 'PASS') { for (const line of o.lines.slice(-MAX_FAIL_LINES)) process.stdout.write(` | ${line}\n`); if (o.log) process.stdout.write(` log: ${o.log}\n`); } + } + if (ledger.notCovered.length) process.stdout.write(`NOT_COVERED ${ledger.notCovered.join(' ')} (platform lanes /ship's pregate owns)\n`); + if (outcomes.every(o => o.verdict === 'PASS')) return 0; + return outcomes.some(o => o.verdict === 'FAIL' || o.verdict === 'ZERO_RUN' || o.verdict === 'UNMAPPED' || o.verdict === 'TOO_BROAD' || o.verdict === 'INCOMPLETE') ? 1 : 2; +} + +main(process.argv.slice(2)).then(code => process.exit(code), e => { process.stderr.write(`gstack-checks: ${e?.stack ?? e}\n`); process.exit(1); }); diff --git a/bin/gstack-config b/bin/gstack-config index 6fff279f9..8992806e2 100755 --- a/bin/gstack-config +++ b/bin/gstack-config @@ -194,6 +194,9 @@ CONFIG_HEADER='# gstack configuration — edit freely, changes take effect on ne # Optional pins: model_frontier_claude, model_frontier_openai, # model_smart_claude and model_smart_openai. Leave pins absent for catalog defaults; # empty pins are invalid. gstack-models list prints copyable set/unset commands. +# agent_model: the model for gstack agents (lanes, subagents, reviewers): host, +# a family (opus, fable, sonnet, haiku, astra, sol, luna, terra) or /. +# Absent = host. A preference, not a policy: gstack-models resolve --role agent. # Invalid writes are rejected and preserve the stored value. # codex_effort: # Codex reasoning effort for outside reviews and /codex: # # minimal | low | medium | high | xhigh | max | ultra. @@ -362,6 +365,7 @@ lookup_default() { plan_review_tier) echo "frontier" ;; # frontier | smart | host — lib/model-policy.ts reads it strictly implementation_tier) echo "smart" ;; # frontier | smart model_frontier_claude|model_frontier_openai|model_smart_claude|model_smart_openai) echo "" ;; # empty = shipped catalog ID (gstack-models list) + agent_model) echo "" ;; # empty = host (agents keep their own model); gstack-models resolve --role agent codex_effort) echo "" ;; # empty = each gate's own effort; /codex --effort, then GSTACK_CODEX_EFFORT, win (gstack-codex-probe run-with-timeout --effort) review_effort_tiers) echo "on" ;; # on | off — gstack-review-plan effort tiers (docs/model-policy.md#reasoning-effort) ship_greptile_early) echo "true" ;; # true | false — /ship's early Greptile PR @@ -836,6 +840,16 @@ $_gstack_legacy_root" exit 1 ;; esac fi + if [ "$KEY" = "agent_model" ]; then + VALUE="${VALUE#"${VALUE%%[![:space:]]*}"}" + VALUE="${VALUE%"${VALUE##*[![:space:]]}"}" + case "$(printf '%s' "$VALUE" | LC_ALL=C tr 'A-Z' 'a-z')" in + host|opus|fable|sonnet|haiku|astra|sol|luna|terra) ;; + *) printf '%s' "$VALUE" | LC_ALL=C grep -qE '^[a-z][a-z0-9-]{0,31}/[A-Za-z0-9][A-Za-z0-9._:@+-]{0,199}$' || { + echo "Error: agent_model '$VALUE' not recognized. Use host, a family (opus, fable, sonnet, haiku, astra, sol, luna, terra) or / such as anthropic/claude-opus-5-5. Existing value left unchanged. fix: gstack-config unset agent_model returns to host (https://github.com/garrytan/gstack/blob/main/docs/model-policy.md#your-model-preference)" >&2 + exit 1; } ;; + esac + fi case "$KEY" in plan_review_tier|implementation_tier|model_frontier_claude|model_frontier_openai|model_smart_claude|model_smart_openai) _mp_doc="https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#model-policy-config" @@ -1086,7 +1100,7 @@ $_gstack_legacy_root" ship_measure_judge_outputs ship_measure_ask_per_trial_usd ship_measure_budget_usd \ ship_measure_max_rounds ship_measure_sweep_cases ship_measure_sweep_budget_usd ship_rerun_backend test_backend \ plan_review_tier implementation_tier model_frontier_claude model_frontier_openai \ - model_smart_claude model_smart_openai codex_effort review_effort_tiers; do + model_smart_claude model_smart_openai codex_effort review_effort_tiers agent_model; do gstack_config_select "$KEY" VALUE="$_gstack_cfg_value" SOURCE="default" @@ -1111,7 +1125,7 @@ $_gstack_legacy_root" ship_measure_judge_outputs ship_measure_ask_per_trial_usd ship_measure_budget_usd \ ship_measure_max_rounds ship_measure_sweep_cases ship_measure_sweep_budget_usd ship_rerun_backend test_backend \ plan_review_tier implementation_tier model_frontier_claude model_frontier_openai \ - model_smart_claude model_smart_openai codex_effort review_effort_tiers; do + model_smart_claude model_smart_openai codex_effort review_effort_tiers agent_model; do printf ' %-24s %s\n' "$KEY:" "$(lookup_default "$KEY")" done ;; diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index f3c867766..dd65a98f8 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -8,7 +8,7 @@ GSTACK_DOCTOR_COMPONENTS="claude codex patch codex-cli browse-bundle browser cso GSTACK_DOCTOR_CORE="runtime pins state-root privacy cores revision floor wrapper" GSTACK_DOCTOR_HOSTS="claude codex" GSTACK_DOCTOR_OPTIONAL="codex-cli cso" -GSTACK_DOCTOR_SKILLS="autoplan plan-ceo-review plan-eng-review plan-design-review plan-devex-review plan-tune office-hours spec review ship investigate codex cso browse qa qa-only design-review design-consultation design-html design-motion devex-review scrape skillify canary benchmark make-pdf diagram pair-agent open-gstack-browser setup-browser-cookies connect-chrome land-and-deploy benchmark-models captain careful claude-code context-restore context-save design-shotgun deslop-shared-libs document-generate document-release eval-plan freeze gstack-upgrade guard health ios-clean ios-design-review ios-fix ios-qa ios-sync landing-report learn write-skill modernize retro setup-deploy setup-gbrain sync-gbrain test-audit ubicloud unfreeze review-voice" +GSTACK_DOCTOR_SKILLS="autoplan plan-ceo-review plan-eng-review plan-design-review plan-devex-review plan-tune office-hours spec review ship investigate codex cso browse qa qa-only design-review design-consultation design-html design-motion devex-review scrape skillify canary benchmark make-pdf diagram pair-agent open-gstack-browser setup-browser-cookies connect-chrome land-and-deploy benchmark-models captain careful claude-code context-restore context-save design-shotgun deslop-shared-libs document-generate document-release eval-plan freeze gstack-upgrade guard health ios-clean ios-design-review ios-fix ios-qa ios-sync landing-report learn write-skill modernize retro setup-deploy setup-gbrain sync-gbrain test-audit ubicloud unfreeze verify review-voice" GSTACK_BROWSER_LAZY_REASON="lazy; gstack-browser-ensure installs on first use" GSTACK_DOCTOR_HELPERS="gstack-pregate gstack-plan-reality gstack-artifact gstack-autoplan" GSTACK_DOCTOR_NOT_NEEDED="none" @@ -69,7 +69,7 @@ gstack_doctor_skill_requires() { codex) printf '%s' 'claude codex patch codex-cli' ;; cso) printf '%s' 'claude cso' ;; browse|qa|qa-only|design-review|design-consultation|design-html|design-motion|devex-review|scrape|skillify|canary|benchmark|make-pdf|diagram|pair-agent|open-gstack-browser|setup-browser-cookies|connect-chrome|land-and-deploy) printf '%s' 'claude codex patch browse-bundle browser' ;; - benchmark-models|captain|careful|claude-code|context-restore|context-save|design-shotgun|deslop-shared-libs|document-generate|document-release|eval-plan|freeze|gstack-upgrade|guard|health|ios-clean|ios-design-review|ios-fix|ios-qa|ios-sync|landing-report|learn|write-skill|modernize|retro|setup-deploy|setup-gbrain|sync-gbrain|test-audit|ubicloud|unfreeze) printf '%s' 'claude' ;; + benchmark-models|captain|careful|claude-code|context-restore|context-save|design-shotgun|deslop-shared-libs|document-generate|document-release|eval-plan|freeze|gstack-upgrade|guard|health|ios-clean|ios-design-review|ios-fix|ios-qa|ios-sync|landing-report|learn|write-skill|modernize|retro|setup-deploy|setup-gbrain|sync-gbrain|test-audit|ubicloud|unfreeze|verify) printf '%s' 'claude' ;; review-voice) printf '%s' 'helpers' ;; *) return 1 ;; esac @@ -82,7 +82,7 @@ gstack_doctor_skill_optional() { codex) printf '%s' '' ;; cso) printf '%s' '' ;; browse|qa|qa-only|design-review|design-consultation|design-html|design-motion|devex-review|scrape|skillify|canary|benchmark|make-pdf|diagram|pair-agent|open-gstack-browser|setup-browser-cookies|connect-chrome|land-and-deploy) printf '%s' 'codex-cli' ;; - benchmark-models|captain|careful|claude-code|context-restore|context-save|design-shotgun|deslop-shared-libs|document-generate|document-release|eval-plan|freeze|gstack-upgrade|guard|health|ios-clean|ios-design-review|ios-fix|ios-qa|ios-sync|landing-report|learn|write-skill|modernize|retro|setup-deploy|setup-gbrain|sync-gbrain|test-audit|ubicloud|unfreeze) printf '%s' '' ;; + benchmark-models|captain|careful|claude-code|context-restore|context-save|design-shotgun|deslop-shared-libs|document-generate|document-release|eval-plan|freeze|gstack-upgrade|guard|health|ios-clean|ios-design-review|ios-fix|ios-qa|ios-sync|landing-report|learn|write-skill|modernize|retro|setup-deploy|setup-gbrain|sync-gbrain|test-audit|ubicloud|unfreeze|verify) printf '%s' '' ;; review-voice) printf '%s' '' ;; *) return 1 ;; esac @@ -281,6 +281,7 @@ gstack_result_anchor() { QUEUE_TRAIN_BISECT_CAPPED) printf '%s' 'queue-train-bisect-capped' ;; QUEUE_TRAIN_PREFIX_INVALID) printf '%s' 'queue-train-prefix-invalid' ;; QUEUE_TRAIN_REBUILD_REFUSED) printf '%s' 'queue-train-rebuild-refused' ;; + QUEUE_TRAIN_STAMP_MISMATCH) printf '%s' 'queue-train-stamp-mismatch' ;; QUEUE_TRAIN_TREE_MISMATCH) printf '%s' 'queue-train-tree-mismatch' ;; QUEUE_TRAIN_STALE) printf '%s' 'queue-train-stale' ;; QUEUE_TRAIN_FROZEN) printf '%s' 'queue-train-frozen' ;; @@ -315,8 +316,14 @@ gstack_result_anchor() { RECEIPT_PROSE_MISMATCH) printf '%s' 'receipt-prose-mismatch' ;; RECEIPT_CARRY_PREGATE_STALE) printf '%s' 'receipt-carry-pregate-stale' ;; RECEIPT_GIT_TOO_OLD) printf '%s' 'receipt-git-too-old' ;; + CHANGELOG_FRAGMENT_INVALID) printf '%s' 'changelog-fragment-invalid' ;; + QUEUE_LAND_LOCKED) printf '%s' 'queue-land-locked' ;; + QUEUE_LAND_CONFLICT) printf '%s' 'queue-land-conflict' ;; + QUEUE_LAND_DRIFT) printf '%s' 'queue-land-drift' ;; + QUEUE_LAND_BASE_BUSY) printf '%s' 'queue-land-base-busy' ;; PR_WAIT_BLOCKED) printf '%s' 'pr-wait-blocked' ;; PR_WAIT_REFUSED) printf '%s' 'pr-wait-refused' ;; + PREGATE_HEAD_POLICY_LOOSENS) printf '%s' 'pregate-head-policy-loosens' ;; APPROVAL_RECORD_INVALID) printf '%s' 'approval-record-invalid' ;; APPROVAL_RECORD_SECRET) printf '%s' 'approval-record-secret' ;; APPROVAL_RECORD_NO_BRANCH) printf '%s' 'approval-record-no-branch' ;; diff --git a/bin/gstack-evidence b/bin/gstack-evidence index d36ae3391..59f8bbe30 100755 --- a/bin/gstack-evidence +++ b/bin/gstack-evidence @@ -14,7 +14,7 @@ * `run` is a TRANSPARENT wrapper: it streams the child's output through * unchanged, tees it to a 0600 log (2MB cap with a truncation marker), and * appends {ts, label, command, cmd_sha256, exit, duration_s, commit, tree, - * dirty, wtree, log_path, tests_ran} to ~/.gstack/projects//-evidence.jsonl. + * dirty, wtree or wtree_changed, log_path, tests_ran} to ~/.gstack/projects//-evidence.jsonl. * * `tests_ran` (zero-run green, W3 of docs/designs/HONEST_WORK_GATE_INTEGRITY.md) * is parsed from a bounded tail of the streamed output for the supported @@ -89,6 +89,8 @@ interface EvidenceRecord { tree?: string; dirty?: boolean; wtree?: string; + /** Up to five paths whose content changed between the before-run and after-run fingerprints (set instead of wtree). */ + wtree_changed?: string[]; log_path?: string; redacted?: boolean; /** The runner's own test count (executed for bun/jest/vitest/pytest/rspec; ran with skips included for gstack's shard runner and the remote gate), 0 for ZERO-RUN, or "unknown" when no supported summary was seen. */ @@ -524,7 +526,10 @@ function record( if (wtreeBefore && wtreeAfter && wtreeBefore === wtreeAfter) { rec.wtree = wtreeAfter; } else if (wtreeBefore || wtreeAfter) { - warn("working-tree content changed during the run — evidence recorded without a content fingerprint (will grade STALE)"); + const changed = wtreeBefore && wtreeAfter ? (git(["diff", "--name-only", wtreeBefore, wtreeAfter]) ?? "").split("\n").map((s) => s.trim()).filter(Boolean) : []; + if (changed.length) rec.wtree_changed = changed.slice(0, 5); + const named = changed.length ? `: ${changed.slice(0, 5).join(", ")}${changed.length > 5 ? ", ..." : ""}` : ""; + warn(`working-tree content changed during the run${named} — evidence recorded without a content fingerprint (will grade STALE)`); } } if (logPath) rec.log_path = logPath; @@ -599,6 +604,7 @@ function cmdCheck(argv: string[]): number { continue; } const testsRan = typeof latest.tests_ran === "number" ? latest.tests_ran : "unknown"; + const changedDuringRun = Array.isArray(latest.wtree_changed) ? latest.wtree_changed.filter((p): p is string => typeof p === "string" && p !== "" && !/[\u0000-\u001f\u007f]/.test(p)).slice(0, 5) : []; const detail = `label=${label} exit=${latest.exit} tests_ran=${testsRan} ts=${latest.ts}${latest.log_path ? ` log=${latest.log_path}` : ""}`; let verdict: "FRESH" | "STALE" | "ZERO-RUN" = "FRESH"; let reason = ""; @@ -631,7 +637,9 @@ function cmdCheck(argv: string[]): number { // forged/corrupt ledger line must degrade, never inject options. verdict = "STALE"; reason = !latest.wtree - ? "record has no content fingerprint" + ? changedDuringRun.length + ? `content changed during the run: ${changedDuringRun.join(", ")}` + : "record has no content fingerprint" : !/^[0-9a-f]{40}$/.test(latest.wtree) ? "record has malformed fingerprint" : "current fingerprint unavailable"; diff --git a/bin/gstack-factory-scorecard b/bin/gstack-factory-scorecard index e488f7a37..76793c70c 100755 --- a/bin/gstack-factory-scorecard +++ b/bin/gstack-factory-scorecard @@ -15,6 +15,8 @@ * [--out-dir ] [--csv ] [--json] [--cache-dir ] * [--fixtures ] [--now ] * + * The window is [now - since-days, now): --now (default: the current time) is + * its end, and every line counts only items inside it. * --repo defaults to the GitHub owner/name of the origin remote; without one, * pass it. Every run writes this window's scorecard.{csv,md} and appends its * rows to trend.csv in --out-dir, so the weeks line up. diff --git a/bin/gstack-harness-pid.sh b/bin/gstack-harness-pid.sh index 2d1718281..397c49dff 100644 --- a/bin/gstack-harness-pid.sh +++ b/bin/gstack-harness-pid.sh @@ -24,3 +24,15 @@ gstack_harness_pid() { done printf '%s\n' "$_hp_pid" } + +# Harnesses that run every session on a machine under one process: Capy runs +# each tool call as a fresh shell under capy-server, so every session's lease +# names the same pid and a caller's own ancestry includes every sibling's +# holder. Matched on comm, path and a leading - stripped as above. +GSTACK_SHARED_HARNESSES="capy-server" +# gstack_shared_harness PID — true when PID's command is a shared harness. +gstack_shared_harness() { + _sh_comm=$(ps -o comm= -p "$1" 2>/dev/null | head -1) || return 1 + _sh_comm=${_sh_comm##*/}; _sh_comm=${_sh_comm#-} + case " $GSTACK_SHARED_HARNESSES " in *" $_sh_comm "*) [ -n "$_sh_comm" ] ;; *) return 1 ;; esac +} diff --git a/bin/gstack-lease b/bin/gstack-lease index 2073af92d..7a0aa3348 100755 --- a/bin/gstack-lease +++ b/bin/gstack-lease @@ -16,11 +16,14 @@ # passes its parent pid); leases older than 120 min are pruned. Exits 3 # and writes nothing when a live process holds the directory lock or # the lock cannot be taken -# gstack-lease live [--root ] [--exclude-ancestry-of ] +# gstack-lease live [--root ] [--exclude-ancestry-of ] [--count-shared-harness] # print ` m ` per lease held by a live process that # is neither the given pid nor one of its ancestors (the caller's own # session); exit 0 when any live lease exists, 1 when none. A stale lease -# is reclaimed (deleted, one `gstack-lease: reclaimed …` line on stderr) +# is reclaimed (deleted, one `gstack-lease: reclaimed …` line on stderr). +# --count-shared-harness (bin/gstack-upgrade only) still prints an +# ancestor that is a shared harness (capy-server: every session on the +# machine runs under it) while its lease is under 120 minutes old # gstack-lease list [--root ] # print ` m alive|dead|stale` for every lease # A pid alone is not a holder: pids are reused after a reboot or a machine @@ -38,23 +41,27 @@ BIN="$(cd "$(dirname "$0")" && pwd -P)" # shellcheck source=bin/gstack-install-verdict.sh . "$BIN/gstack-install-verdict.sh" 2>/dev/null || gstack_source_root() { (cd "$1/.." && pwd -P); } # shellcheck source=bin/gstack-harness-pid.sh -. "$BIN/gstack-harness-pid.sh" 2>/dev/null || gstack_harness_pid() { printf '%s\n' "$1"; } +. "$BIN/gstack-harness-pid.sh" 2>/dev/null || { + 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 ]; } +} VERB="${1:-}"; [ $# -gt 0 ] && shift -ROOT="" PID="" EXCLUDE="" FROM="" +ROOT="" PID="" EXCLUDE="" FROM="" SHARED=0 while [ $# -gt 0 ]; do case "$1" in --root) ROOT="${2:-}"; shift ;; --pid) PID="${2:-}"; shift ;; --from) FROM="${2:-}"; shift ;; --exclude-ancestry-of) EXCLUDE="${2:-}"; shift ;; + --count-shared-harness) SHARED=1 ;; *) echo "gstack-lease: unknown argument '$1'" >&2; exit 2 ;; esac shift done case "$VERB" in touch|live|list) ;; - -h|--help|'') sed -n '2,25p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + -h|--help|'') sed -n '2,28p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "gstack-lease: unknown verb '$VERB'" >&2; exit 2 ;; esac [ -n "$ROOT" ] || ROOT=$(gstack_source_root "$BIN") @@ -290,8 +297,9 @@ FOUND=1 for f in "$DIR"/*; do [ -f "$f" ] || continue p=${f##*/} - case "$ANCESTRY" in *" $p "*) continue ;; esac - _rec=$(head -1 "$f" 2>/dev/null) _age=$(age_min "$f") + _age=$(age_min "$f") + case "$ANCESTRY" in *" $p "*) [ "$SHARED" -eq 1 ] && [ "$_age" -lt 120 ] && gstack_shared_harness "$p" || continue ;; esac + _rec=$(head -1 "$f" 2>/dev/null) case "$(state "$p" "$_rec" "$_age")" in dead) continue ;; stale) diff --git a/bin/gstack-model-benchmark b/bin/gstack-model-benchmark index 81ed9dd1f..dfcb22693 100755 --- a/bin/gstack-model-benchmark +++ b/bin/gstack-model-benchmark @@ -7,7 +7,8 @@ * gstack-model-benchmark [options] * * Options: - * --models claude,gpt,gemini Comma-separated provider list (default: claude) + * --models claude,gpt,gemini Comma-separated provider list (default: claude); particle and + * deepseek run in Claude Code through OpenRouter (OPENROUTER_API_KEY) * --prompt "" Inline prompt instead of a file * --workdir Working dir passed to each CLI (default: cwd) * --timeout-ms Per-provider timeout (default: 300000) @@ -28,15 +29,7 @@ import '../lib/conductor-env-shim'; import * as fs from 'fs'; import * as path from 'path'; import { runBenchmark, formatTable, formatJson, formatMarkdown, type BenchmarkInput } from '../test/helpers/benchmark-runner'; -import { ClaudeAdapter } from '../test/helpers/providers/claude'; -import { GptAdapter } from '../test/helpers/providers/gpt'; -import { GeminiAdapter } from '../test/helpers/providers/gemini'; - -const ADAPTER_FACTORIES = { - claude: () => new ClaudeAdapter(), - gpt: () => new GptAdapter(), - gemini: () => new GeminiAdapter(), -}; +import { PROVIDERS, PROVIDER_NAMES, isProviderName, type ProviderName } from '../test/helpers/providers/registry'; type OutputFormat = 'table' | 'json' | 'markdown'; @@ -76,16 +69,20 @@ function positionalArgs(args: string[]): string[] { return positional; } -function parseProviders(s: string | undefined): Array<'claude' | 'gpt' | 'gemini'> { +function parseProviders(s: string | undefined): ProviderName[] { if (!s) return ['claude']; - const seen = new Set<'claude' | 'gpt' | 'gemini'>(); + const seen = new Set(); for (const p of s.split(',').map(x => x.trim()).filter(Boolean)) { - if (p === 'claude' || p === 'gpt' || p === 'gemini') seen.add(p); + if (isProviderName(p)) seen.add(p); else { - console.error(`WARN: unknown provider '${p}' — skipping. Valid: claude, gpt, gemini.`); + console.error(`WARN: unknown provider '${p}' — skipping. Valid: ${PROVIDER_NAMES.join(', ')}.`); } } - return seen.size ? Array.from(seen) : ['claude']; + if (!seen.size) { + console.error(`No valid provider in --models '${s}'. Valid: ${PROVIDER_NAMES.join(', ')}.`); + process.exit(1); + } + return Array.from(seen); } function parsePositiveIntegerFlag(name: string, def: string): number { @@ -163,7 +160,7 @@ async function main(): Promise { async function dryRunReport(opts: { prompt: string; - providers: Array<'claude' | 'gpt' | 'gemini'>; + providers: ProviderName[]; workdir: string; timeoutMs: number; output: OutputFormat; @@ -181,7 +178,7 @@ async function dryRunReport(opts: { lines.push('Adapter availability:'); let authFailures = 0; for (const name of opts.providers) { - const factory = ADAPTER_FACTORIES[name]; + const factory = PROVIDERS[name]; if (!factory) { lines.push(` ${name}: UNKNOWN PROVIDER`); authFailures += 1; diff --git a/bin/gstack-owner-brief b/bin/gstack-owner-brief index a6468e875..bdce6e054 100755 --- a/bin/gstack-owner-brief +++ b/bin/gstack-owner-brief @@ -3,7 +3,7 @@ * gstack-owner-brief — the one-page owner brief at the autoplan gate (plan E3). * * gstack-owner-brief render --out [--page N] [--summary ] [--write] [--json] - * gstack-owner-brief render --captain --out [--allow-incomplete] [--write] [--json] + * gstack-owner-brief render --captain --out [--captain-name ] [--allow-incomplete] [--write] [--json] * gstack-owner-brief close --out --plan [--date YYYY-MM-DD] [--json] * * `render` prints the plain-language summary (--summary , else /summary.md @@ -12,8 +12,9 @@ * taken if unanswered, approval items stay pending) and points at review-record.md * for the full review; --write also saves brief.md in the run directory. * `render --captain` prints the plan ask in the shape Capy Captains relay (lib/captain-brief.ts): header with - * the one-word reply, Before → after, Why it matters, What caused this work, Big decisions, What we need from - * you, and one trailing line for the relaying agent; a plan missing a section exits 1 + * the "do it" reply, Before → after, Why it matters, What caused this work, Big decisions, What we need from + * you (the lettered ask lines of docs/captain.md § The ask format, headed by --captain-name), and one + * trailing line for the relaying agent; a plan missing a section exits 1 * (CAPTAIN_BRIEF_INCOMPLETE) unless --allow-incomplete. --write saves captain-brief.md. * `close` rewrites every `draft direction stands until the owner decides` line in * the plan to the decided option and date; pending lines stay and are reported @@ -29,7 +30,7 @@ import { resultLine } from '../lib/result-codes'; const HELP = `gstack-owner-brief — one page for the owner: summary, URGENT block, numbered decisions (docs/unattended.md#owner-brief) render --out [--page N] [--summary ] [--write] [--json] - render --captain --out [--allow-incomplete] [--write] [--json] the plan ask for a Capy Captain (capy/skill/gstack/captain.md) + render --captain --out [--captain-name ] [--allow-incomplete] [--write] [--json] the plan ask for a Capy Captain (capy/skill/gstack/captain.md); --captain-name heads the lettered ask close --out --plan [--date YYYY-MM-DD] [--json] ${exitTableHelp()}`; @@ -49,7 +50,7 @@ function main(argv: string[]): number { const json = rest.includes('--json'); if (cmd === 'render' && rest.includes('--captain')) { - const brief = renderCaptainBrief(loaded.inputs, { outDir: path.resolve(out) }); + const brief = renderCaptainBrief(loaded.inputs, { outDir: path.resolve(out), captainName: flag(rest, '--captain-name') }); if (rest.includes('--write')) fs.writeFileSync(path.join(path.resolve(out), 'captain-brief.md'), brief.text); if (json) process.stdout.write(JSON.stringify({ run: loaded.inputs.gate.run, gate_rev: loaded.inputs.gate.gate_rev, rec_hash: brief.recHash, pending: brief.pending, missing: brief.missing, brief: brief.text }) + '\n'); else process.stdout.write(brief.text); diff --git a/bin/gstack-pregate b/bin/gstack-pregate index a7995aa41..b3f5297eb 100755 --- a/bin/gstack-pregate +++ b/bin/gstack-pregate @@ -67,15 +67,17 @@ const HELP = `gstack-pregate — cheap checks before anything paid or remote (do --only restrict to these checks (${CHECK_IDS.join(', ')}; tier 2 later: ${PREGATE_TIER2.join(', ')}) --base a branch on origin, not a commit (default: origin/HEAD's branch, else main) --allow-repo-commands run pin-file commands and the test runner (what /ship passes); without it those checks are incomplete - --policy-from base|head base (default, reviewed) or head (unreviewed; needs --allow-repo-commands) + --policy-from base|head base (default, reviewed) or head (unreviewed; needs --allow-repo-commands; the head file may + only add test lanes over the base copy, else PREGATE_HEAD_POLICY_LOOSENS) --out pregate.json path (default ${PREGATE_OUT_REL}) - --timeout timeout for each runner process (default 600): the unit-file group, each serial file, each guard - without timeout_s; the stall timeout catches a silent one sooner + --timeout timeout for each runner process (default timeout_s from the base .gstack/pregate.json, else 600): + the unit-file group, each serial file, each guard without timeout_s, the remote gate; the stall + timeout catches a silent one sooner --stall-timeout kill a test command's process group after this long with no output and record the check incomplete (PREGATE_STALLED); default stall_timeout_s from the base .gstack/pregate.json, - else ${DEFAULT_STALL_TIMEOUT_S}; 0 disables - --remote run the base branch's remote_gate now instead of local tests (needs --allow-repo-commands and - --policy-from base); it clears the requires-remote obligation only on its + else ${DEFAULT_STALL_TIMEOUT_S}; 0 disables; the --remote gate is exempt (only --timeout bounds it) + --remote run the base branch's remote_gate now instead of local tests (needs --allow-repo-commands; + under --policy-from head the gate is still the base copy's); it clears the requires-remote obligation only on its PREGATE_REMOTE: tree= tests= failed=0 line with n > 0 --spend-cap the cap --remote passes to the gate (default \$GSTACK_SPEND_CAP_USD); spend is reported as spent, reserved and unknown @@ -139,14 +141,15 @@ async function cmdRun(root: string, rest: string[], json: boolean): Promise (or set GSTACK_SPEND_CAP_USD)\n'); return EXIT.usage; } remote = { spendCapUsd: cap }; diff --git a/bin/gstack-review-dispatch b/bin/gstack-review-dispatch new file mode 100755 index 000000000..d7dd38f51 --- /dev/null +++ b/bin/gstack-review-dispatch @@ -0,0 +1,316 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * gstack-review-dispatch — /ship's reviewers get their briefs byte for byte and the parent changes + * nothing they return (GSTA-167 no-loss gate; docs/review-policy.md#verbatim-dispatch). + * + * gstack-review-dispatch render --role [--name ] --out [slots] write the brief, print its sha256 + * gstack-review-dispatch sent --ledger --role [--name ] --sent the prompt actually passed; mismatch fails + * gstack-review-dispatch collect --ledger --role [--name ] --output --merged + * gstack-review-dispatch judge --ledger --merged --judged no drop, no downgrade + * gstack-review-dispatch verify --ledger [--targeted-out ] replay every hash and the judgment + * gstack-review-dispatch pass --base --out --pass [-- plan flags] the pass's staged manifest + * gstack-review-dispatch show|stage|chunk|mark --manifest ... one manifest step + * gstack-review-dispatch program [--ledger ] the checked-in Capy pass program + * + * Logic: lib/review-brief.ts (rendering from the sections), lib/review-ledger.ts (ledger, collect, judge, verify), + * lib/review-pass.ts (the staged manifest) and lib/capy-review-pass.js (the Capy program that runs it). + */ +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 { BRIEF_ROLES, BriefError, briefFile, promptHash, renderBrief, sectionTexts, type BriefRole, type Slots } from '../lib/review-brief'; +import { cleanMarkers, collect, mayBeUnavailable, parseFindings, readJsonl, readLedger, readerKey, recordJudgment, recordSent, appendEvent, verify, type JudgedLine, type MergedLine, type VerifyRow } from '../lib/review-ledger'; +import { buildManifest, chunkCount, chunkOf, manifestPath, markReader, readManifest, renderStage, writeManifest, STAGES, type Extra, type Manifest, type PassReader, type ReaderState, type Stage } from '../lib/review-pass'; +import type { Dispatch } from '../lib/review-depth'; +import { runScriptSync } from '../lib/script-invocation'; +import { TARGETED_RULES, parseClassList, targetedBriefSha, targetedPatchId } from '../lib/review-targeted'; +import { resolveBaseBranch } from '../lib/ship-policy'; + +const HELP = `gstack-review-dispatch — verbatim reviewer briefs and loss-free collection for /ship + + render --role [--name ] --out [--ledger ] [slots] + roles: ${BRIEF_ROLES.join(', ')} + slots: --diff-base (every role but fix-check) --exclude '' --stack --test-fw + --learnings-file --checklist (default /review/specialists/.md; red-team.md for red-team) + --checklists (specialist-batched: the plan's checklists= names, or paths) --findings-file --specialists (red-team) + --fix-list --hunks --tests [--callers ] (fix-check) + --classes (targeted: the plan's TARGETED classes; the brief is review/specialists/targeted.md; + --diff-base must be the merge base with --base, default origin/HEAD's branch, on every pass) + writes /[-].prompt.md, records it in the ledger (default /review-ledger.jsonl) and prints + BRIEF: reader= sha256= bytes= file=. Pass that file's content as the reader's prompt, unchanged. + sent --ledger --role [--name ] --sent + the exact prompt a dispatch passed: BRIEF_SENT: … match, or BRIEF_MISMATCH: … (exit 1; the pass is not reviewed) + collect --ledger --role [--name ] --output --merged + the reader's raw output: hashes it and appends each finding to merged.jsonl with its label as written. A reply with + no finding must carry its brief's clean marker (NO FINDINGS; the Recommendation: line for the voices); without one it is + COLLECT_NOT_REVIEWED (exit 1): a refusal, an empty reply or a reader that never saw the diff, and verify reports NOT_COLLECTED + until the brief is re-sent and answered with a review, which voids it. --unavailable '' (the outside voice only; refused when the + output holds findings) records its failure text as missing coverage: COLLECT_UNAVAILABLE, and verify prints UNAVAILABLE and unavailable=N, never a review + judge --ledger --merged --judged + judged lines {"id","severity","reason"?,"duplicate_of"?}: every merged id kept at its severity or above (a + duplicate folds into one at least as severe); added and promoted findings need a reason. JUDGMENT: ok …, or + JUDGMENT_REJECTED: dropped=… downgraded=… (exit 1) + verify --ledger [--targeted-out ] + BRIEF, OUTPUT and JUDGE rows from the ledger alone, then VERIFY: clean (exit 0), VERIFY: dirty (exit 1) or + VERIFY: no brief records (exit 3: this run's ledger kept no prompts). A ledger with a targeted brief also prints + TARGETED_RECORD: and --targeted-out writes it as the JSON gstack-ship-receipt write --review-targeted reads + pass --base --out --pass [--ledger ] [--diff-base ] [--learnings-file ] [--extras ] + [--checklist-root ] [-- ] + runs gstack-review-plan and writes /pass-manifest.json: stage first (audit readers marked first in --extras), + specialists (with the other --extras readers), red-team, voices (Step 11). Renders first and specialists now; prints + the plan, MANIFEST: and one READER: line per reader. A plan whose NEXT is not full or scoped prints PASS: none. + An existing manifest for the same --pass is reused (resumed). --extras: [{"name","prompt_file","first"?,"model"?}] + show --manifest MANIFEST_JSON: + stage --manifest --stage + renders a stage; the Red Team only after every earlier reader is collected, its findings file being the + specialists' merged.jsonl lines byte for byte + chunk --manifest --reader --index + BRIEF_CHUNK: reader=… index=i of=n sha256=…, then one JSON string line of at most 65,536 brief characters + mark --manifest --reader --state [--path

] [--output ] [--error ] + mark --manifest --before , + mark --manifest --log-start --token records a review-log start token once, so a rerun starts only what is missing + reader states move forward only; intent is recorded before the subagent is created, its path right after + program [--ledger ] + PROGRAM: v sha256=… bytes=…, then lib/capy-review-pass.js as one JSON string line (see the gstack Capy skill) +${exitTableHelp()}`; + +const args = process.argv.slice(2); +const flag = (n: string) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : undefined; }; +const readFile = (f: string | undefined, what: string) => { + if (!f) return undefined; + try { return fs.readFileSync(f, 'utf8'); } catch { throw new BriefError(`cannot read ${what} file ${f}`); } +}; +const ROOT = path.resolve(import.meta.dir, '..'); + +function render(): number { + const role = flag('--role') as BriefRole | undefined; + const out = flag('--out'); + if (!role || !BRIEF_ROLES.includes(role) || !out) { process.stderr.write(`gstack-review-dispatch render: needs --role <${BRIEF_ROLES.join('|')}> and --out

\n`); return EXIT.usage; } + const name = flag('--name'); + const diffBase = flag('--diff-base'); + const checklist = flag('--checklist') ?? (role === 'red-team' ? path.join(ROOT, 'review/specialists/red-team.md') : role === 'targeted' ? path.join(ROOT, 'review/specialists/targeted.md') : role === 'specialist' && name ? path.join(ROOT, 'review/specialists', `${name}.md`) : undefined); + if (checklist && (role === 'specialist' || role === 'red-team' || role === 'targeted') && !fs.existsSync(checklist)) throw new BriefError(`checklist not found: ${checklist}`); + const brief = role === 'targeted' ? readFile(checklist, 'targeted brief') : undefined; + if (role === 'targeted') { + const base = resolveBaseBranch(process.cwd(), flag('--base')); + const mb = [`origin/${base}`, base].map(ref => spawnSync('git', ['merge-base', ref, 'HEAD'], { encoding: 'utf8', timeout: 30_000 })).find(r => r.status === 0)?.stdout.trim(); + const full = diffBase ? spawnSync('git', ['rev-parse', '--verify', '--quiet', `${diffBase}^{commit}`], { encoding: 'utf8', timeout: 30_000 }).stdout?.trim() : undefined; + if (!full || full !== mb) throw new BriefError(`the targeted reader reads the whole diff on every pass: --diff-base must be the merge base with ${base} (${mb ?? 'unresolved'}), got ${diffBase ?? 'none'}`); + } + const checklists = flag('--checklists')?.split(',').map(s => s.trim()).filter(Boolean).map(c => (c.includes('/') ? c : path.join(ROOT, 'review/specialists', `${c}.md`))); + for (const c of checklists ?? []) if (!fs.existsSync(c)) throw new BriefError(`checklist not found: ${c}`); + let diff: string | undefined; + if (role === 'outside-voice' && diffBase) { + const r = spawnSync('git', ['-c', 'core.quotePath=false', 'diff', '--no-color', '--no-ext-diff', diffBase], { encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); + if (r.status !== 0) throw new BriefError(`git diff ${diffBase} failed: ${(r.stderr ?? '').trim().split('\n')[0]}`); + diff = r.stdout; + } + const slots: Slots = { + name, diff_base: diffBase, exclude: flag('--exclude'), stack: flag('--stack'), test_fw: flag('--test-fw'), + learnings: readFile(flag('--learnings-file'), 'learnings'), checklist, checklists: checklists?.join(','), + findings: readFile(flag('--findings-file'), 'findings'), specialists: flag('--specialists'), diff, + classes: flag('--classes'), brief, + fix_list: readFile(flag('--fix-list'), 'fix list'), hunks: readFile(flag('--hunks'), 'hunks'), tests: readFile(flag('--tests'), 'tests'), callers: readFile(flag('--callers'), 'callers'), + }; + const text = renderBrief(role, slots, sectionTexts(ROOT)); + fs.mkdirSync(out, { recursive: true, mode: 0o700 }); + const file = path.join(path.resolve(out), briefFile(role, name)); + fs.writeFileSync(file, text, { mode: 0o600 }); + const ledger = flag('--ledger') ?? path.join(out, 'review-ledger.jsonl'); + const sha = promptHash(text); + const targeted = brief === undefined ? {} : { classes: parseClassList(flag('--classes')!), rules: TARGETED_RULES, brief_sha: targetedBriefSha(checklist), diff_base: diffBase ?? null, patch_id: diffBase ? targetedPatchId(process.cwd(), diffBase) : 'none' }; + appendEvent(ledger, { event: 'rendered', reader: readerKey(role, name), role, name: name ?? null, file, sha256: sha, bytes: Buffer.byteLength(text), ...targeted }); + process.stdout.write(`BRIEF: reader=${readerKey(role, name)} sha256=${sha} bytes=${Buffer.byteLength(text)} file=${file}\n`); + return EXIT.ok; +} + +const PROGRAM_FILE = path.join(ROOT, 'lib', 'capy-review-pass.js'); +const PROGRAM_VERSION = 1; +const git = (a: string[]) => { const r = spawnSync('git', a, { encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); return r.status === 0 ? r.stdout : null; }; +const readerLine = (m: Manifest, r: PassReader) => `READER: ${r.reader} stage=${r.stage} state=${r.state} title="${r.title}"${r.sha256 ? ` sha256=${r.sha256} bytes=${r.bytes} chunks=${r.chunks}` : ''}${r.path ? ` path=${r.path}` : ''}`; +const branchDiff = (base: string) => { + const d = git(['-c', 'core.quotePath=false', 'diff', '--no-color', '--no-ext-diff', base]); + if (d === null) throw new BriefError(`git diff ${base} failed`); + return d; +}; + +function pass(): number { + const base = flag('--base'), out = flag('--out'), id = flag('--pass'); + if (!base || !out || !id || !/^[a-z0-9-]+$/.test(id)) { process.stderr.write('gstack-review-dispatch pass: needs --base , --out and --pass (lowercase letters, digits, dashes)\n'); return EXIT.usage; } + const file = manifestPath(out); + if (fs.existsSync(file)) { + const m = readManifest(file); + if (m.pass !== id) throw new BriefError(`${file} belongs to pass ${m.pass}, not ${id}`); + process.stdout.write([...m.plan_lines, `MANIFEST: file=${file} pass=${m.pass} readers=${m.readers.length} resumed`, ...m.readers.map(r => readerLine(m, r))].join('\n') + '\n'); + return EXIT.ok; + } + const planArgs = args.includes('--') ? args.slice(args.indexOf('--') + 1) : []; + const plan = (json: boolean) => runScriptSync(path.join(ROOT, 'bin', 'gstack-review-plan'), ['--base', base, ...planArgs, ...(json ? ['--json'] : [])], { encoding: 'utf8', timeout: 180_000, maxBuffer: 64 * 1024 * 1024 }); + const text = plan(false); + if (text.status !== 0) { process.stdout.write(text.stdout ?? ''); process.stderr.write(text.stderr ?? ''); return EXIT.fail; } + const j = plan(true); + if (j.status !== 0) { process.stderr.write(j.stderr ?? ''); return EXIT.fail; } + const p = JSON.parse(j.stdout) as { next: { step: string }; dispatches: Dispatch[]; targeted?: { classes: string[] } }; + const planLines = text.stdout.trimEnd().split('\n'); + const step = p.next.step; + if (step !== 'full' && step !== 'scoped') { process.stdout.write([...planLines, `PASS: none next=${step} (no reviewer pass; follow NEXT)`].join('\n') + '\n'); return EXIT.ok; } + const diffBase = flag('--diff-base') ?? git(['merge-base', base, 'HEAD'])?.trim(); + if (!diffBase) throw new BriefError(`no merge base between ${base} and HEAD`); + const root = git(['rev-parse', '--show-toplevel'])?.trim() ?? process.cwd(); + const extrasFile = flag('--extras'); + const extras = extrasFile ? JSON.parse(readFile(extrasFile, 'extras')!) as Extra[] : []; + const m = buildManifest({ pass: id, out, ledger: flag('--ledger') ?? path.join(out, 'review-ledger.jsonl'), base, diffBase, root, checklistRoot: flag('--checklist-root') ?? ROOT, + dispatches: p.dispatches, next: step, planLines, learnings: readFile(flag('--learnings-file'), 'learnings') ?? null, extras, + targetedClasses: p.targeted?.classes, mergeBase: git(['merge-base', base, 'HEAD'])?.trim() }); + fs.mkdirSync(m.out, { recursive: true, mode: 0o700 }); + const t = sectionTexts(ROOT); + renderStage(m, 'first', t, branchDiff); + renderStage(m, 'specialists', t, branchDiff); + writeManifest(file, m); + const count = (s: string) => m.readers.filter(r => r.stage === s).length; + process.stdout.write([...planLines, `MANIFEST: file=${file} pass=${id} readers=${m.readers.length} first=${count('first')} specialists=${count('specialists')} red-team=${count('red-team')} voices=${count('voices')}`, ...m.readers.map(r => readerLine(m, r))].join('\n') + '\n'); + return EXIT.ok; +} + +function passStep(cmd: string): number { + const file = flag('--manifest'); + if (!file) { process.stderr.write(`gstack-review-dispatch ${cmd}: --manifest is required\n`); return EXIT.usage; } + const m = readManifest(file); + if (cmd === 'show') { process.stdout.write(`MANIFEST_JSON: ${JSON.stringify(m)}\n`); return EXIT.ok; } + if (cmd === 'stage') { + const stage = flag('--stage') as Stage | undefined; + if (!stage || !STAGES.includes(stage)) { process.stderr.write(`gstack-review-dispatch stage: --stage ${STAGES.join('|')}\n`); return EXIT.usage; } + const done = renderStage(m, stage, sectionTexts(ROOT), branchDiff); + writeManifest(file, m); + process.stdout.write([`STAGE: ${stage} rendered=${done.length}`, ...done.map(r => readerLine(m, r))].join('\n') + '\n'); + return EXIT.ok; + } + if (cmd === 'chunk') { + const r = m.readers.find(x => x.reader === flag('--reader')); + if (!r?.file || !r.sha256) { process.stderr.write(`gstack-review-dispatch chunk: no rendered reader ${flag('--reader')}\n`); return EXIT.usage; } + const text = readFile(r.file, 'brief')!; + if (promptHash(text) !== r.sha256) throw new BriefError(`${r.reader}'s brief ${r.file} changed since it was rendered`); + const index = Number(flag('--index') ?? '0'); + process.stdout.write(`BRIEF_CHUNK: reader=${r.reader} index=${index} of=${chunkCount(text)} sha256=${r.sha256}\n${JSON.stringify(chunkOf(text, index))}\n`); + return EXIT.ok; + } + if (cmd === 'mark') { + const logStart = flag('--log-start'); + if (logStart) { + const token = flag('--token'); + if (!token) { process.stderr.write('gstack-review-dispatch mark: --log-start --token \n'); return EXIT.usage; } + m.log_starts ??= {}; + m.log_starts[logStart] ??= token; + writeManifest(file, m); + process.stdout.write(`LOG_START: ${logStart} token=${m.log_starts[logStart]}\n`); + return EXIT.ok; + } + const before = flag('--before'); + if (before) { + const [tokens, credits] = before.split(',').map(Number); + if (!Number.isFinite(tokens) || !Number.isFinite(credits)) { process.stderr.write('gstack-review-dispatch mark: --before ,\n'); return EXIT.usage; } + m.before ??= { tokens: tokens!, credits: credits! }; + writeManifest(file, m); + process.stdout.write(`BEFORE: tokens=${m.before.tokens} credits=${m.before.credits}\n`); + return EXIT.ok; + } + const r = markReader(m, flag('--reader') ?? '', flag('--state') as ReaderState, { path: flag('--path'), output: flag('--output'), error: flag('--error') }); + writeManifest(file, m); + process.stdout.write(readerLine(m, r) + '\n'); + return EXIT.ok; + } + return EXIT.usage; +} + +function program(): number { + const text = readFile(PROGRAM_FILE, 'pass program')!; + const sha = promptHash(text); + const ledger = flag('--ledger'); + if (ledger) appendEvent(ledger, { event: 'program', version: PROGRAM_VERSION, sha256: sha }); + process.stdout.write(`PROGRAM: v${PROGRAM_VERSION} sha256=${sha} bytes=${Buffer.byteLength(text)}\n${JSON.stringify(text)}\n`); + return EXIT.ok; +} + +/** + * The receipt's review_targeted record from the newest targeted dispatch: done only when its brief was sent verbatim, its output + * collected, and the committed diff it was rendered on is still the one at verify (targetedPatchId; uncommitted never proves it). + */ +function targetedRecord(ledger: string, rows: VerifyRow[]): { classes: string[]; rules: string; brief_sha: string; status: 'done' | 'failed'; findings: number; raised_by: string } | null { + const events = readLedger(ledger); + const render = events.filter(e => e.event === 'rendered' && e.reader === 'targeted').at(-1); + if (!render) return null; + const label = rows.filter(r => r.kind === 'BRIEF' && r.reader.split('@')[0] === 'targeted').at(-1)?.reader; + const brief = rows.filter(r => r.kind === 'BRIEF' && r.reader === label).at(-1); + const output = rows.filter(r => r.kind === 'OUTPUT' && r.reader === label).at(-1); + const read = typeof render.patch_id === 'string' && !['uncommitted', 'none'].includes(render.patch_id) && typeof render.diff_base === 'string' && targetedPatchId(process.cwd(), render.diff_base) === render.patch_id; + const done = brief?.status === 'MATCH' && output?.status === 'MATCH' && read; + const ids = events.filter(e => e.event === 'output' && e.reader === 'targeted').at(-1)?.ids; + return { classes: (render.classes as string[]) ?? [], rules: String(render.rules), brief_sha: String(render.brief_sha), status: done ? 'done' : 'failed', findings: done && Array.isArray(ids) ? ids.length : 0, raised_by: 'targeted' }; +} + +function main(): number { + const cmd = args[0]; + if (!cmd || cmd === '--help' || cmd === '-h') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; } + if (cmd === 'render') return render(); + if (cmd === 'pass') return pass(); + if (cmd === 'program') return program(); + if (['show', 'stage', 'chunk', 'mark'].includes(cmd)) return passStep(cmd); + const ledger = flag('--ledger'); + if (!ledger) { process.stderr.write(`gstack-review-dispatch ${cmd}: --ledger is required\n`); return EXIT.usage; } + const reader = flag('--role') ? readerKey(flag('--role')!, flag('--name')) : ''; + if (cmd === 'sent') { + const sent = readFile(flag('--sent'), 'sent prompt'); + if (!reader || sent === undefined) { process.stderr.write('gstack-review-dispatch sent: needs --role and --sent \n'); return EXIT.usage; } + const r = recordSent(ledger, reader, sent); + process.stdout.write(r.ok ? `BRIEF_SENT: reader=${reader} sha256=${r.sent} match\n` + : `BRIEF_MISMATCH: reader=${reader} rendered=${r.rendered ?? 'none'} sent=${r.sent} (dispatch the rendered file unchanged; this reader's review does not count)\n`); + return r.ok ? EXIT.ok : EXIT.fail; + } + if (cmd === 'collect') { + const outFile = flag('--output'); + const output = readFile(outFile, 'reader output'); + const merged = flag('--merged'); + if (!reader || output === undefined || !merged) { process.stderr.write('gstack-review-dispatch collect: needs --role, --output and --merged \n'); return EXIT.usage; } + const unavailable = flag('--unavailable'); + if (unavailable !== undefined && !mayBeUnavailable(reader)) { process.stderr.write(`gstack-review-dispatch collect: --unavailable is for the outside voice only; ${reader}'s missing coverage leaves the review incomplete, never clean\n`); return EXIT.usage; } + if (unavailable !== undefined && !unavailable.trim()) { process.stderr.write('gstack-review-dispatch collect: --unavailable needs a reason\n'); return EXIT.usage; } + if (unavailable !== undefined && parseFindings(reader, output).length) { process.stderr.write(`gstack-review-dispatch collect: ${reader}'s output holds findings; collect it without --unavailable so none is lost\n`); return EXIT.usage; } + const r = collect(ledger, reader, output, merged, path.resolve(outFile!), unavailable); + if (unavailable !== undefined) { process.stdout.write(`COLLECT_UNAVAILABLE: reader=${reader} sha256=${r.sha} reason=${JSON.stringify(unavailable)} (missing outside coverage: unavailable, never clean)\n`); return EXIT.ok; } + if (!r.review) { + process.stdout.write(`COLLECT_NOT_REVIEWED: reader=${reader} findings=0 sha256=${r.sha} (no finding and no ${cleanMarkers(reader).map(([m]) => m).join(' or ')} line: a refusal, an empty reply or a reader that never saw the diff is not a review; verify reports this brief NOT_COLLECTED)\n`); + return EXIT.fail; + } + process.stdout.write(`COLLECT: reader=${reader} findings=${r.lines.length} sha256=${r.sha} merged=${merged}\n`); + return EXIT.ok; + } + if (cmd === 'judge') { + const merged = flag('--merged'); + const judged = flag('--judged'); + if (!merged || !judged) { process.stderr.write('gstack-review-dispatch judge: needs --merged and --judged \n'); return EXIT.usage; } + const r = recordJudgment(ledger, readJsonl(merged), readJsonl(judged), judged, merged); + process.stdout.write(r.ok ? `JUDGMENT: ok added=${r.added.length} promoted=${r.promoted.length} folded=${r.folded.length}\n` + : `JUDGMENT_REJECTED: dropped=${JSON.stringify(r.dropped)} downgraded=${JSON.stringify(r.downgraded)} unexplained=${JSON.stringify(r.unexplained)} invalid=${JSON.stringify(r.invalid)} (lead judgment may add or promote a finding, never drop or downgrade one)\n`); + return r.ok ? EXIT.ok : EXIT.fail; + } + if (cmd === 'verify') { + const v = verify(ledger); + for (const r of v.rows) process.stdout.write(`${r.kind} ${r.reader} ${r.status} ${r.detail}\n`); + if (!v.briefs) { process.stdout.write('VERIFY: no brief records (this run\'s ledger kept no prompts; dispatched-vs-rendered cannot be checked)\n'); return EXIT.refused; } + const record = targetedRecord(ledger, v.rows); + if (record) { + process.stdout.write(`TARGETED_RECORD: classes=${record.classes.join(',')} status=${record.status} findings=${record.findings} brief=${record.brief_sha.slice(0, 12)} rules=${record.rules}\n`); + if (flag('--targeted-out')) fs.writeFileSync(flag('--targeted-out')!, JSON.stringify(record) + '\n'); + } + process.stdout.write(`VERIFY: ${v.clean ? 'clean' : 'dirty'} briefs=${v.briefs} outputs=${v.rows.filter(r => r.kind === 'OUTPUT').length} voided=${v.voided}${v.unavailable ? ` unavailable=${v.unavailable}` : ''}\n`); + return v.clean ? EXIT.ok : EXIT.fail; + } + process.stderr.write(`gstack-review-dispatch: unknown command ${cmd}\n${HELP}\n`); + return EXIT.usage; +} + +try { process.exit(main()); } catch (e) { + if (e instanceof BriefError) { process.stderr.write(`BRIEF_RENDER_FAILED: ${e.message}\n`); process.exit(EXIT.fail); } + throw e; +} diff --git a/bin/gstack-review-log b/bin/gstack-review-log index 0a7037120..ae60e73a7 100755 --- a/bin/gstack-review-log +++ b/bin/gstack-review-log @@ -6,7 +6,8 @@ # Under a /ship token cap (docs/ship-budget.md): --start SKILL --reservation ID # with the RESERVATION id gstack-ship-budget check printed for this dispatch # batch; refuses (exit 1, BUDGET_CHECK_SKIPPED) without an unspent one, and -# --finish settles it. Without a cap no marker exists and nothing changes. +# --finish settles it with the pass's other dispatch reservations of that +# step. Without a cap no marker exists and nothing changes. # Fix-range repeat (#3339): gstack-review-log --start review --fix-range # prints the token, then FIX_BASE=; refuses (exit 1) unless the latest # pass completed with fixes on unchanged content and its commit is an @@ -151,12 +152,13 @@ try { echo "$STAMPED" >> "$GSTACK_HOME/projects/$SLUG/$BRANCH-reviews.jsonl" -# A finished dispatch settles the budget reservation its start consumed (its -# completion receipt); stdout stays unchanged and a failure never undoes the row. +# A finished pass settles the budget reservation its start consumed (its +# completion receipt) and every other dispatch reservation started in the same +# step; stdout stays unchanged and a failure never undoes the row. if [ -n "$TOKEN" ] && [ -f "$GSTACK_SHIP_BUDGET_MARKER" ]; then GSTACK_REVIEW_TOKEN="$TOKEN" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e ' const { settleReviewFinish } = await import(process.env.GSTACK_SHIP_BUDGET_LIB); - try { const id = settleReviewFinish(process.env.GSTACK_SHIP_BUDGET_MARKER, process.env.GSTACK_REVIEW_TOKEN); if (id) console.error("review-log: settled budget reservation " + id); } + try { const id = settleReviewFinish(process.env.GSTACK_SHIP_BUDGET_MARKER, process.env.GSTACK_REVIEW_TOKEN); if (id) console.error("review-log: settled budget reservations " + id); } catch (e) { console.error("review-log: budget reservation not settled: " + e.message); } ' || true fi diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan index 06f3e3976..818d3c6a8 100755 --- a/bin/gstack-review-plan +++ b/bin/gstack-review-plan @@ -4,14 +4,16 @@ * * gstack-review-plan --base [--pass ] [--last none|full|fix-check] [--fixed-blocking] [--fixed-below] * [--blocking-open] [--touched-gate] [--critical-found] [--adversarial-ran] [--gate-tagged ] [--gated a,b] [--force a,b|all] - * [--reviewed-numbers ] [--depth-floor standard|full] [--no-tiers] [--json] + * [--reviewed-numbers ] [--depth-floor standard|full] [--range-base ] [--pass1-depth light|standard|full] [--no-tiers] + * [--targeted-ran ] [--json] * gstack-review-plan --fix-check-prompt --fix-list --hunks --tests [--callers ] * * Reads the diff against the merge base with (committed, tracked uncommitted * edits and untracked files, through lib/review-collect.ts collectLive), runs * gstack-diff-scope and, unless --gate-tagged is given, gstack-gate-diff; prints * REVIEW_CLASS:, REVIEW_DEPTH: (depth, runtime lines, the rules hash, reasons and - * result codes), GATE_SCAN:, REVIEW_PLAN:, one DEPTH_ERROR: per input that failed + * result codes), GATE_SCAN:, TARGETED: (the money, gate, auth and secret classes, lib/review-targeted.ts), + * FIX_RANGE: (with --range-base), REVIEW_PLAN:, one DEPTH_ERROR: per input that failed * the depth closed, one DISPATCH: plus DIFF_CMD: (and DIFF_EXCLUDE: none) per * reviewer and one SKIP: per reviewer left out. A plan that fails closed to full * exits 0; a diff git cannot list exits 1. Logic: lib/review-depth.ts. @@ -21,8 +23,9 @@ import * as path from 'node:path'; import { spawnSync } from 'node:child_process'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { runScriptSync } from '../lib/script-invocation'; -import { collectLive } from '../lib/review-collect'; -import { diffCommand, planReview, reviewDepthLine, reviewPlanLine, scanNumbers, type Depth, type History } from '../lib/review-depth'; +import { collectCommit, collectLive } from '../lib/review-collect'; +import { classifyDiff, diffCommand, planReview, reviewDepthLine, reviewPlanLine, scanNumbers, SCOPED_RANGE_LINES, type Depth, type History } from '../lib/review-depth'; +import { classList, targetedBriefSha, targetedClasses, targetedPatchId } from '../lib/review-targeted'; import { renderFixCheckPrompt } from '../scripts/resolvers/fix-check'; const HELP = `gstack-review-plan — the review depth of the next /ship step (docs/review-policy.md#review-depth) @@ -31,21 +34,31 @@ const HELP = `gstack-review-plan — the review depth of the next /ship step (do --pass full review passes already run in this invocation (default 0) --last none|full|fix-check the step that just finished (default none: plan pass 1) --fixed-blocking the finished step fixed a blocking finding (raises light to standard) - --fixed-below the finished step fixed findings below the floor + --fixed-below the finished step fixed findings below the floor (ignored after a fix-check: below-floor + fixes never repeat review, so only --fixed-blocking or --blocking-open stops there) --blocking-open a blocking finding is still open in fix scope --touched-gate a fix touched a gate-class path --critical-found a specialist reported a CRITICAL finding (Red Team on code class; raises light to standard) --adversarial-ran Step 11's native adversarial pass already ran (a repeat skips it) --gate-tagged gate hunks the gate scan tagged (default: run gstack-gate-diff; failure means unavailable) --gated a,b specialists the hit-rate stats tag GATE_CANDIDATE - --force a,b|all specialists forced by prompt flags (--all-specialists is all) + --force a,b|all specialists forced by prompt flags (--all-specialists is all): at standard and full depth they join the + batched specialist's checklists, where maintainability, performance and simplification are read only when + forced; light runtime-0 and scoped passes dispatch them one reader each --reviewed-numbers the numeric-claim fingerprint the outside voice already reviewed --depth-floor standard|full raise the depth to at least this (never lowers it); /ship passes its prompt flag on every run - --no-tiers audits and watchers at the host's default effort too (as gstack-config review_effort_tiers off does) + --range-base the fix range's base (this pass's PASS_HEAD): after a fixed blocker on a diff below full depth, a + committed range of at most ${SCOPED_RANGE_LINES} runtime lines plans a scoped pass; anything unread plans the full pass + --no-tiers specialists, audits and watchers at the host's default effort too (as gstack-config review_effort_tiers off does) --json the plan as JSON (depth, runtime_lines, rules, errors with input and repair, gate_scan, per-dispatch exclude) + --pass1-depth pass 1's REVIEW_DEPTH depth: full, or absent, keeps pass 2 full + --targeted-ran the TARGETED line's targeted_patch_id (the whole committed diff, tests included) when the targeted + reader last read it: the same patch skips it; any other id, none, or uncommitted edits dispatch it again --fix-check-prompt print the fix-check reviewer's prompt from --fix-list, --hunks, --tests and --callers files -Depth: light (runtime lines <= 50), standard (above 50), full (gate class or any DEPTH_ERROR). A full plan +Depth: light (runtime lines <= 50), standard (above 50), full (gate class or any DEPTH_ERROR). TARGETED: the money, +gate, auth and secret classes the diff touches; any class dispatches the targeted reader at every depth. NEXT: full, scoped +(a full pass on the range: fix-check, Red Team, native adversarial), fix-check, stop or done. A full plan from an error exits 0; exit 1 means no plan could be built (git could not list the diff). ${exitTableHelp()}`; @@ -72,10 +85,14 @@ function main(): number { if (!base) { process.stderr.write(`gstack-review-plan: --base is required\n${HELP}\n`); return EXIT.usage; } const last = (flag('--last') ?? 'none') as History['last']; if (!['none', 'full', 'fix-check'].includes(last)) { process.stderr.write('gstack-review-plan: --last must be none, full or fix-check\n'); return EXIT.usage; } + const pass1Depth = (flag('--pass1-depth') ?? 'full') as Depth; + if (!['light', 'standard', 'full'].includes(pass1Depth)) { process.stderr.write('gstack-review-plan: --pass1-depth must be light, standard or full\n'); return EXIT.usage; } const pass = Number(flag('--pass') ?? '0'); if (!Number.isInteger(pass) || pass < 0) { process.stderr.write('gstack-review-plan: --pass needs an integer >= 0\n'); return EXIT.usage; } const floor = flag('--depth-floor') as Depth | undefined; if (has('--depth-floor') && floor !== 'standard' && floor !== 'full') { process.stderr.write('gstack-review-plan: --depth-floor must be standard or full (a floor only raises the depth)\n'); return EXIT.usage; } + const rangeBase = flag('--range-base'); + if (has('--range-base') && (!rangeBase || rangeBase.startsWith('-'))) { process.stderr.write('gstack-review-plan: --range-base needs the fix range\'s base commit (this pass\'s PASS_HEAD)\n'); return EXIT.usage; } const root = git(['rev-parse', '--show-toplevel'])?.trim(); if (!root) { process.stderr.write('gstack-review-plan: run it inside a git checkout\n'); return EXIT.fail; } process.chdir(root); @@ -86,34 +103,58 @@ function main(): number { } const head = git(['rev-parse', 'HEAD'])?.trim() ?? 'unknown'; const binDir = path.dirname(Bun.fileURLToPath(import.meta.url)); - const scopeRun = runScriptSync(path.join(binDir, 'gstack-diff-scope'), [base], { encoding: 'utf8', timeout: 60_000 }); - const scope: Record = {}; - for (const l of (scopeRun.stdout ?? '').split('\n')) { const m = /^(SCOPE_[A-Z_]+)=(.*)$/.exec(l); if (m) scope[m[1]!] = m[2]!; } - if (scopeRun.status !== 0 && !scope.SCOPE_ERROR) scope.SCOPE_ERROR = `exit ${scopeRun.status}`; - let gateTagged: number | null = null; - if (flag('--gate-tagged') !== undefined) gateTagged = Number(flag('--gate-tagged')); - else { - const g = runScriptSync(path.join(binDir, 'gstack-gate-diff'), [base], { encoding: 'utf8', timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }); + const scopeOf = (args: string[]): Record => { + const run = runScriptSync(path.join(binDir, 'gstack-diff-scope'), args, { encoding: 'utf8', timeout: 60_000 }); + const s: Record = {}; + for (const l of (run.stdout ?? '').split('\n')) { const m = /^(SCOPE_[A-Z_]+)=(.*)$/.exec(l); if (m) s[m[1]!] = m[2]!; } + if (run.status !== 0 && !s.SCOPE_ERROR) s.SCOPE_ERROR = `exit ${run.status}`; + return s; + }; + const gateTagsOf = (args: string[]): number | null => { + const g = runScriptSync(path.join(binDir, 'gstack-gate-diff'), args, { encoding: 'utf8', timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }); const m = /GATE_SUMMARY: .*?tagged=\{([^}]*)\}/.exec(g.stdout ?? ''); - gateTagged = g.status === 0 && m ? m[1]!.split(',').reduce((n, kv) => n + (Number(kv.split(':')[1]) || 0), 0) : null; - } + return g.status === 0 && m ? m[1]!.split(',').reduce((n, kv) => n + (Number(kv.split(':')[1]) || 0), 0) : null; + }; + const scope = scopeOf([base]); + let gateTagged = flag('--gate-tagged') !== undefined ? Number(flag('--gate-tagged')) : gateTagsOf([base]); if (gateTagged !== null && !Number.isFinite(gateTagged)) gateTagged = null; const force = flag('--force') === 'all' ? 'all' as const : list('--force'); const tiersSetting = runScriptSync(path.join(binDir, 'gstack-config'), ['get', 'review_effort_tiers'], { encoding: 'utf8', timeout: 15_000 }); const auditEffort = has('--no-tiers') || (tiersSetting.stdout ?? '').trim() === 'off' ? 'host' : 'light'; const { added, diffLines, paths, deleted, stampOnly, perPath, registry } = collected; + let fixRange: { base: string; runtime_lines: number | null; error?: string; touched_gate?: true } | undefined; + if (rangeBase) { + const unread = (error: string) => ({ base: rangeBase, runtime_lines: null, error }); + const resolved = git(['rev-parse', '--verify', '--quiet', `${rangeBase}^{commit}`])?.trim(); + if (!resolved) fixRange = unread('not a commit in this repository'); + else if (git(['merge-base', '--is-ancestor', resolved, 'HEAD']) === null) fixRange = unread('not an ancestor of HEAD'); + else if (git(['diff', '--quiet', 'HEAD', '--']) === null || collected.untracked.length) fixRange = unread('uncommitted or untracked edits: commit the fixes first'); + else { + const commit = collectCommit(root, resolved, 'HEAD'); + const range = classifyDiff({ ...commit, registry, scope: scopeOf([resolved, '--head', 'HEAD']), gateTagged: gateTagsOf([resolved]) }); + fixRange = range.errors.length ? unread(range.errors.map(e => `${e.code} ${e.input}`).join('; ')) + : !commit.paths.length ? unread('the fix range is empty: commit the fix after the range base') + : { base: rangeBase, runtime_lines: range.runtimeLines, ...(range.class === 'gate' ? { touched_gate: true as const } : {}) }; + } + } + const targeted = targetedClasses({ ...collected, scope, gateTagged }); + const patch = collected.mergeBase ? targetedPatchId(process.cwd(), collected.mergeBase) : 'none'; + const brief = targetedBriefSha(); const plan = planReview({ - ...collected, scope, gateTagged, numbers: scanNumbers(added), force, gated: list('--gated'), floor, + ...collected, scope, gateTagged, targeted: { classes: targeted.classes, ran: !['uncommitted', 'none'].includes(patch) && flag('--targeted-ran') === patch }, numbers: scanNumbers(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'), blockingOpen: has('--blocking-open'), touchedGate: has('--touched-gate') }, + history: { fullPasses: pass, last, fixedBlocking: has('--fixed-blocking'), fixedBelow: has('--fixed-below') && last !== 'fix-check', blockingOpen: has('--blocking-open'), touchedGate: has('--touched-gate') || !!fixRange?.touched_gate, pass1Depth, rangeRuntimeLines: fixRange?.runtime_lines }, }); const gateScan = { tagged: gateTagged, head }; if (has('--json')) { const { runtimeLines, stepDepth, depthReasons, ...rest } = plan; - process.stdout.write(JSON.stringify({ ...rest, step_depth: stepDepth, runtime_lines: runtimeLines, depth_reasons: depthReasons, depth_floor: floor ?? null, gate_scan: gateScan, registry: { sha: registry.sha, outputs: registry.outputs }, per_path: perPath, diff_lines: diffLines, pass, audit_effort: auditEffort, scope, gate_tagged: gateTagged, paths, deleted, stamp_only: stampOnly }) + '\n'); + process.stdout.write(JSON.stringify({ ...rest, targeted: { ...targeted, brief, targeted_patch_id: patch }, step_depth: stepDepth, runtime_lines: runtimeLines, depth_reasons: depthReasons, depth_floor: floor ?? null, gate_scan: gateScan, fix_range: fixRange ?? null, registry: { sha: registry.sha, outputs: registry.outputs }, per_path: perPath, diff_lines: diffLines, pass, audit_effort: auditEffort, scope, gate_tagged: gateTagged, paths, deleted, stamp_only: stampOnly, consumed: collected.consumed }) + '\n'); return EXIT.ok; } - const out = [`REVIEW_CLASS: ${plan.class} (${plan.reasons.slice(0, 3).join('; ') || 'no signals'})`, reviewDepthLine(plan), `GATE_SCAN: ${gateTagged === null ? 'unavailable' : `tagged=${gateTagged}`} head=${head}`, reviewPlanLine(plan, pass + (plan.next.step === 'full' ? 1 : 0)), `NEXT: ${plan.next.step} (${plan.next.reason})`]; + const out = [`REVIEW_CLASS: ${plan.class} (${plan.reasons.slice(0, 3).join('; ') || 'no signals'})`, reviewDepthLine(plan), `GATE_SCAN: ${gateTagged === null ? 'unavailable' : `tagged=${gateTagged}`} head=${head}`, + `TARGETED: classes=${classList(targeted.classes)} rules=${targeted.rules} brief=${brief} targeted_patch_id=${patch}${targeted.reasons.length ? ` reasons=${targeted.reasons.join('; ')}` : ''}`]; + if (fixRange) out.push(`FIX_RANGE: ${fixRange.runtime_lines === null ? `unread (${fixRange.error})` : `runtime_lines=${fixRange.runtime_lines}`} base=${fixRange.base}`); + out.push(reviewPlanLine(plan, pass + (plan.next.step === 'full' || plan.next.step === 'scoped' ? 1 : 0)), `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]; @@ -121,7 +162,7 @@ function main(): number { if (!d.exclude.length) out.push(`DIFF_EXCLUDE: ${key} none`); } for (const s of plan.skipped) out.push(`SKIP: ${s}`); - out.push(`AUDIT_EFFORT: ${auditEffort} (coverage, plan-completion and docs audits, decision-trail reviewers, watchers; reviewers above stay full)`); + out.push(`AUDIT_EFFORT: ${auditEffort} (coverage, plan-completion and docs audits, decision-trail reviewers, watchers; reviewers above run at their effort=)`); process.stdout.write(out.join('\n') + '\n'); return EXIT.ok; } diff --git a/bin/gstack-review-scope b/bin/gstack-review-scope index 569aba495..3d4c843b6 100755 --- a/bin/gstack-review-scope +++ b/bin/gstack-review-scope @@ -224,6 +224,8 @@ function cmdRender(rest: string[]): number { let noted: ScopedFinding[] = []; try { if (deferredFile) deferred = JSON.parse(fs.readFileSync(deferredFile, 'utf8')); + const wrapped = deferred as unknown as { deferred?: unknown }; + if (!Array.isArray(deferred) && Array.isArray(wrapped?.deferred)) deferred = wrapped.deferred as DeferredRecord[]; const findingsFile = flag(rest, '--findings'); if (findingsFile) noted = (readFindings(findingsFile, 'classified findings') as ScopedFinding[]).filter(f => f.scope === 'note'); } catch (e: any) { return refuse('render', 'REVIEW_SCOPE_INPUT', e.message); } diff --git a/bin/gstack-ship-budget b/bin/gstack-ship-budget index ecb3277dc..fd9c5119f 100755 --- a/bin/gstack-ship-budget +++ b/bin/gstack-ship-budget @@ -3,12 +3,17 @@ * gstack-ship-budget — the /ship token budget and fresh-context handoff * (docs/ship-budget.md). An admission cap: no step or dispatch starts unless * used + open reservations + unknown + its projection + the tail and stop - * reserve fit under the cap. + * reserve fit under the cap. --mode observe (ship/DRIVER.md) only records: + * note at each program's end, and the cap is one hard stop. Every --reading + * takes --credits beside it. * - * start --record [--token-cap ] [--meter capy|claude|estimate] [--reading ] [--prior-reading ] - * [--session |--nonce ] [--reserve ] [--delegate auto|never] [--calibration ] [--ledger ] - * check --run |--record --step --next [,...]> [--reading ] [--prior-reading ] - * settle --run|--record --reservation [--unknown] release --run|--record --reservation + * start --record [--token-cap ] [--mode admit|observe] [--meter capy|claude|estimate] [--reading ] [--credits ] + * [--prior-reading ] [--session |--nonce ] [--reserve ] [--delegate auto|never] [--calibration ] [--ledger ] + * note --run|--record --step [--label ] --reading [--credits ] [--dispatched-at [--dispatched-credits ] --readers ] + * check --run |--record --step --next [,...]> [--reading ] [--credits ] [--prior-reading ] + * [--returned [,...]] [--runtime-lines ] [--dispatched-at --readers ] + * settle --run|--record --reservation [--unknown] [--reading ] [--credits ] [--dispatched-at --readers ] + * release --run|--record --reservation * handoff --run|--record --from --to --base origin/ [--reviewed-tree ] [--trail --trail-run ] * [--sub-cap ] [--reading ] [--child-session ] * launch --in (Claude Code: background headless child with explicit permissions) @@ -18,24 +23,26 @@ * resume --record |--run [--reading ] [--meter ] [--session ] [--token-cap --approved-by --words ] * [--rebuild-from-record] * close --run|--record [--reading ] [--approved-by --words ] + * calls --events [--since ] [--until ] (the host's transcript items: one CALLS: line, lib/ship-calls.ts) * * Exit: 0 continue/delegate · 3 stop (the next step does not start) · 2 usage * or validation (stderr). Logic: lib/ship-budget.ts, lib/ship-budget-cli.ts, * lib/ship-handoff.ts. */ import { BudgetError } from '../lib/ship-budget'; -import { cmdCheck, cmdClose, cmdResume, cmdSettle, cmdStart, type Outcome } from '../lib/ship-budget-cli'; +import { cmdCalls, cmdCheck, cmdClose, cmdNote, cmdResume, cmdSettle, cmdStart, type Outcome } from '../lib/ship-budget-cli'; import { cmdHandoff, cmdLaunch, cmdReconcile, cmdReturn, cmdVerifyHandoff } from '../lib/ship-handoff'; const [command, ...rest] = process.argv.slice(2); const ctx = { env: process.env, cwd: process.cwd() }; const commands: Record Outcome> = { - start: () => cmdStart(rest, ctx), check: () => cmdCheck(rest, ctx), settle: () => cmdSettle(rest, ctx), release: () => cmdSettle(rest, ctx, true), + start: () => cmdStart(rest, ctx), note: () => cmdNote(rest, ctx), check: () => cmdCheck(rest, ctx), settle: () => cmdSettle(rest, ctx), release: () => cmdSettle(rest, ctx, true), handoff: () => cmdHandoff(rest, ctx), launch: () => cmdLaunch(rest, ctx), 'verify-handoff': () => cmdVerifyHandoff(rest, ctx), return: () => cmdReturn(rest, ctx), - reconcile: () => cmdReconcile(rest, ctx), resume: () => cmdResume(rest, ctx), close: () => cmdClose(rest, ctx), + reconcile: () => cmdReconcile(rest, ctx), resume: () => cmdResume(rest, ctx), close: () => cmdClose(rest, ctx), calls: () => cmdCalls(rest), }; if (!command || command === '--help' || command === '-h' || !commands[command]) { - const text = (await Bun.file(import.meta.path).text()).split('\n').slice(2, 26).map(l => l.replace(/^ \* ?/, '')).join('\n'); + const lines = (await Bun.file(import.meta.path).text()).split('\n'); + const text = lines.slice(2, lines.indexOf(' */')).map(l => l.replace(/^ \* ?/, '')).join('\n'); (command && command !== '--help' && command !== '-h' ? console.error : console.log)(text); process.exit(command && command !== '--help' && command !== '-h' ? 2 : 0); } diff --git a/bin/gstack-ship-policy b/bin/gstack-ship-policy index 7437dfd43..f01db4679 100755 --- a/bin/gstack-ship-policy +++ b/bin/gstack-ship-policy @@ -18,7 +18,7 @@ import * as path from 'node:path'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { resultLine } from '../lib/result-codes'; import { - POLICY_KEYS, POLICY_KEY_INTRODUCED, SHIP_POLICY_PATH, examplePolicyJson, explainPolicy, isUnavailable, loadPolicyFromBase, loadPolicyFromHead, + BUMP_NEVER_KEY_VERSION, POLICY_KEYS, POLICY_KEY_INTRODUCED, SHIP_POLICY_PATH, examplePolicyJson, explainPolicy, isUnavailable, loadPolicyFromBase, loadPolicyFromHead, minimumReader, policyUnavailableLine, renderEffective, resolveBaseBranch, type LoadedPolicy, } from '../lib/ship-policy'; @@ -87,8 +87,8 @@ function main(argv: string[]): number { const loaded = load(root, rest, cmd === 'validate' ? 'head' : 'base'); if (typeof loaded === 'number') return loaded; const set = POLICY_KEYS.filter(k => loaded.values[k] && loaded.values[k] !== 'default'); - const introduced = Object.fromEntries(set.map(k => [k, POLICY_KEY_INTRODUCED[k]])); - const minReader = set.length ? minimumReader(introduced) : null; + const introduced = Object.fromEntries(set.map(k => [k, k === 'bump' && loaded.policy.bump === 'never' ? BUMP_NEVER_KEY_VERSION : POLICY_KEY_INTRODUCED[k]])); + const minReader = set.length ? minimumReader(Object.fromEntries(set.map(k => [k, loaded.policy[k]]))) : null; if (json) { process.stdout.write(JSON.stringify({ valid: loaded.errors.length === 0, present: loaded.present, source: loaded.source, policy: loaded.policy, values: loaded.values, introduced, min_reader: minReader, errors: loaded.errors }) + '\n'); return loaded.errors.length ? EXIT.fail : EXIT.ok; diff --git a/bin/gstack-ship-preflight b/bin/gstack-ship-preflight new file mode 100755 index 000000000..3664d9353 --- /dev/null +++ b/bin/gstack-ship-preflight @@ -0,0 +1,10 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * gstack-ship-preflight — /ship Steps 1-3 and Step 5's pregate and lanes in one call, with + * STOP:/NEXT: lines wherever the agent must judge. Logic: lib/ship-preflight.ts. + */ +import { preflight } from '../lib/ship-preflight'; + +const out = await preflight(process.argv.slice(2), process.cwd()); +(out.exit === 2 ? process.stderr : process.stdout).write(out.text); +process.exit(out.exit); diff --git a/bin/gstack-ship-queue b/bin/gstack-ship-queue index b130a7133..0584c3bba 100755 --- a/bin/gstack-ship-queue +++ b/bin/gstack-ship-queue @@ -14,11 +14,15 @@ * gstack-ship-queue gate-ahead --list --pr * gstack-ship-queue verify --pr --screen (train policy: the head's screen verdict from its run) * gstack-ship-queue verify --post-merge [--timeout ] (after a merge: main's push workflows at that commit until they settle) + * gstack-ship-queue land --pr [--dry-run] [--no-wait] [--break-lock] (the merge step; lib/ship-queue-land.ts) + * gstack-ship-queue land --pr --repair (after QUEUE_LAND_DRIFT: open the outside merge's release PR) + * gstack-ship-queue land --census * gstack-ship-queue train build|status|verdict|bisect|rebuild|watch|prune ... (merge trains; train --help) * * Every subcommand takes --base (default origin/HEAD, else main) and * ends with GSTACK_RESULT: skill=ship-queue status=complete|refused run=. - * gstack-restamp stays the primitive. Nothing here pushes, except under a + * gstack-restamp stays the primitive. Nothing here pushes, except land, ready + * under changelog_fragments (its READY receipt note), and under a * ship policy with a `train` block: merge trains push train/ branches * and the refs/notes/gstack-trains records, and dispatch through eval-bg. * Logic: lib/ship-queue.ts, lib/ship-queue-gate.ts, lib/ship-queue-train*.ts @@ -52,11 +56,18 @@ 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 [--dry-run] [--no-wait] [--timeout ] [--break-lock] [--allow-repo-commands] + 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 + 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) train build|status|verdict|bisect|rebuild|watch|prune ... merge trains, when the base policy declares a train block (train --help; docs/ship-policy.md#run-a-merge-train); ready then takes --screen|--no-screen ---base : base branch (default: origin/HEAD, else main). Nothing here pushes. +--base : base branch (default: origin/HEAD, else main). Nothing here pushes, except land (the stamp commit and the +refs/notes/gstack-land lock), ready under changelog_fragments (its READY receipt note) and merge trains. ${exitTableHelp()}`; function flag(args: string[], name: string): string | undefined { @@ -152,6 +163,13 @@ async function main(argv: string[]): Promise { return train.trainMain(ctx, args); } if (cmd === 'verify' && flag(args, '--post-merge') !== undefined) return (await import('../lib/ship-queue-train-cli')).postMergeMain(ctx, args); + if (cmd === 'land') { + 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 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'), 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'); if (gateExit !== undefined && !/^-?\d+$/.test(gateExit)) return usage('--gate-exit needs an exit code'); diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 1b24fd1af..f7b30d005 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -44,7 +44,7 @@ import { receiptIssuesFrom, receiptSummaryLine, renderCensus, renderReceiptBlock, validateReceipt, type CensusPr, } from '../lib/ship-receipt'; import { checkDocsCaps, docsCapLine, docsExceptionLine, parseReceiptDocs } from '../lib/ship-receipt-docs'; -import { deeper, depthBelow, exceptionProblems, parseReviewLoopException, receiptDepthAtHead, reviewLoopExceptionLine } from '../lib/ship-receipt-depth'; +import { deeper, depthBelow, exceptionProblems, parseReviewLoopException, parseReviewTargeted, receiptDepthAtHead, reviewLoopExceptionLine } from '../lib/ship-receipt-depth'; import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose'; import { resolveStateRoot } from '../lib/state-root'; import { isRegistryUnavailable, loadRegistryFromBase } from '../lib/regen'; @@ -89,6 +89,9 @@ write flags: --pr --head --base --version --gated-tree --predecessor --gate ({classes, rules, brief_sha, status, findings, raised_by}: gstack-review-dispatch verify + --targeted-out); recorded as review_targeted bound to the receipt's product_patch_id. Without it the receipt has no + review_targeted, which the queue reports as legacy. --approval-run (repeatable; resolves plan-sha citations) (W2: a class declared in origin/'s .gstack/approval-classes.json with hits needs a citation that resolves and binds to its effects: APPROVAL_CITATION_MISSING) --out --body . Defaults: head=HEAD, base=origin/HEAD's branch, version=the @@ -207,6 +210,12 @@ function cmdWrite(rest: string[], json: boolean): number { if (bodyFile && !bodyText.split(/\r?\n/).some(l => l.trim() === line)) return refuse(`${bodyFile} does not carry the exception line verbatim: ${JSON.stringify(line)}`); } const reviewDepth = receiptDepthAtHead(repoRoot, base, path.dirname(Bun.fileURLToPath(import.meta.url)), headSha ?? head); + const product = reviewedProduct(repoRoot, base, head, pregateFile); + let targeted: ReturnType | undefined; + if (flag(rest, '--review-targeted') !== undefined) { + try { targeted = parseReviewTargeted(jsonArg(flag(rest, '--review-targeted')), product.product_patch_id ?? 'none'); } catch (e: any) { targeted = { ok: false, message: `--review-targeted: ${e.message}` }; } + } + if (targeted && !targeted.ok) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${targeted.message}; nothing written`) + '\n'); return EXIT.fail; } const approval = approvalForReceipt({ repoRoot, base, head, citationText: [bodyText, ...flags(rest, '--approval')].join('\n'), runDirs: flags(rest, '--approval-run') }); if (approval.kind === 'invalid') { for (const line of approval.lines) process.stderr.write(resultLine('gstack-ship-receipt write', 'APPROVAL_CLASSES_INVALID', line) + '\n'); @@ -236,8 +245,8 @@ function cmdWrite(rest: string[], json: boolean): number { 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 } : {}), ...reviewedProduct(repoRoot, base, head, pregateFile), - gstack_version: runningGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, + review_loop: reviewLoop, ...(docs?.ok ? { docs: docs.docs } : {}), ...product, + gstack_version: runningGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined, }; } catch (e: any) { process.stderr.write(`gstack-ship-receipt write: ${e.message}\n`); return EXIT.usage; } if (input.pr !== undefined && !Number.isInteger(input.pr)) { process.stderr.write('gstack-ship-receipt write: --pr must be an integer\n'); return EXIT.usage; } @@ -428,12 +437,13 @@ function verifiedOutputs(repoRoot: string, base: string, pregateFile: string | u return regen.proven.filter(p => !/[*?[\]\\]/.test(p) && matchesAny(owned, p)); } -interface ProductRules { extra: { metadata: string[]; outputs: readonly string[] }; metadata: string[]; templates: readonly string[] } +interface ProductRules { extra: { metadata: string[]; outputs: readonly string[]; fragments?: string }; metadata: string[]; templates: readonly string[] } function productRules(repoRoot: string, base: string, outputs: readonly string[]): ProductRules { const load = loadPolicyFromBase(repoRoot, base); const policy: ShipPolicy | null = isUnavailable(load) ? null : load.policy; - const extra = { metadata: [...(policy?.stamp_files ?? []), ...(policy?.stamp_paths ?? []), ...(policy?.release_outputs ?? []), ...(policy?.changelog ? [policy.changelog] : [])], outputs }; - return { extra, metadata: [...CARRY_METADATA_GLOBS, ...extra.metadata, ...outputs], templates: policy?.stamp_patterns ?? [] }; + const fragments = policy?.changelog_fragments?.dir.replace(/^(\.\/)+/, '').replace(/\/+$/, ''); + const extra = { metadata: [...(policy?.stamp_files ?? []), ...(policy?.stamp_paths ?? []), ...(policy?.release_outputs ?? []), ...(policy?.changelog ? [policy.changelog] : [])], outputs, fragments }; + return { extra, metadata: [...CARRY_METADATA_GLOBS, ...extra.metadata, ...(fragments ? [`${fragments}/*.md`] : []), ...outputs], templates: policy?.stamp_patterns ?? [] }; } /** diff --git a/bin/gstack-ship-release b/bin/gstack-ship-release new file mode 100755 index 000000000..48ccff618 --- /dev/null +++ b/bin/gstack-ship-release @@ -0,0 +1,10 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * gstack-ship-release — /ship Step 12 (version), Steps 15-16 (finish) and Step 17 (push), + * with STOP:/NEXT: lines wherever the agent must judge. Logic: lib/ship-release.ts. + */ +import { release } from '../lib/ship-release'; + +const out = await release(process.argv.slice(2), process.cwd()); +(out.exit === 2 ? process.stderr : process.stdout).write(out.text); +process.exit(out.exit); diff --git a/bin/gstack-state-matrix b/bin/gstack-state-matrix index 6e7ac0204..f17ee2cd0 100755 --- a/bin/gstack-state-matrix +++ b/bin/gstack-state-matrix @@ -5,6 +5,7 @@ * gstack-state-matrix detect [--base ] [--diff-base ] * gstack-state-matrix check [--repo ] [--expect ] [--json] * gstack-state-matrix outfile + * gstack-state-matrix findings * * `detect` prints `SCOPE_STATE_MACHINE=true|false` (shell-safe for * `source <(...)`, with `# state-machine:` comment lines naming the hits) from @@ -14,7 +15,10 @@ * last; exit 0 ok, 1 incomplete (STATE_MATRIX_INCOMPLETE). `outfile` creates and * prints a new empty 0600 file in the repo's private `.gstack/tmp/` (0700, kept * out of git through info/exclude) for the specialist's output, so a later - * review never checks or commits an earlier run's file. Logic: lib/state-matrix.ts. + * review never checks or commits an earlier run's file. `findings` prints the + * output for Step 9.3's merge with each untested cell mapped below the floor + * (lib/review-scope.ts mapStateMatrixOutput) and `STATE_MATRIX_FINDINGS:` on + * stderr. Logic: lib/state-matrix.ts. */ import { spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; @@ -24,6 +28,7 @@ import { addedLines } from '../lib/banned-terms'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { resultLine } from '../lib/result-codes'; import { resolveBaseBranch } from '../lib/ship-policy'; +import { mapStateMatrixOutput } from '../lib/review-scope'; import { checkStateMatrix, detectStateMachine, renderStateMatrixCheck, type Expectation } from '../lib/state-matrix'; const HELP = `gstack-state-matrix — kind × owner action × resulting row for proposal, hold and approval state machines @@ -32,6 +37,7 @@ const HELP = `gstack-state-matrix — kind × owner action × resulting row for check [--repo ] [--expect ] [--json] gaps in the state-machines specialist's output (review/specialists/state-machines.md) outfile print a new empty private file for that output + findings that output for the Step 9.3 merge, each untested cell mapped below the floor ${exitTableHelp()}`; @@ -71,6 +77,15 @@ function check(rest: string[]): number { return EXIT.ok; } +function findings(rest: string[]): number { + const input = rest.find(a => !a.startsWith('--')); + if (!input) { process.stderr.write(`gstack-state-matrix findings: a reviewer output file (or -) is required\n${HELP}\n`); return EXIT.usage; } + const r = mapStateMatrixOutput(input === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(input, 'utf8')); + process.stdout.write(r.text.endsWith('\n') ? r.text : `${r.text}\n`); + process.stderr.write(`STATE_MATRIX_FINDINGS: mapped=${r.mapped} (untested cells below the floor; docs/review-policy.md test gap)\n`); + return EXIT.ok; +} + function outfile(): number { const root = git(['rev-parse', '--show-toplevel']); const exclude = git(['rev-parse', '--git-path', 'info/exclude']); @@ -94,6 +109,7 @@ function main(argv: string[]): number { if (cmd === 'detect') return detect(rest); if (cmd === 'check') return check(rest); if (cmd === 'outfile') return outfile(); + if (cmd === 'findings') return findings(rest); process.stderr.write(`gstack-state-matrix: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; } diff --git a/bin/gstack-upgrade b/bin/gstack-upgrade index 0fde3bf72..c658f175b 100755 --- a/bin/gstack-upgrade +++ b/bin/gstack-upgrade @@ -64,6 +64,8 @@ bounded() { if command -v timeout >/dev/null 2>&1; then timeout "${GSTACK_UPGRAD # Git for Windows answers --show-toplevel as C:/x while pwd -P in Git Bash is # /c/x; compare the paths, not their spellings. +# shellcheck source=bin/gstack-harness-pid.sh +. "$ROOT/bin/gstack-harness-pid.sh" 2>/dev/null || GSTACK_SHARED_HARNESSES="capy-server" # shellcheck source=bin/gstack-path-spelling.sh . "$ROOT/bin/gstack-path-spelling.sh" 2>/dev/null || gstack_path_same() { [ "$1" = "$2" ]; } TOPLEVEL=$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null) @@ -208,14 +210,24 @@ if ! git -C "$ROOT" merge-base --is-ancestor HEAD FETCH_HEAD 2>/dev/null; then fi # Workflow leases (bin/gstack-lease): sessions sharing this installation that # are alive and not this process's own chain. Moving the checkout under them -# is what the lease exists to prevent; the caller's own session never counts. +# is what the lease exists to prevent; the caller's own session never counts, +# except under a shared harness (capy-server), where every session on the +# machine is in the caller's chain: its lease counts until it is 120 minutes +# old (GST-396). if [ "${GSTACK_UPGRADE_FORCE:-}" != 1 ] && [ -x "$ROOT/bin/gstack-lease" ] \ - && BUSY=$("$ROOT/bin/gstack-lease" live --root "$ROOT" --exclude-ancestry-of $$ 2>/dev/null); then - HOLDERS="" - while read -r _pid _age; do HOLDERS="$HOLDERS${HOLDERS:+, }pid $_pid ($_age)"; done </dev/null); then + HOLDERS="" SHARED_HOLDER="" + while read -r _pid _age _comm; do + HOLDERS="$HOLDERS${HOLDERS:+, }pid $_pid ($_age${_comm:+ $_comm})" + case " $GSTACK_SHARED_HARNESSES " in *" ${_comm:-none} "*) SHARED_HOLDER="$_comm, pid $_pid) holds a lease $_age old" ;; esac + done <&2 + if [ -n "$SHARED_HOLDER" ]; then + echo "gstack-upgrade: a shared harness ($SHARED_HOLDER; every session on this machine runs under it, so the upgrade waits until the lease is 120 minutes old (counted from the last renewal by any session); nothing was changed; fix: re-run then, or with GSTACK_UPGRADE_FORCE=1 when no other session uses this checkout (UPGRADE_BUSY)" >&2 + else + echo "gstack-upgrade: live gstack sessions hold this installation: $HOLDERS; nothing was changed; fix: wait for those sessions to finish, or re-run with GSTACK_UPGRADE_FORCE=1 when you know they are idle (UPGRADE_BUSY)" >&2 + fi exit 3 fi # shellcheck source=bin/gstack-bun-version.sh diff --git a/bin/gstack-wtree b/bin/gstack-wtree index 341268623..c8034e375 100755 --- a/bin/gstack-wtree +++ b/bin/gstack-wtree @@ -1,10 +1,16 @@ #!/usr/bin/env bash # gstack-wtree — print a working-tree CONTENT fingerprint (a git tree hash). # -# Builds a temp index, stages the full working tree into it (`git add -A`, so -# .gitignore'd scratch stays out and UNTRACKED source is included), and prints -# `git write-tree` of that index. Properties that make this the right -# staleness fingerprint, vs `git rev-parse HEAD^{tree}`: +# Builds a temp index, stages the full working tree into it (`git add -u` for +# every tracked file, then `git add -A` for the rest, so .gitignore'd scratch +# stays out and UNTRACKED source is included), and prints `git write-tree` of +# that index. An untracked `.bun/` folder at the repository root (Bun's install +# cache, which a test run can create) is left out so a passing run does not +# look like a mid-run edit (GST-421); tracked files under it still count, and a +# tree without that folder (or with it gitignored) hashes exactly as a plain +# `git add -A` would. +# Properties that make this the right staleness fingerprint, vs +# `git rev-parse HEAD^{tree}`: # # - Committing identical content does NOT change the fingerprint, so a # record made on a dirty tree stays valid after the exact same content is @@ -15,7 +21,7 @@ # # Performance: the temp index is seeded by COPYING the real index (git writes # it atomically via rename, so the copy is a consistent snapshot). That -# preserves the stat cache, so `git add -A` only re-hashes files whose stat +# preserves the stat cache, so staging only re-hashes files whose stat # changed — measured 40x faster than a `read-tree HEAD` seed, which zeroes # stat data and forces a full re-hash of every tracked file. Both seeds # produce the identical write-tree hash. Fallback: `read-tree HEAD` when the @@ -82,7 +88,14 @@ if [ -n "$REAL_INDEX" ] && [ -f "$REAL_INDEX" ] && cp "$REAL_INDEX" "$TMPIDX" 2> else git -C "$TOP" read-tree HEAD 2>/dev/null || exit 1 fi -if ! ERR=$(git -C "$TOP" add -A 2>&1 >/dev/null); then +# The exclude is added only when the root .bun/ exists and is not ignored: an +# exclude pathspec naming an ignored path makes `git add -A` exit 1 (GST-449), +# and an ignored .bun/ stays out of a plain `git add -A` anyway. --no-index +# asks the ignore rules alone; without it a tracked file under .bun/ makes git +# call .bun not ignored. +EXCLUDE_BUN="" +if [ -e "$TOP/.bun" ] && ! git -C "$TOP" check-ignore --no-index -q .bun 2>/dev/null; then EXCLUDE_BUN=':(exclude,top).bun'; fi +if ! ERR=$(git -C "$TOP" add -u 2>&1 >/dev/null) || ! ERR=$(git -C "$TOP" add -A -- . ${EXCLUDE_BUN:+"$EXCLUDE_BUN"} 2>&1 >/dev/null); then echo "gstack-wtree: cannot stage the working tree: $(printf '%s' "$ERR" | head -1)" >&2 exit 1 fi diff --git a/browse/test/playwright-core-patch.test.ts b/browse/test/playwright-core-patch.test.ts index d09e136c9..f0974cbd3 100644 --- a/browse/test/playwright-core-patch.test.ts +++ b/browse/test/playwright-core-patch.test.ts @@ -60,3 +60,16 @@ describe('playwright-core windowsHide patch (#2160, #1989)', () => { expect(bundle).toContain('shell: true, windowsHide: true'); }); }); + +// Windows Free Tests 40656299153 and 41056150287 (cookie-picker-ui, serial retry passed): goto failed with +// net::ERR_NO_BUFFER_SPACE on 127.0.0.1. Chromium's TcpPortRandomizationWin raises WSAENOBUFS with ports free; +// microsoft/playwright#43605 disables it in 1.65, and the 1.62.1 patch backports it; drop this block at 1.65. +describe('playwright-core TcpPortRandomizationWin backport (microsoft/playwright#43605)', () => { + test('the patch and the installed tree disable the feature in the --disable-features list', () => { + expect(fs.readFileSync(path.join(ROOT, 'patches', 'playwright-core@1.62.1.patch'), 'utf-8')).toContain('+ "TcpPortRandomizationWin"'); + const bundle = fs.readFileSync(path.join(ROOT, 'node_modules', 'playwright-core', 'lib', 'coreBundle.js'), 'utf-8'); + const list = bundle.slice(bundle.indexOf('disabledFeatures = ['), bundle.indexOf('].filter(Boolean);', bundle.indexOf('disabledFeatures = ['))); + expect(list).toContain('"TcpPortRandomizationWin"'); + expect(bundle).toContain('"--disable-features=" + disabledFeatures.join(",")'); + }); +}); diff --git a/captain/SKILL.md b/captain/SKILL.md index 6a1f0f270..9cfb80418 100644 --- a/captain/SKILL.md +++ b/captain/SKILL.md @@ -261,6 +261,13 @@ Never merge out of order, never merge anything else while a train is merging, an skip the second verify: a mismatch there is what writes the freeze. When every slot has merged, `train prune --train "$NONCE"` deletes the train branch. +**Under `changelog_fragments`** (a stamped train: `train build` printed `S1:`..`Sk:` lines) +there is no slot call and no lane stamp. Per slot, in `ORDER`, run +`gstack-ship-queue train land --train "$NONCE" --pr "$PR"` until it exits 0. It pushes the +stamped prefix S_i as a commit on [pin, `BASE`], waits for the policy's `required_checks`, +merges with `--match-head-commit` and confirms `BASE` is S_i exactly. A rerun resumes from +its journal, and any other `BASE` freezes the queue as above (docs/ship-policy.md#train-land). + **The tree rule.** A gate covers a tree, not a commit. A head whose diff from the gated prefix touches only `STAMP_FILES` reuses the gate; that is what lets the lane stamp after the gate ran. Anything else is a new tree and needs a new gate. @@ -317,12 +324,13 @@ to be outside the merged PR. Reruns on `BASE` are never a way to get a green. The controller keeps one digest file (`captain/templates/DIGEST.md`), rewritten at every turn, three sections in this order, each row with its thread, one line, and an age: -1. **Needs you**: decisions only the owner can make, each with the plain-language ask and - the one-word default. Empty means the owner has nothing to do. +1. **Needs you**: decisions only the owner can make, in the ask format below (the + Captain's name, one lettered line per decision). Empty means the owner has nothing to do. 2. **New**: what landed or changed since the last digest (merges with versions, READYs received, trains built, incidents), newest first. 3. **In progress**: every working lane, what it owns, its state (building, READY, in - train slot i, blocked on …) and how long since it last reported. + train slot i, blocked on …) and how long since it last reported. A thread the Captain + archives leaves this list in the same turn. Ages make stalls visible: a lane in progress with no report for hours, or a READY waiting longer than `FILL_HOURS`, is the controller's next action. @@ -345,17 +353,28 @@ says so instead of looking empty. **B. The plan ask**, in this order, written for someone outside the project (no gate codes in the body): before → after with concrete examples; why it matters, with numbers; what caused the work (issue, run, report, or the owner's words quoted); the big decisions -(options, pick, why, what would flip it); what we need from you, one decision with each -option's cost and the recommended one-word reply as the default; and a closing -**"do it"** reply that takes every recommendation at full scope, follow-ons included, -with one line saying what it covers. `gstack-owner-brief render --captain` prints this shape from -a plan; relay it whole. Template: `captain/templates/plan-ask.md`. +(options, pick, why, what would flip it); what we need from you in the ask format; and a +closing **"do it"** reply that takes every recommendation at full scope, follow-ons +included. `gstack-owner-brief render --captain --captain-name ""` prints this +shape from a plan; relay it whole. Template: `captain/templates/plan-ask.md`. + +**The ask format** (every ask to the owner, the digest's Needs you included), explained like +the owner is five: the Captain's name, then one lettered line per decision, letters unique +across the list: `- A: hit problem p, which happens when h. We could fix it in these +ways: 1) x; 2) y; 3) z. Recommendation: x because why. A1 to take recommendation.` The +recommendation is option 1; "do it" takes every recommendation in the last list, and a named +option ("A2") takes that option instead. When the owner has to do something, the line +carries the exact link to the page (never a menu path; a Capy app page gets its exact path +and field), numbered steps in the simplest words, and the one word to reply when done. +Home: `docs/captain.md`, The ask format. **Plan before build.** A lane that builds something runs a sized `/autoplan` on its brief as its first act after the session-start check and sends the controller the plan ask above; the controller relays it, and the lane builds only after the owner's word is answered into the run and it reports `APPROVED`. New scope taken on part-way gets its own plan. Read-only lanes, the flaky pass's repairs, -slot stamps, CHANGELOG resolves and cap re-pins under a grant are exempt. The brief a +slot stamps, CHANGELOG resolves, cap re-pins under a grant, S1 emergencies (broken install +or upgrade, red main, a security bug) and fixes from an already-diagnosed, audited problem +list are exempt; every other fix gets a one-round, eng-only plan. The brief a controller hands a lane, with its `Plan: required | approved | exempt` line, is `captain/templates/brief.md`; the rule is `docs/captain.md` (Plan before build). diff --git a/captain/SKILL.md.tmpl b/captain/SKILL.md.tmpl index 87ed80e88..6e895baaf 100644 --- a/captain/SKILL.md.tmpl +++ b/captain/SKILL.md.tmpl @@ -189,6 +189,13 @@ Never merge out of order, never merge anything else while a train is merging, an skip the second verify: a mismatch there is what writes the freeze. When every slot has merged, `train prune --train "$NONCE"` deletes the train branch. +**Under `changelog_fragments`** (a stamped train: `train build` printed `S1:`..`Sk:` lines) +there is no slot call and no lane stamp. Per slot, in `ORDER`, run +`gstack-ship-queue train land --train "$NONCE" --pr "$PR"` until it exits 0. It pushes the +stamped prefix S_i as a commit on [pin, `BASE`], waits for the policy's `required_checks`, +merges with `--match-head-commit` and confirms `BASE` is S_i exactly. A rerun resumes from +its journal, and any other `BASE` freezes the queue as above (docs/ship-policy.md#train-land). + **The tree rule.** A gate covers a tree, not a commit. A head whose diff from the gated prefix touches only `STAMP_FILES` reuses the gate; that is what lets the lane stamp after the gate ran. Anything else is a new tree and needs a new gate. @@ -245,12 +252,13 @@ to be outside the merged PR. Reruns on `BASE` are never a way to get a green. The controller keeps one digest file (`captain/templates/DIGEST.md`), rewritten at every turn, three sections in this order, each row with its thread, one line, and an age: -1. **Needs you**: decisions only the owner can make, each with the plain-language ask and - the one-word default. Empty means the owner has nothing to do. +1. **Needs you**: decisions only the owner can make, in the ask format below (the + Captain's name, one lettered line per decision). Empty means the owner has nothing to do. 2. **New**: what landed or changed since the last digest (merges with versions, READYs received, trains built, incidents), newest first. 3. **In progress**: every working lane, what it owns, its state (building, READY, in - train slot i, blocked on …) and how long since it last reported. + train slot i, blocked on …) and how long since it last reported. A thread the Captain + archives leaves this list in the same turn. Ages make stalls visible: a lane in progress with no report for hours, or a READY waiting longer than `FILL_HOURS`, is the controller's next action. @@ -273,17 +281,28 @@ says so instead of looking empty. **B. The plan ask**, in this order, written for someone outside the project (no gate codes in the body): before → after with concrete examples; why it matters, with numbers; what caused the work (issue, run, report, or the owner's words quoted); the big decisions -(options, pick, why, what would flip it); what we need from you, one decision with each -option's cost and the recommended one-word reply as the default; and a closing -**"do it"** reply that takes every recommendation at full scope, follow-ons included, -with one line saying what it covers. `gstack-owner-brief render --captain` prints this shape from -a plan; relay it whole. Template: `captain/templates/plan-ask.md`. +(options, pick, why, what would flip it); what we need from you in the ask format; and a +closing **"do it"** reply that takes every recommendation at full scope, follow-ons +included. `gstack-owner-brief render --captain --captain-name ""` prints this +shape from a plan; relay it whole. Template: `captain/templates/plan-ask.md`. + +**The ask format** (every ask to the owner, the digest's Needs you included), explained like +the owner is five: the Captain's name, then one lettered line per decision, letters unique +across the list: `- A: hit problem p, which happens when h. We could fix it in these +ways: 1) x; 2) y; 3) z. Recommendation: x because why. A1 to take recommendation.` The +recommendation is option 1; "do it" takes every recommendation in the last list, and a named +option ("A2") takes that option instead. When the owner has to do something, the line +carries the exact link to the page (never a menu path; a Capy app page gets its exact path +and field), numbered steps in the simplest words, and the one word to reply when done. +Home: `docs/captain.md`, The ask format. **Plan before build.** A lane that builds something runs a sized `/autoplan` on its brief as its first act after the session-start check and sends the controller the plan ask above; the controller relays it, and the lane builds only after the owner's word is answered into the run and it reports `APPROVED`. New scope taken on part-way gets its own plan. Read-only lanes, the flaky pass's repairs, -slot stamps, CHANGELOG resolves and cap re-pins under a grant are exempt. The brief a +slot stamps, CHANGELOG resolves, cap re-pins under a grant, S1 emergencies (broken install +or upgrade, red main, a security bug) and fixes from an already-diagnosed, audited problem +list are exempt; every other fix gets a one-round, eng-only plan. The brief a controller hands a lane, with its `Plan: required | approved | exempt` line, is `captain/templates/brief.md`; the rule is `docs/captain.md` (Plan before build). diff --git a/captain/templates/AGENTS.md b/captain/templates/AGENTS.md index b9c09f064..c60cb966f 100644 --- a/captain/templates/AGENTS.md +++ b/captain/templates/AGENTS.md @@ -25,9 +25,11 @@ a standing approval instead of asking again. Append; never rewrite an owner's wo rerun: . Over the cap is a fresh ask. ## Asks to the owner (, : "") -- Plain language, each option with what it is, why it matters, what each answer does and - the cost. The recommended one-word reply is the default. Every ask ends with "do it": - every recommendation at full scope, follow-ons included, no further ask. +- The ask format (gstack docs/captain.md), explained like I'm five: , then one + lettered line per decision: "A: hit problem p, which happens when h. We could fix it + in these ways: 1) x; 2) y; 3) z. Recommendation: x because why. A1 to take recommendation." + "do it" takes every recommendation in the list at full scope, follow-ons included, no + further ask; a named option ("A2") takes that option instead. ## Parallelism (, : "") - Keep about lanes working on disjoint files whenever there is backlog. Serial steps diff --git a/captain/templates/CREW.md b/captain/templates/CREW.md index e6bdf2806..311750b23 100644 --- a/captain/templates/CREW.md +++ b/captain/templates/CREW.md @@ -133,7 +133,9 @@ Homes are paths in the gstack checkout the lane checked at session start. answered into the run and it reports `APPROVED`; record it with `gstack-approvals import --autoplan`. New scope taken on part-way gets the same. Exempt: read-only lanes, the daily flaky pass's repairs, slot stamps, CHANGELOG-only resolves, cap - re-pins under a written grant. Home: `docs/captain.md` (Plan before build), + re-pins under a written grant, S1 emergencies (broken install or upgrade, red main, + a security bug) and fixes from an already-diagnosed, audited problem list; every + other fix gets a one-round, eng-only plan. Home: `docs/captain.md` (Plan before build), `captain/templates/brief.md`. ## Crew-specific rules diff --git a/captain/templates/DIGEST.md b/captain/templates/DIGEST.md index 71246ba60..23cfc1357 100644 --- a/captain/templates/DIGEST.md +++ b/captain/templates/DIGEST.md @@ -7,7 +7,12 @@ every row with its thread and an age. Codes are the thread codes the host assign -- · · · default reply: **** · cost: + +- A: hit problem

, which happens when . We could fix it in these ways: 1) ; 2) ; 3) . Recommendation: because (cost: ; asked ago). A1 to take recommendation. +- B: … + +"do it" takes every recommendation above; a named option ("A2") takes that option instead. The +ask format is gstack docs/captain.md, The ask format. ## New @@ -22,5 +27,7 @@ every row with its thread and an age. Codes are the thread codes the host assign |---|---|---|---| | | | | | +A thread the controller archives leaves this table in the same turn. + Stalls to act on: a lane with no report for longer than , a READY older than `FILL_HOURS` with no train, a slot call unanswered for longer than . diff --git a/captain/templates/READY.md b/captain/templates/READY.md index 73ce6de02..bbeb09fa3 100644 --- a/captain/templates/READY.md +++ b/captain/templates/READY.md @@ -20,6 +20,10 @@ SHIP_RECEIPT: pr= head= version=- base= tree= session_kind READY_RECEIPT: () ``` +Under `changelog_fragments` (docs/ship-policy.md#changelog-fragments) the PR's entry is a +fragment, `changelog.d/.md`, never an `[Unreleased]` section or a version, and the +controller merges with `train land` or `land`, so no slot call follows this block. + The lane's own lines, after the block: ```text diff --git a/captain/templates/brief.md b/captain/templates/brief.md index 1f6b0decb..efb283815 100644 --- a/captain/templates/brief.md +++ b/captain/templates/brief.md @@ -17,8 +17,11 @@ Spend cap: set, run dir under ~/.capy/work). Write the plan with its ## ELI5, ## Before → after, ## Why it matters, ## What caused this work, ## Big decisions and ## Implementation plan sections, then run gstack-autoplan next --out --plan - sized to this brief (a one-file fix: --no-ui --no-dx --max-rounds 1 --estimate-usd - --spend-cap ). At the gate send me the output of + sized to this brief (a fix: --no-ui --no-dx --max-rounds 1 --estimate-usd + --spend-cap , then close the CEO phase before dispatching its voices with + gstack-autoplan close --out --phase ceo --deferred "eng-only fix plan" + --by agent:). + At the gate send me the output of gstack-owner-brief render --captain --out whole, as a needs-you report. Build nothing yet. 2. Build after the word. I bring the owner's exact words back. Answer them into the run diff --git a/captain/templates/merge-ask.md b/captain/templates/merge-ask.md index 568a0a287..19e6cc3b6 100644 --- a/captain/templates/merge-ask.md +++ b/captain/templates/merge-ask.md @@ -24,4 +24,8 @@ flaky: · pregate: pass tree= ``` The controller's merge report: the PR link, the key image inline, the version it will -take, the slot, and the one-word reply if a decision is attached. +take, the slot, and, if a decision is attached, its lettered line in the ask format +(gstack docs/captain.md): "A: … Recommendation: x because why. A1 to take recommendation." +If the merge needs the owner to act (approve a deployment, grant access), the line carries +the exact link to that page and numbered steps in the simplest words, ending with the one +word to reply when done (a Capy app page: its exact path and field instead of a link). diff --git a/captain/templates/plan-ask.md b/captain/templates/plan-ask.md index 854998ffc..ba34245c8 100644 --- a/captain/templates/plan-ask.md +++ b/captain/templates/plan-ask.md @@ -5,7 +5,7 @@ gate codes in the body. `gstack-owner-brief render --captain --out ` pr shape from an autoplan run; write it by hand for any other plan. ```text -Decision needed on : . Reply **rec** to take every recommendation. +Decision needed on : . Reply **do it** to take every recommendation. ## ELI5 <5-10 plain sentences: what changes, for whom, and what it costs> @@ -25,10 +25,19 @@ output, a screen, a cost or time number> 2. … ## What we need from you -:

, which happens when . We could fix it in these ways: 1) (); 2) (); 3) (). Recommendation: because . A1 to take recommendation. +- B: … -**do it** = take every recommendation above at full scope, including , and carry them through to done with no further ask. +**do it** = take every recommendation in this list at full scope, including , and carry them through to done with no further ask. A named +option ("A2") takes that option instead. + + +- C: needs you to , because . Open , then: + 1. Click