v1.91.201.0 fix(confidence): one severity scale, CRITICAL/INFORMATIONAL, for /ship's review army and /plan-eng-review (#3349)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
garrytanandcapy-ai[bot] committed 2026-10-25 07:04:52 +00:00
commit af30cb97a5
68 files changed
+3228 -264

No files matched your search

+164 -1
View File
@@ -1,6 +1,6 @@
# Changelog
## [Unreleased]
## [1.91.201.0] - 2026-10-25
**/ship's review army and /plan-eng-review now ask for one severity scale, CRITICAL or INFORMATIONAL, the same scale /review, the specialist JSON and the review checklist already use (#3349).** The shared confidence rubric those two skills render told the model to label findings `[P1]` and `[P2]` and to report a 1-2 confidence finding "only if severity would be P0", while the rest of /ship's Step 9 (Pass 1 CRITICAL, Pass 2 INFORMATIONAL, `"severity":"CRITICAL|INFORMATIONAL"`) used the other scale. A finding from one skill couldn't be compared, deduplicated or gated against a finding from another. Garry picked CRITICAL/INFORMATIONAL for plan-eng-review on 2026-10-24.
@@ -13,6 +13,169 @@
### Gate integrity
- One accepted-input change to review: the paid-test detectors `test/helpers/eng-cache-writer-decision.ts` and `test/helpers/pty/boundaries.ts` accept `[CRITICAL]` and `[INFORMATIONAL]` alongside `[P0]`-`[P3]` in a plan finding's annotation, because the skill now asks for those labels. Without it, both captures relabelled `[CRITICAL]` are rejected. Verdict: not a weakening. The label is metadata, and every substantive check (decision, assessment, actors, options) is unchanged. Mutation checks: restoring `P[0-3]` alone fails the positive cases; `[^\]]+`, `P[0-9]` or a case-insensitive CRITICAL each fail the negative controls. `scripts/harness-version.json` records `test/helpers/pty/boundaries.ts` as non-behavioral at HARNESS_VERSION 6: only the changed plan-eng-review prompt asks for the new labels, and the cases that run it already start their own series. The 11 plan-eng-review size pins in `test/fixtures/skill-md-size-allowlist.json` come down by 75 characters. No threshold, budget, timeout, trial count or case kind changed.
## [1.91.200.0] - 2026-10-25
**/cso doctor no longer calls a Go repository "stack: python".** A repository with a root `go.mod` and no Node, Bun, Rails or JVM build matched no supported stack, so preparation fell back to Python and doctor reported `stack: python` with `MISSING_METADATA requirements.txt`, which sent Go users looking for a Python file they never needed (#3263). Go runtime support itself is not planned for now (Garry, 2026-10-24), so /cso keeps running static assessment on Go repositories; the runtime catalog and the /cso release contract are unchanged.
### Fixed
- **`lib/cso/preparation.ts`**: a root `go.mod` with no other supported stack is reported as `stack: go` with `UNSUPPORTED_STACK` ("Go (go.mod) is not a supported runtime stack yet; supported runtime stacks are Node, Bun, Python, and Rails."), the way a Maven or Gradle build is already reported as Java. Python helper metadata beside `go.mod` (a docs `requirements.txt`, say) no longer turns the repository into Python. A `go.mod` beside a Node, Bun or Rails lockfile leaves that stack's detection as it was.
### Tests
- `test/cso-preparation.test.ts` checks that a Go module is `go` with exactly that prerequisite and never mentions `requirements.txt`, and that a hashed `requirements.txt` beside `go.mod` stays Go. Both fail on main. Controls: `go.mod` beside a Node lockfile stays a ready Node plan, a Python project without `go.mod` stays Python, and a repository with no stack metadata keeps the Python fallback.
- `test/helpers/cso-runtime-catalog.ts` leaves `go` out of its qualified-runtime fixture list, as it already did `java`.
### Gate integrity
- No gate edit. No threshold, budget, timeout, trial count or case kind changed.
## [1.91.199.0] - 2026-10-25
**When /sync-gbrain refuses because a gbrain autopilot is running, it now says which process it found and what to do.** The guard against syncing while `gbrain autopilot` runs is machine-wide on purpose: two syncs sharing one brain or working tree can race and delete files (#1734). But the refusal only said `(process:gbrain autopilot)`, so someone whose autopilot served a different brain could not tell what was blocking them (#3360, part 1). Garry decided on 2026-10-24 to keep the check machine-wide and improve the message.
### Changed
- **`lib/gbrain-guards.ts`**: the live-process probe still runs `pgrep -f "gbrain autopilot"` across the whole machine, then reads each match's command line with `ps`. The refusal names every match as `pid <n> \`<command>\``, says the check counts any process on the machine whose command line contains "gbrain autopilot" (an autopilot serving another brain or repo included), and says to stop that autopilot or its `gbrain autopilot --install` service, or end a process that only mentions it. Commands are cut at 200 characters and the user and password part of a URL is masked. A pid that `ps` cannot describe still refuses, as `command unavailable`. The header comment now gives the machine-wide reason in place of the stale gbrain #1226 note.
### Tests
- `test/gbrain-guards.test.ts` pins the full refusal for one matched process, lists two matches, keeps an empty match inactive, and runs the real probe against a live process whose command line carries "gbrain autopilot" and a database URL with a password: the refusal names its pid and masks the password. All four fail on main. The existing probe, lock and stale-lock tests are unchanged.
### Gate integrity
- No gate edit: the guard refuses in exactly the cases it did before, and only its message changed. No threshold, budget, timeout, trial count or case kind changed.
## [1.91.198.0] - 2026-10-25
**A second-opinion reviewer that says "not ready" is no longer reported as clean.** When the outside reviewer (Codex or Claude Code) ended its reply with `Verdict: not ready` but listed only advisory P2 or P3 findings, `lib/outside-review-result.ts` printed `VERDICT: clean` and exited 0, so /ship and /codex carried on as if the reviewer had approved. The not-ready check only ran when no severity parsed at all, so a parsed P2 or P3 switched it off (#3329). Ported from #3364 by @mvanhorn.
### Fixed
- **`lib/outside-review-result.ts`**: when the reply's last recognized `Verdict:` line says `not ready`, the result is `findings` (exit 3) whatever severities parsed, and `FINDINGS:` still names the highest one. Advisory P2/P3 findings with a ready verdict, or with no verdict, stay `clean`. A `Verdict:` line quoted in a code fence or inline code still does not count, and the proposal and spec gates ignore it as before.
- **`docs/troubleshooting.md`**: the "Every review gate" rule under *How the verdict is read from a review* now says a not-ready reply blocks even when P2 or P3 parsed.
### Tests
- `test/outside-review-unparsed-severity.test.ts` covers the issue's reply (numbered bold P2 plus P3, then `Verdict: not ready`) on the execution, structured and review gates, P3-only and unlabeled not-ready replies, the last verdict winning in both directions, bold, bulleted and heading verdict lines, and an unparsed label beside a parsed P2. Five of its tests fail on main's classifier and pass with the fix. Controls that stay `clean`: P2/P3 with `Verdict: ready` or no verdict, a not-ready verdict inside a code fence or inline code, and `ready-one-p3.txt`. Missing review markers, a failed execution, and the proposal and spec gates keep their old results.
### Gate integrity
- One gate edit, and it strengthens the gate: the pinned `bare-dash-p2.txt` fixture (two P2 lines, then `Verdict: not ready (2 P2)`) moves from `VERDICT: clean`, exit 0 to `VERDICT: findings`, exit 3. Garry approved this reversal on 2026-10-24. No threshold, budget, timeout, trial count or case kind changed.
## [1.91.197.0] - 2026-10-25
**Pregate gives touched Rust files a test lane, and runs a nested pnpm or vitest package with its own runner (#3344).** In a mixed Cargo and JavaScript repo, every touched `.rs` file failed `lanes` with "has no test lane", so /ship could not get a receipt, and a nested package's vitest tests ran under `bun test` from the repo root (about 98 false failures in the reporter's repo). Ported from #3346 by vilano93, whose two commits carry the feature; our commits on top close four findings from a security-focused review of the port and make the new fixtures hermetic.
### Fixed
- **`lib/pregate/rust.ts`** (new, vilano93): a crate is the nearest Cargo.toml with `[package]`. Its `.rs` files under `tests/` or holding a `#[cfg(test)]` are tests, and every `.rs` file of a crate and its Cargo.toml select that crate's tests and those of every crate depending on it. Manifests are parsed as TOML, so renamed, inherited, dotted, table-form and target-specific dependencies all count, and a crate runs from the workspace it is a member of under Cargo's rules (members, exclude, `package.workspace`). Nothing runs cargo to build the graph.
- **`lib/pregate/checks/lanes.ts`** (vilano93): selected Rust tests run per crate as `cargo test -p <name>` from the workspace root and are judged on the summed `test result:` lines; zero tests is ZERO-RUN and a missing cargo is incomplete. A JS/TS test owned by a nested package.json that declares vitest or jest runs from that package through the package manager its `packageManager` field or nearest lockfile names (`pnpm exec`, `yarn`, `bun x`, else `npx`).
- **`lib/pregate/checks/lanes.ts`**: the crate name comes from the repo's Cargo.toml and reaches the lane's shell. Before, a crate named `evil;touch pwned` ran `touch pwned` in the workspace, and a name containing `{files}` spliced the file list into the command. A name outside Cargo's grammar (letters, digits, `_`, `-`) now gets no runner, so its files are unclaimed and the lane is incomplete, as Cargo would refuse the manifest anyway; a valid name is quoted like every file and cwd. The lane only runs with `--allow-repo-commands`, under which the repo's tests run anyway, but no other repo input reached the shell unquoted.
- **`lib/pregate/rust.ts`**: Cargo `members` globs are matched per path component and by Unicode code point, in one pass. The first cut used the policy glob matcher, which matched `[ab]` literally (a member listed that way lost its inherited workspace dependencies, so its tests were never selected) and backtracked for seconds on a hostile glob. Past 4096 characters of `members` globs, membership is undecided: every crate under the workspace counts as a member for dependency edges (more tests, never fewer), but its own tests are unclaimed and the lane is incomplete, because running `cargo test -p <name>` from the wrong root can test a same-named member instead.
- **`lib/pregate/rust.ts`**: a plain `#[test]` or `#[tokio::test]` function in `src/` makes the file a test, so a dependent crate tested that way runs when its dependency changes. The `#[cfg(...)]` scan reads each attribute once, up to its closing `]`, so a file of unclosed attributes no longer takes seconds, and an attribute it cannot close counts as a test (more tests selected, never fewer).
- **`lib/pregate/init-draft.ts`** (vilano93): `init` notes that Rust tests run per crate.
### Tests
- `test/pregate-rust.test.ts` (new, vilano93) covers the crate model, the dependency forms, workspace membership, the cargo summary parser and three end-to-end lane runs. New cases: crates named `evil;touch pwned-by-crate-name` and `evil{files}` never reach the shell (nothing is created, both are unclaimed) while `naïve_crate-2` still runs quoted; `crates/[ab]`, `nested/**/leaf` and `unicode/?` (a 📦 directory) members inherit workspace dependencies; a plain `#[test]` dependent and a `cfg(any(test, feature = "<300 chars>"))` are tests; and a same-named non-member past the size cap is unclaimed rather than run as the member; a hostile members glob, a million unmatched `[` and 100,000 unclosed `#[cfg(` run in a supervised Bun that kills a super-linear version at 30 s. Each failed before its fix.
- The cargo stand-in is hermetic on POSIX: where Bun and cargo share a directory, the lane puts Bun's directory first and the real cargo ran against the fixture, so the shim PATH now uses the platform delimiter and the lane's bash puts the shim first again through `BASH_ENV`. On windows-free-shard (5) the two cases that run the stand-in failed deterministically (`local lane exited 1` with an empty log) and still did after the delimiter and a `Path`-key repair, so they are skipped on Windows (`test.skipIf(process.platform === 'win32')`, as other POSIX-shim pregate fixtures are); the selection, planning and hostile-name cases still run there.
- `test/pregate-selection.test.ts` (vilano93) covers nested pnpm/yarn/vitest/jest packages. Its `pnpm` stand-in gets the same `BASH_ENV` fix: on a host with a real pnpm beside Bun, the end-to-end case installed vitest from the network and came back incomplete.
### Gate integrity
- One coverage change to review: the two new end-to-end cargo-lane cases in `test/pregate-rust.test.ts` are skipped on Windows (they never passed there); Linux and macOS run them, and the rest of the file runs on Windows.
- No threshold, budget, timeout, trial count or case kind changed. Pregate's lanes now map and run tests for `.rs` files that previously failed closed with "no test lane", and nested vitest/jest packages run under their own runner instead of `bun test`. A `.rs` file outside any crate, a crate with no tests, and a missing cargo or package manager still fail closed or stay incomplete; the tests above cover each.
- No new dependency (Cargo.toml is parsed with Bun's built-in TOML parser), no network call in pregate itself, no workflow change. As with the root runner detection on main (`npx vitest run`), a nested package's detected runner (`npx`, `bun x`) may fetch a missing tool when it runs under `--allow-repo-commands`.
## [1.91.196.0] - 2026-10-25
**`/land-and-deploy` no longer stops parallel PRs with a false "VERSION drift detected".** Step 3.4 compared the branch VERSION with the next free patch slot (`gstack-next-version --bump patch --exclude-pr`) under every ship policy. So it stopped a stamp-at-merge PR whenever a sibling shared its tentative stamp, a claim-at-open PR whenever a sibling had claimed a higher slot, and every MICRO bump even with no other PR open. Reported with a full reproduction by Evgenii Lopatin (@exGeni) in #3318.
### Fixed
- **`land-and-deploy/SKILL.md.tmpl` Step 3.4**: reads `gstack-ship-policy show-effective` and prints one `VERSION_CHECK:` verdict. Under `stamp-at-merge` it ignores claims and checks the exact head stamp: VERSION is the base's version plus one bump, and the changelog's top two headings are that version and then the base's top entry. Otherwise it stops with `STOP stamp stale` and names the `gstack-restamp --next` command. Under `claim-at-open`, and with no policy file, it stops only on a real collision: another open PR holds the same VERSION, or the base is already at or above it. MICRO bumps and versions below a sibling's claim pass.
### Documentation
- `docs/ship-policy.md` gains "What `/land-and-deploy` reads from it", which gives Step 3.4's stop and pass conditions for each `queue_mode`.
### Tests
- `test/land-and-deploy-version-check.test.ts` runs the template's own Step 3.4 block against real git fixtures with the real `gstack-ship-policy` and a stubbed claim list, under bash and, when installed, zsh. It covers the three false stops from #3318 (all pass now) and the real stops: a same-VERSION claim, a base at or above the branch, a stale stamp after a sibling landed, a base that moved by MICRO under a stamp, an `[Unreleased]` entry, and a two-bump stamp. A missing VERSION, an invalid policy and unread claims are `unavailable`.
### Gate integrity
- Step 3.4 now stops on fewer inputs: a unique VERSION below a sibling's claim, a MICRO bump, and a stamp-at-merge stamp that siblings share no longer stop. Every real collision still stops, and six mutation controls of the block (drop the collision check, the base check, the changelog binding, the one-bump rule, the policy read, or the unread-claims rule) each turn the new tests red. One new `unavailable` path: an invalid ship policy. It mirrors the existing offline path, and a base at or above the branch still stops there.
- Owner-approved budget raise (Garry, 2026-10-24: "do it"): land-and-deploy's exact size pins in `test/fixtures/skill-md-size-allowlist.json` move up by 1,084 to 1,111 characters on 11 hosts, and its parity `maxSizeRatio` in `test/helpers/carve-guards.ts` goes from 1.112 to 1.125 (measured 1.1201). No threshold, timeout, trial count or case kind changed.
## [1.91.195.0] - 2026-10-25
**Four skill prompts stop contradicting themselves or their code.** dgrant's issues #3347, #3350, #3351 and #3352 each found a skill telling the model something wrong or ambiguous: /office-hours read a master-based repo as "no changes", /plan-design-review named a vision model the design binary no longer uses, /health gave two different GBrain scores for the same readings, and /ios-qa's demo mode claimed to override every other rule in the skill.
### Fixed
- **`office-hours/SKILL.md.tmpl`** (#3347): Phase 1 runs `git diff origin/HEAD --stat`, the remote's default branch, instead of `git diff origin/main --stat 2>/dev/null`. On a clone whose default branch is `master`, the old command exited 128 with its error hidden, so the model read the empty output as "no changes"; the new one shows the diff, and a repo without `origin/HEAD` now shows its error instead of passing for "no diff". The line is the same length, so office-hours stays at its pinned size on every host (the shared `{{BASE_BRANCH_DETECT}}` block would have added 1,727 chars, past the size-guard pins and the parity skeleton cap).
- **`plan-design-review/SKILL.md.tmpl`** (#3350): the design binary's `check` command is described as "OpenAI vision" instead of "GPT-4o vision", so the prose no longer pins a model. The binary defaults to gpt-5.5 (`design/src/models.ts`), `GSTACK_DESIGN_MODEL` overrides it, and gpt-4o cannot drive gpt-image-2 at all. The swap is the same length, so the pinned host sizes don't move.
- **`health/SKILL.md.tmpl`** (#3351): the GBrain score is computed by a `bun -e` snippet from the doctor component (10 for `ok`, 7 for `warnings`, else 0), the queue length and the hours since the last push, like the composite already was. The snippet takes only numeric `<N|null>` inputs, the placeholder form the generated-bash lint already allows. The rubric row's 10/7/4 bands, which disagreed with the weighted formula (doctor ok, queue 50, pushed 2h: 7 by the rubric, 9.1 by the formula) and overlapped (a queue of 3 matched both 10 and 7), now point at that computation. The bands are half-open (<10, <100 lines; <24, <72 hours), and with sync off the doctor component carries the whole score. History records `gbrain` with one decimal.
- **`ios-qa/SKILL.md.tmpl`** (#3352): "DEMO MODE OVERRIDES ALL OTHER RULES" becomes the narrow rule it meant: in demo mode drive every action through visible UI rather than `POST /state/*` writes, and every other rule in the skill (the device lock, no replay of a lost tap, never hand-editing DebugBridge) still applies.
### Tests
- `test/qa-health-rubric.test.ts` checks that the GBrain rubric row defers to the computation, then runs the template's own snippet: the issue's two inputs score 9.1 and 8.5, the band edges (9/10/99/100 lines, 23.9/24/71.9/72 hours) land on the right side, a missing doctor reading counts as 0, and sync off gives 10, 7 and 0. All four new tests fail on the old template.
- `test/helpers/safety-rules.ts`: the `ios-qa-demo-override` row's anchor moves from `/demo mode overrides/i` to `/drive every action through visible UI/i`, and its hash to the reworded paragraph, in the #3352 commit as the registry requires. `test/safety-rule-registry.test.ts` passes, including its unique-anchor and rule-removed-arm checks.
### Gate integrity
- One gate edit to review: the safety-rule registry row for `safety-ios-demo-ui-only` now anchors on the reworded paragraph. Verdict: not weaker. The paragraph still requires visible UI (`/tap`, `/swipe`, `/type`) over `POST /state/*` writes, and the only text removed is the "overrides all other rules" claim. The case's rule-removed arm deletes the same paragraph as before. No threshold, budget, timeout, trial count or case kind changed.
## [1.91.194.0] - 2026-10-25
**A read-only repo can now opt in to Memorable recall, one remote at a time, and a corrupt policy store no longer turns the recall veto off.** #3359 (exGeni) asked for a way to keep a repo out of the brain while still letting its prompts reach Memorable: today the recall hook skips every `deny` and `read-only` repo, and `read-only` is also the tier people pick just to stop code ingest. Garry approved a per-remote flag on 2026-10-24: off by default, and a `deny` always wins. While building the negative controls we found that the hook's policy lookup went through `get`, which quarantines a corrupt store and answers "unset", so a truncated `gbrain-repo-policy.json` let recall run in every repo, read-only and deny included, and reset the store on the way.
### Added
- **`bin/gstack-gbrain-repo-policy memorable set <remote-url> <allow|off>`** stores the opt-in under a reserved `_memorable_recall` map in the policy store. It is refused unless the remote is read-only (deny vetoes recall; read-write never needed it). `memorable get [<remote-url>]` prints `<tier>\t<allow|off>`, and `list` adds a `memorable=allow` column. Changing a remote's tier clears its opt-in, and the two metadata keys (`_schema_version`, `_memorable_recall`) are refused as remotes.
- **`lib/gbrain-repo-policy-client.ts`**: `memorableRecallPolicy(url)` returns the tier and the opt-in in one spawn. Anything but exactly `<tier>\t<allow|off>` reads as `unreadable`.
### Changed
- **`hosts/claude/hooks/memorable-user-prompt-hook.ts`**: a `read-only` remote is recalled only when it is opted in; `deny` is always skipped. The skip line in `hook-errors.log` names the opt-in command.
### Fixed
- The recall hook's policy lookup is now a pure read that fails closed in either state root: a corrupt, empty or non-object store, a present key with an unknown tier, a path that is not a readable file (a dangling symlink included) and a path whose existence an unsearchable ancestor directory hides are all errors, never "no policy", and nothing is migrated, quarantined or rewritten. The opt-in counts only when it is exactly `"allow"` and every store that makes the remote read-only (including `~/.gstack` under a custom state root) opts it in.
- The hook looks policy up by every configured `remote.origin.url`, as `get` and `/sync-gbrain` read it, instead of the first URL after `url.*.insteadOf` rewriting. A rewrite to another host, or a second origin URL, no longer dodges a deny: any denied or not-opted-in read-only URL skips recall. `hasRepoPolicyStore()` treats only confirmed absence as "no store", so a dangling symlink at or above the store, a file in its path, or an unreadable directory reaches the script's fail-closed checks instead of the no-policy fast path. Origin URLs are read NUL-delimited and used verbatim, so a valid local path containing a newline or edge whitespace is looked up whole.
### Docs
- `docs/memorable-workflow-memory.md` has a short "Recall in a read-only repo" section and updated refusal and troubleshooting lines.
### Tests
- `test/memorable-user-prompt-hook.test.ts` drives the real hook: read-only stays blocked by default, the opt-in recalls on that remote and not on a second read-only remote, `deny` with a hand-written opt-in is skipped, and a corrupt store skips recall and is left in place.
- `test/gbrain-repo-policy.test.ts` covers the CLI: per-remote keying (a different remote, a prefix-sharing remote and an unset remote stay off; the SSH spelling of the same remote matches), refusal on deny, read-write and unset, clearing on a tier change, malformed opt-ins reading off, corrupt and non-file stores in both roots failing with exit 2, and the second-store rule.
- `test/gbrain-repo-policy-client.test.ts` covers `memorableRecallPolicy`: fast path, per-remote opt-in, deny, corrupt store, an unknown tier, a dangling-symlink store and a timeout.
- Review hardening, each test red at the pre-review head: empty, whitespace, `null`, array, number and two-document stores and `false`/`null`/unknown tier values fail with exit 2 in either root; dangling symlinks and an unsearchable directory or ancestor fail closed; the lookup leaves a schema-less store byte-for-byte unchanged; and the hook refuses a deny remote whose origin is rewritten to another host or carries a second, unlisted URL in either order, or whose local-path URL contains a newline or edge whitespace; and a dangling symlink above the store or a file in its path skips the no-store fast path.
### Gate integrity
- One deliberate widening of a privacy veto, approved by Garry: a read-only remote with an explicit opt-in is recalled. Nothing else is loosened, and the corrupt-store path is tightened. Seventeen mutations of the new gate were run against the focused tests. Sixteen turn at least one test red: the hook ignoring the opt-in, the hook dropping deny, the CLI reporting the opt-in on any tier, an unkeyed opt-in, a corrupt store read as no policy, the second store ignored, an opt-in accepted on deny, the hook using the rewritten URL, an existsSync fast path, any JSON document accepted, a non-file path read as absent, the hook checking only the last origin URL, a missing path trusted without checking its ancestors, origin URLs split on newlines or trimmed, and the client fast path ignoring a dangling ancestor symlink. The seventeenth, the client reading unknown script output as no policy, stays green because the script can no longer produce such output. That check is a second layer and is left in place. No threshold, budget, timeout, trial count or case kind changed.
- Known limit, unchanged by this PR: remotes that the store already treats as one key (`host:8443/x` and `host/8443/x`, or paths that differ only in case) share the opt-in exactly as they already share a tier.
## [1.91.193.0] - 2026-10-25
**Windows: the browse terminal agent stops respawning every 60 seconds and stops flashing a console when Bun came from npm (#2295; ported from #3357 by @adammartin0087).** The agent was spawned as a bare `bun`. With Bun installed through `npm install -g bun`, that name resolves to npm's `bun.cmd` shim and runs as `cmd.exe /c bun …`, so `windowsHide` hid only `cmd.exe` while `bun.exe` opened its own visible console, and the recorded pid was `cmd.exe`'s. The agent's startup check never matched its record, it exited after 2 seconds, and the watchdog respawned it.
### Fixed
- **`browse/src/terminal-agent-control.ts`**: `spawnTerminalAgent` spawns `resolveBunExecutable()`, which on Windows is the real `bun.exe`: the running `bun.exe` itself, then `BUN_INSTALL\bin`, each absolute `PATH` entry (and, next to an npm `bun.cmd` shim, the `node_modules\bun\bin\bun.exe` it forwards to), then `USERPROFILE\.bun\bin`. With none found it falls back to `bun`, as before. macOS and Linux are unchanged.
- **`browse/src/bun-child-config.ts`**, **`browse/src/cookie-import-native.ts`**: that lookup is `findWindowsBunExe()`, and the Windows native cookie-import worker now uses it instead of its own copy, so it also finds an npm-global Bun. It lives in `bun-child-config.ts` because that file is already in the native import's source-bound qualification set (`NATIVE_CODE_INPUTS`). The edit changes the hash of `cookie-import-native.ts` and `bun-child-config.ts`; the qualification list is empty today, so no receipt is invalidated.
### Tests
- `browse/test/terminal-agent-bun-exe.test.ts` (from the PR) covers POSIX, the running `bun.exe`, a compiled `browse.exe`, the npm shim, lookup order and the fallback, plus a source check that the spawn site never passes a bare `'bun'`. New: the shared lookup returns null when nothing is installed, finds the npm-global `bun.exe` for the cookie worker, and `cookie-import-native.ts` has no candidate list of its own.
- Not verified here: real Windows behaviour. The PR author tested on Windows 11; the `windows-free-tests` lane runs the new unit tests.
## [1.91.192.0] - 2026-10-25
**Merge trains stop refusing correct heads and stop passing damaged CHANGELOGs.** This week's trains hit five defects in the ship-queue tooling. #3331's READY was invisible to the coordinator because its lane's origin was `https://git.capy.ai/...`. #3345's pin replaced the released `## [1.91.179.0]` heading, and three things then failed. The Version Gate passed the pin. `mergeChangelogs` copied 179's body into `[Unreleased]`. `verify --train` refused the correct hand-resolved head at 593e61c. Separately, the train slotted the /cso docs PR (#3337) ahead of the catalog PR it describes (#3343). Each defect now has a regression test built from the real case.
### Fixed
- **`lib/version-gate-train.ts`**: the unstamped-head check read CHANGELOG.md through `spawnSync`'s default 1 MiB buffer. gstack's CHANGELOG is 1.67 MB, so both reads failed and the check compared two empty strings and passed. That is how #3345's 1eb7092 got through: `classifyTrainHead(base a59b5e4, head 1eb7092)` returned `unstamped`. The buffer is now 64 MiB, a CHANGELOG that can't be read is refused, and a dropped released heading is named in the error ("CHANGELOG.md drops released heading 1.91.179.0"). `gstack-ship-queue ready` runs the same check and refuses with `QUEUE_NOT_READY`.
- **`lib/changelog-check.ts`**: `mergeChangelogs(ours, theirs, base?)` returns null, meaning resolve by hand, when either side damaged released history. Damage means one of two things: a released heading the merge base carries is missing from that side (dropped or renamed), or a section only that side carries holds a paragraph of a released entry the other side has. The train merge, the gate-ahead recompute and `gstack-restamp --after` all pass the merge base. A damaged PR is now `QUEUE_TRAIN_CONFLICT` on CHANGELOG.md with the reason. Before, the damage went into T<i>.
- **`lib/ship-queue-train-verify.ts`**: `verify --train` refused #3345's correct stamped head because T1's CHANGELOG was the damaged mechanical merge. The refusal printed the diff against the pin (main's files), not the diff against T1. A merged-in head is now accepted when it contains main and equals T<i> modulo stamps, with its CHANGELOG judged against main: main's header and sections must be unchanged, with only lines from the pin's own CHANGELOG diff above them. The refusal now names the real difference.
- **`lib/ship-queue-train-record.ts`**: READY receipts, train records and freezes are keyed on origin normalized to `https://github.com/<owner>/<repo>`, whatever URL form the lane uses (github.com, git.capy.ai, scp, ssh, a token URL, with or without `.git`). The canonical key equals the github.com key existing records already use. Readers also accept the keys older versions wrote for the common URL forms, so #3331's `1fb5dd69740a8cf8` receipt is found. The stored `repo` URL never carries credentials.
- **`lib/restamp.ts`**: its git reads use a 64 MiB buffer too. Before, `gstack-restamp --after` read each CHANGELOG conflict stage through the 1 MiB default.
### Added
- **`gstack-ship-queue train build --order <pr>,...`**: an explicit slot order naming every pinned PR once. The default order (screened first, then READY order) is unchanged, and the train's later `NEXT:` rebuild lines keep the explicit order.
### Tests
- `test/changelog-merge-damage.test.ts`: the GSTA-64 repro, plus #3345's real CHANGELOGs (pin 1eb7092, base a59b5e4, main 4a98e40, train T1 6755ab8, stamped de23f5d, under `test/fixtures/merge-train-3345/`). Negative controls: a correct hand resolve, a shared tentative stamp, and two `[Unreleased]` blocks are not damage. An invented line, an edited main section, a changed header and a duplicate heading are still refused.
- `test/compare-pr-version.test.ts`: on a CHANGELOG over 1 MiB, #3345's edit is refused naming 1.91.179.0, an additive entry passes, and a corrupt CHANGELOG object is refused. All three failed before the fix.
- `test/ship-queue-train.test.ts`: a git.capy.ai lane writes the owner/repo key, and a legacy-key receipt is admitted. A damaged PR is a CHANGELOG conflict, and ready refuses it. `--order` sets and records the order. A hand-resolved merged-in head verifies, while an invented CHANGELOG line, a head without main and a stray file are refused. `test/ship-queue-train-logic.test.ts`: URL normalization, #3331's real keys, `orderSlots` and `parseOrder`.
### Gate integrity
- Version Gate unstamped check: **stronger**. It refuses a head it can't read and names dropped headings. Additive heads still pass at full size.
- `mergeChangelogs` and the train CHANGELOG merge: **stronger**. Damage is now a conflict.
- `verify --train` merged-in path: **narrower in one place, stronger elsewhere**. The head must now contain main. A CHANGELOG that differs from T<i> is accepted only as main's CHANGELOG plus lines the pin itself added. Every other file must still equal T<i> modulo stamps, and the paid gate never reads CHANGELOG text.
- READY receipt lookup: **unchanged strength**. The head and CI binding are the same; only the repository key is normalized.
## [1.91.191.0] - 2026-10-25
**`gstack-version-bump write --changelog` moves the branch's `[Unreleased]` entry under the new version, and /ship Step 12 stops treating a provisional queue pick as a verified slot.** Stamping by hand meant writing VERSION with `gstack-version-bump write` and then renaming the `## [Unreleased]` heading yourself, because only `gstack-restamp` re-headed the CHANGELOG. Separately, when `gstack-next-version` could not read some open PRs' VERSION it returned `complete:false` and a provisional pick, and Step 12 printed the warning and then wrote that version as if the queue had been checked (left over from #3258, noted in GSTA-45).
+1 -1
View File
@@ -1 +1 @@
1.91.191.0
1.91.201.0
+1 -1
View File
@@ -1,4 +1,4 @@
# gstack digest v1.91.191.0 — regenerate/re-copy after upgrading gstack
# gstack digest v1.91.201.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,
+182 -8
View File
@@ -15,10 +15,22 @@
# rather than bypass a set policy.
#
# gstack-gbrain-repo-policy set <remote-url> <read-write|read-only|deny>
# Persist a tier for the given remote. Exits 0 on success.
# Persist a tier for the given remote. Exits 0 on success. Changing a
# remote's tier clears its Memorable recall opt-in.
#
# gstack-gbrain-repo-policy memorable get [<remote-url>]
# Print "<tier>\t<allow|off>": the tier (as `get` prints it) and whether
# Memorable recall is opted in for this remote. Read-only lookup for the
# recall hook: a corrupt store is a hard error (exit 2), never quarantined.
#
# gstack-gbrain-repo-policy memorable set <remote-url> <allow|off>
# Opt a read-only remote in to (or back out of) Memorable recall. Off by
# default. Refused unless the remote's tier is read-only: a deny tier
# always vetoes recall, and read-write never needed an opt-in.
#
# gstack-gbrain-repo-policy list
# Print every entry as "<key>\t<tier>", sorted by key.
# Print every entry as "<key>\t<tier>", sorted by key, with a third
# column "memorable=allow" on remotes opted in to Memorable recall.
#
# gstack-gbrain-repo-policy normalize <url>
# Print the normalized (canonical) key for a given remote URL.
@@ -33,8 +45,11 @@
# {
# "_schema_version": 2,
# "github.com/foo/bar": "read-write",
# "github.com/baz/qux": "deny"
# "github.com/baz/qux": "deny",
# "_memorable_recall": { "github.com/foo/bar": "allow" }
# }
# The keys _schema_version and _memorable_recall are reserved; other keys
# name remotes (including the _unattributed sentinel memory-ingest uses).
#
# Tier semantics:
# read-write — agent may search AND write new pages from this repo.
@@ -43,6 +58,11 @@
# decision.)
# deny — no gbrain interaction at all.
#
# Memorable recall opt-in: the recall hook skips deny and read-only remotes.
# A read-only remote listed in _memorable_recall with exactly "allow" is
# recalled anyway; any other value or shape counts as off. Every store that
# makes the remote read-only (see the merge below) must opt it in.
#
# Legacy migration:
# On any read of a file missing `_schema_version` (or with version < 2),
# legacy `allow` values are atomically rewritten to `read-write`, and
@@ -187,6 +207,24 @@ ensure_file() {
fi
}
# memorable_optin FILE KEY — "allow" when FILE's _memorable_recall map holds
# exactly the string "allow" for KEY; any other value or shape is "off".
memorable_optin() {
jq -r --arg key "$2" '(._memorable_recall | if type == "object" then .[$key] else null end) as $v
| if $v == "allow" then "allow" else "off" end' "$1"
}
# jq filter that removes $key's opt-in (and an emptied map).
DROP_MEMORABLE_OPTIN='if (._memorable_recall | type) == "object" then (._memorable_recall |= del(.[$key])) | (if ._memorable_recall == {} then del(._memorable_recall) else . end) else . end'
# _schema_version and _memorable_recall hold store metadata; a remote that
# normalizes to one of them cannot be stored.
reject_reserved_key() {
case "$1" in
_schema_version|_memorable_recall) die "'$1' is a reserved key in the policy store, not a remote" ;;
esac
}
_tier_rank() {
case "$1" in deny) echo 0 ;; read-only) echo 1 ;; read-write) echo 2 ;; *) echo 3 ;; esac
}
@@ -295,13 +333,146 @@ cmd_set() {
local key
key=$(normalize "$url")
[ -z "$key" ] && die "cannot normalize remote URL: $url"
reject_reserved_key "$key"
ensure_file
local tmp
local previous opted tmp
previous=$(jq -r --arg key "$key" '.[$key] // "unset"' "$POLICY_FILE")
opted=$(memorable_optin "$POLICY_FILE" "$key")
tmp=$(mktemp "$POLICY_FILE.tmp.XXXXXX")
jq --arg key "$key" --arg tier "$tier" '.[$key] = $tier' "$POLICY_FILE" > "$tmp"
if [ "$previous" != "$tier" ]; then
jq --arg key "$key" --arg tier "$tier" ".[\$key] = \$tier | $DROP_MEMORABLE_OPTIN" "$POLICY_FILE" > "$tmp"
else
jq --arg key "$key" --arg tier "$tier" '.[$key] = $tier' "$POLICY_FILE" > "$tmp"
fi
mv "$tmp" "$POLICY_FILE"
chmod 0600 "$POLICY_FILE"
echo "Set $key → $tier"
if [ "$previous" != "$tier" ] && [ "$opted" = "allow" ]; then
echo "Cleared the Memorable recall opt-in for $key (the tier changed; opt in again with: gstack-gbrain-repo-policy memorable set $key allow)"
fi
}
# memorable_store_answer FILE KEY — "<tier> <allow|off>" for KEY in one store,
# read from a single snapshot of the file with no write, migration or
# quarantine (tier is none when the file or the key is absent; a legacy
# "allow" reads as read-write in memory). Dies (exit 2) on anything else: a
# path that is present but not a readable regular file, a path whose
# existence cannot be confirmed (an unsearchable ancestor), content that is not exactly one JSON object, or a
# present key whose value is not a known tier.
memorable_store_answer() {
local store="$1" key="$2" up raw
if ! [ -e "$store" ] && ! [ -L "$store" ]; then
# Absent only if the nearest existing ancestor is a searchable directory:
# an unsearchable one hides an existing store from every test above.
up=$(dirname "$store")
while ! [ -e "$up" ] && ! [ -L "$up" ] && [ "$up" != "/" ] && [ "$up" != "." ]; do up=$(dirname "$up"); done
if [ -d "$up" ] && [ -x "$up" ]; then
printf 'none off\n'
return 0
fi
die "cannot confirm whether $store exists ($up is not a searchable directory) — refusing the Memorable recall lookup."
fi
if ! [ -f "$store" ] || ! [ -r "$store" ]; then
die "policy store $store exists but is not a readable file — refusing the Memorable recall lookup. Inspect or remove it."
fi
raw=$(cat -- "$store") || die "cannot read policy store $store — refusing the Memorable recall lookup."
printf '%s' "$raw" | jq -e -s -r --arg key "$key" '
if length == 1 and (.[0] | type) == "object" then .[0] else error("not one JSON object") end
| (if has($key) then
(.[$key] | if . == "allow" then "read-write"
elif . == "deny" or . == "read-only" or . == "read-write" then .
else error("invalid tier") end)
else "none" end) as $tier
| ((._memorable_recall | if type == "object" then .[$key] else null end) == "allow") as $opt
| "\($tier) \(if $opt then "allow" else "off" end)"' 2>/dev/null \
|| die "policy store $store is corrupt (not one JSON object, or an invalid tier for $key) — refusing the Memorable recall lookup. Inspect with: gstack-gbrain-repo-policy list; re-run /setup-gbrain to rebuild the store."
}
# memorable get — tier plus the effective Memorable recall opt-in, for the
# recall hook. Pure read: each store is read once, never migrated, never
# quarantined, and any doubt about a present store is a hard error (exit 2),
# because reading it as "no policy" would silently lift a deny or read-only
# veto. The tier merges as get does (the ~/.gstack store contributes only deny
# or read-only). The opt-in counts only when the merged tier is read-only and
# every store that restricts the remote (deny or read-only) opts it in, so an
# opt-in can never relax a restriction another store imposed.
cmd_memorable_get() {
local url="${1:-}"
require_jq
if [ -z "$url" ]; then
url=$(git config --get remote.origin.url 2>/dev/null || true)
fi
local key
key=$(normalize "$url")
if [ -z "$key" ]; then
printf 'unset\toff\n'
return 0
fi
local answer p_tier p_opt l_tier="none" l_opt="off"
answer=$(memorable_store_answer "$POLICY_FILE" "$key") || exit 2
read -r p_tier p_opt <<<"$answer"
if [ -n "$_gstack_legacy_root" ]; then
answer=$(memorable_store_answer "$_gstack_legacy_root/gbrain-repo-policy.json" "$key") || exit 2
read -r l_tier l_opt <<<"$answer"
fi
local merged="$p_tier"
case "$l_tier" in
deny|read-only)
if [ "$(_tier_rank "$l_tier")" -lt "$(_tier_rank "$merged")" ]; then merged="$l_tier"; fi ;;
esac
if [ "$merged" != "read-only" ]; then
[ "$merged" = "none" ] && merged="unset"
printf '%s\toff\n' "$merged"
return 0
fi
local optin="allow"
case "$p_tier" in deny|read-only) [ "$p_opt" = "allow" ] || optin="off" ;; esac
case "$l_tier" in deny|read-only) [ "$l_opt" = "allow" ] || optin="off" ;; esac
printf 'read-only\t%s\n' "$optin"
}
cmd_memorable_set() {
local url="${1:-}" value="${2:-}"
if [ -z "$url" ] || [ -z "$value" ]; then die "usage: memorable set <remote-url> <allow|off>"; fi
case "$value" in
allow|off) ;;
*) die "invalid value '$value' (must be allow or off)" ;;
esac
local key
key=$(normalize "$url")
[ -z "$key" ] && die "cannot normalize remote URL: $url"
reject_reserved_key "$key"
if [ "$value" = "allow" ]; then
local current
current=$(cmd_memorable_get "$url" | cut -f1)
case "$current" in
read-only) ;;
deny) die "$key is deny: a deny tier always vetoes Memorable recall, so an opt-in is refused. Change the tier first if you mean it: gstack-gbrain-repo-policy set $key read-only" ;;
*) die "$key is $current, not read-only: the opt-in only applies to read-only remotes (read-write is already recalled; an unset remote has no veto)" ;;
esac
fi
ensure_file
local tmp
tmp=$(mktemp "$POLICY_FILE.tmp.XXXXXX")
if [ "$value" = "allow" ]; then
jq --arg key "$key" '._memorable_recall = ((._memorable_recall | if type == "object" then . else {} end) + {($key): "allow"})' "$POLICY_FILE" > "$tmp"
else
jq --arg key "$key" "$DROP_MEMORABLE_OPTIN" "$POLICY_FILE" > "$tmp"
fi
mv "$tmp" "$POLICY_FILE"
chmod 0600 "$POLICY_FILE"
echo "Set $key memorable recall → $value"
if [ "$value" = "allow" ] && [ "$(cmd_memorable_get "$url" | cut -f2)" != "allow" ]; then
echo "gstack-gbrain-repo-policy: $LEGACY_POLICY_FILE also makes $key read-only and does not opt it in, so recall stays off. Opt in there too: GSTACK_STATE_ROOT=$_gstack_legacy_root gstack-gbrain-repo-policy memorable set $key allow" >&2
fi
}
cmd_memorable() {
case "${1:-}" in
get) shift; cmd_memorable_get "$@" ;;
set) shift; cmd_memorable_set "$@" ;;
*) die "usage: memorable {get [<remote-url>]|set <remote-url> <allow|off>}" ;;
esac
}
cmd_list() {
@@ -310,7 +481,9 @@ cmd_list() {
return 0
fi
ensure_file
jq -r 'to_entries[] | select(.key != "_schema_version") | "\(.key)\t\(.value)"' "$POLICY_FILE" | sort
jq -r '(._memorable_recall | if type == "object" then . else {} end) as $m
| to_entries[] | select(.key != "_schema_version" and .key != "_memorable_recall")
| "\(.key)\t\(.value)" + (if $m[.key] == "allow" then "\tmemorable=allow" else "" end)' "$POLICY_FILE" | sort
}
cmd_normalize() {
@@ -323,8 +496,9 @@ case "${1:-}" in
get) shift; cmd_get "$@" ;;
set) shift; cmd_set "$@" ;;
list) shift; cmd_list "$@" ;;
memorable) shift; cmd_memorable "$@" ;;
normalize) shift; cmd_normalize "$@" ;;
--help|-h|help) sed -n '2,54p' "$0" | sed 's/^# \{0,1\}//' ;;
"") die "usage: gstack-gbrain-repo-policy {get|set|list|normalize|--help}" ;;
--help|-h|help) sed -n '2,73p' "$0" | sed 's/^# \{0,1\}//' ;;
"") die "usage: gstack-gbrain-repo-policy {get|set|memorable|list|normalize|--help}" ;;
*) die "unknown subcommand: $1" ;;
esac
+38
View File
@@ -33,3 +33,41 @@ export function emptyBunConfig(platform: NodeJS.Platform = process.platform): st
emptyConfig = file;
return file;
}
export interface BunExeLookup {
env?: NodeJS.ProcessEnv;
execPath?: string;
isBun?: boolean;
isFile?: (p: string) => boolean;
}
/**
* The bun.exe a Windows parent spawns its bun children with, or null when
* none is installed: the running bun.exe itself, then BUN_INSTALL\bin, each
* absolute PATH entry (plus, beside npm's bun.cmd shim, the bun.exe it
* forwards to), then USERPROFILE\.bun\bin. The terminal agent and the native
* cookie-import worker (cookie-import-native.ts) both resolve through it; it
* lives here because this file is part of the native import's source-bound
* qualification (NATIVE_CODE_INPUTS), and terminal-agent-control.ts is not.
*/
export function findWindowsBunExe(opts: BunExeLookup = {}): string | null {
const win = path.win32;
const env = opts.env ?? process.env;
const execPath = opts.execPath ?? process.execPath;
const isBun = opts.isBun ?? !!process.versions.bun;
const isFile = opts.isFile ?? ((p: string) => { try { return fs.statSync(p).isFile(); } catch { return false; } });
// A compiled browse.exe also reports versions.bun, so check the name too.
if (isBun && /^bun\.exe$/i.test(win.basename(execPath))) return execPath;
const dirs = (env.PATH || env.Path || '').split(';').filter(d => d && win.isAbsolute(d));
const candidates = [
...(env.BUN_INSTALL ? [win.join(env.BUN_INSTALL, 'bin', 'bun.exe')] : []),
...dirs.flatMap(d => [
win.join(d, 'bun.exe'),
// npm global install: PATH holds only the bun.cmd shim; the real
// binary it forwards to lives under node_modules.
...(isFile(win.join(d, 'bun.cmd')) ? [win.join(d, 'node_modules', 'bun', 'bin', 'bun.exe')] : []),
]),
...(env.USERPROFILE ? [win.join(env.USERPROFILE, '.bun', 'bin', 'bun.exe')] : []),
];
return candidates.find(isFile) ?? null;
}
+2 -9
View File
@@ -4,7 +4,7 @@ import { createRequire } from 'node:module';
import { release } from 'node:os';
import path from 'node:path';
import { CookieImportError, normalizeCookieDomain, type PlaywrightCookie } from './cookie-import-browser';
import { emptyBunConfig } from './bun-child-config';
import { emptyBunConfig, findWindowsBunExe } from './bun-child-config';
import { hashNativeFile, nativeCodeHashes, nativeCodeMatches, readNativeQualifications, type NativeQualifiedBuild } from './cookie-import-native-integrity';
type BrowserName = 'Chrome' | 'Chromium' | 'Brave' | 'Edge';
@@ -107,14 +107,7 @@ export async function importNativeCookies(options: {
} catch (error) {
throw new CookieImportError('The native browser build could not be checked safely. Sign in manually in the gstack browser.', error instanceof Error && error.message === 'native_timeout' ? 'native_timeout' : 'native_unqualified');
}
const bunCandidates = [
...(process.env.BUN_INSTALL ? [path.join(process.env.BUN_INSTALL, 'bin', 'bun.exe')] : []),
...(process.env.PATH || process.env.Path || '').split(path.delimiter).filter(directory => path.isAbsolute(directory)).map(directory => path.join(directory, 'bun.exe')),
...(process.env.USERPROFILE ? [path.join(process.env.USERPROFILE, '.bun', 'bin', 'bun.exe')] : []),
];
const bunExecutable = bunCandidates.find(candidate => {
try { return statSync(candidate).isFile(); } catch { return false; }
});
const bunExecutable = findWindowsBunExe();
if (!bunExecutable || !qualified.some(build => build.executableSha256 === executableSha256 && build.playwrightVersion === playwrightVersion)) {
throw new CookieImportError('This browser build or supervisor runtime has not passed native qualification. Sign in manually in the gstack browser.', 'native_unqualified');
}
+18 -2
View File
@@ -22,7 +22,7 @@ import { safeUnlink, isProcessAlive } from './error-handling';
import { restrictFilePermissions, mkdirSecure } from './file-permissions';
import { atomicWriteSync } from '../../lib/fs-atomic';
import { readPidCmdline, readPidStartTime } from './xvfb';
import { emptyBunConfig } from './bun-child-config';
import { emptyBunConfig, findWindowsBunExe, type BunExeLookup } from './bun-child-config';
function agentProcessInfo(pid: number): { startTime: string; commandLine: string } {
if (!Number.isSafeInteger(pid) || pid <= 0) return { startTime: '', commandLine: '' };
@@ -149,6 +149,22 @@ export function bunChildFlags(): string[] {
return ['--no-env-file', `--config=${emptyBunConfig()}`];
}
/**
* The bun executable to spawn the agent with. On Windows a bare 'bun' under
* the Node polyfill resolves (via cross-spawn) to npm's bun.cmd shim, run as
* `cmd.exe /c bun ...`. That breaks two ways: windowsHide only hides cmd.exe,
* and the detached cmd.exe has no console, so bun.exe allocates a fresh
* visible one (a window that steals focus on every spawn); and proc.pid is
* cmd.exe's, so the agent's startup check (record.pid === process.pid) never
* matches and it exits after 2s, which the 60s watchdog then respawns.
* Spawning bun.exe directly fixes both. Falls back to 'bun' when no .exe is
* found, which is the old behavior.
*/
export function resolveBunExecutable(opts: BunExeLookup & { platform?: string } = {}): string {
if ((opts.platform ?? process.platform) !== 'win32') return 'bun';
return findWindowsBunExe(opts) ?? 'bun';
}
export function resolveTerminalAgentScript(searchHints: { metaDir?: string; execPath?: string } = {}): string | null {
const meta = searchHints.metaDir || __dirname;
const exec = searchHints.execPath || process.execPath;
@@ -208,7 +224,7 @@ export function spawnTerminalAgent(opts: {
writeAgentRecord(stateDir, reservation);
let proc: any;
try {
proc = (Bun as any).spawn(['bun', 'run', ...bunChildFlags(), script, `--agent-gen=${gen}`], {
proc = (Bun as any).spawn([resolveBunExecutable(), 'run', ...bunChildFlags(), script, `--agent-gen=${gen}`], {
cwd: opts.cwd || process.cwd(),
env: {
...process.env,
+1 -1
View File
@@ -233,7 +233,7 @@ describe('cli.ts: sidebar-agent is no longer spawned', () => {
'utf-8',
);
expect(CONTROL_SRC).toContain('terminal-agent.ts');
expect(CONTROL_SRC).toMatch(/\.spawn\(\['bun',\s*'run',\s*\.\.\.bunChildFlags\(\),\s*script,\s*`--agent-gen=\$\{gen\}`\]/);
expect(CONTROL_SRC).toMatch(/\.spawn\(\[resolveBunExecutable\(\),\s*'run',\s*\.\.\.bunChildFlags\(\),\s*script,\s*`--agent-gen=\$\{gen\}`\]/);
expect(CONTROL_SRC).toContain('BROWSE_OWNER_PID: String(opts.ownerPid)');
});
});
@@ -0,0 +1,85 @@
/**
* Windows terminal-agent console flash: under the Node polyfill a bare 'bun'
* resolved to npm's bun.cmd shim and ran as `cmd.exe /c bun ...`. The detached
* cmd.exe had no console, so bun.exe opened a visible one on every spawn, and
* proc.pid was cmd.exe's, so the agent failed its startup record check and
* exited, and the 60s watchdog respawned it. spawnTerminalAgent now spawns
* bun.exe directly.
*/
import { describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { findWindowsBunExe } from '../src/bun-child-config';
import { resolveBunExecutable } from '../src/terminal-agent-control';
const files = (...paths: string[]) => (p: string) => paths.some(f => f.toLowerCase() === p.toLowerCase());
describe('resolveBunExecutable', () => {
test('POSIX keeps bare bun', () => {
expect(resolveBunExecutable({ platform: 'linux', isFile: () => true })).toBe('bun');
expect(resolveBunExecutable({ platform: 'darwin', isFile: () => true })).toBe('bun');
});
test('Windows under bun.exe reuses its own executable', () => {
expect(resolveBunExecutable({
platform: 'win32', isBun: true, execPath: 'C:\\Tools\\bun.exe', env: {}, isFile: () => false,
})).toBe('C:\\Tools\\bun.exe');
});
test('a compiled browse.exe is not mistaken for bun', () => {
expect(resolveBunExecutable({
platform: 'win32', isBun: true, execPath: 'C:\\gstack\\browse\\dist\\browse.exe',
env: { PATH: 'C:\\bun\\bin' }, isFile: files('C:\\bun\\bin\\bun.exe'),
})).toBe('C:\\bun\\bin\\bun.exe');
});
test('npm global install resolves through the bun.cmd shim to the real bun.exe', () => {
const npm = 'C:\\Users\\u\\AppData\\Roaming\\npm';
expect(resolveBunExecutable({
platform: 'win32', isBun: false, execPath: 'C:\\Program Files\\nodejs\\node.exe',
env: { PATH: `C:\\Windows\\System32;${npm}` },
isFile: files(`${npm}\\bun.cmd`, `${npm}\\node_modules\\bun\\bin\\bun.exe`),
})).toBe(`${npm}\\node_modules\\bun\\bin\\bun.exe`);
});
test('BUN_INSTALL wins over PATH, and USERPROFILE\\.bun is the last resort', () => {
const isFile = files('C:\\bi\\bin\\bun.exe', 'C:\\p\\bun.exe', 'C:\\Users\\u\\.bun\\bin\\bun.exe');
const base = { platform: 'win32', isBun: false, execPath: 'node.exe', isFile };
expect(resolveBunExecutable({ ...base, env: { BUN_INSTALL: 'C:\\bi', PATH: 'C:\\p' } })).toBe('C:\\bi\\bin\\bun.exe');
expect(resolveBunExecutable({ ...base, env: { PATH: 'C:\\p' } })).toBe('C:\\p\\bun.exe');
expect(resolveBunExecutable({ ...base, env: { PATH: 'C:\\none', USERPROFILE: 'C:\\Users\\u' } })).toBe('C:\\Users\\u\\.bun\\bin\\bun.exe');
});
test('falls back to bare bun when no bun.exe exists', () => {
expect(resolveBunExecutable({
platform: 'win32', isBun: false, execPath: 'node.exe', env: { PATH: 'C:\\x;relative' }, isFile: () => false,
})).toBe('bun');
});
test('spawnTerminalAgent spawns through the resolver, not a bare bun', () => {
const source = fs.readFileSync(path.resolve(import.meta.dir, '../src/terminal-agent-control.ts'), 'utf8');
const spawnSite = source.slice(source.indexOf('export function spawnTerminalAgent'));
expect(spawnSite).toContain('spawn([resolveBunExecutable(), \'run\'');
expect(spawnSite).not.toMatch(/spawn\(\[\s*'bun'/);
});
});
describe('findWindowsBunExe is the one bun.exe lookup', () => {
test('returns null, not a bare bun, when no bun.exe is installed', () => {
expect(findWindowsBunExe({ isBun: false, execPath: 'node.exe', env: { PATH: 'C:\\x;relative' }, isFile: () => false })).toBeNull();
});
test('the native cookie-import worker finds an npm-global bun.exe through the same lookup', () => {
const npm = 'C:\\Users\\u\\AppData\\Roaming\\npm';
expect(findWindowsBunExe({
isBun: false, execPath: 'C:\\Program Files\\nodejs\\node.exe', env: { PATH: npm },
isFile: files(`${npm}\\bun.cmd`, `${npm}\\node_modules\\bun\\bin\\bun.exe`),
})).toBe(`${npm}\\node_modules\\bun\\bin\\bun.exe`);
});
test('cookie-import-native has no bun.exe candidate list of its own', () => {
const source = fs.readFileSync(path.resolve(import.meta.dir, '../src/cookie-import-native.ts'), 'utf8');
expect(source).toContain('const bunExecutable = findWindowsBunExe();');
expect(source).not.toContain("'bun.exe'");
});
});
+34 -5
View File
@@ -94,10 +94,11 @@ It refuses the hand-off, with one rate-limited line in
- the prompt carries a HIGH-tier credential shape (checked on the raw bytes
and on the decoded string values, so a JSON-escaped key does not slip by),
or is larger than 1 MiB;
- the repo's per-remote trust policy is `deny` or `read-only` (judged by the
session's working directory, so a session that touches other repositories
is not covered), or that policy could not be looked up at all (git could
not read the repository, the store is unreadable): the lookup fails closed;
- the repo's per-remote trust policy is `deny`, or `read-only` without the
recall opt-in below (judged by the session's working directory, so a
session that touches other repositories is not covered), or that policy
could not be looked up at all (git could not read the repository, the store
is unreadable or corrupt): the lookup fails closed;
- the receipt cannot be written, or the hook's 4.5 s budget cannot afford the
next step (the secret scan of a very large prompt, or the vendor spawn).
@@ -163,6 +164,34 @@ whatever it stored are untouched: `memorable disable` stops capture,
The entry also comes out with `gstack-uninstall` (named in its summary) and
survives `./setup --no-team`, which only tears down team-mode hooks.
## Recall in a read-only repo (per-remote opt-in)
`read-only` keeps a repo's content out of the brain, and by default it also
keeps that repo's prompts away from Memorable. If you chose `read-only` only
to stop code ingest, and you have no objection to Memorable seeing prompts
from that repo, opt that one remote in:
```bash
gstack-gbrain-repo-policy memorable set github.com/acme/client-a allow
gstack-gbrain-repo-policy memorable get github.com/acme/client-a # read-only allow
gstack-gbrain-repo-policy memorable set github.com/acme/client-a off
```
The opt-in is off by default and covers only the remote you name (the SSH and
HTTPS spellings of it are one key). It is refused on a `deny` remote, and a
`deny` vetoes recall even if an opt-in was written into the store by hand.
Changing the remote's tier clears it, so moving a repo back to `read-only`
later never silently re-opens recall. When `~/.gstack` also makes the remote
read-only (see [state roots](state-root.md)), that store has to opt it in too.
A corrupt, empty or unreadable policy store (or a dangling symlink in its
place) skips recall for every repo until you fix it; the hook never resets it
to "no policy" and never rewrites it. The lookup checks every configured
`remote.origin.url`, not the URL after `url.*.insteadOf` rewriting, and any
denied or not-opted-in read-only one skips recall. `gstack-gbrain-repo-policy list` shows
opted-in remotes with a `memorable=allow` column. Nothing about gbrain
ingest changes: the repo stays `read-only` for `/sync-gbrain` and every
other gbrain writer.
## If you run gbrain
Memorable can keep its procedures in your own gbrain database instead of its
@@ -189,7 +218,7 @@ and `/sync-gbrain` are unrelated to it.
(roughly 4 seconds after gstack's own work). That is usually network.
- **`hook-errors.log` names a refusal.** `refused:redaction-high` means a
credential shape was in the prompt; `trust policy ... deny or read-only`
means the repo is protected; `receipt-unwritable` means
means the repo is protected (see the per-remote opt-in above); `receipt-unwritable` means
`~/.gstack/security` is not writable.
- **`enable` says the stable install predates this bridge.** Run `./setup`
(or `/gstack-upgrade`) so the hook registered at `~/.claude/skills/gstack`
+11 -4
View File
@@ -59,7 +59,7 @@ the byte-pinned `/ship` renders in `test/fixtures/golden/`).
| Key | Meaning |
|---|---|
| `runner` | the local test command with `{files}` (gstack: `bun test {files}`); unset, it is detected (bun, vitest, jest, pytest, `node --test`, and `flutter test`/`dart test` per Dart package root, through fvm when that package or an ancestor pins it with `.fvmrc` or `.fvm/fvm_config.json` and fvm is on PATH); nothing detected, a Dart SDK missing from PATH, or a `.dart` file with no `pubspec.yaml` above it is `incomplete` (the runnable groups still run, so a real failure still fails) |
| `runner` | the local test command with `{files}` (gstack: `bun test {files}`); unset, it is detected (bun, vitest, jest, pytest, `node --test`, and `flutter test`/`dart test` per Dart package root, through fvm when that package or an ancestor pins it with `.fvmrc` or `.fvm/fvm_config.json` and fvm is on PATH; `cargo test -p <name>` per Rust crate, run from the root of the workspace the crate is a member of (Cargo's `members` globs, `exclude` and `package.workspace`), else the crate directory; a JS/TS test whose nearest package.json is a nested package declaring vitest or jest (a dependency or its `test` script) runs from that package, with package-relative paths, through the package manager its `packageManager` field or the nearest lockfile up to the repo root names: `pnpm exec`, `yarn`, `bun x`, else `npx`; every other JS/TS test keeps the root detection); nothing detected, a Dart SDK, cargo or package manager missing from PATH, a `.dart` file with no `pubspec.yaml` above it, a `.rs` file outside any crate, or one in a crate whose name Cargo would reject (anything but letters, digits, `_` and `-`), is `incomplete` (the runnable groups still run, so a real failure still fails) |
| `dependencies` | glob → test files for subprocess targets, runtime reads and generated inputs the import graph cannot see; `[]` declares "no lane needed" (docs, licences) |
| `empty_lanes` | extra globs for the docs/no-tests empty lane. Any Markdown file already qualifies with no pin file when no test depends on it (the same import graph as other files: a quoted path, a `join()` of path segments, an import, or a `dependencies` entry). reStructuredText and AsciiDoc count as Markdown here. README, CHANGELOG, CONTRIBUTING, LICENSE, AGENTS and CLAUDE qualify even without `.md`, and so does licence text under any vendored name (`roboto-LICENSE.txt`, `LICENSE-MIT`, `licenses/*.txt`). Source code and files under a test directory never qualify. A test that reads the file still selects that test |
| `selection` | `workflow.yml/job` → a command printing the lane's file list, for matrices a planner computes (gstack: `scripts/test-free-shards.ts --list`) |
@@ -135,7 +135,13 @@ Two stages with separate clocks, both printed:
one has no lane until you declare `"**/integration_test/**": []` (and
`"**/test_driver/**": []`) under `dependencies` and let CI run them; Dart files, device tests
included, are source code, so a `dependencies` `[]` declaration clears them and `empty_lanes`
does not), transitively through
does not); in a Rust crate (the nearest Cargo.toml with a `[package]` name) a `.rs` file is a
test when it sits under `<crate>/tests/`, holds a `#[cfg(test)]` (any cfg predicate naming
`test`) or a test attribute (`#[test]`, `#[tokio::test]`), and every `.rs` file of the crate and its Cargo.toml select the crate's tests and
those of every crate whose manifest depends on it, directly or through other crates (cargo
runs a crate's tests, not a file, so the lane is the crate; a crate with no tests still has
no lane, and a workspace-only Cargo.toml or Cargo.lock needs a `dependencies` entry),
transitively through
non-test files; deleted and renamed files select the tests that named them.
An extensionless JS/TS import (relative, a tsconfig/jsconfig `paths` alias or
`baseUrl`) tries the exact path, then `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`,
@@ -172,7 +178,8 @@ Two stages with separate clocks, both printed:
that step's `working-directory`, else the job's or workflow's
`defaults.run.working-directory`): local ones run through the runner under
`set -o pipefail`, judged on the runner's summary line (zero tests ran is a
failure, a `| tail`-hidden exit is still an exit); a platform lane this
failure, a `| tail`-hidden exit is still an exit; cargo's `test result:` lines, one per
test binary and doc-tests included, are summed); a platform lane this
machine cannot run becomes a `requires-remote` obligation naming
`workflow.yml/job`. `--explain` prints each test's provenance and every
uncertain mapping (a planner-computed matrix without a `selection` manifest
@@ -234,7 +241,7 @@ test-tier command:
Per-file lines come from a progress adapter where the runner's reporter
provides them: `bun test` (its `<file>:` headers) is the only adapter today;
a one-file run (each serial file) reports its file from the launch for any
runner. Other runners (node --test, vitest, jest, pytest, flutter test, dart test) get heartbeats
runner. Other runners (node --test, vitest, jest, pytest, flutter test, dart test, cargo test) get heartbeats
only. A heartbeat follows each 60 s with no progress line;
- is killed as **stalled** when its log does not grow for the stall timeout
(`--stall-timeout <s>`, else `stall_timeout_s`, else 300; `0` disables): the
+27 -6
View File
@@ -337,7 +337,9 @@ gstack-ship-queue train build --prs 41@<sha>,42@<sha>,43@<sha>
It prints `ORDER:` (the slot order to announce: screened PRs first in READY
order, then unscreened; when `max_size` or more unscreened PRs wait they form
their own train and `HELD:` lists them), one `PREFIX: T<i> <commit>
their own train and `HELD:` lists them; `--order <pr>,<pr>,...` naming every
pinned PR once replaces that rule, for a PR that must merge before another,
and the train's later `NEXT:` rebuilds keep it), one `PREFIX: T<i> <commit>
tree=<tree>` per prefix and one `SLOT:` per PR. `--dry-run` adds the
`ESTIMATE:` line and writes, pushes and dispatches nothing. Otherwise it
writes `train.json`, pushes `train/<nonce>`, dispatches `free_workflow` there
@@ -355,7 +357,11 @@ merging #<a>,#<b>; nothing dispatched, no branch pushed; fix: …` line names
the build without that PR) and `QUEUE_TRAIN_FREE_RED` (free tests red,
missing, cancelled or on another SHA). In a merge, version files take the
prefix's side and the CHANGELOG merges by section, since the stamp at merge
rewrites both.
rewrites both; a PR whose CHANGELOG drops or renames a released heading (or
carries a released entry's text in a section of its own) is a CHANGELOG
conflict, never merged with the damage. READY receipts and train records are
keyed on origin's GitHub owner/repo, so lanes whose origin uses another URL
form (git.capy.ai, ssh, a token URL) share the coordinator's queue.
**3. Coordinator: status and verdict.**
@@ -406,13 +412,13 @@ EVAL_POLICY records it. Bisect results never turn a train green.
```bash
git fetch origin main
git merge --no-ff --no-commit origin/main # expect a CHANGELOG.md conflict only
bun --no-env-file --config=/dev/null -e "import { mergeChangelogs } from './lib/changelog-check'; import { spawnSync } from 'node:child_process'; import { writeFileSync } from 'node:fs'; const s = (n) => spawnSync('git', ['show', ':' + n + ':CHANGELOG.md'], { encoding: 'utf8', maxBuffer: 1 << 26, timeout: 30000 }).stdout; const m = mergeChangelogs(s(2), s(3)); if (!m) { console.error('CHANGELOG needs a hand merge'); process.exit(1); } writeFileSync('CHANGELOG.md', m);"
bun --no-env-file --config=/dev/null -e "import { mergeChangelogs } from './lib/changelog-check'; import { spawnSync } from 'node:child_process'; import { writeFileSync } from 'node:fs'; const s = (n) => spawnSync('git', ['show', ':' + n + ':CHANGELOG.md'], { encoding: 'utf8', maxBuffer: 1 << 26, timeout: 30000 }).stdout; const m = mergeChangelogs(s(2), s(3), s(1)); if (!m) { console.error('CHANGELOG needs a hand merge'); process.exit(1); } writeFileSync('CHANGELOG.md', m);"
git add CHANGELOG.md && git commit --no-edit
gstack-restamp --next --base main --pr 42 --expect-base <main sha> --expect-order <order> --allow-repo-commands
git add CHANGELOG.md VERSION package.json <release outputs> && git commit -m "v<X> stamp" && git push
```
A conflict in any file other than CHANGELOG.md means the merge isn't the train's prefix. Stop and report it. `verify` accepts the resulting head because its tree equals T<i> modulo stamps; the `head:` line says "T<i> with main merged in".
A conflict in any file other than CHANGELOG.md means the merge isn't the train's prefix. Stop and report it. When the helper says the CHANGELOG needs a hand merge, take main's CHANGELOG unchanged and put your own entry above it. `verify` accepts the resulting head because it contains main and its tree equals T<i> modulo stamps, with its CHANGELOG judged as main's plus lines your pin added, however the conflict was resolved; the `head:` line says "T<i> with main merged in".
**5. Coordinator: verify, merge, verify again.** For each slot in order:
@@ -423,8 +429,9 @@ gstack-ship-queue verify --pr 41 --train <nonce> # VERIFY_TRAIN: #41 merged; m
```
Before a merge, main's tree must equal the prefix before the PR modulo stamps
and the PR must be at its pin (stamps aside) or at T<i> modulo stamps (its pin
with main merged in); after it, main's tree
and the PR must be at its pin (stamps aside) or contain main and be T<i>
modulo stamps (its pin with main merged in; its CHANGELOG must be main's with
only lines from the pin's own CHANGELOG diff above it); after it, main's tree
must equal the prefix after it. Anything else is `QUEUE_TRAIN_TREE_MISMATCH`
(or `QUEUE_TRAIN_MOVED`). When nothing of the train has merged, that is a plain
refusal: build a new train on current main. When earlier slots already
@@ -471,6 +478,20 @@ which carry the workflow consequences the skill prose would otherwise spell out:
The PR body's first section is the ship receipt (`gstack-ship-receipt write … --body`),
written by the pr-body section of `/ship` after the body is composed.
## What `/land-and-deploy` reads from it
Step 3.4 runs `show-effective --base <base>` before the merge and prints one
`VERSION_CHECK:` verdict for the PR head:
| Policy | Stops when | Passes |
|---|---|---|
| `queue_mode: stamp-at-merge` | the head's VERSION is not the base's version plus one bump, or the changelog's top two headings at the head are not that version and then the base's top entry (`STOP stamp stale`: run `gstack-restamp --next` on the branch, push the stamp, rerun) | an exact stamp; other open PRs' tentative stamps are ignored |
| `queue_mode: claim-at-open` (and no policy file) | another open PR holds the same VERSION, or the base is already at or above it (`VERSION drift detected`: rerun `/ship`) | any unique VERSION above the base, including a MICRO bump or one below a sibling's claim |
An invalid policy, an unreadable claim list or a missing VERSION is `unavailable`:
the skill reports it and CI's version gate is the backstop. A base at or above the
branch VERSION still stops.
<a id="stamp-at-merge"></a>
## `queue_mode: stamp-at-merge`
+4 -2
View File
@@ -170,8 +170,10 @@ the readiness dashboard and the PR body, and never count it as a pass.
findings.
- **Every review gate.** These rules apply to every gate that summarises a
review, including the `execution` gate behind `/codex` consult and challenge.
A reply whose last `Verdict:` line says `not ready` but carries no readable
severity prints `FINDINGS: unspecified` and exits 3 like a blocking finding.
A reply whose last `Verdict:` line says `not ready` is `findings` and exits
3 even when readable advisory severities (P2 or P3) were parsed; `FINDINGS:`
names the highest one. A not-ready reply with no readable severity still
prints `FINDINGS: unspecified` and exits 3.
- **No findings.** A review with no tag and no label is `clean` only when its
conclusion says so: the last sentence (or its last ", and" clause), or the
`because` clause of its `Recommendation:` line, opens with `NO_FINDINGS`,
+25 -13
View File
@@ -500,7 +500,7 @@ Score each category on a 0-10 scale using this rubric:
| Tests | 28% | All pass (exit 0) | >95% pass | >80% pass | <=80% pass |
| Dead code | 13% | Clean (exit 0) | <5 unused exports | <20 unused | >=20 unused |
| Shell lint | 9% | Clean (exit 0) | <5 issues | >=5 issues | N/A (skip) |
| GBrain | 10% | doctor=ok, queue<10, pushed <24h | doctor=warnings OR queue<100 OR pushed <72h | doctor broken OR queue>=100 OR pushed >=72h | N/A (gbrain not installed) |
| GBrain | 10% | Computed in code: see **GBrain sub-score computation** below | — | — | N/A (gbrain not installed) |
**Parsing tool output for counts:**
Use the complete captured output, not the displayed tail. A zero match count cannot
@@ -534,17 +534,28 @@ a numeric composite, and skip numeric history persistence and trend calculation.
**GBrain sub-score computation:**
```
doctor_component: 10 if `gbrain doctor --json | jq -r .status` == "ok";
7 if "warnings"; 0 otherwise (or command times out after 5s).
queue_component: 10 if ~/.gstack/.brain-queue.jsonl has <10 lines;
7 if 10-100; 0 if >=100 (suggests secret-scan rejections
piling up). N/A if artifacts_sync_mode == off.
push_component: 10 if (now - mtime of ~/.gstack/.brain-last-push) < 24h;
7 if <72h; 0 if >=72h. N/A if artifacts_sync_mode == off.
gbrain_score = 0.5 * doctor_component + 0.3 * queue_component + 0.2 * push_component
(redistribute 0.3 + 0.2 into doctor when sync_mode is off:
gbrain_score = doctor_component in that case)
Compute the GBrain score in code, not by hand, and pass the printed
`GBRAIN_SCORE` as `gbrain` to the composite above. Gather three readings:
- **doctor:** 10 when `gbrain doctor --json` reports `status` `ok`, 7 for
`warnings`, 0 for anything else or when the call times out after 5s.
- **queue:** the line count of `~/.gstack/.brain-queue.jsonl` (0 when absent).
A long queue suggests secret-scan rejections piling up.
- **pushHours:** hours since the mtime of `~/.gstack/.brain-last-push`.
Pass `null` for both queue and pushHours when `artifacts_sync_mode` is `off`;
the doctor component then carries the whole score:
```bash
bun --no-env-file --config=/dev/null -e '
const doctor = <N|null>;
const queue = <N|null>;
const pushHours = <N|null>;
const d = doctor ?? 0;
const band = (v, ten, seven) => (v < ten ? 10 : v < seven ? 7 : 0);
const score = queue === null || pushHours === null ? d : 0.5 * d + 0.3 * band(queue, 10, 100) + 0.2 * band(pushHours, 24, 72);
console.log("GBRAIN_SCORE: " + score.toFixed(1));
'
```
The `gbrain doctor --json` call MUST be wrapped in `timeout 5s` so a hung
@@ -625,7 +636,8 @@ Fields:
- `ts` -- ISO 8601 timestamp
- `branch` -- current git branch
- `score` -- composite score (one decimal)
- `typecheck`, `lint`, `test`, `deadcode`, `shell`, `gbrain` -- individual category scores (integer 0-10)
- `typecheck`, `lint`, `test`, `deadcode`, `shell` -- individual category scores (integer 0-10)
- `gbrain` -- the printed `GBRAIN_SCORE` (0-10, one decimal)
- `duration_s` -- total time for all tools in seconds
If a category was skipped, set its value to `null`. Treat a history entry
+25 -13
View File
@@ -177,7 +177,7 @@ Score each category on a 0-10 scale using this rubric:
| Tests | 28% | All pass (exit 0) | >95% pass | >80% pass | <=80% pass |
| Dead code | 13% | Clean (exit 0) | <5 unused exports | <20 unused | >=20 unused |
| Shell lint | 9% | Clean (exit 0) | <5 issues | >=5 issues | N/A (skip) |
| GBrain | 10% | doctor=ok, queue<10, pushed <24h | doctor=warnings OR queue<100 OR pushed <72h | doctor broken OR queue>=100 OR pushed >=72h | N/A (gbrain not installed) |
| GBrain | 10% | Computed in code: see **GBrain sub-score computation** below | — | — | N/A (gbrain not installed) |
**Parsing tool output for counts:**
Use the complete captured output, not the displayed tail. A zero match count cannot
@@ -211,17 +211,28 @@ a numeric composite, and skip numeric history persistence and trend calculation.
**GBrain sub-score computation:**
```
doctor_component: 10 if `gbrain doctor --json | jq -r .status` == "ok";
7 if "warnings"; 0 otherwise (or command times out after 5s).
queue_component: 10 if ~/.gstack/.brain-queue.jsonl has <10 lines;
7 if 10-100; 0 if >=100 (suggests secret-scan rejections
piling up). N/A if artifacts_sync_mode == off.
push_component: 10 if (now - mtime of ~/.gstack/.brain-last-push) < 24h;
7 if <72h; 0 if >=72h. N/A if artifacts_sync_mode == off.
gbrain_score = 0.5 * doctor_component + 0.3 * queue_component + 0.2 * push_component
(redistribute 0.3 + 0.2 into doctor when sync_mode is off:
gbrain_score = doctor_component in that case)
Compute the GBrain score in code, not by hand, and pass the printed
`GBRAIN_SCORE` as `gbrain` to the composite above. Gather three readings:
- **doctor:** 10 when `gbrain doctor --json` reports `status` `ok`, 7 for
`warnings`, 0 for anything else or when the call times out after 5s.
- **queue:** the line count of `~/.gstack/.brain-queue.jsonl` (0 when absent).
A long queue suggests secret-scan rejections piling up.
- **pushHours:** hours since the mtime of `~/.gstack/.brain-last-push`.
Pass `null` for both queue and pushHours when `artifacts_sync_mode` is `off`;
the doctor component then carries the whole score:
```bash
bun --no-env-file --config=/dev/null -e '
const doctor = <N|null>;
const queue = <N|null>;
const pushHours = <N|null>;
const d = doctor ?? 0;
const band = (v, ten, seven) => (v < ten ? 10 : v < seven ? 7 : 0);
const score = queue === null || pushHours === null ? d : 0.5 * d + 0.3 * band(queue, 10, 100) + 0.2 * band(pushHours, 24, 72);
console.log("GBRAIN_SCORE: " + score.toFixed(1));
'
```
The `gbrain doctor --json` call MUST be wrapped in `timeout 5s` so a hung
@@ -301,7 +312,8 @@ Fields:
- `ts` -- ISO 8601 timestamp
- `branch` -- current git branch
- `score` -- composite score (one decimal)
- `typecheck`, `lint`, `test`, `deadcode`, `shell`, `gbrain` -- individual category scores (integer 0-10)
- `typecheck`, `lint`, `test`, `deadcode`, `shell` -- individual category scores (integer 0-10)
- `gbrain` -- the printed `GBRAIN_SCORE` (0-10, one decimal)
- `duration_s` -- total time for all tools in seconds
If a category was skipped, set its value to `null`. Treat a history entry
@@ -10,7 +10,8 @@
* and clean removal. This file is that mediation.
*
* stdin JSON -> cap 1 MiB -> parse -> MEMORABLE=0? -> gate memorable_recall == on?
* -> win32? -> trust policy (deny / read-only veto, by session cwd; fail-closed)
* -> win32? -> trust policy (deny / read-only veto, by session cwd; fail-closed;
* a read-only remote's explicit per-remote opt-in lifts it, deny never)
* -> HIGH-tier secret scan (raw bytes AND decoded string leaves, each admitted by the clock)
* -> resolve vendor -> budget >= 500 ms? -> gate re-check
* -> receipt (fail-closed: no receipt, no send)
@@ -57,7 +58,7 @@ import {
} from '../../../lib/egress-receipt';
import { wrapUntrustedTrackerContent } from '../../../lib/tracker-guard';
import { scan } from '../../../lib/redact-engine';
import { hasRepoPolicyStore, repoPolicyTier } from '../../../lib/gbrain-repo-policy-client';
import { hasRepoPolicyStore, memorableRecallPolicy } from '../../../lib/gbrain-repo-policy-client';
import { LOG_RATE_LIMIT_MS, logHookError as sharedLogHookError } from './hook-log';
export { LOG_RATE_LIMIT_MS };
@@ -393,13 +394,30 @@ async function policyVeto(cwd: string, timeoutMs: number, remaining: () => numbe
if (git.status === GIT_NO_REMOTE) return 'ok';
if (git.status === GIT_FATAL && NOT_A_REPO_RE.test(git.stderrTail.trim())) return 'ok';
if (git.status !== 0) return 'error';
const url = git.stdout.toString('utf8').trim();
if (!url) return 'ok';
const res = repoPolicyTier(url, process.env, Math.max(1, Math.min(STAGE_CAP_MS, remaining())));
if (res.error) return 'error';
// `deny` and `read-only` are the tiers a user picks so a repo's content
// never lands in a shared store; a third-party memory service is one.
return res.tier === 'deny' || res.tier === 'read-only' ? 'skip' : 'ok';
if (!git.stdout.toString('utf8').trim()) return 'ok';
// The store is keyed by the configured URLs (what `gstack-gbrain-repo-policy
// get` and /sync-gbrain read), not the url.*.insteadOf rewrite that
// `remote get-url` applies, and every configured origin URL is checked:
// neither a rewrite nor an added URL may dodge a deny.
const raw = await runExternal('git', ['config', '--null', '--get-all', 'remote.origin.url'], {
cwd, timeoutMs: Math.max(1, Math.min(timeoutMs, remaining())), maxBuffer: GIT_MAX_BUFFER, env: gitEnv(process.env),
onSpawn: (kill) => { killInflight = kill; },
});
killInflight = null;
if (raw.timedOut || raw.error || raw.status !== 0) return 'error';
const urls = raw.stdout.toString('utf8').split('\0').filter((u) => u !== '');
if (urls.length === 0) return 'error';
for (const url of urls) {
const res = memorableRecallPolicy(url, process.env, Math.max(1, Math.min(STAGE_CAP_MS, remaining())));
if (res.error) return 'error';
// `deny` and `read-only` are the tiers a user picks so a repo's content
// never lands in a shared store; a third-party memory service is one.
// Only an explicit per-remote opt-in (`gstack-gbrain-repo-policy memorable
// set <url> allow`) lifts the read-only veto; nothing lifts deny.
if (res.tier === 'deny') return 'skip';
if (res.tier === 'read-only' && !res.memorableOptIn) return 'skip';
}
return 'ok';
}
function writeStdout(text: string): Promise<void> {
@@ -446,7 +464,7 @@ export async function main(): Promise<void> {
const payloadCwd = (payload as { cwd?: unknown }).cwd;
const cwd = typeof payloadCwd === 'string' && isDirectory(payloadCwd) ? payloadCwd : process.cwd();
const veto = await policyVeto(cwd, Math.min(STAGE_CAP_MS, remaining()), remaining);
if (veto === 'skip') { logHookError(`trust policy for ${cwd} is deny or read-only, recall skipped`, Date.now(), 'trust policy skip'); return; }
if (veto === 'skip') { logHookError(`trust policy for ${cwd} is deny or read-only, recall skipped (a read-only remote can opt in: gstack-gbrain-repo-policy memorable set <origin-url> allow)`, Date.now(), 'trust policy skip'); return; }
if (veto === 'error') { logHookError('trust policy lookup failed (store or repository unreadable), recall skipped (fail-closed)'); return; }
// HIGH-tier pre-scan over the raw text and the decoded string leaves (a JSON
+4 -4
View File
@@ -593,10 +593,10 @@ If the user says "demo", "demo mode", "show me", or "I want to see it
working", run in **DEMO MODE**. This changes how the agent interacts with
the app:
**DEMO MODE OVERRIDES ALL OTHER RULES.** When demo mode is active, the
agent MUST drive every action through visible UI (`/tap`, `/swipe`, `/type`)
and NEVER use `POST /state/*` writes to skip steps. Viewers see the agent
type every key, tap every button. The on-device DebugOverlay attribution
In demo mode, drive every action through visible UI (`/tap`, `/swipe`,
`/type`) rather than `POST /state/*` writes, because viewers watch each
step: they see the agent type every key and tap every button. All other
rules in this skill still apply. The on-device DebugOverlay attribution
chip shows "Driven by Claude Code (demo)" or the remote agent identity.
In demo mode, the screencap rate is bumped to 4fps so the recording feels
+4 -4
View File
@@ -249,10 +249,10 @@ If the user says "demo", "demo mode", "show me", or "I want to see it
working", run in **DEMO MODE**. This changes how the agent interacts with
the app:
**DEMO MODE OVERRIDES ALL OTHER RULES.** When demo mode is active, the
agent MUST drive every action through visible UI (`/tap`, `/swipe`, `/type`)
and NEVER use `POST /state/*` writes to skip steps. Viewers see the agent
type every key, tap every button. The on-device DebugOverlay attribution
In demo mode, drive every action through visible UI (`/tap`, `/swipe`,
`/type`) rather than `POST /state/*` writes, because viewers watch each
step: they see the agent type every key and tap every button. All other
rules in this skill still apply. The on-device DebugOverlay attribution
chip shows "Driven by Claude Code (demo)" or the remote agent identity.
In demo mode, the screencap rate is bumped to 4fps so the recording feels
+34 -24
View File
@@ -708,35 +708,45 @@ approves each), or C) stop.
## Step 3.4: VERSION drift detection (workspace-aware ship)
Check that another workspace has not claimed this PR's VERSION since `/ship`.
```bash
BRANCH_VERSION=$(git show "$PR_HEAD:VERSION" 2>/dev/null | tr -d '\r\n[:space:]')
BASE_VERSION=$(git show "$BASE_SHA:VERSION" 2>/dev/null | tr -d '\r\n[:space:]')
QUEUE_JSON=$(bun --no-env-file --config=/dev/null run ~/.claude/skills/gstack/bin/gstack-next-version \
--base "$BASE_BRANCH" \
--exclude-pr "$PR_NUMBER" \
--bump patch \
--current-version "$BASE_VERSION" 2>/dev/null || echo '{"offline":true}')
NEXT_SLOT=$(echo "$QUEUE_JSON" | jq -r '.version // empty')
OFFLINE=$(echo "$QUEUE_JSON" | jq -r '.offline // false')
NO_VERSION=$(echo "$QUEUE_JSON" | jq -r '.no_version // false')
git fetch -q origin "$BASE_BRANCH"
read -r MODE CL < <(~/.claude/skills/gstack/bin/gstack-ship-policy show-effective --base "$BASE_BRANCH" --json |
jq -r 'select(.valid).policy | "\(.queue_mode) \(.changelog)"')
Q=$(bun --no-env-file --config=/dev/null run ~/.claude/skills/gstack/bin/gstack-next-version --base "$BASE_BRANCH" \
--exclude-pr "$PR_NUMBER" --bump patch --current-version "$BASE_VERSION" 2>/dev/null || echo '{"offline":true}')
Q=$(echo "$Q" | jq -r --arg v "$BRANCH_VERSION" '[.claimed[]? | select(.version == $v).pr] as $c | if .no_version
then "NO_VERSION" elif $c != [] then "STOP also claimed by #\($c[0])" elif .offline or (.complete | not)
then "unavailable: claims unread" else "ok" end')
cl() { sed -n 's/^## \[\([^]]*\)\].*/\1/p' | head -2 | xargs; }
H=$(git show "$PR_HEAD:$CL" 2>/dev/null | cl); B=$(git show "$BASE_SHA:$CL" 2>/dev/null | cl)
V=$(awk -v a="$BASE_VERSION" -v b="$BRANCH_VERSION" 'BEGIN { r = "^[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?$"
if (a !~ r || b !~ r || split(a, x, ".") != (n = split(b, y, "."))) { print "bad"; exit }
for (i = 1; i <= n && x[i] == y[i]; i++); if (i > n || y[i] < x[i]) { print "low"; exit }
s = y[i] == x[i] + 1; for (j = i + 1; j <= n; j++) s = s && !y[j]; print s ? "one" : "up" }')
if [ "$Q" = NO_VERSION ]; then R=$Q
elif [ "$V" = bad ]; then R="unavailable: bad version"
elif [ "$MODE" = stamp-at-merge ]; then
[ "$V" = one ] && { [ -z "$H" ] || [ "$H" = "$(echo $BRANCH_VERSION ${B%% *})" ]; } && R=ok || R="STOP stamp stale"
elif [ "$V" = low ]; then R="STOP base is at or above it"
elif [ -z "$MODE" ]; then R="unavailable: no policy"
else R=$Q; fi
echo "VERSION_CHECK: $R ($MODE: $BRANCH_VERSION, base $BASE_VERSION)"
```
Use the existing conservative patch-level allocation; compare numeric version
components, not lexical strings. A missing/unparseable version on only one side is
unavailable, not green.
0. `NO_VERSION=true` (no configured version source, the same signal `/ship` reads):
print `VERSION check: not applicable (<version_source.reason>)` and continue to
Step 3.5. Never expect a version-prefixed title, CHANGELOG version header or tag.
1. `OFFLINE=true`, helper failure or invalid result: report VERSION check unavailable
with the reason; continue to Step 3.5. CI's version gate is the backstop.
2. `BRANCH_VERSION >= NEXT_SLOT`: no drift; continue.
3. `BRANCH_VERSION < NEXT_SLOT`: **STOP** with "VERSION drift detected", both versions
and instructions to rerun `/ship` from the feature branch. Its ALREADY_BUMPED path
reconciles VERSION, package.json, CHANGELOG header and PR title together. Do NOT
auto-bump or merge here: duplicate versions can overwrite another branch's release notes.
- `NO_VERSION`: print `VERSION check: not applicable (<version_source.reason>)`; never
expect a version-prefixed title, CHANGELOG version header or tag.
- `unavailable`: report it; continue to Step 3.5 (CI's version gate is the backstop).
- `ok`: continue; a higher sibling claim or a MICRO bump is not drift.
- `STOP stamp stale` (stamp-at-merge: not base + one bump, or the top CHANGELOG headings
are not it then the base's): **STOP**; on the PR branch run `gstack-restamp --next --base
<base> --pr <n> --expect-base <BASE_SHA> --allow-repo-commands`, push the stamp diff,
wait for CI, rerun.
- Other `STOP`: **STOP** with "VERSION drift detected", the verdict and: rerun `/ship`
from the feature branch (its ALREADY_BUMPED path reconciles VERSION, package.json,
CHANGELOG header and PR title). Never auto-bump or merge here: duplicate versions can
overwrite another branch's release notes.
---
+34 -24
View File
@@ -191,35 +191,45 @@ approves each), or C) stop.
## Step 3.4: VERSION drift detection (workspace-aware ship)
Check that another workspace has not claimed this PR's VERSION since `/ship`.
```bash
BRANCH_VERSION=$(git show "$PR_HEAD:VERSION" 2>/dev/null | tr -d '\r\n[:space:]')
BASE_VERSION=$(git show "$BASE_SHA:VERSION" 2>/dev/null | tr -d '\r\n[:space:]')
QUEUE_JSON=$(bun --no-env-file --config=/dev/null run ~/.claude/skills/gstack/bin/gstack-next-version \
--base "$BASE_BRANCH" \
--exclude-pr "$PR_NUMBER" \
--bump patch \
--current-version "$BASE_VERSION" 2>/dev/null || echo '{"offline":true}')
NEXT_SLOT=$(echo "$QUEUE_JSON" | jq -r '.version // empty')
OFFLINE=$(echo "$QUEUE_JSON" | jq -r '.offline // false')
NO_VERSION=$(echo "$QUEUE_JSON" | jq -r '.no_version // false')
git fetch -q origin "$BASE_BRANCH"
read -r MODE CL < <(~/.claude/skills/gstack/bin/gstack-ship-policy show-effective --base "$BASE_BRANCH" --json |
jq -r 'select(.valid).policy | "\(.queue_mode) \(.changelog)"')
Q=$(bun --no-env-file --config=/dev/null run ~/.claude/skills/gstack/bin/gstack-next-version --base "$BASE_BRANCH" \
--exclude-pr "$PR_NUMBER" --bump patch --current-version "$BASE_VERSION" 2>/dev/null || echo '{"offline":true}')
Q=$(echo "$Q" | jq -r --arg v "$BRANCH_VERSION" '[.claimed[]? | select(.version == $v).pr] as $c | if .no_version
then "NO_VERSION" elif $c != [] then "STOP also claimed by #\($c[0])" elif .offline or (.complete | not)
then "unavailable: claims unread" else "ok" end')
cl() { sed -n 's/^## \[\([^]]*\)\].*/\1/p' | head -2 | xargs; }
H=$(git show "$PR_HEAD:$CL" 2>/dev/null | cl); B=$(git show "$BASE_SHA:$CL" 2>/dev/null | cl)
V=$(awk -v a="$BASE_VERSION" -v b="$BRANCH_VERSION" 'BEGIN { r = "^[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?$"
if (a !~ r || b !~ r || split(a, x, ".") != (n = split(b, y, "."))) { print "bad"; exit }
for (i = 1; i <= n && x[i] == y[i]; i++); if (i > n || y[i] < x[i]) { print "low"; exit }
s = y[i] == x[i] + 1; for (j = i + 1; j <= n; j++) s = s && !y[j]; print s ? "one" : "up" }')
if [ "$Q" = NO_VERSION ]; then R=$Q
elif [ "$V" = bad ]; then R="unavailable: bad version"
elif [ "$MODE" = stamp-at-merge ]; then
[ "$V" = one ] && { [ -z "$H" ] || [ "$H" = "$(echo $BRANCH_VERSION ${B%% *})" ]; } && R=ok || R="STOP stamp stale"
elif [ "$V" = low ]; then R="STOP base is at or above it"
elif [ -z "$MODE" ]; then R="unavailable: no policy"
else R=$Q; fi
echo "VERSION_CHECK: $R ($MODE: $BRANCH_VERSION, base $BASE_VERSION)"
```
Use the existing conservative patch-level allocation; compare numeric version
components, not lexical strings. A missing/unparseable version on only one side is
unavailable, not green.
0. `NO_VERSION=true` (no configured version source, the same signal `/ship` reads):
print `VERSION check: not applicable (<version_source.reason>)` and continue to
Step 3.5. Never expect a version-prefixed title, CHANGELOG version header or tag.
1. `OFFLINE=true`, helper failure or invalid result: report VERSION check unavailable
with the reason; continue to Step 3.5. CI's version gate is the backstop.
2. `BRANCH_VERSION >= NEXT_SLOT`: no drift; continue.
3. `BRANCH_VERSION < NEXT_SLOT`: **STOP** with "VERSION drift detected", both versions
and instructions to rerun `/ship` from the feature branch. Its ALREADY_BUMPED path
reconciles VERSION, package.json, CHANGELOG header and PR title together. Do NOT
auto-bump or merge here: duplicate versions can overwrite another branch's release notes.
- `NO_VERSION`: print `VERSION check: not applicable (<version_source.reason>)`; never
expect a version-prefixed title, CHANGELOG version header or tag.
- `unavailable`: report it; continue to Step 3.5 (CI's version gate is the backstop).
- `ok`: continue; a higher sibling claim or a MICRO bump is not drift.
- `STOP stamp stale` (stamp-at-merge: not base + one bump, or the top CHANGELOG headings
are not it then the base's): **STOP**; on the PR branch run `gstack-restamp --next --base
<base> --pr <n> --expect-base <BASE_SHA> --allow-repo-commands`, push the stamp diff,
wait for CI, rerun.
- Other `STOP`: **STOP** with "VERSION drift detected", the verdict and: rerun `/ship`
from the feature branch (its ALREADY_BUMPED path reconciles VERSION, package.json,
CHANGELOG header and PR title). Never auto-bump or merge here: duplicate versions can
overwrite another branch's release notes.
---
+75 -2
View File
@@ -115,6 +115,76 @@ export function normalizeChangelog(text: string): string {
return [parsed.header.join('\n').replace(/\n+$/, ''), ...sections].join('\n\u0000');
}
/**
* A merged-in head's CHANGELOG, however its conflict was resolved: why it is
* not main's CHANGELOG with the PR's own entry above it, or null. Main's
* header and every main section must follow unchanged and in order, and the
* sections above them may hold only lines the PR itself added (`authored`,
* the + lines of its pin's CHANGELOG diff), so a hand resolve can drop
* damage but never add text the train gate did not carry.
*/
export function ownEntryAboveMain(head: string, main: string, authored: ReadonlySet<string>): string | null {
const h = parseChangelog(head);
const m = parseChangelog(main);
const trim = (lines: string[]) => { const out = [...lines]; while (out.length && !out[out.length - 1]!.trim()) out.pop(); return out.join('\n'); };
if (trim(h.header) !== trim(m.header)) return 'the header differs from main';
const own = h.sections.length - m.sections.length;
if (own < 0) return `it has ${h.sections.length} sections, main has ${m.sections.length}`;
const moved = m.sections.findIndex((s, i) => trim(s.lines) !== trim(h.sections[own + i]!.lines));
if (moved >= 0) return `main's ${m.sections[moved]!.heading.trim()} is not carried unchanged below the PR's entry`;
const mainKeys = new Set(m.sections.map(s => s.version ?? 'Unreleased'));
const clash = h.sections.slice(0, own).find(s => mainKeys.has(s.version ?? 'Unreleased'));
if (clash) return `${clash.heading.trim()} is headed twice`;
const added = h.sections.slice(0, own).flatMap(s => s.lines.slice(1)).find(l => l.trim() && !authored.has(l));
return added === undefined ? null : `the PR's entry holds a line its pin never added: ${JSON.stringify(added.slice(0, 80))}`;
}
const MIN_BLOCK_CHARS = 12;
/** Paragraph blocks of a section's entry text (heading lines dropped), long enough to identify one entry. */
function entryBlocks(s: ChangelogSection): string[] {
const blocks: string[] = [];
let run: string[] = [];
const flush = () => { const text = run.join('\n').trim(); if (text.length >= MIN_BLOCK_CHARS) blocks.push(text); run = []; };
for (const line of s.lines.slice(1)) {
if (!line.trim() || line.startsWith('#')) flush();
else run.push(line);
}
flush();
return blocks;
}
/**
* Why one side of a CHANGELOG merge damaged released history, or null. A
* side damages it when it lacks a released heading the merge base carries
* (dropped, or renamed), or when a section only that side carries holds a
* paragraph of a released entry the other side carries (a released heading
* replaced, so its body reads as part of the section above it; #3345).
*/
export function changelogDamage(ours: string, theirs: string, base?: string): string | null {
const sides = [{ name: 'ours', parsed: parseChangelog(ours) }, { name: 'theirs', parsed: parseChangelog(theirs) }];
const key = (s: ChangelogSection) => (s.unreleased ? 'Unreleased' : s.version!);
if (base !== undefined) {
const released = parseChangelog(base).sections.filter(s => !s.unreleased).map(key);
for (const side of sides) {
const has = new Set(side.parsed.sections.map(key));
const missing = released.find(v => !has.has(v));
if (missing) return `${side.name} drops released heading ${missing} that the merge base carries`;
}
}
for (const [i, side] of sides.entries()) {
const other = sides[1 - i]!.parsed.sections;
const otherKeys = new Set(other.map(key));
const releasedText = new Map<string, string>();
for (const s of other.filter(s => !s.unreleased)) for (const b of entryBlocks(s)) releasedText.set(b, s.version!);
for (const s of side.parsed.sections.filter(s => !otherKeys.has(key(s)))) {
const hit = entryBlocks(s).find(b => releasedText.has(b));
if (hit) return `${side.name}'s ${key(s)} section holds released ${releasedText.get(hit)} text (${JSON.stringify(hit.slice(0, 60))}); a released heading was dropped or renamed`;
}
}
return null;
}
/**
* Gate-ahead merge of two CHANGELOGs that conflict textually but not
* semantically: the predecessor's header and sections, with the branch's own
@@ -122,9 +192,12 @@ export function normalizeChangelog(text: string): string {
* branch's top section carries the same version heading as a predecessor
* section with a different body (both took the same tentative stamp), the
* branch's entry is kept under `[Unreleased]` so the restamp re-heads it.
* Both sides carrying `[Unreleased]` is a real conflict and returns null.
* Both sides carrying `[Unreleased]` is a real conflict and returns null, and
* so is damage to released history (`changelogDamage`): null means a hand
* resolve, never a merge that carries the damage through.
*/
export function mergeChangelogs(ours: string, theirs: string): string | null {
export function mergeChangelogs(ours: string, theirs: string, base?: string): string | null {
if (changelogDamage(ours, theirs, base)) return null;
const a = parseChangelog(ours);
const b = parseChangelog(theirs);
const key = (s: ChangelogSection) => (s.unreleased ? 'Unreleased' : s.version!);
+14 -5
View File
@@ -5,8 +5,8 @@ import { createHash } from 'node:crypto';
import { lstatSync, readFileSync, realpathSync } from 'node:fs';
import { isAbsolute, relative, resolve, sep } from 'node:path';
/** 'java' (Maven or Gradle) is detected so it is reported as itself; no runtime prepares it. */
export type CsoStack = 'node' | 'bun' | 'python' | 'rails' | 'java';
/** 'java' (Maven or Gradle) and 'go' (go.mod) are detected so they are reported as themselves; no runtime prepares them. */
export type CsoStack = 'node' | 'bun' | 'python' | 'rails' | 'java' | 'go';
export interface PreparationPrerequisite {
code: string;
message: string;
@@ -1205,12 +1205,15 @@ export function inspectPreparation(snapshotPath: string, stack?: CsoStack): Prep
detectedStacks.push('node');
if (read(root, 'Gemfile.lock', true) !== undefined || read(root, 'Gemfile', true) !== undefined)
detectedStacks.push('rails');
// A root Maven or Gradle build names the repository's language; Python
// metadata beside it is helper tooling, not a second application stack.
// A root Maven or Gradle build, or a root go.mod with no other supported
// stack, names the repository's language; Python metadata beside it is
// helper tooling, not a second application stack.
const jvmBuild = ['pom.xml', 'build.gradle', 'build.gradle.kts'].find(
(file) => read(root, file, true) !== undefined,
);
if (jvmBuild) detectedStacks.push('java');
else if (detectedStacks.length === 0 && read(root, 'go.mod', true) !== undefined)
detectedStacks.push('go');
else if (
read(root, 'uv.lock', true) !== undefined ||
read(root, 'requirements.txt', true) !== undefined ||
@@ -1231,10 +1234,16 @@ export function inspectPreparation(snapshotPath: string, stack?: CsoStack): Prep
`Java (${jvmBuild ?? 'Maven or Gradle'}) is not a supported runtime stack yet; supported runtime stacks are Node, Bun, Python, and Rails.`,
jvmBuild,
);
if (detected === 'go')
fail(
'UNSUPPORTED_STACK',
'Go (go.mod) is not a supported runtime stack yet; supported runtime stacks are Node, Bun, Python, and Rails.',
'go.mod',
);
if (!['node', 'bun', 'python', 'rails'].includes(detected))
fail('UNSUPPORTED_STACK', 'Supported runtime stacks are Node, Bun, Python, and Rails.');
({ node: inspectNode, bun: inspectBun, python: inspectPython, rails: inspectRails })[
detected as Exclude<CsoStack, 'java'>
detected as Exclude<CsoStack, 'java' | 'go'>
](root, plan);
} catch (error) {
plan.status = 'prerequisites';
+40 -13
View File
@@ -17,9 +17,12 @@
* subcommand `--help` is generic — so capability detection is best-effort and
* defaults to "unsupported". When we can't protect a user-managed source's
* files, we FAIL CLOSED (refuse the remove) rather than delete unprotected.
* - The autopilot lock filename isn't documented and (gbrain #1226) ignores
* GBRAIN_HOME, so the live `gbrain autopilot` process is the PRIMARY signal;
* known lock paths under both the configured home and ~/.gbrain are secondary.
* - The live `gbrain autopilot` process is the PRIMARY signal and it is
* deliberately machine-wide (#3360, Garry 2026-10-24): any autopilot on the
* machine refuses, whichever brain or repo it serves, because two syncs that
* share one brain or working tree can race. The refusal names the matched
* pid and command so the user can tell whose it is. Known lock paths under
* both the configured home and ~/.gbrain are secondary.
* - We refuse only on an AFFIRMATIVE autopilot signal — inability to introspect
* never blocks a normal sync (that would brick the tool).
* - Path containment uses realpath so a symlink inside ~/.gbrain/clones can't
@@ -69,11 +72,17 @@ export interface AutopilotStatus {
signal: string | null;
}
/** A running process whose command line matches `gbrain autopilot`. */
export interface AutopilotProcess {
pid: number;
command: string;
}
export interface AutopilotProbe {
/** Override the lock-path list (tests). */
lockPaths?: string[];
/** Override the live-process check (tests). */
processRunning?: () => boolean;
/** Override the live-process check (tests): a bare boolean, or the matched processes. */
processRunning?: () => boolean | AutopilotProcess[];
}
/**
@@ -109,10 +118,17 @@ export function detectAutopilot(
// Stale lock (holder pid is dead): ignore this signal, keep checking. Pure
// decision function — we do NOT delete the file here; the caller may clean it.
}
// Primary signal: a live `gbrain autopilot` process.
const running = (probe.processRunning ?? defaultProcessRunning)();
if (running) return { active: true, signal: "process:gbrain autopilot" };
return { active: false, signal: null };
// Primary signal: a live `gbrain autopilot` process anywhere on the machine.
const running = (probe.processRunning ?? autopilotProcesses)();
if (running === true) return { active: true, signal: "process:gbrain autopilot" };
if (!Array.isArray(running) || running.length === 0) return { active: false, signal: null };
const listed = running.map(p => `pid ${p.pid} \`${p.command}\``).join(", ");
return {
active: true,
signal: `process:gbrain autopilot ${listed}; this check counts any process on this machine whose command line contains ` +
`"gbrain autopilot", even an autopilot serving another brain or repo. Stop that autopilot (or its service, if ` +
`\`gbrain autopilot --install\` set one up), or end the process that only mentions it`,
};
}
/** Read the holder pid from a lock/pid file. Returns null if no integer pid is present. */
@@ -143,11 +159,22 @@ function isPidAlive(pid: number): boolean {
}
}
function defaultProcessRunning(): boolean {
function autopilotProcesses(): AutopilotProcess[] {
// No reliable pgrep on Windows; rely on the lock-file signal there.
if (process.platform === "win32") return false;
const r = spawnSync("pgrep", ["-f", "gbrain autopilot"], { encoding: "utf-8", timeout: 3_000 });
return r.status === 0 && (r.stdout || "").trim().length > 0;
if (process.platform === "win32") return [];
const found = spawnSync("pgrep", ["-f", "gbrain autopilot"], { encoding: "utf-8", timeout: 3_000 });
const pids = found.status === 0 ? (found.stdout || "").split(/\s+/).filter(p => /^\d+$/.test(p)) : [];
if (pids.length === 0) return [];
const ps = spawnSync("ps", ["-o", "pid=,args=", "-p", pids.join(",")], { encoding: "utf-8", timeout: 3_000 });
const commands = new Map<string, string>();
for (const line of (ps.stdout || "").split("\n")) {
const m = line.match(/^\s*(\d+)\s+(.*\S)/);
if (m) commands.set(m[1], m[2]);
}
return pids.map(pid => ({
pid: Number(pid),
command: (commands.get(pid) ?? "command unavailable").replace(/\/\/[^\s/@]+@/g, "//***@").slice(0, 200),
}));
}
// ── Capability detection (E4 + Codex: per-process memo, no persistent cache) ─
+74 -3
View File
@@ -17,8 +17,8 @@
*/
import { spawnSync } from "child_process";
import { existsSync } from "fs";
import { join } from "path";
import { lstatSync, statSync } from "fs";
import { dirname, join } from "path";
import { mergedStateRoots, resolveStateRoot } from "./state-root";
export type RepoPolicyTierValue = "deny" | "read-only" | "read-write" | "none";
@@ -46,9 +46,36 @@ export function repoPolicyStorePath(env: NodeJS.ProcessEnv = process.env): strin
/**
* No store on disk = no policy was ever set (the fast path — no subprocess).
* The ~/.gstack store counts too: its deny tiers merge into every state root.
* Only confirmed absence is "no store": ENOENT whose nearest existing
* ancestor resolves (so no dangling symlink cut the walk short). A dangling
* symlink at the store or above it, a non-directory component, or a path that
* cannot be checked (an unsearchable directory) counts as a store, so the
* caller spawns the script and its own fail-closed rules apply.
*/
export function hasRepoPolicyStore(env: NodeJS.ProcessEnv = process.env): boolean {
return mergedStateRoots(env).some((root) => existsSync(join(root, "gbrain-repo-policy.json")));
return mergedStateRoots(env).some((root) => {
let path = join(root, "gbrain-repo-policy.json");
try {
lstatSync(path);
return true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") return true;
}
for (let up = dirname(path); up !== path; path = up, up = dirname(up)) {
try {
lstatSync(up);
} catch {
continue;
}
try {
statSync(up);
return false;
} catch {
return true;
}
}
return false;
});
}
/** The bash script that owns the store — resolved relative to this file (lib/ → bin/), never cwd. */
@@ -94,6 +121,50 @@ export function repoPolicyTier(
return { tier: "none", error: "unreadable" }; // unexpected output — a read failure, not a tier
}
export interface MemorableRecallPolicy extends RepoPolicyResult {
/**
* True only when the tier is `read-only` and the store opts this remote in
* to Memorable recall. Never true alongside `error` or any other tier.
*/
memorableOptIn: boolean;
}
/**
* Tier plus the per-remote Memorable recall opt-in, via
* `gstack-gbrain-repo-policy memorable get <url>` (one spawn). Unlike
* repoPolicyTier, the script never quarantines a corrupt store on this path,
* so a corrupt store reads as `unreadable` instead of as "no policy".
* Fast paths and failure classification match repoPolicyTier; anything but
* exactly "<tier>\t<allow|off>" is `unreadable`. POLARITY IS THE CALLER'S.
*/
export function memorableRecallPolicy(
url: string | null,
env: NodeJS.ProcessEnv = process.env,
timeoutMs: number = 10_000,
): MemorableRecallPolicy {
if (!hasRepoPolicyStore(env)) return { tier: "none", memorableOptIn: false };
if (!url) return { tier: "none", memorableOptIn: false };
const [cmd, args]: [string, string[]] =
process.platform === "win32"
? ["bash", [POLICY_SCRIPT, "memorable", "get", url]]
: [POLICY_SCRIPT, ["memorable", "get", url]];
const res = spawnSync(cmd, args, {
encoding: "utf-8",
timeout: Math.max(1, timeoutMs),
env: { ...env } as NodeJS.ProcessEnv,
});
if (res.error) {
const code = (res.error as NodeJS.ErrnoException).code;
return { tier: "none", memorableOptIn: false, error: code === "ENOENT" ? "spawn-failed" : "unreadable" };
}
const unreadable: MemorableRecallPolicy = { tier: "none", memorableOptIn: false, error: "unreadable" };
if (res.status !== 0) return unreadable;
const match = /^(deny|read-only|read-write|unset)\t(allow|off)\n?$/.exec(res.stdout || "");
if (!match) return unreadable;
const tier = match[1] === "unset" ? "none" : (match[1] as RepoPolicyTierValue);
return { tier, memorableOptIn: tier === "read-only" && match[2] === "allow" };
}
/**
* Bulk trust-tier lookup via `gstack-gbrain-repo-policy get --batch` — ONE
* spawn total for the whole url list (memory-ingest checks every distinct
+2 -1
View File
@@ -263,7 +263,8 @@ export function classifyOutsideReview(input: OutsideReviewInput): OutsideReviewC
}
if (!reviewed) return result(blocking ? 'findings' : 'clean');
const unparsed = firstUnparsed(code);
const notReady = !findings.highest && verdictNotReady(plainCode);
// A last explicit not-ready blocks even when the only parsed severities are advisory.
const notReady = verdictNotReady(plainCode);
if (blocking || notReady) return { ...result('findings'), ...(unparsed ? { unparsed } : {}) };
if (unparsed) return { ...result('unverified', 'unparsed_severity', unparsed), unparsed };
if ((input.gate === 'structured' || input.gate === 'review') && !findings.highest && !concludesNoFindings(code)) {
+114 -17
View File
@@ -16,9 +16,10 @@ import * as os from 'node:os';
import * as path from 'node:path';
import { baseInputs, sha256 } from '../context';
import { PREGATE_CONFIG_PATH } from '../config';
import { isDeviceDart, readRepoFile } from '../import-graph';
import { isDeviceDart, listRepoFiles, readRepoFile } from '../import-graph';
import { selectLanes, type Selection } from '../lane-selection';
import { launchRuntime } from '../runtime';
import { cargoModel, type CargoModel } from '../rust';
import { adapterFor, readRange, supervise, type Counter, type Supervised } from '../supervise';
import { matchesAny } from '../../ship-policy';
import type { CheckDef, CheckResult, PregateContext, RemoteObligation } from '../types';
@@ -42,21 +43,24 @@ export function detectRunner(ctx: Pick<PregateContext, 'config' | 'repoRoot'>, f
/** One runner invocation: `files` relative to `cwd` (repo-relative, `''` for the root). */
export interface RunGroup { runner: string; cwd: string; files: string[] }
/** The nearest directory at or above `file` holding a pubspec.yaml, repo-relative; null outside any Dart package. `seen` memoises per directory. */
function dartRoot(repoRoot: string, file: string, seen: Map<string, string | null>): string | null {
/** The nearest directory at or above `file` holding `marker`, repo-relative; null when none does. `seen` memoises per directory (one map per marker). */
function nearestRoot(repoRoot: string, file: string, marker: string, seen: Map<string, string | null>): string | null {
const walked: string[] = [];
let found: string | null = null;
for (let d = path.posix.dirname(file); ; d = path.posix.dirname(d)) {
const rel = d === '.' ? '' : d;
if (seen.has(rel)) { found = seen.get(rel)!; break; }
walked.push(rel);
if (fs.existsSync(path.join(repoRoot, rel, 'pubspec.yaml'))) { found = rel; break; }
if (fs.existsSync(path.join(repoRoot, rel, marker))) { found = rel; break; }
if (d === '.' || d === '/' || d === '') break;
}
for (const w of walked) seen.set(w, found);
return found;
}
/** The nearest directory at or above `file` holding a pubspec.yaml, repo-relative; null outside any Dart package. */
function dartRoot(repoRoot: string, file: string, seen: Map<string, string | null>): string | null { return nearestRoot(repoRoot, file, 'pubspec.yaml', seen); }
/** An fvm pin (`.fvmrc` or `.fvm/fvm_config.json`) at the package root `root` or any ancestor up to the repo root. */
function fvmPinned(repoRoot: string, root: string): boolean {
for (let d = root; ; d = path.posix.dirname(d)) {
@@ -72,6 +76,9 @@ function fvmPinnedFor(repoRoot: string, files: readonly string[]): boolean {
return files.some(f => { const root = f.endsWith('.dart') ? dartRoot(repoRoot, f, seen) : null; return root !== null && fvmPinned(repoRoot, root); });
}
/** Whether `bin` is on the PATH of `env` (the PATH the runner will get). */
const onPath = (bin: string, env: NodeJS.ProcessEnv) => !!Bun.which(bin, { PATH: env.PATH ?? '' });
/**
* `flutter test` for a package on the Flutter SDK, else `dart test`; through fvm
* when the package or an ancestor up to the repo root pins one and fvm is on PATH. `missing` names the tool when
@@ -82,48 +89,129 @@ export function dartRunner(repoRoot: string, root: string, env: NodeJS.ProcessEn
const pubspec = readRepoFile(repoRoot, path.posix.join(root, 'pubspec.yaml')) ?? '';
// `sdk: flutter` (the key optionally quoted) under any dependency name (flutter, flutter_test, ...), block style or inside a flow mapping a key opens, comments stripped.
const tool = /^[ \t]*(['"]?)sdk\1:[ \t]*['"]?flutter\b|^[ \t]*[\w-]+:[ \t]*\{(?:[^\n]*[{,])?[ \t]*(['"]?)sdk\2:[ \t]*['"]?flutter\b/m.test(pubspec.replace(/(^|\s)#.*$/gm, '$1')) ? 'flutter' : 'dart';
const onPath = (bin: string) => !!Bun.which(bin, { PATH: env.PATH ?? '' });
const fvm = fvmPinned(repoRoot, root) && onPath('fvm');
if (!fvm && !onPath(tool)) return { missing: tool };
const fvm = fvmPinned(repoRoot, root) && onPath('fvm', env);
if (!fvm && !onPath(tool, env)) return { missing: tool };
return { runner: `${fvm ? 'fvm ' : ''}${tool} test {files}` };
}
/** The run plan: the groups that can run, the files no runner claims, Dart SDKs missing from PATH, and `.dart` files with no pubspec.yaml above. */
/**
* `cargo test -p <name>` for a crate (cargo runs a crate's tests, never a file list), or the missing tool when cargo is
* not on PATH. The name comes from the repo's Cargo.toml and reaches a shell and the `{files}` expansion: a name outside
* Cargo's grammar (letters, digits, `_`, `-`) gets no runner (null), and a valid one is still quoted like every file and cwd.
*/
function cargoRunner(name: string, env: NodeJS.ProcessEnv): { runner: string } | { missing: string } | null {
if (!/^[\p{ID_Continue}-]+$/u.test(name)) return null;
return onPath('cargo', env) ? { runner: `cargo test -p ${quote(name)}` } : { missing: 'cargo' };
}
type PackageJson = { packageManager?: string; devDependencies?: Record<string, string>; dependencies?: Record<string, string>; scripts?: Record<string, string> };
function readPackageJson(repoRoot: string, dir: string): PackageJson | null {
try { return JSON.parse(readRepoFile(repoRoot, path.posix.join(dir, 'package.json')) ?? 'null'); } catch { return null; }
}
const LOCKFILES: Array<[string, string]> = [['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn'], ['bun.lock', 'bun'], ['bun.lockb', 'bun'], ['package-lock.json', 'npm'], ['npm-shrinkwrap.json', 'npm']];
const PM_EXEC: Record<string, string> = { pnpm: 'pnpm exec', yarn: 'yarn', bun: 'bun x', npm: 'npx' };
/** The package manager for a package: the first `packageManager` field or lockfile from its directory up to the repo root; npm when none. */
function packageManager(repoRoot: string, dir: string): string {
for (let d = dir; ; d = path.posix.dirname(d)) {
const rel = d === '.' ? '' : d;
const declared = /^(pnpm|yarn|bun|npm)@/.exec(readPackageJson(repoRoot, rel)?.packageManager ?? '')?.[1];
if (declared) return declared;
const lock = LOCKFILES.find(([f]) => fs.existsSync(path.join(repoRoot, rel, f)));
if (lock) return lock[1];
if (rel === '') return 'npm';
}
}
/**
* The runner a nested package (not the repo root) declares for itself: vitest
* or jest in its dependencies or its `test` script, through the package manager
* its `packageManager` field or nearest lockfile names; null when it declares
* neither, so its files stay with the root runner. `missing` names a package
* manager that is not on PATH.
*/
function packageRunner(repoRoot: string, dir: string, env: NodeJS.ProcessEnv): { runner: string } | { missing: string } | null {
const pkg = readPackageJson(repoRoot, dir);
if (!pkg) return null;
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
const script = pkg.scripts?.test ?? '';
const tool = deps.vitest || /\bvitest\b/.test(script) ? 'vitest run' : deps.jest || /\bjest\b/.test(script) ? 'jest' : null;
if (!tool) return null;
const pm = packageManager(repoRoot, dir);
const bin = pm === 'npm' ? 'npx' : pm;
if (!onPath(bin, env)) return { missing: bin };
return { runner: `${PM_EXEC[pm]} ${tool} {files}` };
}
/** The run plan: the groups that can run, the files no runner claims, tools missing from PATH, and `.dart` files with no pubspec.yaml above. */
export interface RunPlan { groups: RunGroup[]; unclaimed: string[]; missing: string[]; noPubspec: string[] }
/**
* The invocations that run `files`. A declared runner takes every file. Otherwise
* Dart tests run from their own package root (a sub-package's imports resolve
* against its own pubspec), and the rest go to the detected runner. Files no
* runner claims (a Dart SDK missing from PATH, a `.dart` file outside any
* package, no detected runner) are `unclaimed`: the lane is `incomplete`, never a pass.
* against its own pubspec); Rust tests run per crate as `cargo test -p <name>`
* from the crate's workspace root; JS/TS tests owned by a nested package that
* declares vitest or jest run from that package; the rest go to the detected
* runner from the repo root. Files no runner claims (a tool missing from PATH,
* a `.dart` file outside any package, a `.rs` file outside any crate or in a
* crate whose name Cargo would reject, no detected runner) are `unclaimed`: the lane is `incomplete`, never a pass.
*/
export function planRuns(ctx: PregateContext, files: readonly string[]): RunPlan {
if (ctx.config.runner) return { groups: [{ runner: ctx.config.runner, cwd: '', files: [...files] }], unclaimed: [], missing: [], noPubspec: [] };
const groups: RunGroup[] = [];
const dart = new Map<string, string[]>();
const cargo = new Map<string, { name: string; cwd: string; files: string[] }>();
const packages = new Map<string, string[]>();
const seen = new Map<string, string | null>();
const seenPackage = new Map<string, string | null>();
let model: CargoModel | null = null;
const pkgRunners = new Map<string, ReturnType<typeof packageRunner>>();
const rest: string[] = [];
const noPubspec: string[] = [];
const unclaimed: string[] = [];
const missing = new Set<string>();
const add = <T>(map: Map<string, T[]>, key: string, value: T) => { let list = map.get(key); if (!list) map.set(key, (list = [])); list.push(value); };
const under = (root: string, f: string) => (root ? f.slice(root.length + 1) : f);
for (const f of files) {
if (f.endsWith('.rs')) {
model ??= cargoModel(listRepoFiles(ctx.repoRoot), rel => readRepoFile(ctx.repoRoot, rel));
const crate = model.crateOf(f);
const cwd = crate?.workspace ?? null;
if (!crate || cwd === null) { unclaimed.push(f); continue; }
const key = `${cwd}\0${crate.name}`;
if (!cargo.has(key)) cargo.set(key, { name: crate.name, cwd, files: [] });
cargo.get(key)!.files.push(under(cwd, f));
continue;
}
const pkg = /\.[cm]?[jt]sx?$/.test(f) ? nearestRoot(ctx.repoRoot, f, 'package.json', seenPackage) : null;
if (pkg) {
if (!pkgRunners.has(pkg)) pkgRunners.set(pkg, packageRunner(ctx.repoRoot, pkg, ctx.env));
const r = pkgRunners.get(pkg);
if (r && 'missing' in r) { missing.add(r.missing); unclaimed.push(f); continue; }
if (r) { add(packages, pkg, under(pkg, f)); continue; }
}
if (!f.endsWith('.dart')) { rest.push(f); continue; }
const root = dartRoot(ctx.repoRoot, f, seen);
if (root === null) { noPubspec.push(f); continue; }
let list = dart.get(root);
if (!list) dart.set(root, (list = []));
list.push(root ? f.slice(root.length + 1) : f);
add(dart, root, under(root, f));
}
const unclaimed: string[] = [];
const missing = new Set<string>();
for (const [root, list] of [...dart].sort(([a], [b]) => a.localeCompare(b))) {
const r = dartRunner(ctx.repoRoot, root, ctx.env);
if ('missing' in r) { missing.add(r.missing); unclaimed.push(...list.map(f => (root ? `${root}/${f}` : f))); } else groups.push({ runner: r.runner, cwd: root, files: list });
}
for (const [, c] of [...cargo].sort(([a], [b]) => a.localeCompare(b))) {
const r = cargoRunner(c.name, ctx.env);
if (r && 'runner' in r) { groups.push({ runner: r.runner, cwd: c.cwd, files: c.files }); continue; }
if (r) missing.add(r.missing);
unclaimed.push(...c.files.map(f => (c.cwd ? `${c.cwd}/${f}` : f)));
}
if (rest.length) {
const runner = detectRunner(ctx, rest);
if (runner) groups.push({ runner, cwd: '', files: rest });
else unclaimed.push(...rest);
}
for (const [root, list] of [...packages].sort(([a], [b]) => a.localeCompare(b))) groups.push({ runner: (pkgRunners.get(root) as { runner: string }).runner, cwd: root, files: list });
return { groups, unclaimed: [...unclaimed, ...noPubspec], missing: [...missing].sort(), noPubspec };
}
@@ -153,9 +241,18 @@ function parseDart(output: string): RunnerSummary | null {
return d ? { ran: Number(d[1]) + Number(d[2] ?? 0), failed: Number(d[2] ?? 0) } : null;
}
/** The runner's own summary line: bun, node --test, vitest, jest, pytest, bats, dart/flutter test. A bats or dart/flutter runner's summary is tried first; for any other runner those formats are a last resort. `ran: null` when not recognised. Colour codes are dropped and a carriage return ends a line, so a coloured or redrawn verdict still reads. */
/** cargo test: one `test result: ok|FAILED. N passed; M failed; …` line per test binary (unit tests, each integration test, doc-tests), summed; ignored and filtered-out tests did not run. */
function parseCargo(output: string): RunnerSummary | null {
const lines = [...output.matchAll(/^test result: \w+\. (\d+) passed; (\d+) failed;/gm)];
if (!lines.length) return null;
const failed = lines.reduce((n, m) => n + Number(m[2]), 0);
return { ran: lines.reduce((n, m) => n + Number(m[1]), 0) + failed, failed };
}
/** The runner's own summary line: bun, node --test, vitest, jest, pytest, bats, dart/flutter test, cargo test. A bats, dart/flutter or cargo runner's summary is tried first (cargo's only there: its `N passed` lines would misread as another runner's); for any other runner the bats and dart formats are a last resort. `ran: null` when not recognised. Colour codes are dropped and a carriage return ends a line, so a coloured or redrawn verdict still reads. */
export function parseSummary(raw: string, runner = ''): RunnerSummary {
const output = raw.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r/g, '\n');
if (/(?<![\w-])cargo\s+test(?![\w-])/.test(runner)) return parseCargo(output) ?? { ran: null, failed: null };
if (/(?<![\w-])bats(?![\w-])/.test(runner)) { const b = parseBats(output); if (b) return b; }
const dartRun = /(?<![\w-])(?:dart|flutter)(?![\w-])/.test(runner);
if (dartRun) { const d = parseDart(output); if (d) return d; }
+8 -1
View File
@@ -12,7 +12,10 @@
* 3. the `bin/<name>` → `test/<name>*.test.*` convention (with and without
* the `gstack-` prefix);
* 4. explicit `.gstack/pregate.json` `dependencies` declarations;
* 5. in a Django project, the files Django loads by name (lib/pregate/django.ts).
* 5. in a Django project, the files Django loads by name (lib/pregate/django.ts);
* 6. in a Cargo crate, every `.rs` file and the Cargo.toml select the crate's
* tests and its dependents' (lib/pregate/rust.ts); in-source
* `#[cfg(test)]` files and `<crate>/tests/` files are the tests.
* Dart directives (`import`/`export`/`part`, conditional URIs included) resolve
* `package:<name>/x` through every tracked pubspec.yaml to `<root>/lib/x`.
* Uncertainty selects more tests, never fewer: a dependency on a directory
@@ -25,6 +28,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import { matchesAny } from '../ship-policy';
import { djangoEdges } from './django';
import { rustEdges } from './rust';
export const SOURCE_EXT = /\.(?:[cm]?[jt]sx?|py|rb|sh|bash|go|rs|dart)$/;
export const TEST_FILE_RE = /(?:^|\/)(?:test|tests|spec|__tests__)\/.*\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)test_[^/]*\.py$|_test\.(?:py|go|rb)$|_spec\.rb$|(?:^|\/)[^/]*\.bats$|(?:^|\/)test\/(?:.*\/)?[^/]*_test\.dart$/;
@@ -465,6 +469,9 @@ export function buildGraph(repoRoot: string, opts: BuildOptions = {}): Graph {
for (const { target, via } of referencesIn(files, dirs, rel, source, config, graph.tests.has(rel) ? unresolved : undefined, packages)) addEdge(graph, target, rel, via);
if (unresolved.length) graph.unresolved!.set(rel, unresolved);
}
const rust = rustEdges(all, rel => readRepoFile(repoRoot, rel, maxBytes));
for (const t of rust.tests) graph.tests.add(t);
for (const e of rust.edges) addEdge(graph, e.dependency, e.dependent, e.via);
const django = djangoEdges({ files: [...files], tests: graph.tests, read: rel => pySources.get(rel) ?? readRepoFile(repoRoot, rel, maxBytes), code: pythonCode, resolveDotted: dotted => pythonPatchTarget(files, dotted) });
for (const e of django) addEdge(graph, e.dependency, e.dependent, 'framework');
for (const test of graph.tests) {
+3 -2
View File
@@ -72,13 +72,14 @@ export function draftConfig(repoRoot: string): InitDraft {
}
const groups = new Map<string, string[]>();
for (const t of tests) { const lang = t.endsWith('.dart') ? 'dart' : t.endsWith('.py') ? 'python' : /\.[cm]?[jt]sx?$/.test(t) ? 'javascript' : 'other'; groups.set(lang, [...(groups.get(lang) ?? []), t]); }
for (const t of tests) { const lang = t.endsWith('.dart') ? 'dart' : t.endsWith('.rs') ? 'rust' : t.endsWith('.py') ? 'python' : /\.[cm]?[jt]sx?$/.test(t) ? 'javascript' : 'other'; groups.set(lang, [...(groups.get(lang) ?? []), t]); }
const notes = [...groups].map(([lang, list]) => {
if (lang === 'dart') return `${list.length} Dart test file(s) run per package with flutter test or dart test`;
if (lang === 'rust') return `${list.length} Rust test file(s) run per crate with cargo test -p`;
const runner = detectRunner({ repoRoot, config: DEFAULT_CONFIG }, list);
return runner ? `${lang} tests detected at run time: ${runner}` : `no runner detected for ${list.length} ${lang} test file(s); set runner (with {files})`;
});
const mixed = [...groups.keys()].filter(l => l !== 'dart').length > 1 ? '; a selection mixing these languages needs runner set' : '';
const mixed = [...groups.keys()].filter(l => l !== 'dart' && l !== 'rust').length > 1 ? '; a selection mixing these languages needs runner set' : '';
const runnerNote = notes.length ? notes.join('; ') + mixed : 'no test files found';
const selectionTodo = discoverLanes(repoRoot).filter(l => l.runsTests && l.matrixExpression && l.testFiles.length === 0).map(l => l.id);
+258
View File
@@ -0,0 +1,258 @@
/**
* pregate/rust — Cargo crates for the import graph and the `lanes` runner.
* A crate is the nearest directory holding a Cargo.toml with a `[package]`
* name. Its `.rs` files are tests when they sit under `<crate>/tests/` or hold
* a `#[cfg(test)]` (in-source unit tests). Cargo runs tests per crate, never
* per file, so the graph maps at crate level: every `.rs` file of a crate,
* and its Cargo.toml, select that crate's tests and the tests of every crate
* that depends on it, transitively.
* Manifests are parsed as TOML (Bun.TOML, as lib/model-policy.ts does), so
* dotted keys, `[dependencies.<name>]` tables, target-specific tables and
* `{ workspace = true }` inheritance read as Cargo reads them. A dependency
* resolves by `path` (relative to the manifest declaring it) to a tracked
* crate, else by package name (`package = ` or the key); a name match only
* widens. The workspace a crate runs in follows Cargo's membership rules:
* `package.workspace`, else the nearest `[workspace]` above it, when that
* workspace is the crate's own manifest, lists it in `members` or reaches it
* by a path dependency, and does not `exclude` it; otherwise the crate
* directory. Nothing here runs cargo: pregate reads files only.
*/
import * as path from 'node:path';
/** Reads a repo-relative file's text, or null when it is absent or unreadable. */
export type ReadFile = (rel: string) => string | null;
type Table = Record<string, unknown>;
const isTable = (v: unknown): v is Table => typeof v === 'object' && v !== null && !Array.isArray(v);
const strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []);
const DEP_TABLES = ['dependencies', 'dev-dependencies', 'build-dependencies'] as const;
/** One dependency: the crate directory its `path` names (repo-relative, normalized) and the package name it asks for. */
interface DepSpec { path: string | null; name: string }
export interface Crate {
root: string;
name: string;
/** Where `cargo test -p <name>` runs: the root of the workspace it is a member of, else the crate directory; null when membership is undecided. */
workspace: string | null;
/** Roots of the tracked crates it depends on. */
deps: string[];
}
export interface CargoModel { crates: Map<string, Crate>; crateOf(file: string): Crate | null }
interface Manifest { dir: string; toml: Table }
const dirOf = (manifest: string) => (path.posix.dirname(manifest) === '.' ? '' : path.posix.dirname(manifest));
/** `dir` joined with a manifest-relative path, normalized; null when it leaves the repository. */
function joinRel(dir: string, rel: string): string | null {
const joined = path.posix.normalize(path.posix.join(dir || '.', rel.replace(/\\/g, '/'))).replace(/\/+$/, '');
if (joined === '..' || joined.startsWith('../') || path.posix.isAbsolute(joined)) return null;
return joined === '.' ? '' : joined;
}
/** One glob component (`*`, `?`, `[...]` with `!`/`^` negation and ranges, else literal) against one path component, by Unicode code point and dynamic programming: O(pattern × name), no regex backtracking. */
function componentMatch(glob: string, name: string): boolean {
const g = Array.from(glob);
const s = Array.from(name);
const nextClose = new Array<number>(g.length + 1).fill(-1);
for (let i = g.length - 1; i >= 0; i--) nextClose[i] = g[i] === ']' ? i : nextClose[i + 1]!;
const tokens: Array<'*' | ((c: string) => boolean)> = [];
for (let i = 0; i < g.length; i++) {
const ch = g[i]!;
const negate = ch === '[' && /[!^]/.test(g[i + 1] ?? '');
const close = ch === '[' ? nextClose[i + (negate ? 3 : 2)] ?? -1 : -1;
if (ch === '*') tokens.push('*');
else if (ch === '?') tokens.push(() => true);
else if (close > 0) {
const body = g.slice(i + (negate ? 2 : 1), close).map(c => c.codePointAt(0)!);
tokens.push(c => {
const p = c.codePointAt(0)!;
let hit = false;
for (let j = 0; j < body.length; j++) {
if (body[j + 1] === 0x2d && j + 2 < body.length) { hit ||= p >= body[j]! && p <= body[j + 2]!; j += 2; } else hit ||= p === body[j];
}
return hit !== negate;
});
i = close;
} else tokens.push(c => c === ch);
}
let row = s.map(() => false).concat(false);
row[0] = true;
for (const t of tokens) {
const next = row.map(() => false);
next[0] = t === '*' && row[0]!;
for (let j = 1; j <= s.length; j++) next[j] = t === '*' ? row[j]! || next[j - 1]! : row[j - 1]! && t(s[j - 1]!);
row = next;
}
return row[s.length]!;
}
/** A Cargo `members` glob against a workspace-relative crate directory, component by component; `**` spans any number of components. */
function memberMatch(glob: string, rel: string): boolean {
const p = rel.split('/').filter(Boolean);
let row = p.map(() => false).concat(false);
row[0] = true;
for (const part of glob.split('/').filter(Boolean)) {
const next = row.map(() => false);
next[0] = part === '**' && row[0]!;
for (let j = 1; j <= p.length; j++) next[j] = part === '**' ? row[j]! || next[j - 1]! : row[j - 1]! && componentMatch(part, p[j - 1]!);
row = next;
}
return row[p.length]!;
}
/**
* Past this many characters of `members` globs a workspace's membership is undecided: every crate under it counts as a
* member for dependency edges (more tests, never fewer), but where its tests run is unknown, so they are unclaimed and the
* lane is incomplete (running from the wrong root can test a same-named member instead).
*/
const MAX_MEMBER_GLOB_CHARS = 4096;
const inside = (dir: string, root: string) => root === '' || dir === root || dir.startsWith(`${root}/`);
const relTo = (dir: string, root: string) => (root === '' ? dir : dir === root ? '' : dir.slice(root.length + 1));
/** Every dependency of a manifest: `[*dependencies]` and `[target.<cfg>.*dependencies]`, `{ workspace = true }` read from `ws`'s `[workspace.dependencies]` (its paths relative to the workspace root). */
function depSpecs(m: Manifest, ws: Manifest | null): DepSpec[] {
const tables: Table[] = [];
for (const key of DEP_TABLES) if (isTable(m.toml[key])) tables.push(m.toml[key] as Table);
if (isTable(m.toml.target)) for (const cfg of Object.values(m.toml.target)) if (isTable(cfg)) for (const key of DEP_TABLES) if (isTable(cfg[key])) tables.push(cfg[key] as Table);
const inherited = ws && isTable(ws.toml.workspace) && isTable(ws.toml.workspace.dependencies) ? ws.toml.workspace.dependencies : {};
const out: DepSpec[] = [];
for (const table of tables) {
for (const [key, raw] of Object.entries(table)) {
const fromWorkspace = isTable(raw) && raw.workspace === true;
const spec = fromWorkspace ? inherited[key] : raw;
const renamed = [spec, raw].find(s => isTable(s) && typeof s.package === 'string') as Table | undefined;
const p = isTable(spec) && typeof spec.path === 'string' ? joinRel(fromWorkspace ? ws!.dir : m.dir, spec.path) : null;
out.push({ path: p, name: (renamed?.package as string | undefined) ?? key });
}
}
return out;
}
/** The tracked crates among `files` (the paths `git ls-files` reports), what each depends on, and the workspace each runs in. */
export function cargoModel(files: readonly string[], read: ReadFile): CargoModel {
const manifests = new Map<string, Manifest>();
for (const f of files) {
if (path.posix.basename(f) !== 'Cargo.toml') continue;
const text = read(f);
if (text === null) continue;
try { const toml = Bun.TOML.parse(text); if (isTable(toml)) manifests.set(dirOf(f), { dir: dirOf(f), toml }); } catch { /* an unparsable manifest names no crate */ }
}
const nameOf = (dir: string) => { const pkg = manifests.get(dir)?.toml.package; return isTable(pkg) && typeof pkg.name === 'string' ? pkg.name : null; };
const roots = [...manifests.keys()].filter(d => nameOf(d) !== null);
const workspaces = [...manifests.values()].filter(m => isTable(m.toml.workspace));
const byName = new Map<string, string[]>();
for (const r of roots) byName.set(nameOf(r)!, [...(byName.get(nameOf(r)!) ?? []), r]);
// `package.workspace` names the workspace; otherwise Cargo consults only the nearest [workspace] at or above the crate.
const candidate = (root: string): Manifest | null => {
const pkg = manifests.get(root)!.toml.package as Table;
if (typeof pkg.workspace === 'string') { const w = manifests.get(joinRel(root, pkg.workspace) ?? '\0'); return w && isTable(w.toml.workspace) ? w : null; }
return workspaces.filter(w => inside(root, w.dir)).sort((a, b) => b.dir.length - a.dir.length)[0] ?? null;
};
const memberCache = new Map<string, Set<string>>();
const undecided = new Set<string>();
const membersOf = (ws: Manifest): Set<string> => {
const cached = memberCache.get(ws.dir);
if (cached) return cached;
const conf = ws.toml.workspace as Table;
const norm = (g: string) => joinRel('', g) ?? '\0';
const globs = strings(conf.members).map(norm);
const exclude = strings(conf.exclude).map(norm);
const own = new Set(roots.filter(r => candidate(r)?.dir === ws.dir));
const excluded = (r: string) => exclude.some(e => { const rel = relTo(r, ws.dir); return rel === e || rel.startsWith(`${e}/`); });
// Cargo's rules: the root package and a literally listed member always belong; a glob match or a path dependency of a
// member inside the workspace belongs unless `exclude` names it or a directory above it.
const literal = (r: string) => globs.some(g => !/[*?[]/.test(g) && relTo(r, ws.dir) === g);
const oversized = globs.join('').length > MAX_MEMBER_GLOB_CHARS;
const members = new Set([...own].filter(r => r === ws.dir || literal(r) || ((oversized || globs.some(g => memberMatch(g, relTo(r, ws.dir)))) && !excluded(r))));
if (oversized) for (const r of members) if (r !== ws.dir && !literal(r)) undecided.add(r);
memberCache.set(ws.dir, members);
const queue = [...members];
while (queue.length) {
for (const dep of depSpecs(manifests.get(queue.shift()!)!, ws)) {
if (dep.path === null || members.has(dep.path) || !own.has(dep.path) || !inside(dep.path, ws.dir) || excluded(dep.path)) continue;
members.add(dep.path);
queue.push(dep.path);
}
}
return members;
};
// A path names one crate; without a path (or when it names no tracked crate) every crate of that package name is a candidate.
const resolve = (specs: DepSpec[]) => [...new Set(specs.flatMap(s => (s.path !== null && nameOf(s.path) !== null ? [s.path] : byName.get(s.name) ?? [])))];
const crates = new Map<string, Crate>();
for (const root of roots) {
const ws = candidate(root);
const member = ws !== null && membersOf(ws).has(root) ? ws : null;
crates.set(root, { root, name: nameOf(root)!, workspace: undecided.has(root) ? null : member?.dir ?? root, deps: resolve(depSpecs(manifests.get(root)!, member)).filter(d => d !== root) });
}
const crateOf = (file: string): Crate | null => {
for (let d = path.posix.dirname(file); ; d = path.posix.dirname(d)) {
const c = crates.get(d === '.' ? '' : d);
if (c) return c;
if (d === '.' || d === '/' || d === '') return null;
}
};
return { crates, crateOf };
}
/**
* Whether Rust source declares tests: a `#[test]` or `#[<path>::test]` attribute (a plain test function, `#[tokio::test]`),
* or a `#[cfg(...)]` whose predicate names `test` outside a string (`cfg(test)`, `cfg(all(test, unix))`; never
* `cfg(feature = "test")`). One forward scan: each attribute is read once to its `]`, and one this scan cannot close
* (an unterminated string, no `]` before the end) counts as a test, which selects more, never fewer.
*/
export function hasCfgTest(source: string): boolean {
if (/#\s*\[\s*(?:[A-Za-z_]\w*\s*::\s*)*test\s*[\]()]/.test(source)) return true;
const open = /#\s*\[\s*cfg\s*\(/g;
for (let m = open.exec(source); m; m = open.exec(source)) {
let predicate = '';
let i = open.lastIndex;
for (; i < source.length && source[i] !== ']'; i++) {
if (source[i] !== '"') { predicate += source[i]; continue; }
const close = source.indexOf('"', i + 1);
if (close < 0) return true;
predicate += '""';
i = close;
}
if (i >= source.length) return true;
const body = predicate.trimEnd();
if (body.endsWith(')') && /\btest\b/.test(body.slice(0, -1))) return true;
open.lastIndex = i + 1;
}
return false;
}
export interface RustGraph {
tests: string[];
edges: Array<{ dependency: string; dependent: string; via: 'import' | 'convention' }>;
}
/**
* The Rust part of the reverse graph over the tracked `files`: each crate's
* test files, an edge from every `.rs` file of a crate to its Cargo.toml (the
* crate's node), and an edge from each Cargo.toml to the tests of its crate
* (`convention`) and of every crate depending on it, transitively (`import`).
*/
export function rustEdges(files: readonly string[], read: ReadFile): RustGraph {
const { crates, crateOf } = cargoModel(files, read);
const out: RustGraph = { tests: [], edges: [] };
if (!crates.size) return out;
const testsOf = new Map<string, string[]>([...crates.keys()].map(k => [k, []]));
const manifestOf = (root: string) => (root ? `${root}/Cargo.toml` : 'Cargo.toml');
for (const f of files) {
if (!f.endsWith('.rs')) continue;
const crate = crateOf(f);
if (!crate) continue;
out.edges.push({ dependency: f, dependent: manifestOf(crate.root), via: 'convention' });
if (f.startsWith(crate.root ? `${crate.root}/tests/` : 'tests/') || hasCfgTest(read(f) ?? '')) { out.tests.push(f); testsOf.get(crate.root)!.push(f); }
}
const dependents = new Map<string, Set<string>>();
for (const c of crates.values()) for (const d of c.deps) dependents.set(d, (dependents.get(d) ?? new Set()).add(c.root));
for (const root of crates.keys()) {
const reach = new Set<string>([root]);
const queue = [root];
while (queue.length) for (const next of dependents.get(queue.shift()!) ?? []) if (!reach.has(next)) { reach.add(next); queue.push(next); }
for (const r of reach) for (const t of testsOf.get(r)!) out.edges.push({ dependency: manifestOf(root), dependent: t, via: r === root ? 'convention' : 'import' });
}
return out;
}
+4 -2
View File
@@ -68,7 +68,7 @@ export interface RestampResult {
function sha256(buf: Buffer | string): string { return createHash('sha256').update(buf).digest('hex'); }
function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv): { ok: boolean; out: string; err: string; status: number | null } {
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, env: env ?? process.env });
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, env: env ?? process.env, maxBuffer: 64 * 1024 * 1024 });
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim(), status: r.status };
}
class Refusal extends Error { constructor(public code: ResultCodeName, message: string, public extra: Partial<RestampResult> = {}) { super(message); } }
@@ -578,7 +578,9 @@ function gateAhead(o: RestampOptions, plan: Plan, stages: StageRecord[], common:
if (resolvable) {
for (const c of conflicts) {
if (c === plan.policy.changelog) {
const merged = mergeChangelogs(git(dir, ['show', `:2:${c}`]).out + '\n', git(dir, ['show', `:3:${c}`]).out + '\n');
const stage = (n: number) => git(dir, ['show', `:${n}:${c}`]);
const [base, ours, theirs] = [stage(1), stage(2), stage(3)];
const merged = ours.ok && theirs.ok ? mergeChangelogs(ours.out + '\n', theirs.out + '\n', base.ok ? base.out + '\n' : undefined) : null;
if (merged === null) { unresolved = [c]; break; }
fs.writeFileSync(path.join(dir, c), merged);
} else git(dir, ['checkout', '--theirs', '--', c]);
+2 -1
View File
@@ -99,7 +99,8 @@ export function recomputeMergeTree(repoRoot: string, branchHead: string, predece
if (!ours || !theirs) return { error: `${file} conflicts beyond a content merge (added or deleted on one side)` };
if (file === policy.changelog) {
const text = (sha: string) => git(repoRoot, ['cat-file', 'blob', sha]).out + '\n';
const merged = mergeChangelogs(text(ours), text(theirs));
const base = entry.get(1);
const merged = mergeChangelogs(text(ours), text(theirs), base ? text(base) : undefined);
if (merged === null) return { error: `${file} conflicts beyond a heading move` };
const blob = git(repoRoot, ['hash-object', '-w', '--stdin'], undefined, merged);
if (!blob.ok) return { error: `cannot write the merged ${file}: ${blob.err}` };
+5 -2
View File
@@ -15,7 +15,9 @@ import { trainBisect, trainRebuild, trainVerdict } from './ship-queue-train-verd
import { verifyTrain } from './ship-queue-train-verify';
import { redactCause } from './ship-queue-train-record';
export const TRAIN_HELP = ` train build --prs <n>@<sha>[,...] [--urgent | --repair] [--dry-run] [--free-timeout <s>]
export const TRAIN_HELP = ` train build --prs <n>@<sha>[,...] [--order <n>,...] [--urgent | --repair] [--dry-run] [--free-timeout <s>]
--order: explicit slot order, every PR in --prs once (default: screened
first, then READY order)
train build --train <nonce> resume a train (push, free tests, dispatch) from its record
merge pinned unstamped heads in slot order onto main, free tests on
train/<nonce>, then one full gate through eval-bg's nonce
@@ -77,8 +79,9 @@ export async function trainMain(ctx: QueueContext, args: string[]): Promise<numb
const freeTimeoutSec = positive(flag(rest, '--free-timeout'), 2700);
if (Number.isNaN(freeTimeoutSec)) return usage('--free-timeout needs seconds');
if (rest.includes('--urgent') && rest.includes('--repair')) return usage('--urgent and --repair are separate one-PR trains; pass one');
if (rest.includes('--order') && (nonce || !flag(rest, '--order'))) return usage('--order <n>,... orders a new train from --prs; a resumed train keeps its recorded order');
return guarded('train build', () => buildTrain(ctx, {
pins: flag(rest, '--prs'), resume: nonce, dryRun, urgent: rest.includes('--urgent'), repair: rest.includes('--repair'), freeTimeoutSec,
pins: flag(rest, '--prs'), order: flag(rest, '--order'), resume: nonce, dryRun, urgent: rest.includes('--urgent'), repair: rest.includes('--repair'), freeTimeoutSec,
pollMs: Number(process.env.GSTACK_SHIP_QUEUE_POLL_MS) || 30_000,
}));
}
+4 -1
View File
@@ -14,6 +14,7 @@ import { randomBytes } from 'node:crypto';
import { DISPATCH_INPUTS, awaitNonceRun, dedupeKey, dispatchWorkflow, findDuplicateRun, listDispatchRuns, makeNonce, type WorkflowDispatch } from '../scripts/eval-bg';
import { EXIT } from './headless-artifacts';
import { ready, type QueueContext } from './ship-queue';
import { classifyTrainHead } from './version-gate-train';
import { git } from './ship-queue-gate';
import { execFor, repoSlug } from './ship-queue-train-github';
import { loadReady, nowIso, persist, readyPath, type ReadyReceipt, type ScreenChoice } from './ship-queue-train-record';
@@ -100,6 +101,8 @@ export async function trainReady(ctx: QueueContext, o: ReadyOptions): Promise<Tr
}
const head = git(ctx.repoRoot, ['rev-parse', 'HEAD']).out;
const baseSha = git(ctx.repoRoot, ['rev-parse', `${env.remote}/${ctx.base}`]).out;
const kind = classifyTrainHead({ repoRoot: ctx.repoRoot, baseRef: ctx.base, head });
if (kind.kind === 'invalid') return outRefused({ code: 'QUEUE_NOT_READY', message: `the Version Gate refuses ${head.slice(0, 12)}: ${kind.reason}` }, base.lines, `fix the head, push, then ${Q} ready --pr ${o.pr} --screen|--no-screen`, 'none');
const sel = await screenSelection(env, head, baseSha);
const lines = [...base.lines, ...sel.lines];
const rec = sel.recommend ?? 'no-screen';
@@ -119,7 +122,7 @@ export async function trainReady(ctx: QueueContext, o: ReadyOptions): Promise<Tr
}
lines.splice(1, 0, `screen: ${choice.choice}${choice.policy ? ` policy=${choice.policy} nonce=${choice.nonce} run=${choice.run ?? '-'}` : ''}`);
const now = nowIso();
const readyAt = loadReady(env.repo.key, o.pr, head)?.ready_at ?? now;
const readyAt = loadReady(env.repo.keys, o.pr, head)?.ready_at ?? now;
const receipt: ReadyReceipt = { schema: 1, kind: 'ready', repo_key: env.repo.key, pr: o.pr, head, base_sha: baseSha, ready_at: readyAt, screen: choice, updated_at: now };
if (o.dryRun) return outOk([...lines, 'DRY-RUN: no READY receipt written, nothing dispatched'], `${Q} ready --pr ${o.pr} --${o.screen}${o.broad ? ' --broad' : ''}`, 'none');
const p = persist(ctx.repoRoot, [receipt], { remote: env.remote });
+40 -11
View File
@@ -31,7 +31,7 @@ export interface FreeRun { run: number | null; url: string | null; head_sha: str
export interface TrainRecord {
schema: 1; kind: 'train'; nonce: string; key: string; repo_key: string; repo: string; base: { ref: string; sha: string }; policy: string;
slots: TrainSlot[]; held: string[]; prefixes: TrainPrefix[]; head: string; tree: string; branch: string;
urgent: boolean; repair: boolean; state: TrainState; free: FreeRun | null; attempts: string[];
urgent: boolean; repair: boolean; explicit_order?: boolean; state: TrainState; free: FreeRun | null; attempts: string[];
merged: Array<{ pr: string; sha: string; tree: string; at: string }>; superseded_by: string | null;
effects: Array<{ at: string; what: string }>; error: string | null; created_at: string; updated_at: string;
}
@@ -87,11 +87,34 @@ const bisectPath = (nonce: string) => path.join(trainDir(nonce), 'bisect.json');
const freezePath = (repoKey: string) => path.join(queueRoot(), 'freeze', `${repoKey}.json`);
export const readyPath = (repoKey: string, pr: string, head: string) => path.join(queueRoot(), 'ready', repoKey, `${pr}-${head}.json`);
/** The repository's identity: origin's URL, keyed so records of different repositories never mix. */
export function repoIdentity(repoRoot: string): { key: string; url: string } {
const url = git(repoRoot, ['config', '--get', 'remote.origin.url']).out.trim() || repoRoot;
const norm = url.replace(/\.git$/, '').replace(/^git@github\.com:/, 'https://github.com/').replace(/\/+$/, '');
return { key: sha256(norm).slice(0, 16), url: norm };
/** Hosts that serve GitHub repositories at /<owner>/<repo> (git.capy.ai is Capy's GitHub proxy, set through url.insteadOf). */
const GITHUB_HOSTS = ['github.com', 'www.github.com', 'ssh.github.com', 'git.capy.ai'];
/** Before 1.91.187.0 the key hashed origin's URL with only .git, git@github.com: and trailing slashes normalized. */
const legacyNorm = (url: string) => url.replace(/\.git$/, '').replace(/^git@github\.com:/, 'https://github.com/').replace(/\/+$/, '');
/** A remote URL as https://github.com/<owner>/<repo> when it names a GitHub repository in any form (scp, ssh, http(s), credentials, proxy host); otherwise the legacy form. */
export function normalizeRemoteUrl(url: string): string {
const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)(?::\d+)?[:/]+([^/]+)\/([^/]+?)(?:\.git)?\/*$/i.exec(url.trim());
if (m && GITHUB_HOSTS.includes(m[1]!.toLowerCase())) return `https://github.com/${m[2]!.toLowerCase()}/${m[3]!.toLowerCase()}`;
return legacyNorm(url.trim().replace(/^([a-z+]+:\/\/)[^@/]+@/i, '$1'));
}
/**
* The repository's identity, keyed so records of different repositories
* never mix: a hash of origin's URL normalized to owner/repo, so lanes whose
* origin names the same GitHub repository in another form share one key.
* `keys` adds the keys earlier versions wrote for this URL and for the
* repository's common URL forms; readers accept all of them, writers use `key`.
*/
export function repoIdentity(repoRoot: string): { key: string; url: string; keys: string[] } {
const raw = git(repoRoot, ['config', '--get', 'remote.origin.url']).out.trim() || repoRoot;
const url = normalizeRemoteUrl(raw);
const key = sha256(url).slice(0, 16);
const gh = /^https:\/\/github\.com\/(.+)$/.exec(url)?.[1];
const forms = gh ? GITHUB_HOSTS.flatMap(h => ['https', 'http', 'ssh://git@'].map(s => `${s.includes('://') ? s : `${s}://`}${h}/${gh}`)) : [];
const keys = [...new Set([key, ...[raw, ...forms].map(u => sha256(legacyNorm(u)).slice(0, 16))])];
return { key, url, keys };
}
function readJson<T>(file: string, kind: string): T | null {
@@ -101,19 +124,25 @@ function readJson<T>(file: string, kind: string): T | null {
export const loadTrain = (nonce: string) => (/^[A-Za-z0-9._-]{1,128}$/.test(nonce) ? readJson<TrainRecord>(trainFile(nonce), 'train') : null);
export const loadAttempt = (nonce: string, id: string) => (/^[A-Za-z0-9._-]{1,64}$/.test(id) ? readJson<AttemptRecord>(attemptPath(nonce, id), 'train-attempt') : null);
export const loadBisect = (nonce: string) => readJson<BisectRecord>(bisectPath(nonce), 'train-bisect');
export const loadFreeze = (repoKey: string) => readJson<FreezeRecord>(freezePath(repoKey), 'freeze');
export const loadReady = (repoKey: string, pr: string, head: string) => readJson<ReadyReceipt>(readyPath(repoKey, pr, head), 'ready');
export const activeFreeze = (repoKey: string): FreezeRecord | null => { const f = loadFreeze(repoKey); return f && !f.cleared_at ? f : null; };
/** A reader's repo keys: the current key first, then the legacy keys (repoIdentity().keys). */
type RepoKeys = string | readonly string[];
const keyList = (k: RepoKeys): readonly string[] => (typeof k === 'string' ? [k] : k);
const firstOf = <T>(k: RepoKeys, read: (key: string) => T | null): T | null => { for (const key of keyList(k)) { const r = read(key); if (r) return r; } return null; };
export const loadFreeze = (repoKeys: RepoKeys) => firstOf(repoKeys, key => readJson<FreezeRecord>(freezePath(key), 'freeze'));
export const loadReady = (repoKeys: RepoKeys, pr: string, head: string) => firstOf(repoKeys, key => readJson<ReadyReceipt>(readyPath(key, pr, head), 'ready'));
export const activeFreeze = (repoKeys: RepoKeys): FreezeRecord | null => firstOf(repoKeys, key => { const f = readJson<FreezeRecord>(freezePath(key), 'freeze'); return f && !f.cleared_at ? f : null; });
export function attemptsOf(train: TrainRecord): AttemptRecord[] {
return train.attempts.map(id => loadAttempt(train.nonce, id)).filter((a): a is AttemptRecord => !!a);
}
/** Every train of this repository, newest first. */
export function listTrains(repoKey: string): TrainRecord[] {
export function listTrains(repoKeys: RepoKeys): TrainRecord[] {
const dir = path.join(queueRoot(), 'trains');
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir).map(n => loadTrain(n)).filter((t): t is TrainRecord => !!t && t.repo_key === repoKey)
const keys = keyList(repoKeys);
return fs.readdirSync(dir).map(n => loadTrain(n)).filter((t): t is TrainRecord => !!t && keys.includes(t.repo_key))
.sort((a, b) => b.created_at.localeCompare(a.created_at) || b.nonce.localeCompare(a.nonce));
}
+3 -3
View File
@@ -23,7 +23,7 @@ import {
type AttemptRecord, type BisectRecord, type CasePanel, type GateOutcome, type PrefixResult, type TrainRecord,
} from './ship-queue-train-record';
import {
dispatchAttempt, effect, findTrain, gateDispatch, nextFor, outFailed, outOk, outPending, outRefused, pinList, save, trainEnv,
dispatchAttempt, effect, findTrain, gateDispatch, nextFor, outFailed, outOk, outPending, outRefused, prsArgs, save, trainEnv,
type TrainEnv, type TrainOut,
} from './ship-queue-train';
@@ -309,7 +309,7 @@ export async function trainRebuild(ctx: QueueContext, o: { train: string; infra:
const run = trainFile(t.nonce);
const gates = gateAttempts(t);
const last = gates.at(-1);
const repair = `route ${last?.red_cases.join(',') || 'the red cases'} to a repair lane (GStack Minder); the train is rebuilt only once the repair merges: ${Q} train build --prs ${pinList(t.slots)}`;
const repair = `route ${last?.red_cases.join(',') || 'the red cases'} to a repair lane (GStack Minder); the train is rebuilt only once the repair merges: ${Q} train build ${prsArgs(t.slots, t.explicit_order)}`;
const refuse = (reason: string) => outRefused({ code: 'QUEUE_TRAIN_REBUILD_REFUSED', message: `rebuild refused: ${reason}` }, gates.map(attemptLine), repair, run);
if (o.infra) {
if (!last || last.outcome !== 'INCOMPLETE' || !last.infra_eligible) return refuse(`no INFRA/INCOMPLETE-only record (the last gate is ${last?.outcome ?? 'missing'})`);
@@ -321,7 +321,7 @@ export async function trainRebuild(ctx: QueueContext, o: { train: string; infra:
if (b.outcome.kind !== 'unattributed' || !b.outcome.all_green) return refuse(`the bisect was not all green (${Object.entries(b.outcome.patterns).map(([c, s]) => `${c}=${s}`).join(' ')})`);
}
const tip = remoteBranchSha(args => git(ctx.repoRoot, args), env.remote, t.branch);
if (tip !== t.head) return outRefused({ code: 'QUEUE_TRAIN_MOVED', message: `${t.branch} is at ${tip?.slice(0, 12) ?? 'nothing'}, not the recorded head ${t.head.slice(0, 12)}` }, [], `${Q} train build --prs ${pinList(t.slots)}`, run);
if (tip !== t.head) return outRefused({ code: 'QUEUE_TRAIN_MOVED', message: `${t.branch} is at ${tip?.slice(0, 12) ?? 'nothing'}, not the recorded head ${t.head.slice(0, 12)}` }, [], `${Q} train build ${prsArgs(t.slots, t.explicit_order)}`, run);
const slug = repoSlug(ctx);
if (!slug) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: 'gh repo view could not name the repository' }, [], `${Q} train rebuild --train ${t.nonce}${o.infra ? ' --infra' : ''}`, run);
const a = await dispatchAttempt(env, slug, t, o.infra ? 'infra-redispatch' : 'rebuild', gateDispatch(env, t, `${t.nonce}.${gates.length + 1}`));
+39 -8
View File
@@ -20,8 +20,9 @@ import { git } from './ship-queue-gate';
import { checkRun, execFor, repoSlug } from './ship-queue-train-github';
import { activeFreeze, attemptsOf, nowIso, persist, trainFile, type FreezeRecord, type TrainRecord } from './ship-queue-train-record';
import {
effect, fetchBase, fetchTrainBranch, findTrain, frozenLines, nextFor, outFailed, outOk, outRefused, pinList, save, trainEnv, type TrainEnv, type TrainOut,
effect, fetchBase, fetchTrainBranch, findTrain, frozenLines, nextFor, outFailed, outOk, outRefused, pinList, prsArgs, save, trainEnv, type TrainEnv, type TrainOut,
} from './ship-queue-train';
import { ownEntryAboveMain } from './changelog-check';
import { buildReceipt } from './tree-receipt';
const Q = 'gstack-ship-queue';
@@ -32,6 +33,37 @@ function sameModuloStamps(env: TrainEnv, gated: string, current: string): { same
return { same: r.tree === 'same-modulo-stamps', detail: r.tree === 'same-modulo-stamps' ? `same modulo stamps (${r.files.length} stamp file(s))` : `differs: ${r.residual.slice(0, 8).join(', ')}` };
}
/**
* A slot head with main merged in (from slot 2 on the lane merges main into
* its pin so GitHub can merge it): it must contain main, and its tree must be
* the slot's prefix T<i> modulo stamps. The CHANGELOG is judged against main
* instead of T<i>'s mechanical merge, so a hand resolve is accepted when it
* is main's CHANGELOG plus the PR's own entry (ownEntryAboveMain); any other
* difference is refused.
*/
function mergedIn(env: TrainEnv, t: TrainRecord, i: number, head: string, main: string): { same: boolean; detail: string } {
const after = t.prefixes[i + 1]!;
const root = env.ctx.repoRoot;
if (!git(root, ['merge-base', '--is-ancestor', main, head]).ok) return { same: false, detail: `does not contain main ${main.slice(0, 12)}` };
const r = buildReceipt({ repoRoot: root, gated: after.commit, current: head, policy: env.policy.policy, policyLabel: env.policy.source.label });
if ('error' in r) return { same: false, detail: r.error };
const stamps = `${r.files.filter(f => f.verdict === 'stamp').length} stamp file(s)`;
if (r.tree === 'same-modulo-stamps') return { same: true, detail: `T${after.index} with main merged in, same modulo stamps (${stamps})` };
const cl = env.policy.policy.changelog;
const beyond = r.residual.filter(f => f !== cl);
if (beyond.length || !cl) return { same: false, detail: `differs from T${after.index}: ${r.residual.slice(0, 8).join(', ')}` };
const pin = t.slots[i]!.head;
const forkPoint = git(root, ['merge-base', pin, t.prefixes[0]!.commit]).out;
const diff = git(root, ['diff', '--unified=0', '--no-color', '--no-ext-diff', forkPoint, pin, '--', cl]);
const show = (rev: string) => git(root, ['show', `${rev}:${cl}`]);
const [headCl, mainCl] = [show(head), show(main)];
if (!forkPoint || !diff.ok || !headCl.ok || !mainCl.ok) return { same: false, detail: `cannot read ${cl} at the pin, the head or main` };
const authored = new Set(diff.out.split('\n').filter(l => l.startsWith('+') && !l.startsWith('+++')).map(l => l.slice(1)));
const why = ownEntryAboveMain(headCl.out, mainCl.out, authored);
if (why) return { same: false, detail: `differs from T${after.index} in ${cl}, which is not main's plus #${t.slots[i]!.pr}'s own entry: ${why}` };
return { same: true, detail: `T${after.index} with main merged in, same modulo stamps (${stamps}) except ${cl}, resolved as main's ${cl} plus #${t.slots[i]!.pr}'s own entry` };
}
/**
* Freeze the queue: the record goes to local state and the notes ref before
* anything remote, then the backstop gate is dispatched on main's sha.
@@ -61,8 +93,8 @@ async function freezeQueue(env: TrainEnv, t: TrainRecord, reason: string, mainSh
/** Interrupted publication: freeze when earlier slots merged; otherwise a plain refusal (nothing was published). */
async function stopped(env: TrainEnv, t: TrainRecord, code: 'QUEUE_TRAIN_TREE_MISMATCH' | 'QUEUE_TRAIN_MOVED', message: string, mainSha: string, lines: string[]): Promise<TrainOut> {
const run = trainFile(t.nonce);
if (!t.merged.length) return outFailed({ code, message: `${message}; nothing of train ${t.nonce} merged, so the queue is not frozen` }, lines, `${Q} train build --prs ${pinList(t.slots)} (a new train on current main)`, run);
const f = activeFreeze(env.repo.key) ?? await freezeQueue(env, t, message, mainSha);
if (!t.merged.length) return outFailed({ code, message: `${message}; nothing of train ${t.nonce} merged, so the queue is not frozen` }, lines, `${Q} train build ${prsArgs(t.slots, t.explicit_order)} (a new train on current main)`, run);
const f = activeFreeze(env.repo.keys) ?? await freezeQueue(env, t, message, mainSha);
return outFailed({ code, message: `${message}; the queue is frozen` }, [...lines, ...frozenLines(f)], `${Q} train build --repair --prs <repair-pr>@<sha>`, run);
}
@@ -84,7 +116,7 @@ export async function verifyTrain(ctx: QueueContext, o: { pr: string; train: str
if (check?.conclusion !== 'success') return outRefused({ code: 'QUEUE_GATE_MISSING', message: `no successful ${env.train.full_gate_check} check run on the train head ${t.head.slice(0, 12)}` }, [], `${Q} train verdict --train ${t.nonce}`, run);
if (!fetchTrainBranch(env, t)) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: `the train's prefix commits are not here and ${t.branch} could not be fetched` }, [], `${Q} train status --train ${t.nonce}`, run);
const main = git(ctx.repoRoot, ['rev-parse', `${env.remote}/${ctx.base}`]).out;
const freeze = activeFreeze(env.repo.key);
const freeze = activeFreeze(env.repo.keys);
if (freeze && freeze.repair?.train !== t.nonce) return outRefused({ code: 'QUEUE_TRAIN_FROZEN', message: `the queue is frozen (${freeze.reason}); only the admitted repair train merges` }, frozenLines(freeze), `${Q} train build --repair --prs <repair-pr>@<sha>`, run);
const after = t.prefixes[i + 1]!;
const before = t.prefixes[i]!;
@@ -98,9 +130,8 @@ export async function verifyTrain(ctx: QueueContext, o: { pr: string; train: str
const headRef = o.noFetch ? '' : (git(ctx.repoRoot, ['fetch', '--no-tags', '-q', env.remote, `+refs/pull/${o.pr}/head:refs/gstack/queue/pr-${o.pr}`]).ok ? `refs/gstack/queue/pr-${o.pr}` : '');
const head = headRef ? git(ctx.repoRoot, ['rev-parse', headRef]).out : t.slots[i]!.head;
const pinned = head === t.slots[i]!.head ? { same: true, detail: 'the pinned head' } : sameModuloStamps(env, t.slots[i]!.head, head);
const asPrefix = pinned.same ? null : sameModuloStamps(env, after.commit, head);
const stampOnly = asPrefix?.same ? { same: true, detail: `T${after.index} with main merged in, ${asPrefix.detail}` } : pinned;
if (!stampOnly.same) return stopped(env, t, 'QUEUE_TRAIN_MOVED', `#${o.pr} moved past its pinned head ${t.slots[i]!.head.slice(0, 12)} and is not T${after.index} modulo stamps (${head.slice(0, 12)}: ${pinned.detail})`, main, lines);
const stampOnly = pinned.same ? pinned : mergedIn(env, t, i, head, main);
if (!stampOnly.same) return stopped(env, t, 'QUEUE_TRAIN_MOVED', `#${o.pr} moved past its pinned head ${t.slots[i]!.head.slice(0, 12)} and is not T${after.index} modulo stamps (${head.slice(0, 12)}: ${stampOnly.detail}; against the pin it ${pinned.detail})`, main, lines);
return outOk([...lines, `main: ${main} = T${before.index} (${pre.detail})`, `head: ${head} (${stampOnly.detail})`,
`VERIFY_TRAIN: #${o.pr} may merge as slot ${i + 1} of train ${t.nonce} (green run ${gate.run?.id ?? '-'}, ${env.train.full_gate_check} success)`, `MERGE_CONDITION: sha=${head}`],
`merge #${o.pr} with expected head ${head.slice(0, 12)} (gstack-restamp stamps at merge), then ${Q} verify --pr ${o.pr} --train ${t.nonce}`, run);
@@ -113,7 +144,7 @@ function confirmMerged(env: TrainEnv, t: TrainRecord, pr: string, main: string,
effect(t, `verified #${pr} merged as T${index}`);
save(env, t);
lines.push(`VERIFY_TRAIN: #${pr} merged; main's tree is T${index} of train ${t.nonce} (${t.merged.length}/${t.slots.length} merged)`);
const freeze = activeFreeze(env.repo.key);
const freeze = activeFreeze(env.repo.keys);
if (freeze && freeze.repair?.train === t.nonce && t.state === 'merged') {
freeze.cleared_at = nowIso();
freeze.cleared_by = `repair #${pr} via train ${t.nonce}; main ${main.slice(0, 12)} carries a green record`;
+53 -25
View File
@@ -16,7 +16,7 @@
*/
import { randomBytes } from 'node:crypto';
import { DISPATCH_INPUTS, awaitNonceRun, dispatchWorkflow, listDispatchRuns, makeNonce, runForNonce, type WorkflowDispatch } from '../scripts/eval-bg';
import { mergeChangelogs, parseChangelog, type ChangelogSection } from './changelog-check';
import { changelogDamage, mergeChangelogs, parseChangelog, type ChangelogSection } from './changelog-check';
import type { ResultStatus } from './headless-artifacts';
import { versionAtRef, versionFiles } from './restamp';
import type { LoadedPolicy, ShipPolicy, TrainPolicy } from './ship-policy';
@@ -34,7 +34,7 @@ export const outRefused = (failure: QueueFailure, lines: string[], next: string,
export const outFailed = (failure: QueueFailure, lines: string[], next: string, run: string): TrainOut => ({ exit: 1, status: 'refused', lines, next, failure, run });
export const outPending = (failure: QueueFailure, lines: string[], next: string, run: string): TrainOut => ({ exit: 3, status: 'incomplete', lines, next, failure, run });
export interface TrainEnv { ctx: QueueContext; policy: LoadedPolicy; train: TrainPolicy; repo: { key: string; url: string }; remote: string }
export interface TrainEnv { ctx: QueueContext; policy: LoadedPolicy; train: TrainPolicy; repo: { key: string; url: string; keys: string[] }; remote: string }
const HEX = /^[0-9a-f]{40,64}$/;
const Q = 'gstack-ship-queue';
@@ -92,9 +92,20 @@ export function parsePins(spec: string | undefined): Array<{ pr: string; sha: st
}
export const pinList = (slots: Array<{ pr: string; head: string }>) => slots.map(s => `${s.pr}@${s.head}`).join(',');
/** `--prs <pins>` for a rebuild of these slots, plus `--order` when the train was built with an explicit order. */
export const prsArgs = (slots: Array<{ pr: string; head: string }>, explicit?: boolean) => `--prs ${pinList(slots)}${explicit ? ` --order ${slots.map(s => s.pr).join(',')}` : ''}`;
/** Slot order: screened PRs first, then unscreened, each in READY order; enough unscreened PRs form their own train. */
export function orderSlots(slots: TrainSlot[], max: number): { train: TrainSlot[]; held: TrainSlot[]; split: boolean } {
/**
* Slot order: screened PRs first, then unscreened, each in READY order;
* enough unscreened PRs form their own train. An explicit order (`--order`,
* every admitted PR once) replaces that rule: slots follow it, the first
* `max` ride and the rest are held.
*/
export function orderSlots(slots: TrainSlot[], max: number, explicit?: readonly string[]): { train: TrainSlot[]; held: TrainSlot[]; split: boolean } {
if (explicit) {
const all = explicit.map(pr => slots.find(s => s.pr === pr)!);
return { train: all.slice(0, max), held: all.slice(max), split: false };
}
const byReady = (a: TrainSlot, b: TrainSlot) => a.ready_at.localeCompare(b.ready_at) || Number(a.pr) - Number(b.pr);
const screened = slots.filter(s => s.screen.choice === 'screen').sort(byReady);
const unscreened = slots.filter(s => s.screen.choice !== 'screen').sort(byReady);
@@ -130,7 +141,9 @@ function unionChangelog(ours: string, theirs: string): string {
* One train merge, in object storage: the PR head onto the previous prefix.
* Version files take the prefix's side; the CHANGELOG merges by section (the
* gate-ahead rule, else a union of sections, since each heading is restamped
* at merge). Any other conflict is reported with every conflicting path.
* at merge), unless a side damaged released history (changelogDamage), which
* is a conflict the lane resolves. Any other conflict is reported with every
* conflicting path.
*/
export function mergeStep(repoRoot: string, pred: string, head: string, policy: ShipPolicy): { tree: string } | { conflicts: string[] } {
const r = git(repoRoot, ['merge-tree', '--write-tree', head, pred]);
@@ -157,6 +170,9 @@ export function mergeStep(repoRoot: string, pred: string, head: string, policy:
if (!ours || !theirs) conflicts.push(file);
else if (file === policy.changelog) {
const text = (sha: string) => git(repoRoot, ['cat-file', 'blob', sha]).out + '\n';
const base = entry.get(1);
const damage = changelogDamage(text(ours), text(theirs), base ? text(base) : undefined);
if (damage) { conflicts.push(`${file} (${damage})`); continue; }
const merged = mergeChangelogs(text(ours), text(theirs)) ?? unionChangelog(text(ours), text(theirs));
const blob = git(repoRoot, ['hash-object', '-w', '--stdin'], undefined, merged);
if (blob.ok) resolved.push({ path: file, blob: blob.out }); else conflicts.push(file);
@@ -207,12 +223,12 @@ export function nextFor(t: TrainRecord): string {
case 'attributed': {
const drop = loadBisect(n)?.outcome?.prs ?? [];
const keep = t.slots.filter(s => !drop.includes(s.pr));
return keep.length ? `${Q} train build --prs ${pinList(keep)}` : 'none (every PR was dropped)';
return keep.length ? `${Q} train build ${prsArgs(keep, t.explicit_order)}` : 'none (every PR was dropped)';
}
case 'red-on-main': return `fix forward on main first, then ${Q} train build --prs ${pinList(t.slots)}`;
case 'red-on-main': return `fix forward on main first, then ${Q} train build ${prsArgs(t.slots, t.explicit_order)}`;
case 'unattributed': return loadBisect(n)?.outcome?.all_green && !attemptsOf(t).some(a => a.purpose === 'rebuild')
? `${Q} train rebuild --train ${n}`
: `route the red cases to a repair lane (GStack Minder); once the repair merges: ${Q} train build --prs ${pinList(t.slots)}`;
: `route the red cases to a repair lane (GStack Minder); once the repair merges: ${Q} train build ${prsArgs(t.slots, t.explicit_order)}`;
default: return `${Q} train prune --train ${n}`;
}
}
@@ -249,7 +265,17 @@ export function gateDispatch(env: TrainEnv, train: TrainRecord, nonce: string):
return { workflow: env.train.gate_workflow, inputs: { [DISPATCH_INPUTS.evalsAll]: 'true', [DISPATCH_INPUTS.expectedSha]: train.head, [DISPATCH_INPUTS.nonce]: nonce } };
}
export interface BuildOptions { pins?: string; resume?: string; dryRun: boolean; urgent: boolean; repair: boolean; freeTimeoutSec: number; pollMs: number }
export interface BuildOptions { pins?: string; order?: string; resume?: string; dryRun: boolean; urgent: boolean; repair: boolean; freeTimeoutSec: number; pollMs: number }
/** `--order <pr>,<pr>,...`: every pinned PR exactly once (a leading # allowed). */
export function parseOrder(spec: string | undefined, pins: Array<{ pr: string }>): string[] | undefined | { error: string } {
if (spec === undefined) return undefined;
const order = spec.split(',').map(s => s.trim().replace(/^#/, '')).filter(Boolean);
const want = pins.map(p => p.pr).sort((a, b) => Number(a) - Number(b));
const got = [...order].sort((a, b) => Number(a) - Number(b));
if (order.some(pr => !/^\d+$/.test(pr)) || got.join(',') !== want.join(',')) return { error: `--order must list every PR in --prs exactly once (--prs has ${want.map(p => '#' + p).join(',')}; got ${spec})` };
return order;
}
/** The slots a new train would carry: trusted, unmoved, READY PRs, in slot order. */
function admitSlots(env: TrainEnv, pins: Array<{ pr: string; sha: string }>): { slots: TrainSlot[]; lines: string[] } | TrainOut {
@@ -267,7 +293,7 @@ function admitSlots(env: TrainEnv, pins: Array<{ pr: string; sha: string }>): {
if (!info.headRefOid.startsWith(p.sha) || fetched !== info.headRefOid) {
return outRefused({ code: 'QUEUE_TRAIN_MOVED', message: `PR #${p.pr} moved: pinned ${p.sha.slice(0, 12)}, head is now ${info.headRefOid.slice(0, 12)}` }, [], `ask #${p.pr}'s lane for READY on ${info.headRefOid.slice(0, 12)}, then ${Q} train build --prs <pins>`, 'none');
}
const ready = loadReady(env.repo.key, p.pr, info.headRefOid);
const ready = loadReady(env.repo.keys, p.pr, info.headRefOid);
if (!ready) return outRefused({ code: 'QUEUE_NOT_READY', message: `no READY receipt for #${p.pr} at ${info.headRefOid.slice(0, 12)} (local state or ${'refs/notes/gstack-trains'})` }, [], `the lane runs ${Q} ready --pr ${p.pr} --screen|--no-screen`, 'none');
slots.push({ pr: p.pr, head: info.headRefOid, ready_at: ready.ready_at, screen: ready.screen });
}
@@ -280,28 +306,30 @@ async function newTrain(env: TrainEnv, o: BuildOptions): Promise<{ t: TrainRecor
if (typeof pins === 'string') return outRefused({ code: 'QUEUE_PROOF_MISSING', message: pins }, [], 'none', 'none');
if ((o.urgent || o.repair) && pins.length !== 1) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: `${o.repair ? '--repair' : '--urgent'} admits exactly one PR` }, [], 'none', 'none');
rebuildFromNotes(env.ctx.repoRoot, env.remote);
const freeze = activeFreeze(env.repo.key);
const freeze = activeFreeze(env.repo.keys);
if (freeze && !o.repair) return outRefused({ code: 'QUEUE_TRAIN_FROZEN', message: `the queue is frozen since ${freeze.created_at}: train ${freeze.train} stopped after merging ${freeze.merged.map(p => '#' + p).join(',')} (${freeze.reason})` },
frozenLines(freeze), `${Q} train build --repair --prs <repair-pr>@<sha>`, 'none');
const explicit = parseOrder(o.order, pins);
if (explicit && 'error' in explicit) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: explicit.error }, [], 'none', 'none');
const admitted = admitSlots(env, pins);
if ('exit' in admitted) return admitted;
const order = orderSlots(admitted.slots, o.repair ? 1 : env.train.max_size);
const order = orderSlots(admitted.slots, o.repair ? 1 : env.train.max_size, explicit);
const lines = [
`ORDER: ${order.train.map((s, i) => `${i + 1}:#${s.pr}(${s.screen.choice === 'screen' ? 'screened' : 'unscreened'})`).join(' ')}`,
`ORDER: ${order.train.map((s, i) => `${i + 1}:#${s.pr}(${s.screen.choice === 'screen' ? 'screened' : 'unscreened'})`).join(' ')}${explicit ? ' (explicit --order)' : ''}`,
...(order.held.length ? [`HELD: ${order.held.map(s => '#' + s.pr).join(',')} (${order.split ? 'unscreened PRs form their own train' : `over the train size ${env.train.max_size}`})`] : []),
];
const due = fillDue(order.train, env.train, nowIso(), o.urgent || o.repair);
if (due && !o.dryRun) return outPending({ code: 'QUEUE_TRAIN_WAITING', message: `${order.train.length} of ${env.train.max_size} PRs; the oldest READY dispatches at ${due}` }, lines, `${Q} train build --prs ${pinList(order.train)} (after ${due}, or with more PRs, or --urgent for one)`, 'none');
if (due && !o.dryRun) return outPending({ code: 'QUEUE_TRAIN_WAITING', message: `${order.train.length} of ${env.train.max_size} PRs; the oldest READY dispatches at ${due}` }, lines, `${Q} train build ${prsArgs(order.train, !!explicit)} (after ${due}, or with more PRs, or --urgent for one)`, 'none');
const baseSha = git(env.ctx.repoRoot, ['rev-parse', `${env.remote}/${env.ctx.base}`]).out;
const key = sha256(JSON.stringify({ base: baseSha, slots: order.train.map(s => `${s.pr}@${s.head}`) }));
const live = listTrains(env.repo.key).find(t => t.key === key && !TERMINAL_STATES.includes(t.state) && t.state !== 'red' && t.state !== 'unattributed');
const live = listTrains(env.repo.keys).find(t => t.key === key && !TERMINAL_STATES.includes(t.state) && t.state !== 'red' && t.state !== 'unattributed');
if (live) return { t: Object.assign(live, { held: order.held.map(s => s.pr) }), lines };
const chain = buildChain(env.ctx.repoRoot, baseSha, order.train, env.policy.policy);
if ('stoppedAt' in chain) {
const without = order.train.filter(s => s.pr !== chain.stoppedAt);
return outFailed({ code: 'QUEUE_TRAIN_CONFLICT', message: `#${chain.stoppedAt} conflicts with the prefix before it` }, [...lines,
`QUEUE_TRAIN_CONFLICT: train ${key.slice(0, 12)} stopped at #${chain.stoppedAt} (conflicts: ${chain.conflicts.join(', ')}) after merging ${chain.merged.map(p => '#' + p).join(',') || '(none)'}; nothing dispatched, no branch pushed; fix: ${Q} train build --prs ${pinList(without)}`],
without.length ? `${Q} train build --prs ${pinList(without)}` : 'none', 'none');
`QUEUE_TRAIN_CONFLICT: train ${key.slice(0, 12)} stopped at #${chain.stoppedAt} (conflicts: ${chain.conflicts.join(', ')}) after merging ${chain.merged.map(p => '#' + p).join(',') || '(none)'}; nothing dispatched, no branch pushed; fix: ${Q} train build ${prsArgs(without, !!explicit)}`],
without.length ? `${Q} train build ${prsArgs(without, !!explicit)}` : 'none', 'none');
}
const head = chain.prefixes.at(-1)!;
const nonce = makeNonce('gate', head.commit, baseSha, randomBytes(3).toString('hex'), { purpose: 'train' });
@@ -309,7 +337,7 @@ async function newTrain(env: TrainEnv, o: BuildOptions): Promise<{ t: TrainRecor
return { lines, t: {
schema: 1, kind: 'train', nonce, key, repo_key: env.repo.key, repo: env.repo.url, base: { ref: env.ctx.base, sha: baseSha }, policy: env.policy.source.label,
slots: order.train, held: order.held.map(s => s.pr), prefixes: chain.prefixes, head: head.commit, tree: head.tree, branch: `train/${nonce}`,
urgent: o.urgent, repair: o.repair, state: 'built', free: null, attempts: [], merged: [], superseded_by: null, effects: [], error: null,
urgent: o.urgent, repair: o.repair, ...(explicit ? { explicit_order: true } : {}), state: 'built', free: null, attempts: [], merged: [], superseded_by: null, effects: [], error: null,
created_at: now, updated_at: now,
} };
}
@@ -342,7 +370,7 @@ async function freePhase(env: TrainEnv, slug: string, t: TrainRecord, o: BuildOp
t.state = 'free-red';
effect(t, `${env.train.free_workflow} dispatch refused by gh`);
save(env, t);
return outFailed({ code: 'QUEUE_TRAIN_FREE_RED', message: `gh could not dispatch ${env.train.free_workflow} on ${t.branch}` }, describe(t), `${Q} train build --prs ${pinList(t.slots)}`, run);
return outFailed({ code: 'QUEUE_TRAIN_FREE_RED', message: `gh could not dispatch ${env.train.free_workflow} on ${t.branch}` }, describe(t), `${Q} train build ${prsArgs(t.slots, t.explicit_order)}`, run);
}
t.state = 'free-pending';
effect(t, `${env.train.free_workflow} dispatched on ${t.branch}`);
@@ -422,12 +450,12 @@ export async function buildTrain(ctx: QueueContext, o: BuildOptions): Promise<Tr
if (!('kind' in t)) return t;
if (o.dryRun) {
return outOk([...lines, ...describe(t), `ESTIMATE: one ${env.train.gate_workflow} full gate (evals_all) on T${t.prefixes.length - 1} plus ${env.train.free_workflow}; dollar figure pending the T0 cost replay (lib/gate-cost.ts)`,
'DRY-RUN: nothing written, pushed or dispatched'], `${Q} train build --prs ${pinList(t.slots)}`, 'none');
'DRY-RUN: nothing written, pushed or dispatched'], `${Q} train build ${prsArgs(t.slots, t.explicit_order)}`, 'none');
}
if (t.state === 'built' && !t.attempts.length && !loadTrain(t.nonce)) {
effect(t, 'train.json written');
save(env, t);
for (const old of listTrains(env.repo.key)) {
for (const old of listTrains(env.repo.keys)) {
if (old.nonce === t.nonce || TERMINAL_STATES.includes(old.state) || old.state === 'green' || old.state === 'merging') continue;
if (!old.slots.some(s => t.slots.some((n: TrainSlot) => n.pr === s.pr))) continue;
old.state = 'superseded';
@@ -435,7 +463,7 @@ export async function buildTrain(ctx: QueueContext, o: BuildOptions): Promise<Tr
save(env, old);
}
if (o.repair) {
const f = activeFreeze(env.repo.key)!;
const f = activeFreeze(env.repo.keys)!;
f.repair = { pr: t.slots[0]!.pr, head: t.slots[0]!.head, train: t.nonce };
f.updated_at = nowIso();
persist(env.ctx.repoRoot, [f], { remote: env.remote });
@@ -454,7 +482,7 @@ export function trainStatus(ctx: QueueContext, o: { train?: string }): TrainOut
if ('code' in env) return outRefused(env, [], 'none', 'none');
const restored = rebuildFromNotes(ctx.repoRoot, env.remote);
const lines = [`NOTES: read ${restored.read} record(s), restored ${restored.restored} (${restored.detail})`];
const trains = o.train ? [loadTrain(o.train)].filter((t): t is TrainRecord => !!t) : listTrains(env.repo.key).filter(t => !TERMINAL_STATES.includes(t.state));
const trains = o.train ? [loadTrain(o.train)].filter((t): t is TrainRecord => !!t) : listTrains(env.repo.keys).filter(t => !TERMINAL_STATES.includes(t.state));
if (o.train && !trains.length) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: `no train record ${o.train} here or in refs/notes/gstack-trains` }, lines, `${Q} train status`, 'none');
const slug = trains.length ? repoSlug(ctx) : null;
const exec = execFor(ctx);
@@ -482,7 +510,7 @@ export function trainStatus(ctx: QueueContext, o: { train?: string }): TrainOut
lines.push(`NEXT(${t.nonce}): ${nextFor(t)}`);
}
if (!trains.length) lines.push('TRAIN: none live');
const freeze = activeFreeze(env.repo.key);
const freeze = activeFreeze(env.repo.keys);
if (freeze) lines.push(...frozenLines(freeze));
const single = trains.length === 1 ? trains[0]! : null;
const next = freeze && !freeze.repair ? `${Q} train build --repair --prs <repair-pr>@<sha>` : single ? nextFor(single) : trains.length ? 'see each NEXT(<nonce>) line' : 'none';
@@ -496,7 +524,7 @@ export function pruneTrains(ctx: QueueContext, o: { dryRun: boolean; train?: str
rebuildFromNotes(ctx.repoRoot, env.remote);
const lines: string[] = [];
const rgit = (args: string[]) => git(ctx.repoRoot, args);
for (const t of listTrains(env.repo.key).filter(x => !o.train || x.nonce === o.train)) {
for (const t of listTrains(env.repo.keys).filter(x => !o.train || x.nonce === o.train)) {
if (!TERMINAL_STATES.includes(t.state)) { lines.push(`KEEP: ${t.branch} (${t.state})`); continue; }
if (!remoteBranchSha(rgit, env.remote, t.branch)) { lines.push(`GONE: ${t.branch} (${t.state})`); continue; }
if (o.dryRun) { lines.push(`WOULD-DELETE: ${t.branch} (${t.state})`); continue; }
+10 -3
View File
@@ -18,7 +18,7 @@ export type TrainHead =
| { kind: 'invalid'; reason: string };
function git(repoRoot: string, args: string[]): string | null {
const r = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 });
const r = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024 });
return r.status === 0 ? r.stdout : null;
}
@@ -50,11 +50,18 @@ export function classifyTrainHead(o: { repoRoot: string; baseRef: string; head:
}
const file = typeof policy.changelog === 'string' ? policy.changelog : 'CHANGELOG.md';
const before = parseChangelog(show(mergeBase, file) ?? '');
const after = parseChangelog(show(o.head, file) ?? '');
const exists = (rev: string) => git(o.repoRoot, ['cat-file', '-e', `${rev}:${file}`]) !== null;
const read = (rev: string) => (exists(rev) ? show(rev, file) : '');
const [beforeText, afterText] = [read(mergeBase), read(o.head)];
if (beforeText === null || afterText === null) return { kind: 'invalid', reason: `cannot read ${file} at ${beforeText === null ? `the merge base ${mergeBase.slice(0, 12)}` : o.head}` };
const before = parseChangelog(beforeText);
const after = parseChangelog(afterText);
const unreleased = after.sections.filter(s => s.unreleased);
if (unreleased.length > 1) return { kind: 'invalid', reason: `${file} has ${unreleased.length} [Unreleased] sections` };
if (unreleased.length === 1 && after.sections[0] !== unreleased[0]) return { kind: 'invalid', reason: `${file}: [Unreleased] must be the top section` };
const kept = new Set(after.sections.filter(s => !s.unreleased).map(s => s.version));
const dropped = before.sections.filter(s => !s.unreleased && !kept.has(s.version)).map(s => s.version);
if (dropped.length) return { kind: 'invalid', reason: `${file} drops released heading ${dropped.slice(0, 3).join(', ')}${dropped.length > 3 ? ` (+${dropped.length - 3})` : ''}; an unstamped head may only add its [Unreleased] section above the latest release` };
const released = (c: typeof after) => [c.header.join('\n'), ...c.sections.filter(s => !s.unreleased).map(s => s.lines.join('\n'))];
const was = released(before);
const now = released(after);
+1 -1
View File
@@ -509,7 +509,7 @@ SLUG=$(~/.claude/skills/gstack/bin/gstack-slug --get SLUG 2>/dev/null)
```
1. Read `CLAUDE.md`, `TODOS.md` (if they exist).
2. Run `git log --oneline -30` and `git diff origin/main --stat 2>/dev/null` to understand recent context.
2. Run `git log --oneline -30` and `git diff origin/HEAD --stat` (default branch) to grasp recent context.
3. Use Grep/Glob to map the codebase areas most relevant to the user's request.
4. **List existing design docs for this project:**
```bash
+1 -1
View File
@@ -81,7 +81,7 @@ Understand the project and the area the user wants to change.
```
1. Read `CLAUDE.md`, `TODOS.md` (if they exist).
2. Run `git log --oneline -30` and `git diff origin/main --stat 2>/dev/null` to understand recent context.
2. Run `git log --oneline -30` and `git diff origin/HEAD --stat` (default branch) to grasp recent context.
3. Use Grep/Glob to map the codebase areas most relevant to the user's request.
4. **List existing design docs for this project:**
```bash
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gstack",
"version": "1.91.191",
"version": "1.91.201",
"description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.",
"license": "MIT",
"type": "module",
+1 -1
View File
@@ -467,7 +467,7 @@ only under the Step 0.5 conditions (no UI scope, designer unavailable, or the us
Commands: `generate` (single mockup), `variants` (multiple directions), `compare`
(side-by-side review board), `iterate` (refine with feedback), `check` (cross-model
quality gate via GPT-4o vision), `evolve` (improve from screenshot).
quality gate via OpenAI vision), `evolve` (improve from screenshot).
Setup is handled by the DESIGN SETUP section below. If `DESIGN_READY` is printed,
the designer is available and you should use it.
+1 -1
View File
@@ -85,7 +85,7 @@ only under the Step 0.5 conditions (no UI scope, designer unavailable, or the us
Commands: `generate` (single mockup), `variants` (multiple directions), `compare`
(side-by-side review board), `iterate` (refine with feedback), `check` (cross-model
quality gate via GPT-4o vision), `evolve` (improve from screenshot).
quality gate via OpenAI vision), `evolve` (improve from screenshot).
Setup is handled by the DESIGN SETUP section below. If `DESIGN_READY` is printed,
the designer is available and you should use it.
+82
View File
@@ -0,0 +1,82 @@
/**
* CHANGELOG merges that would carry damage to released history (GSTA-67,
* from #3345 on 2026-10-22). #3345's pin 1eb7092 replaced main's
* `## [1.91.179.0]` heading with `## [Unreleased]` instead of inserting
* above it, and mergeChangelogs returned non-null output with 179's body
* duplicated into [Unreleased]; the train's T1 6755ab8 carried it. The
* fixtures under test/fixtures/merge-train-3345/ are the real CHANGELOGs at
* those commits, cut below 1.91.177.0. A null merge means a hand resolve.
*/
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { changelogDamage, mergeChangelogs, ownEntryAboveMain, parseChangelog } from '../lib/changelog-check';
const fixture = (name: string) => fs.readFileSync(path.join(import.meta.dir, 'fixtures', 'merge-train-3345', name), 'utf8');
const base = fixture('base-a59b5e4.md');
const pin = fixture('pin-1eb7092.md');
const main = fixture('main-4a98e40.md');
const keys = (text: string) => parseChangelog(text).sections.map(s => s.version ?? 'Unreleased');
describe('mergeChangelogs refuses damage to released history', () => {
test('GSTA-64 repro: a released heading replaced by [Unreleased] is null, not a merge with the 1.0.1 body duplicated', () => {
const ours = '# Changelog\n\n## [Unreleased]\n\nNew entry.\n\nOld 1.0.1 body.\n\n## [1.0.0] - d\n\nOld 1.0.0 body.\n';
const theirs = '# Changelog\n\n## [1.0.2] - d\n\nMain body.\n\n## [1.0.1] - d\n\nOld 1.0.1 body.\n\n## [1.0.0] - d\n\nOld 1.0.0 body.\n';
expect(changelogDamage(ours, theirs)).toContain("ours's Unreleased section holds released 1.0.1 text");
expect(mergeChangelogs(ours, theirs)).toBeNull();
const baseText = '# Changelog\n\n## [1.0.1] - d\n\nOld 1.0.1 body.\n\n## [1.0.0] - d\n\nOld 1.0.0 body.\n';
expect(changelogDamage(ours, theirs, baseText)).toBe('ours drops released heading 1.0.1 that the merge base carries');
});
test('#3345: pin 1eb7092 against main 4a98e40 is null with or without the merge base; the train T1 it produced duplicated 179', () => {
expect(changelogDamage(pin, main, base)).toBe('ours drops released heading 1.91.179.0 that the merge base carries');
expect(changelogDamage(pin, main)).toMatch(/^ours's Unreleased section holds released 1\.91\.179\.0 text/);
expect(mergeChangelogs(pin, main, base)).toBeNull();
expect(mergeChangelogs(pin, main)).toBeNull();
const t1 = fixture('train-T1-6755ab8.md');
expect(keys(t1)).toEqual(['Unreleased', '1.91.181.0', '1.91.180.0', '1.91.179.0', '1.91.178.0', '1.91.177.0']);
expect(changelogDamage(t1, main)).toMatch(/^ours's Unreleased section holds released 1\.91\.179\.0 text/);
});
test('either side, and a renamed heading, count as damage', () => {
expect(changelogDamage(main, pin, base)).toBe('theirs drops released heading 1.91.179.0 that the merge base carries');
const renamed = main.replace('## [1.91.178.0]', '## [1.91.178.9]');
expect(changelogDamage(renamed, main, base)).toBe('ours drops released heading 1.91.178.0 that the merge base carries');
expect(changelogDamage(renamed, main)).toMatch(/^ours's 1\.91\.178\.9 section holds released 1\.91\.178\.0 text/);
});
test('negative controls: the real hand resolve, an entry above a newer main, a shared tentative stamp and two [Unreleased] blocks are not damage', () => {
const fixed = pin.replace(/\n\n\*\*docsync-fault-interface/, '\n\n## [1.91.179.0] - 2026-10-22\n\n**docsync-fault-interface');
expect(keys(fixed)).toEqual(['Unreleased', '1.91.179.0', '1.91.178.0', '1.91.177.0']);
expect(changelogDamage(fixed, main, base)).toBeNull();
const merged = mergeChangelogs(fixed, main, base)!;
expect(keys(merged)).toEqual(['Unreleased', '1.91.181.0', '1.91.180.0', '1.91.179.0', '1.91.178.0', '1.91.177.0']);
expect(merged.split('**docsync-fault-interface fits its budgets').length).toBe(2);
const b = '## [1.2.3.0] - d\n\n- base release entry\n';
expect(mergeChangelogs(`# C\n\n## [1.2.4.0] - d\n\n- mine, a new entry\n\n${b}`, `# C\n\n## [1.2.4.0] - e\n\n- theirs, a new entry\n\n${b}`, `# C\n\n${b}`)).not.toBeNull();
expect(changelogDamage(`# C\n\n## [Unreleased]\n\n- #2 change, its entry\n\n${b}`, `# C\n\n## [Unreleased]\n\n- #1 change, its entry\n\n${b}`, `# C\n\n${b}`)).toBeNull();
});
});
describe("ownEntryAboveMain: a merged-in head's CHANGELOG however it was resolved", () => {
const dir = path.join(import.meta.dir, 'fixtures', 'merge-train-3345');
const diff = spawnSync('git', ['diff', '--no-index', '--unified=0', '--no-color', path.join(dir, 'base-a59b5e4.md'), path.join(dir, 'pin-1eb7092.md')], { encoding: 'utf8', timeout: 30_000 }).stdout;
const authored = new Set(diff.split('\n').filter(l => l.startsWith('+') && !l.startsWith('+++')).map(l => l.slice(1)));
const stamped = fixture('stamped-de23f5d.md');
test("#3345's stamped head de23f5d is main 4a98e40's CHANGELOG plus its own entry; the damaged train T1 is not", () => {
expect(authored.has('### Fixed')).toBe(true);
expect(authored.has('## [1.91.179.0] - 2026-10-22')).toBe(false);
expect(ownEntryAboveMain(stamped, main, authored)).toBeNull();
expect(ownEntryAboveMain(fixture('train-T1-6755ab8.md'), main, authored)).toMatch(/^the PR's entry holds a line its pin never added: "\*\*docsync-fault-interface/);
});
test('negative controls: an invented line, a dropped or edited main section, a changed header and a duplicate heading are refused', () => {
expect(ownEntryAboveMain(stamped.replace('### Fixed\n', '### Fixed\n- added after the gate\n'), main, authored)).toBe('the PR\'s entry holds a line its pin never added: "- added after the gate"');
expect(ownEntryAboveMain(stamped.replace(/## \[1\.91\.180\.0\][^\n]*\n/, ''), main, authored)).toBe("main's ## [1.91.181.0] - 2026-10-23 is not carried unchanged below the PR's entry");
expect(ownEntryAboveMain(stamped.replace('## [1.91.178.0]', '## [1.91.178.0]\n\n- smuggled'), main, authored)).toBe("main's ## [1.91.178.0] - 2026-10-22 is not carried unchanged below the PR's entry");
expect(ownEntryAboveMain(stamped.replace('# Changelog', '# Change log'), main, authored)).toBe('the header differs from main');
expect(ownEntryAboveMain(stamped.replace('## [1.91.182.0]', '## [1.91.181.0]'), main, authored)).toMatch(/is headed twice$/);
});
});
+46
View File
@@ -185,6 +185,52 @@ describe('version gate: unstamped heads under a train policy', () => {
}
});
describe('a CHANGELOG over 1 MiB (GSTA-67: #3345 head 1eb7092 passed because the 1.67 MB CHANGELOG overflowed the read)', () => {
const excerpt = (name: string) => fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'merge-train-3345', name), 'utf8');
const baseTop = excerpt('base-a59b5e4.md');
const padding = Array.from({ length: 2400 }, (_, i) => `## [1.0.${2400 - i}.0] - 2026-01-01\n\nOlder release ${i}: ${'x'.repeat(440)}\n`).join('\n');
const big = `${baseTop}\n${padding}`;
const bigFixture = () => {
const r = fixture();
write(r, 'CHANGELOG.md', big);
commit(r, 'main with a full-size CHANGELOG');
r.git('push', '-q', 'origin', 'main');
r.git('fetch', '-q', 'origin');
branch(r);
expect(Buffer.byteLength(big)).toBeGreaterThan(1.05 * 1024 * 1024);
return r;
};
test("#3345's change (the 1.91.179.0 heading replaced by [Unreleased]) is refused, naming the dropped heading", () => {
const r = bigFixture();
write(r, 'CHANGELOG.md', big.replace(baseTop, excerpt('pin-1eb7092.md')));
const res = run(r, commit(r, 'the 1eb7092 CHANGELOG edit'));
expect(res.code).toBe(1);
expect(res.out).toContain('::error::PR #3320: CHANGELOG.md drops released heading 1.91.179.0; an unstamped head may only add its [Unreleased] section above the latest release.');
});
test('control: an additive [Unreleased] entry above the latest release still passes at full size', () => {
const r = bigFixture();
write(r, 'CHANGELOG.md', big.replace('## [1.91.179.0]', '## [Unreleased]\n\n- the PR entry\n\n## [1.91.179.0]'));
const res = run(r, commit(r, 'additive entry'));
expect(res.code).toBe(0);
expect(res.out).toContain('is unstamped under the base');
});
test('a CHANGELOG that cannot be read is refused, never passed', () => {
const r = bigFixture();
write(r, 'CHANGELOG.md', big.replace('## [1.91.179.0]', '## [Unreleased]\n\n- the PR entry\n\n## [1.91.179.0]'));
const head = commit(r, 'additive entry, then a damaged object');
const blob = r.git('rev-parse', `${head}:CHANGELOG.md`);
const loose = path.join(r.work, '.git', 'objects', blob.slice(0, 2), blob.slice(2));
fs.chmodSync(loose, 0o644);
fs.writeFileSync(loose, fs.readFileSync(loose).subarray(0, 2000));
const res = run(r, head);
expect(res.code).toBe(1);
expect(res.out).toContain(`::error::PR #3320: cannot read CHANGELOG.md at ${head}.`);
});
});
test('the workflow runs the gate from the merge commit with the base ref and head sha', () => {
const workflow = Bun.YAML.parse(fs.readFileSync(path.join(ROOT, '.github', 'workflows', 'version-gate.yml'), 'utf8')) as any;
const steps = workflow.jobs.check.steps;
+26
View File
@@ -170,6 +170,32 @@ describe('CSO inert Python preparation', () => {
});
});
describe('CSO preparation names a Go module as Go (#3263)', () => {
const goFiles = {
'go.mod': 'module example.com/app\n\ngo 1.23\n\nrequire github.com/google/uuid v1.6.0\n',
'go.sum': 'github.com/google/uuid v1.6.0 h1:abc=\n',
'main.go': 'package main\n\nfunc main() {}\n',
};
const GO_UNSUPPORTED = { code: 'UNSUPPORTED_STACK', message: 'Go (go.mod) is not a supported runtime stack yet; supported runtime stacks are Node, Bun, Python, and Rails.', path: 'go.mod' };
test('a go.mod repository is Go, unsupported, and never asks for requirements.txt', () => {
const plan = inspectPreparation(fixture(goFiles));
expect([plan.stack, plan.runtimeProfile, plan.status]).toEqual(['go', 'go', 'prerequisites']);
expect(plan.prerequisites).toEqual([GO_UNSUPPORTED]);
expect(JSON.stringify(plan)).not.toContain('requirements.txt');
});
test('Python helper metadata beside go.mod stays Go', () => {
const plan = inspectPreparation(fixture({ ...goFiles, 'requirements.txt': `mkdocs==1.6.1 --hash=sha256:${hash}\n` }));
expect(plan.stack).toBe('go');
expect(plan.prerequisites).toEqual([GO_UNSUPPORTED]);
});
test('controls: go.mod beside a Node lockfile stays Node; Python without go.mod stays Python', () => {
const node = inspectPreparation(fixture({ ...goFiles, ...nodeFiles() }));
expect([node.stack, node.status]).toEqual(['node', 'ready']);
expect(inspectPreparation(fixture({ 'requirements.txt': `Flask==3.1.0 --hash=sha256:${hash}\n` })).stack).toBe('python');
expect(inspectPreparation(fixture({ 'go.sum': '', 'main.go': '' })).stack).toBe('python');
});
});
describe('CSO inert Rails preparation', () => {
test('does not silently choose Node in a multi-stack repository',()=>{const plan=inspectPreparation(fixture({...nodeFiles(),'Gemfile.lock':gemLock,'Gemfile':''}));expect(plan.status).toBe('prerequisites');expect(plan.prerequisites[0].code).toBe('MULTIPLE_STACKS');expect(inspectPreparation(fixture({...nodeFiles(),'Gemfile.lock':gemLock,'Gemfile':''}),'rails').stack).toBe('rails');});
test('fetches exact gems without evaluating Gemfiles or building native extensions', () => {
+30
View File
@@ -0,0 +1,30 @@
# Changelog
## [1.91.179.0] - 2026-10-22
**docsync-fault-interface fits its budgets under load again.** On 2026-10-18 it timed out under load on a Ubicloud full run. Its nested 36-case suite spent most of its time starting processes: each fault actor spawn loaded about 36 ms of imports (an empty bun takes 5.5 ms), inspect repeated Git reads, and the whole nested run sat under one 120 s outer test. With real Git on 4 cores, inner cases now take a 0.70 s median (max 1.25 s) unloaded, against 1.07 s before. Under 8 busy loops the max is 3.44 s, inside bun's default 5 s; before, cases reached 4.45 s. The worst outer test went from about 100 s of its 120 s cap to 33 s. No timeout, budget, retry, assertion or case changed.
### Fixed
- **`test/helpers/docsync-fault-actor.ts`**: imports only light helper modules, hashes with `Bun.CryptoHasher` instead of loading `node:crypto`, and loads the redaction engine only on the snapshot-failure path. inspect makes 8 Git calls instead of 11, and the snapshot base check reuses the `--base` it just passed. Each actor spawn now costs 15–19 ms.
- **`test/helpers/docsync-repo.ts`, `test/helpers/docsync-interface.ts`** (new): the fixture's Git and file helpers and `docsNativeInterface` moved out of the fixture and observer modules, so the actor stops loading the eval store and the QA observer. `docsync-fixture.ts` and `docsync-observer.ts` re-export them, so no importer changed. The fixture writes its Git identity with one append to `.git/config` instead of three `git config` calls.
- **`bin/gstack-docs-candidate`**: snapshot lists `ls-files` once instead of twice and hashes with `Bun.CryptoHasher`. A snapshot spawn went from 68 ms to 46 ms, and the record it writes is byte-identical.
- **`test/docsync-fault-interface.test.ts`**: the nested callback run is split into three outer tests by test-name pattern (10, 12 and 14 cases). Each part asserts its exact pass count, its exact filtered-out count and `0 fail`, so all 36 cases still run and the patterns are disjoint.
## [1.91.178.0] - 2026-10-22
**A /qa run no longer gets a hint that another report root could change its verdict.** Train gate 39646086155 failed qa-functional-webhook-fix once, and gate 39166935531 failed qa-functional-cli-fix the same way on 2026-10-18. Both times the agent ran `gstack-qa-evidence materialize`, read a fail verdict that ended "this verdict is final for this report root", and its very next call wrote a stray placeholder file in the fixture's parent directory (`qa-reports-placeholder-unused`, `qa-Q3vLqZ-placeholder`) before writing `report.md`. Each agent then reported the stray file itself. The out-of-fixture write detector was right both times and is unchanged.
### Fixed
- **`lib/qa-evidence.ts`**: materialize's `next` instruction now ends "this verdict is final. Next, write the Markdown report beside evidence.json." It names the next write and where it goes, instead of qualifying the verdict by report root.
- **`test/helpers/qa-functional-eval.ts`**: the functional fixture's declared interface says that every Write/Edit targets an owned path inside the working directory, and that a write anywhere else, including the parent directory, fails acceptance. That was already the acceptance rule; the prompt now states it.
### Gate integrity
- No detector, threshold, trial count or case kind changed. `test/qa-evidence.test.ts` pins the new `next` wording and checks that it no longer mentions a report root.
## [1.91.177.0] - 2026-10-22
**The /cso runtime promotion workflow can finish.** Promote run 39691485727 failed after its `cso-runtime-release` approval. Its "Generate a fail-closed catalog candidate" step calls `gh api …/compare` to prove the staged commit is an ancestor of the qualification head, but the step had no `GH_TOKEN`. On a hosted runner `gh` then exits 4 ("set the GH_TOKEN environment variable"). The run stopped before it signed, pushed or opened anything.
### Fixed
- **`.github/workflows/cso-runtime-promote.yml`**: the candidate step gets `GH_TOKEN: ${{ github.token }}`, like every other step there that calls `gh`.
- **`test/workflow-gh-token.test.ts`** (new): fails when any step in any workflow invokes `gh` with no `GH_TOKEN` or `GITHUB_TOKEN` in its step, job or workflow env. actionlint does not check this. This step was the only one in the repository missing a token.
+47
View File
@@ -0,0 +1,47 @@
# Changelog
## [1.91.181.0] - 2026-10-23
**/cso can run its contained runtime checks.** Before this release the runtime catalog qualified nothing, so /cso always fell back to static assessment. It now qualifies ten pinned 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. With Docker installed, comprehensive /cso boots the target app inside the matching image and tests findings and repairs against it. The images passed the private evaluator's release qualification (run-5 statements, re-delivered under Garry's approval). The ingress then checked them in qualify run 39674065531 at 514fbfd.
### Added
- **`lib/cso/runtime-catalog.json`** is now catalog `cso-v3-39674065531-133cb360842d`, which replaces `cso-v3-build-reviewed-2026-09-10`. Promote run 39841502986 generated it from qualification run 39674065531's authenticated statements and attested it. GitHub Actions committed the attested bytes (`sha256:078e0bf6…`). Each runtime's image is pinned to a public `ghcr.io/garrytan/gstack/cso-staging/…@sha256` digest, and each entry records its source commit (133cb36), SBOM and provenance digests, and requalification triggers (`preparationSha256` `c721b585…`).
### For contributors
- **The /cso free tests no longer assume the committed runtime catalog is empty.** Six tests pinned `runtimes: []` and broke as soon as a promotion landed. Tests that need an unqualified catalog now build one with `unqualifiedRuntimeCatalog()`. The replay tests expect whichever fail-closed rejection the committed catalog produces, so the suite passes with the catalog both before and after a promotion.
## [1.91.180.0] - 2026-10-22
**The /cso docs say what the qualified catalogs now allow.** AGENTS.md, the README and `docs/cso-release-qualification.md` still said that no qualified runtime or scanner image existed, so /cso ran static assessment only. The scanner catalog has been qualified since #3042. The runtime catalog becomes qualified with the runtime promotion PR that ships alongside this one.
### Changed
- **AGENTS.md**, **README.md** and **`docs/cso-release-qualification.md`**: the /cso entries name the ten qualified runtime images and the twelve scanner images, and say when /cso still falls back to static assessment: without Docker, or where no profile matches.
## [1.91.179.0] - 2026-10-22
**docsync-fault-interface fits its budgets under load again.** On 2026-10-18 it timed out under load on a Ubicloud full run. Its nested 36-case suite spent most of its time starting processes: each fault actor spawn loaded about 36 ms of imports (an empty bun takes 5.5 ms), inspect repeated Git reads, and the whole nested run sat under one 120 s outer test. With real Git on 4 cores, inner cases now take a 0.70 s median (max 1.25 s) unloaded, against 1.07 s before. Under 8 busy loops the max is 3.44 s, inside bun's default 5 s; before, cases reached 4.45 s. The worst outer test went from about 100 s of its 120 s cap to 33 s. No timeout, budget, retry, assertion or case changed.
### Fixed
- **`test/helpers/docsync-fault-actor.ts`**: imports only light helper modules, hashes with `Bun.CryptoHasher` instead of loading `node:crypto`, and loads the redaction engine only on the snapshot-failure path. inspect makes 8 Git calls instead of 11, and the snapshot base check reuses the `--base` it just passed. Each actor spawn now costs 15–19 ms.
- **`test/helpers/docsync-repo.ts`, `test/helpers/docsync-interface.ts`** (new): the fixture's Git and file helpers and `docsNativeInterface` moved out of the fixture and observer modules, so the actor stops loading the eval store and the QA observer. `docsync-fixture.ts` and `docsync-observer.ts` re-export them, so no importer changed. The fixture writes its Git identity with one append to `.git/config` instead of three `git config` calls.
- **`bin/gstack-docs-candidate`**: snapshot lists `ls-files` once instead of twice and hashes with `Bun.CryptoHasher`. A snapshot spawn went from 68 ms to 46 ms, and the record it writes is byte-identical.
- **`test/docsync-fault-interface.test.ts`**: the nested callback run is split into three outer tests by test-name pattern (10, 12 and 14 cases). Each part asserts its exact pass count, its exact filtered-out count and `0 fail`, so all 36 cases still run and the patterns are disjoint.
## [1.91.178.0] - 2026-10-22
**A /qa run no longer gets a hint that another report root could change its verdict.** Train gate 39646086155 failed qa-functional-webhook-fix once, and gate 39166935531 failed qa-functional-cli-fix the same way on 2026-10-18. Both times the agent ran `gstack-qa-evidence materialize`, read a fail verdict that ended "this verdict is final for this report root", and its very next call wrote a stray placeholder file in the fixture's parent directory (`qa-reports-placeholder-unused`, `qa-Q3vLqZ-placeholder`) before writing `report.md`. Each agent then reported the stray file itself. The out-of-fixture write detector was right both times and is unchanged.
### Fixed
- **`lib/qa-evidence.ts`**: materialize's `next` instruction now ends "this verdict is final. Next, write the Markdown report beside evidence.json." It names the next write and where it goes, instead of qualifying the verdict by report root.
- **`test/helpers/qa-functional-eval.ts`**: the functional fixture's declared interface says that every Write/Edit targets an owned path inside the working directory, and that a write anywhere else, including the parent directory, fails acceptance. That was already the acceptance rule; the prompt now states it.
### Gate integrity
- No detector, threshold, trial count or case kind changed. `test/qa-evidence.test.ts` pins the new `next` wording and checks that it no longer mentions a report root.
## [1.91.177.0] - 2026-10-22
**The /cso runtime promotion workflow can finish.** Promote run 39691485727 failed after its `cso-runtime-release` approval. Its "Generate a fail-closed catalog candidate" step calls `gh api …/compare` to prove the staged commit is an ancestor of the qualification head, but the step had no `GH_TOKEN`. On a hosted runner `gh` then exits 4 ("set the GH_TOKEN environment variable"). The run stopped before it signed, pushed or opened anything.
### Fixed
- **`.github/workflows/cso-runtime-promote.yml`**: the candidate step gets `GH_TOKEN: ${{ github.token }}`, like every other step there that calls `gh`.
- **`test/workflow-gh-token.test.ts`** (new): fails when any step in any workflow invokes `gh` with no `GH_TOKEN` or `GITHUB_TOKEN` in its step, job or workflow env. actionlint does not check this. This step was the only one in the repository missing a token.
+37
View File
@@ -0,0 +1,37 @@
# Changelog
## [Unreleased]
**gstack installs on a project that pins Bun 1.4.4 again.** gbrain master moved its CI to Bun 1.4.4 (gbrain #7374, the Brotli CVE-2026-111497 fix), and gstack's Capy installer then stopped every gbrain session with `RUNTIME_PIN_CONFLICT` ("verified archives: 1.4.2 1.4.3 … pins exactly 1.4.4"), because it installs only Bun archives whose SHA-256 it carries. It now carries 1.4.4, so the same run installs the pinned Bun and ends `gstack: ok`.
### Fixed
- **`bin/gstack-bun-version.sh`**: `GSTACK_BUN_VERIFIED` is now 1.4.2 1.4.3 1.4.4, with 1.4.4's checksums for linux-x64, linux-x64-baseline and linux-aarch64, the targets 1.4.3 covers. They come from the release's `SHASUMS256.txt.asc`, whose clearsigned signature verifies against Bun's release key F3DCC08A8572C0749B3E18888EAB4D40A7B22B59 (Robobun, the key oven-sh/bun's own Dockerfiles assert), and each archive was downloaded and hashed to the same value. The 1.4.2 and 1.4.3 entries are unchanged and verify the same way. gstack's own minimum (1.4.2), install default (1.4.3) and CI pins do not move.
- **`test/gstack-capy-install.test.ts`**: a gbrain-like repo whose CI pins only 1.4.4 refuses `~/.bun` 1.4.3 and installs the 1.4.4 archive. **`test/bun-version-drift.test.ts`**: every verified version must carry a checksum for each installer target. The existing "verified archives" text assertions list 1.4.4.
**docsync-fault-interface fits its budgets under load again.** On 2026-10-18 it timed out under load on a Ubicloud full run. Its nested 36-case suite spent most of its time starting processes: each fault actor spawn loaded about 36 ms of imports (an empty bun takes 5.5 ms), inspect repeated Git reads, and the whole nested run sat under one 120 s outer test. With real Git on 4 cores, inner cases now take a 0.70 s median (max 1.25 s) unloaded, against 1.07 s before. Under 8 busy loops the max is 3.44 s, inside bun's default 5 s; before, cases reached 4.45 s. The worst outer test went from about 100 s of its 120 s cap to 33 s. No timeout, budget, retry, assertion or case changed.
### Fixed
- **`test/helpers/docsync-fault-actor.ts`**: imports only light helper modules, hashes with `Bun.CryptoHasher` instead of loading `node:crypto`, and loads the redaction engine only on the snapshot-failure path. inspect makes 8 Git calls instead of 11, and the snapshot base check reuses the `--base` it just passed. Each actor spawn now costs 15–19 ms.
- **`test/helpers/docsync-repo.ts`, `test/helpers/docsync-interface.ts`** (new): the fixture's Git and file helpers and `docsNativeInterface` moved out of the fixture and observer modules, so the actor stops loading the eval store and the QA observer. `docsync-fixture.ts` and `docsync-observer.ts` re-export them, so no importer changed. The fixture writes its Git identity with one append to `.git/config` instead of three `git config` calls.
- **`bin/gstack-docs-candidate`**: snapshot lists `ls-files` once instead of twice and hashes with `Bun.CryptoHasher`. A snapshot spawn went from 68 ms to 46 ms, and the record it writes is byte-identical.
- **`test/docsync-fault-interface.test.ts`**: the nested callback run is split into three outer tests by test-name pattern (10, 12 and 14 cases). Each part asserts its exact pass count, its exact filtered-out count and `0 fail`, so all 36 cases still run and the patterns are disjoint.
## [1.91.178.0] - 2026-10-22
**A /qa run no longer gets a hint that another report root could change its verdict.** Train gate 39646086155 failed qa-functional-webhook-fix once, and gate 39166935531 failed qa-functional-cli-fix the same way on 2026-10-18. Both times the agent ran `gstack-qa-evidence materialize`, read a fail verdict that ended "this verdict is final for this report root", and its very next call wrote a stray placeholder file in the fixture's parent directory (`qa-reports-placeholder-unused`, `qa-Q3vLqZ-placeholder`) before writing `report.md`. Each agent then reported the stray file itself. The out-of-fixture write detector was right both times and is unchanged.
### Fixed
- **`lib/qa-evidence.ts`**: materialize's `next` instruction now ends "this verdict is final. Next, write the Markdown report beside evidence.json." It names the next write and where it goes, instead of qualifying the verdict by report root.
- **`test/helpers/qa-functional-eval.ts`**: the functional fixture's declared interface says that every Write/Edit targets an owned path inside the working directory, and that a write anywhere else, including the parent directory, fails acceptance. That was already the acceptance rule; the prompt now states it.
### Gate integrity
- No detector, threshold, trial count or case kind changed. `test/qa-evidence.test.ts` pins the new `next` wording and checks that it no longer mentions a report root.
## [1.91.177.0] - 2026-10-22
**The /cso runtime promotion workflow can finish.** Promote run 39691485727 failed after its `cso-runtime-release` approval. Its "Generate a fail-closed catalog candidate" step calls `gh api …/compare` to prove the staged commit is an ancestor of the qualification head, but the step had no `GH_TOKEN`. On a hosted runner `gh` then exits 4 ("set the GH_TOKEN environment variable"). The run stopped before it signed, pushed or opened anything.
### Fixed
- **`.github/workflows/cso-runtime-promote.yml`**: the candidate step gets `GH_TOKEN: ${{ github.token }}`, like every other step there that calls `gh`.
- **`test/workflow-gh-token.test.ts`** (new): fails when any step in any workflow invokes `gh` with no `GH_TOKEN` or `GITHUB_TOKEN` in its step, job or workflow env. actionlint does not check this. This step was the only one in the repository missing a token.
+55
View File
@@ -0,0 +1,55 @@
# Changelog
## [1.91.182.0] - 2026-10-23
**gstack installs on a project that pins Bun 1.4.4 again.** gbrain master moved its CI to Bun 1.4.4 (gbrain #7374, the Brotli CVE-2026-111497 fix), and gstack's Capy installer then stopped every gbrain session with `RUNTIME_PIN_CONFLICT` ("verified archives: 1.4.2 1.4.3 … pins exactly 1.4.4"), because it installs only Bun archives whose SHA-256 it carries. It now carries 1.4.4, so the same run installs the pinned Bun and ends `gstack: ok`.
### Fixed
- **`bin/gstack-bun-version.sh`**: `GSTACK_BUN_VERIFIED` is now 1.4.2 1.4.3 1.4.4, with 1.4.4's checksums for linux-x64, linux-x64-baseline and linux-aarch64, the targets 1.4.3 covers. They come from the release's `SHASUMS256.txt.asc`, whose clearsigned signature verifies against Bun's release key F3DCC08A8572C0749B3E18888EAB4D40A7B22B59 (Robobun, the key oven-sh/bun's own Dockerfiles assert), and each archive was downloaded and hashed to the same value. The 1.4.2 and 1.4.3 entries are unchanged and verify the same way. gstack's own minimum (1.4.2), install default (1.4.3) and CI pins do not move.
- **`test/gstack-capy-install.test.ts`**: a gbrain-like repo whose CI pins only 1.4.4 refuses `~/.bun` 1.4.3 and installs the 1.4.4 archive. **`test/bun-version-drift.test.ts`**: every verified version must carry a checksum for each installer target. The existing "verified archives" text assertions list 1.4.4.
## [1.91.181.0] - 2026-10-23
**/cso can run its contained runtime checks.** Before this release the runtime catalog qualified nothing, so /cso always fell back to static assessment. It now qualifies ten pinned 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. With Docker installed, comprehensive /cso boots the target app inside the matching image and tests findings and repairs against it. The images passed the private evaluator's release qualification (run-5 statements, re-delivered under Garry's approval). The ingress then checked them in qualify run 39674065531 at 514fbfd.
### Added
- **`lib/cso/runtime-catalog.json`** is now catalog `cso-v3-39674065531-133cb360842d`, which replaces `cso-v3-build-reviewed-2026-09-10`. Promote run 39841502986 generated it from qualification run 39674065531's authenticated statements and attested it. GitHub Actions committed the attested bytes (`sha256:078e0bf6…`). Each runtime's image is pinned to a public `ghcr.io/garrytan/gstack/cso-staging/…@sha256` digest, and each entry records its source commit (133cb36), SBOM and provenance digests, and requalification triggers (`preparationSha256` `c721b585…`).
### For contributors
- **The /cso free tests no longer assume the committed runtime catalog is empty.** Six tests pinned `runtimes: []` and broke as soon as a promotion landed. Tests that need an unqualified catalog now build one with `unqualifiedRuntimeCatalog()`. The replay tests expect whichever fail-closed rejection the committed catalog produces, so the suite passes with the catalog both before and after a promotion.
## [1.91.180.0] - 2026-10-22
**The /cso docs say what the qualified catalogs now allow.** AGENTS.md, the README and `docs/cso-release-qualification.md` still said that no qualified runtime or scanner image existed, so /cso ran static assessment only. The scanner catalog has been qualified since #3042. The runtime catalog becomes qualified with the runtime promotion PR that ships alongside this one.
### Changed
- **AGENTS.md**, **README.md** and **`docs/cso-release-qualification.md`**: the /cso entries name the ten qualified runtime images and the twelve scanner images, and say when /cso still falls back to static assessment: without Docker, or where no profile matches.
## [1.91.179.0] - 2026-10-22
**docsync-fault-interface fits its budgets under load again.** On 2026-10-18 it timed out under load on a Ubicloud full run. Its nested 36-case suite spent most of its time starting processes: each fault actor spawn loaded about 36 ms of imports (an empty bun takes 5.5 ms), inspect repeated Git reads, and the whole nested run sat under one 120 s outer test. With real Git on 4 cores, inner cases now take a 0.70 s median (max 1.25 s) unloaded, against 1.07 s before. Under 8 busy loops the max is 3.44 s, inside bun's default 5 s; before, cases reached 4.45 s. The worst outer test went from about 100 s of its 120 s cap to 33 s. No timeout, budget, retry, assertion or case changed.
### Fixed
- **`test/helpers/docsync-fault-actor.ts`**: imports only light helper modules, hashes with `Bun.CryptoHasher` instead of loading `node:crypto`, and loads the redaction engine only on the snapshot-failure path. inspect makes 8 Git calls instead of 11, and the snapshot base check reuses the `--base` it just passed. Each actor spawn now costs 15–19 ms.
- **`test/helpers/docsync-repo.ts`, `test/helpers/docsync-interface.ts`** (new): the fixture's Git and file helpers and `docsNativeInterface` moved out of the fixture and observer modules, so the actor stops loading the eval store and the QA observer. `docsync-fixture.ts` and `docsync-observer.ts` re-export them, so no importer changed. The fixture writes its Git identity with one append to `.git/config` instead of three `git config` calls.
- **`bin/gstack-docs-candidate`**: snapshot lists `ls-files` once instead of twice and hashes with `Bun.CryptoHasher`. A snapshot spawn went from 68 ms to 46 ms, and the record it writes is byte-identical.
- **`test/docsync-fault-interface.test.ts`**: the nested callback run is split into three outer tests by test-name pattern (10, 12 and 14 cases). Each part asserts its exact pass count, its exact filtered-out count and `0 fail`, so all 36 cases still run and the patterns are disjoint.
## [1.91.178.0] - 2026-10-22
**A /qa run no longer gets a hint that another report root could change its verdict.** Train gate 39646086155 failed qa-functional-webhook-fix once, and gate 39166935531 failed qa-functional-cli-fix the same way on 2026-10-18. Both times the agent ran `gstack-qa-evidence materialize`, read a fail verdict that ended "this verdict is final for this report root", and its very next call wrote a stray placeholder file in the fixture's parent directory (`qa-reports-placeholder-unused`, `qa-Q3vLqZ-placeholder`) before writing `report.md`. Each agent then reported the stray file itself. The out-of-fixture write detector was right both times and is unchanged.
### Fixed
- **`lib/qa-evidence.ts`**: materialize's `next` instruction now ends "this verdict is final. Next, write the Markdown report beside evidence.json." It names the next write and where it goes, instead of qualifying the verdict by report root.
- **`test/helpers/qa-functional-eval.ts`**: the functional fixture's declared interface says that every Write/Edit targets an owned path inside the working directory, and that a write anywhere else, including the parent directory, fails acceptance. That was already the acceptance rule; the prompt now states it.
### Gate integrity
- No detector, threshold, trial count or case kind changed. `test/qa-evidence.test.ts` pins the new `next` wording and checks that it no longer mentions a report root.
## [1.91.177.0] - 2026-10-22
**The /cso runtime promotion workflow can finish.** Promote run 39691485727 failed after its `cso-runtime-release` approval. Its "Generate a fail-closed catalog candidate" step calls `gh api …/compare` to prove the staged commit is an ancestor of the qualification head, but the step had no `GH_TOKEN`. On a hosted runner `gh` then exits 4 ("set the GH_TOKEN environment variable"). The run stopped before it signed, pushed or opened anything.
### Fixed
- **`.github/workflows/cso-runtime-promote.yml`**: the candidate step gets `GH_TOKEN: ${{ github.token }}`, like every other step there that calls `gh`.
- **`test/workflow-gh-token.test.ts`** (new): fails when any step in any workflow invokes `gh` with no `GH_TOKEN` or `GITHUB_TOKEN` in its step, job or workflow env. actionlint does not check this. This step was the only one in the repository missing a token.
+64
View File
@@ -0,0 +1,64 @@
# Changelog
## [Unreleased]
**gstack installs on a project that pins Bun 1.4.4 again.** gbrain master moved its CI to Bun 1.4.4 (gbrain #7374, the Brotli CVE-2026-111497 fix), and gstack's Capy installer then stopped every gbrain session with `RUNTIME_PIN_CONFLICT` ("verified archives: 1.4.2 1.4.3 … pins exactly 1.4.4"), because it installs only Bun archives whose SHA-256 it carries. It now carries 1.4.4, so the same run installs the pinned Bun and ends `gstack: ok`.
### Fixed
- **`bin/gstack-bun-version.sh`**: `GSTACK_BUN_VERIFIED` is now 1.4.2 1.4.3 1.4.4, with 1.4.4's checksums for linux-x64, linux-x64-baseline and linux-aarch64, the targets 1.4.3 covers. They come from the release's `SHASUMS256.txt.asc`, whose clearsigned signature verifies against Bun's release key F3DCC08A8572C0749B3E18888EAB4D40A7B22B59 (Robobun, the key oven-sh/bun's own Dockerfiles assert), and each archive was downloaded and hashed to the same value. The 1.4.2 and 1.4.3 entries are unchanged and verify the same way. gstack's own minimum (1.4.2), install default (1.4.3) and CI pins do not move.
- **`test/gstack-capy-install.test.ts`**: a gbrain-like repo whose CI pins only 1.4.4 refuses `~/.bun` 1.4.3 and installs the 1.4.4 archive. **`test/bun-version-drift.test.ts`**: every verified version must carry a checksum for each installer target. The existing "verified archives" text assertions list 1.4.4.
**docsync-fault-interface fits its budgets under load again.** On 2026-10-18 it timed out under load on a Ubicloud full run. Its nested 36-case suite spent most of its time starting processes: each fault actor spawn loaded about 36 ms of imports (an empty bun takes 5.5 ms), inspect repeated Git reads, and the whole nested run sat under one 120 s outer test. With real Git on 4 cores, inner cases now take a 0.70 s median (max 1.25 s) unloaded, against 1.07 s before. Under 8 busy loops the max is 3.44 s, inside bun's default 5 s; before, cases reached 4.45 s. The worst outer test went from about 100 s of its 120 s cap to 33 s. No timeout, budget, retry, assertion or case changed.
### Fixed
- **`test/helpers/docsync-fault-actor.ts`**: imports only light helper modules, hashes with `Bun.CryptoHasher` instead of loading `node:crypto`, and loads the redaction engine only on the snapshot-failure path. inspect makes 8 Git calls instead of 11, and the snapshot base check reuses the `--base` it just passed. Each actor spawn now costs 15–19 ms.
- **`test/helpers/docsync-repo.ts`, `test/helpers/docsync-interface.ts`** (new): the fixture's Git and file helpers and `docsNativeInterface` moved out of the fixture and observer modules, so the actor stops loading the eval store and the QA observer. `docsync-fixture.ts` and `docsync-observer.ts` re-export them, so no importer changed. The fixture writes its Git identity with one append to `.git/config` instead of three `git config` calls.
- **`bin/gstack-docs-candidate`**: snapshot lists `ls-files` once instead of twice and hashes with `Bun.CryptoHasher`. A snapshot spawn went from 68 ms to 46 ms, and the record it writes is byte-identical.
- **`test/docsync-fault-interface.test.ts`**: the nested callback run is split into three outer tests by test-name pattern (10, 12 and 14 cases). Each part asserts its exact pass count, its exact filtered-out count and `0 fail`, so all 36 cases still run and the patterns are disjoint.
## [1.91.181.0] - 2026-10-23
**/cso can run its contained runtime checks.** Before this release the runtime catalog qualified nothing, so /cso always fell back to static assessment. It now qualifies ten pinned 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. With Docker installed, comprehensive /cso boots the target app inside the matching image and tests findings and repairs against it. The images passed the private evaluator's release qualification (run-5 statements, re-delivered under Garry's approval). The ingress then checked them in qualify run 39674065531 at 514fbfd.
### Added
- **`lib/cso/runtime-catalog.json`** is now catalog `cso-v3-39674065531-133cb360842d`, which replaces `cso-v3-build-reviewed-2026-09-10`. Promote run 39841502986 generated it from qualification run 39674065531's authenticated statements and attested it. GitHub Actions committed the attested bytes (`sha256:078e0bf6…`). Each runtime's image is pinned to a public `ghcr.io/garrytan/gstack/cso-staging/…@sha256` digest, and each entry records its source commit (133cb36), SBOM and provenance digests, and requalification triggers (`preparationSha256` `c721b585…`).
### For contributors
- **The /cso free tests no longer assume the committed runtime catalog is empty.** Six tests pinned `runtimes: []` and broke as soon as a promotion landed. Tests that need an unqualified catalog now build one with `unqualifiedRuntimeCatalog()`. The replay tests expect whichever fail-closed rejection the committed catalog produces, so the suite passes with the catalog both before and after a promotion.
## [1.91.180.0] - 2026-10-22
**The /cso docs say what the qualified catalogs now allow.** AGENTS.md, the README and `docs/cso-release-qualification.md` still said that no qualified runtime or scanner image existed, so /cso ran static assessment only. The scanner catalog has been qualified since #3042. The runtime catalog becomes qualified with the runtime promotion PR that ships alongside this one.
### Changed
- **AGENTS.md**, **README.md** and **`docs/cso-release-qualification.md`**: the /cso entries name the ten qualified runtime images and the twelve scanner images, and say when /cso still falls back to static assessment: without Docker, or where no profile matches.
## [1.91.179.0] - 2026-10-22
**docsync-fault-interface fits its budgets under load again.** On 2026-10-18 it timed out under load on a Ubicloud full run. Its nested 36-case suite spent most of its time starting processes: each fault actor spawn loaded about 36 ms of imports (an empty bun takes 5.5 ms), inspect repeated Git reads, and the whole nested run sat under one 120 s outer test. With real Git on 4 cores, inner cases now take a 0.70 s median (max 1.25 s) unloaded, against 1.07 s before. Under 8 busy loops the max is 3.44 s, inside bun's default 5 s; before, cases reached 4.45 s. The worst outer test went from about 100 s of its 120 s cap to 33 s. No timeout, budget, retry, assertion or case changed.
### Fixed
- **`test/helpers/docsync-fault-actor.ts`**: imports only light helper modules, hashes with `Bun.CryptoHasher` instead of loading `node:crypto`, and loads the redaction engine only on the snapshot-failure path. inspect makes 8 Git calls instead of 11, and the snapshot base check reuses the `--base` it just passed. Each actor spawn now costs 15–19 ms.
- **`test/helpers/docsync-repo.ts`, `test/helpers/docsync-interface.ts`** (new): the fixture's Git and file helpers and `docsNativeInterface` moved out of the fixture and observer modules, so the actor stops loading the eval store and the QA observer. `docsync-fixture.ts` and `docsync-observer.ts` re-export them, so no importer changed. The fixture writes its Git identity with one append to `.git/config` instead of three `git config` calls.
- **`bin/gstack-docs-candidate`**: snapshot lists `ls-files` once instead of twice and hashes with `Bun.CryptoHasher`. A snapshot spawn went from 68 ms to 46 ms, and the record it writes is byte-identical.
- **`test/docsync-fault-interface.test.ts`**: the nested callback run is split into three outer tests by test-name pattern (10, 12 and 14 cases). Each part asserts its exact pass count, its exact filtered-out count and `0 fail`, so all 36 cases still run and the patterns are disjoint.
## [1.91.178.0] - 2026-10-22
**A /qa run no longer gets a hint that another report root could change its verdict.** Train gate 39646086155 failed qa-functional-webhook-fix once, and gate 39166935531 failed qa-functional-cli-fix the same way on 2026-10-18. Both times the agent ran `gstack-qa-evidence materialize`, read a fail verdict that ended "this verdict is final for this report root", and its very next call wrote a stray placeholder file in the fixture's parent directory (`qa-reports-placeholder-unused`, `qa-Q3vLqZ-placeholder`) before writing `report.md`. Each agent then reported the stray file itself. The out-of-fixture write detector was right both times and is unchanged.
### Fixed
- **`lib/qa-evidence.ts`**: materialize's `next` instruction now ends "this verdict is final. Next, write the Markdown report beside evidence.json." It names the next write and where it goes, instead of qualifying the verdict by report root.
- **`test/helpers/qa-functional-eval.ts`**: the functional fixture's declared interface says that every Write/Edit targets an owned path inside the working directory, and that a write anywhere else, including the parent directory, fails acceptance. That was already the acceptance rule; the prompt now states it.
### Gate integrity
- No detector, threshold, trial count or case kind changed. `test/qa-evidence.test.ts` pins the new `next` wording and checks that it no longer mentions a report root.
## [1.91.177.0] - 2026-10-22
**The /cso runtime promotion workflow can finish.** Promote run 39691485727 failed after its `cso-runtime-release` approval. Its "Generate a fail-closed catalog candidate" step calls `gh api …/compare` to prove the staged commit is an ancestor of the qualification head, but the step had no `GH_TOKEN`. On a hosted runner `gh` then exits 4 ("set the GH_TOKEN environment variable"). The run stopped before it signed, pushed or opened anything.
### Fixed
- **`.github/workflows/cso-runtime-promote.yml`**: the candidate step gets `GH_TOKEN: ${{ github.token }}`, like every other step there that calls `gh`.
- **`test/workflow-gh-token.test.ts`** (new): fails when any step in any workflow invokes `gh` with no `GH_TOKEN` or `GITHUB_TOKEN` in its step, job or workflow env. actionlint does not check this. This step was the only one in the repository missing a token.
+11 -11
View File
@@ -5,7 +5,7 @@
"agy/gstack-autoplan": 130504,
"agy/gstack-design-consultation": 108184,
"agy/gstack-design-review": 143528,
"agy/gstack-land-and-deploy": 116611,
"agy/gstack-land-and-deploy": 117722,
"agy/gstack-plan-design-review": 140013,
"agy/gstack-plan-devex-review": 135760,
"agy/gstack-plan-eng-review": 152626,
@@ -14,7 +14,7 @@
"codex/gstack-autoplan": 130628,
"codex/gstack-design-consultation": 109452,
"codex/gstack-design-review": 145028,
"codex/gstack-land-and-deploy": 121188,
"codex/gstack-land-and-deploy": 122272,
"codex/gstack-office-hours": 102339,
"codex/gstack-plan-design-review": 142466,
"codex/gstack-plan-devex-review": 138649,
@@ -24,7 +24,7 @@
"copilot/gstack-codex": 100235,
"copilot/gstack-design-consultation": 109536,
"copilot/gstack-design-review": 144833,
"copilot/gstack-land-and-deploy": 117881,
"copilot/gstack-land-and-deploy": 118977,
"copilot/gstack-office-hours": 100495,
"copilot/gstack-plan-design-review": 140884,
"copilot/gstack-plan-devex-review": 136912,
@@ -33,7 +33,7 @@
"cursor/gstack-autoplan": 129278,
"cursor/gstack-design-consultation": 107222,
"cursor/gstack-design-review": 142507,
"cursor/gstack-land-and-deploy": 115550,
"cursor/gstack-land-and-deploy": 116645,
"cursor/gstack-plan-design-review": 138968,
"cursor/gstack-plan-devex-review": 134591,
"cursor/gstack-plan-eng-review": 151480,
@@ -42,7 +42,7 @@
"factory/gstack-codex": 100655,
"factory/gstack-design-consultation": 108670,
"factory/gstack-design-review": 144297,
"factory/gstack-land-and-deploy": 119733,
"factory/gstack-land-and-deploy": 120817,
"factory/gstack-office-hours": 101374,
"factory/gstack-plan-design-review": 141749,
"factory/gstack-plan-devex-review": 137960,
@@ -50,34 +50,34 @@
"factory/gstack-review": 144529,
"gbrain/gstack-autoplan": 129815,
"gbrain/gstack-design-review": 132842,
"gbrain/gstack-land-and-deploy": 116072,
"gbrain/gstack-land-and-deploy": 117167,
"gbrain/gstack-plan-design-review": 127855,
"gbrain/gstack-plan-devex-review": 115129,
"gbrain/gstack-plan-eng-review": 134212,
"hermes/gstack-autoplan": 129905,
"hermes/gstack-design-review": 132949,
"hermes/gstack-land-and-deploy": 116174,
"hermes/gstack-land-and-deploy": 117269,
"hermes/gstack-plan-design-review": 127964,
"hermes/gstack-plan-devex-review": 115215,
"hermes/gstack-plan-eng-review": 134297,
"kiro/gstack-autoplan": 129040,
"kiro/gstack-design-consultation": 107064,
"kiro/gstack-design-review": 142321,
"kiro/gstack-land-and-deploy": 115440,
"kiro/gstack-land-and-deploy": 116533,
"kiro/gstack-plan-design-review": 138808,
"kiro/gstack-plan-devex-review": 134431,
"kiro/gstack-plan-eng-review": 151330,
"kiro/gstack-review": 140562,
"openclaw/gstack-autoplan": 129520,
"openclaw/gstack-design-review": 131647,
"openclaw/gstack-land-and-deploy": 115660,
"openclaw/gstack-land-and-deploy": 116757,
"openclaw/gstack-plan-design-review": 126706,
"openclaw/gstack-plan-devex-review": 113968,
"openclaw/gstack-plan-eng-review": 132609,
"opencode/gstack-autoplan": 131640,
"opencode/gstack-design-consultation": 109357,
"opencode/gstack-design-review": 144705,
"opencode/gstack-land-and-deploy": 117658,
"opencode/gstack-land-and-deploy": 118762,
"opencode/gstack-office-hours": 100329,
"opencode/gstack-plan-design-review": 140738,
"opencode/gstack-plan-devex-review": 136812,
@@ -86,7 +86,7 @@
"slate/gstack-autoplan": 129159,
"slate/gstack-design-consultation": 107143,
"slate/gstack-design-review": 142414,
"slate/gstack-land-and-deploy": 115495,
"slate/gstack-land-and-deploy": 116589,
"slate/gstack-plan-design-review": 138888,
"slate/gstack-plan-devex-review": 134511,
"slate/gstack-plan-eng-review": 151405,
+47
View File
@@ -1,4 +1,5 @@
import { describe, test, expect, afterEach } from "bun:test";
import { spawn } from "child_process";
import * as fs from "fs";
import * as os from "os";
import { join } from "path";
@@ -78,6 +79,52 @@ describe("detectAutopilot", () => {
expect(r.signal).toBe("process:gbrain autopilot");
});
// #3360: the probe stays machine-wide; the refusal names whose autopilot it is.
test("a matched autopilot process is named by pid and command, with how to proceed", () => {
const r = detectAutopilot(process.env, {
lockPaths: [],
processRunning: () => [{ pid: 4242, command: "gbrain autopilot --repo /src/other-brain" }],
});
expect(r.active).toBe(true);
expect(r.signal).toBe(
"process:gbrain autopilot pid 4242 `gbrain autopilot --repo /src/other-brain`; this check counts any process on this machine " +
"whose command line contains \"gbrain autopilot\", even an autopilot serving another brain or repo. Stop that autopilot " +
"(or its service, if `gbrain autopilot --install` set one up), or end the process that only mentions it",
);
});
test("every matched autopilot process is listed", () => {
const r = detectAutopilot(process.env, {
lockPaths: [],
processRunning: () => [
{ pid: 4242, command: "gbrain autopilot --repo /a" },
{ pid: 4343, command: "gbrain autopilot --repo /b" },
],
});
expect(r.signal).toContain("pid 4242 `gbrain autopilot --repo /a`, pid 4343 `gbrain autopilot --repo /b`;");
});
test("no matched process is inactive", () => {
const r = detectAutopilot(process.env, { lockPaths: [], processRunning: () => [] });
expect(r).toEqual({ active: false, signal: null });
});
test.skipIf(process.platform === "win32")("the real probe names a live process anywhere on the machine, credentials masked", async () => {
const url = ["postgres://u", "hunter2@h/db"].join(":");
const child = spawn(process.execPath, ["-e", "console.log('ready'); setTimeout(() => {}, 30000)", `gbrain autopilot --repo /tmp/gstack-3360 --db ${url}`], { stdio: ["ignore", "pipe", "ignore"] });
try {
await new Promise(resolve => child.stdout!.once("data", resolve));
const r = detectAutopilot(process.env, { lockPaths: [] });
expect(r.active).toBe(true);
expect(r.signal).toContain(`pid ${child.pid} \``);
expect(r.signal).toContain("gbrain autopilot --repo /tmp/gstack-3360 --db postgres://***@h/db");
expect(r.signal).not.toContain("hunter2");
expect(r.signal).toContain("Stop that autopilot");
} finally {
child.kill("SIGKILL");
}
});
test("a lock with no parseable pid stays conservative (active, no pid in signal)", () => {
const tmp = fs.mkdtempSync(join(os.tmpdir(), "ap-"));
const lock = join(tmp, "autopilot.lock");
+52 -1
View File
@@ -19,7 +19,7 @@ import * as path from "path";
import * as os from "os";
import { spawnSync } from "child_process";
import { repoPolicyTier, repoPolicyTierBatch } from "../lib/gbrain-repo-policy-client";
import { hasRepoPolicyStore, memorableRecallPolicy, repoPolicyTier, repoPolicyTierBatch } from "../lib/gbrain-repo-policy-client";
import { canonicalizeRemote } from "../lib/gstack-memory-helpers";
const ROOT = path.resolve(import.meta.dir, "..");
@@ -219,3 +219,54 @@ describe("repoPolicyTier timeoutMs (hook deadline seam)", () => {
expect(repoPolicyTier(url, env(), 1)).toEqual({ tier: "none", error: "unreadable" });
});
});
describe("memorableRecallPolicy (#3359: per-remote Memorable recall opt-in)", () => {
const A = "https://github.com/acme/client-a.git";
test("no store: tier none, opt-in false, no error (fast path)", () => {
expect(memorableRecallPolicy(A, env())).toEqual({ tier: "none", memorableOptIn: false });
expect(fs.existsSync(policyFile())).toBe(false);
});
test("read-only defaults to off; the explicit opt-in turns it on for that remote only", () => {
expect(run(["set", A, "read-only"]).status).toBe(0);
expect(run(["set", "https://github.com/acme/client-b", "read-only"]).status).toBe(0);
expect(memorableRecallPolicy(A, env())).toEqual({ tier: "read-only", memorableOptIn: false });
expect(run(["memorable", "set", A, "allow"]).status).toBe(0);
expect(memorableRecallPolicy(A, env())).toEqual({ tier: "read-only", memorableOptIn: true });
expect(memorableRecallPolicy("https://github.com/acme/client-b", env())).toEqual({ tier: "read-only", memorableOptIn: false });
expect(memorableRecallPolicy("https://github.com/acme/other", env())).toEqual({ tier: "none", memorableOptIn: false });
});
test("deny with a hand-written opt-in: opt-in false", () => {
fs.writeFileSync(policyFile(), JSON.stringify({ _schema_version: 2, "github.com/acme/client-a": "deny", _memorable_recall: { "github.com/acme/client-a": "allow" } }));
expect(memorableRecallPolicy(A, env())).toEqual({ tier: "deny", memorableOptIn: false });
});
test("corrupt store: unreadable, never read as no policy, and not quarantined", () => {
fs.writeFileSync(policyFile(), "{not json", { mode: 0o600 });
expect(memorableRecallPolicy(A, env())).toEqual({ tier: "none", memorableOptIn: false, error: "unreadable" });
expect(fs.readFileSync(policyFile(), "utf-8")).toBe("{not json");
});
test("a tier the client does not know (hand-edited store) is unreadable, never no-policy", () => {
fs.writeFileSync(policyFile(), JSON.stringify({ _schema_version: 2, "github.com/acme/client-a": 7, _memorable_recall: { "github.com/acme/client-a": "allow" } }));
expect(memorableRecallPolicy(A, env())).toEqual({ tier: "none", memorableOptIn: false, error: "unreadable" });
});
test("a dangling symlink as the only store is not the no-store fast path: unreadable", () => {
fs.symlinkSync(path.join(tmpHome, "missing.json"), policyFile());
expect(hasRepoPolicyStore(env())).toBe(true);
expect(memorableRecallPolicy(A, env())).toEqual({ tier: "none", memorableOptIn: false, error: "unreadable" });
});
test("a dangling symlink above the store, or a file in its path, is not the no-store fast path", () => {
fs.symlinkSync(path.join(tmpHome, "missing-dir"), path.join(tmpHome, "link"));
const viaLink = { ...env(), GSTACK_TEST_LEGACY_ROOT: path.join(tmpHome, "link", "child") };
expect(hasRepoPolicyStore(viaLink)).toBe(true);
expect(memorableRecallPolicy(A, viaLink)).toEqual({ tier: "none", memorableOptIn: false, error: "unreadable" });
fs.writeFileSync(path.join(tmpHome, "plain-file"), "x");
expect(hasRepoPolicyStore({ ...env(), GSTACK_TEST_LEGACY_ROOT: path.join(tmpHome, "plain-file", "child") })).toBe(true);
fs.mkdirSync(path.join(tmpHome, "real-dir"));
fs.symlinkSync(path.join(tmpHome, "real-dir"), path.join(tmpHome, "good-link"));
expect(hasRepoPolicyStore({ ...env(), GSTACK_TEST_LEGACY_ROOT: path.join(tmpHome, "good-link", "child") })).toBe(false);
expect(hasRepoPolicyStore({ ...env(), GSTACK_TEST_LEGACY_ROOT: path.join(tmpHome, "no", "such", "root") })).toBe(false);
});
test("a timed-out spawn classifies as unreadable", () => {
expect(run(["set", A, "read-only"]).status).toBe(0);
expect(memorableRecallPolicy(A, env(), 1)).toEqual({ tier: "none", memorableOptIn: false, error: "unreadable" });
});
});
+178
View File
@@ -418,3 +418,181 @@ describe('gstack-gbrain-sync code stage honors the repo policy (#2140 sync path)
expect(r.text).not.toContain('refused');
});
});
describe('memorable recall opt-in (#3359)', () => {
const A = 'https://github.com/acme/client-a.git';
const memo = (url: string, extra: Record<string, string> = {}) => run(['memorable', 'get', url], { env: extra });
test('off by default: a read-only remote reports off until it is opted in', () => {
expect(run(['set', A, 'read-only']).status).toBe(0);
expect(memo(A).stdout).toBe('read-only\toff');
const r = run(['memorable', 'set', A, 'allow']);
expect(r.status).toBe(0);
expect(memo(A).stdout).toBe('read-only\tallow');
expect(readPolicy()._memorable_recall).toEqual({ 'github.com/acme/client-a': 'allow' });
expect(run(['list']).stdout).toBe('github.com/acme/client-a\tread-only\tmemorable=allow');
});
test('the opt-in is per remote: another remote, a prefix-sharing remote and an unset remote stay off; the SSH spelling of the same remote is the same key', () => {
for (const u of [A, 'https://github.com/acme/client-b', 'https://github.com/acme/client-a-fork', 'https://github.com/acme/client']) {
expect(run(['set', u, 'read-only']).status).toBe(0);
}
expect(run(['memorable', 'set', A, 'allow']).status).toBe(0);
expect(memo('https://github.com/acme/client-b').stdout).toBe('read-only\toff');
expect(memo('https://github.com/acme/client-a-fork').stdout).toBe('read-only\toff');
expect(memo('https://github.com/acme/client').stdout).toBe('read-only\toff');
expect(memo('https://gitlab.com/acme/client-a').stdout).toBe('unset\toff');
expect(memo('git@github.com:acme/client-a.git').stdout).toBe('read-only\tallow');
});
test('deny always wins: the opt-in is refused on deny, and a hand-written opt-in on a deny remote reads off', () => {
expect(run(['set', A, 'deny']).status).toBe(0);
const before = fs.readFileSync(policyFile(), 'utf-8');
const r = run(['memorable', 'set', A, 'allow']);
expect(r.status).toBe(2);
expect(r.stderr).toContain('deny tier always vetoes');
expect(fs.readFileSync(policyFile(), 'utf-8')).toBe(before);
fs.writeFileSync(policyFile(), JSON.stringify({ ...readPolicy(), _memorable_recall: { 'github.com/acme/client-a': 'allow' } }));
expect(memo(A).stdout).toBe('deny\toff');
});
test('the opt-in is refused on read-write and unset remotes (nothing to lift)', () => {
expect(run(['set', A, 'read-write']).status).toBe(0);
expect(run(['memorable', 'set', A, 'allow']).status).toBe(2);
expect(run(['memorable', 'set', 'https://github.com/acme/never-set', 'allow']).status).toBe(2);
expect(readPolicy()._memorable_recall).toBeUndefined();
});
test('changing the tier clears the opt-in, re-setting the same tier keeps it, and off removes it', () => {
run(['set', A, 'read-only']);
run(['memorable', 'set', A, 'allow']);
expect(run(['set', A, 'read-only']).stdout).not.toContain('Cleared');
expect(memo(A).stdout).toBe('read-only\tallow');
const flip = run(['set', A, 'read-write']);
expect(flip.stdout).toContain('Cleared the Memorable recall opt-in');
run(['set', A, 'read-only']);
expect(memo(A).stdout).toBe('read-only\toff');
run(['memorable', 'set', A, 'allow']);
expect(run(['memorable', 'set', A, 'off']).status).toBe(0);
expect(memo(A).stdout).toBe('read-only\toff');
expect(readPolicy()._memorable_recall).toBeUndefined();
});
test('a malformed opt-in reads off: any value but "allow", or a map that is not an object', () => {
run(['set', A, 'read-only']);
for (const bad of [{ 'github.com/acme/client-a': true }, { 'github.com/acme/client-a': 'ALLOW' }, 'allow', ['github.com/acme/client-a'], null]) {
fs.writeFileSync(policyFile(), JSON.stringify({ _schema_version: 2, 'github.com/acme/client-a': 'read-only', _memorable_recall: bad }));
expect(memo(A).stdout).toBe('read-only\toff');
}
});
test('a corrupt store fails closed: exit 2, never quarantined, store left as is', () => {
fs.writeFileSync(policyFile(), '{"_schema_version":2,"github.com/acme/client-a":"read-only",', { mode: 0o600 });
const r = memo(A);
expect(r.status).toBe(2);
expect(r.stdout).toBe('');
expect(r.stderr).toContain('corrupt');
expect(fs.readFileSync(policyFile(), 'utf-8')).toContain('"read-only",');
expect(fs.readdirSync(tmpHome).some((f) => f.includes('.corrupt-'))).toBe(false);
});
test('a second store that makes the remote read-only must opt it in too; its deny still wins; a corrupt second store fails closed', () => {
const legacy = path.join(tmpHome, 'legacy');
fs.mkdirSync(legacy);
const extra = { GSTACK_TEST_LEGACY_ROOT: legacy };
const legacyStore = path.join(legacy, 'gbrain-repo-policy.json');
run(['set', A, 'read-only'], { env: extra });
expect(run(['memorable', 'set', A, 'allow'], { env: extra }).status).toBe(0);
expect(memo(A, extra).stdout).toBe('read-only\tallow');
fs.writeFileSync(legacyStore, JSON.stringify({ _schema_version: 2, 'github.com/acme/client-a': 'read-only' }));
expect(memo(A, extra).stdout).toBe('read-only\toff');
expect(run(['memorable', 'set', A, 'allow'], { env: extra }).stderr).toContain('Opt in there too');
fs.writeFileSync(legacyStore, JSON.stringify({ _schema_version: 2, 'github.com/acme/client-a': 'read-only', _memorable_recall: { 'github.com/acme/client-a': 'allow' } }));
expect(memo(A, extra).stdout).toBe('read-only\tallow');
fs.writeFileSync(legacyStore, JSON.stringify({ _schema_version: 2, 'github.com/acme/client-a': 'deny', _memorable_recall: { 'github.com/acme/client-a': 'allow' } }));
expect(memo(A, extra).stdout).toBe('deny\toff');
fs.writeFileSync(legacyStore, '{');
expect(memo(A, extra).status).toBe(2);
});
test('a store path that is not a readable file fails closed, in either root', () => {
fs.mkdirSync(policyFile());
expect(memo(A).status).toBe(2);
fs.rmdirSync(policyFile());
const legacy = path.join(tmpHome, 'legacy');
fs.mkdirSync(path.join(legacy, 'gbrain-repo-policy.json'), { recursive: true });
const r = memo(A, { GSTACK_TEST_LEGACY_ROOT: legacy });
expect(r.status).toBe(2);
expect(r.stderr).toContain('not a readable file');
});
test('review hardening: empty, non-object or multi-document stores, and invalid tier values, fail closed in either root', () => {
const legacy = path.join(tmpHome, 'legacy');
fs.mkdirSync(legacy);
const extra = { GSTACK_TEST_LEGACY_ROOT: legacy };
const legacyStore = path.join(legacy, 'gbrain-repo-policy.json');
run(['set', A, 'read-only']);
for (const bad of ['', ' \n', 'null', '[]', '7', '{}{}']) {
fs.writeFileSync(legacyStore, bad);
const r = memo(A, extra);
expect([bad, r.status, r.stdout]).toEqual([bad, 2, '']);
}
fs.rmSync(legacyStore);
for (const value of [false, null, 7, 'none', 'Read-Only']) {
fs.writeFileSync(policyFile(), JSON.stringify({ _schema_version: 2, 'github.com/acme/client-a': value }));
expect([value, memo(A).status]).toEqual([value, 2]);
}
fs.writeFileSync(policyFile(), JSON.stringify({ _schema_version: 2, 'github.com/acme/client-a': false }));
fs.writeFileSync(legacyStore, JSON.stringify({ 'github.com/acme/client-a': 'read-only', _memorable_recall: { 'github.com/acme/client-a': 'allow' } }));
expect(memo(A, extra).status).toBe(2);
});
test('review hardening: a dangling symlink or an unsearchable directory is never read as no store', () => {
fs.symlinkSync(path.join(tmpHome, 'missing.json'), policyFile());
expect(memo(A).status).toBe(2);
fs.rmSync(policyFile());
const legacy = path.join(tmpHome, 'legacy');
fs.mkdirSync(legacy);
fs.symlinkSync(path.join(tmpHome, 'missing.json'), path.join(legacy, 'gbrain-repo-policy.json'));
expect(memo(A, { GSTACK_TEST_LEGACY_ROOT: legacy }).status).toBe(2);
fs.rmSync(path.join(legacy, 'gbrain-repo-policy.json'));
if (!canRevokeReads()) return;
fs.writeFileSync(path.join(legacy, 'gbrain-repo-policy.json'), JSON.stringify({ 'github.com/acme/client-a': 'deny' }));
fs.chmodSync(legacy, 0o600);
try {
expect(memo(A, { GSTACK_TEST_LEGACY_ROOT: legacy }).status).toBe(2);
} finally {
fs.chmodSync(legacy, 0o700);
}
const nested = path.join(tmpHome, 'ancestor', 'nested');
fs.mkdirSync(nested, { recursive: true });
fs.writeFileSync(path.join(nested, 'gbrain-repo-policy.json'), JSON.stringify({ 'github.com/acme/client-a': 'deny' }));
fs.chmodSync(path.join(tmpHome, 'ancestor'), 0o600);
try {
const r = memo(A, { GSTACK_TEST_LEGACY_ROOT: nested });
expect([r.status, r.stdout]).toEqual([2, '']);
expect(r.stderr).toContain('not a searchable directory');
} finally {
fs.chmodSync(path.join(tmpHome, 'ancestor'), 0o700);
}
const absentUnder = path.join(tmpHome, 'no', 'such', 'root');
expect(memo(A, { GSTACK_TEST_LEGACY_ROOT: absentUnder }).stdout).toBe('unset\toff');
});
test('review hardening: the lookup never writes: a schema-less store is not migrated or rewritten', () => {
const legacyShape = JSON.stringify({ 'github.com/acme/client-a': 'read-only', 'github.com/acme/old': 'allow', _memorable_recall: { 'github.com/acme/client-a': 'allow' } });
fs.writeFileSync(policyFile(), legacyShape);
expect(memo(A).stdout).toBe('read-only\tallow');
expect(memo('https://github.com/acme/old').stdout).toBe('read-write\toff');
expect(fs.readFileSync(policyFile(), 'utf-8')).toBe(legacyShape);
});
test('the two metadata keys are never stored as remotes; the _unattributed sentinel still is', () => {
const r = run(['set', '_memorable_recall', 'read-write']);
expect(r.status).toBe(2);
expect(r.stderr).toContain('reserved key');
expect(run(['set', '_schema_version', 'deny']).status).toBe(2);
expect(run(['set', '_unattributed', 'deny']).status).toBe(0);
expect(run(['list']).stdout).toBe('_unattributed\tdeny');
});
});
+1 -1
View File
@@ -539,7 +539,7 @@ do not launch the downstream skill or open a browser.`,
},
behavioral: 'prompt',
maxSkeletonBytes: 74_500, // + Aside browser contract for Step 7 canary ({{ASIDE_SETUP}}); measured 73_523
maxSizeRatio: 1.1120, // + v1.81 Aside contract + gstack-browser fallback block; measured 1.077. + both untrusted-content marker formats in the browser fallback (W7f) + the readiness gate's project test command and live eval-store paths (s06 H6/H7); measured 1.1076 (2026-10-02). Re-measured 1.0943 (2026-10-03); cap = measured + 0.005 headroom. + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 115,226 / 104,578 = 1.1018 (2026-10-07). + Honest Work wave merged (W2/W3 gate integrity in review/ship, W4 kernel + DONE line in every tier-2+ skill, W5/W7 in spec/ship): re-measured on the integrated tree (2026-10-10).
maxSizeRatio: 1.125, // + #3318 Step 3.4 reads the ship policy and prints one VERSION_CHECK verdict (owner-approved raise, Garry 2026-10-24: "do it"); measured 1.1201 (2026-10-24). Before: 1.1120. + v1.81 Aside contract + gstack-browser fallback block; measured 1.077. + both untrusted-content marker formats in the browser fallback (W7f) + the readiness gate's project test command and live eval-store paths (s06 H6/H7); measured 1.1076 (2026-10-02). Re-measured 1.0943 (2026-10-03); cap = measured + 0.005 headroom. + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 115,226 / 104,578 = 1.1018 (2026-10-07). + Honest Work wave merged (W2/W3 gate integrity in review/ship, W4 kernel + DONE line in every tier-2+ skill, W5/W7 in spec/ship): re-measured on the integrated tree (2026-10-10).
minUnionBytes: 91_000, // Phase 4 wave 1; estimated union ~94.9KB
mustContain: ['readiness', 'merge', 'canary', 'revert', 'staging'],
},
+1 -1
View File
@@ -1,6 +1,6 @@
import type { CsoStack } from '../../lib/cso/preparation';
type RuntimeStack = Exclude<CsoStack, 'java'>;
type RuntimeStack = Exclude<CsoStack, 'java' | 'go'>;
import { canonical, sha256 } from '../../lib/cso/contracts';
import { ISOLATION_POLICY_HASH } from '../../lib/cso/docker';
import {
+1
View File
@@ -138,6 +138,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = {
'test/fixtures/investigate-owned-question-39195396438.json': ['test/workflow-boundaries-fixture.test.ts'],
'test/fixtures/judge-calibration/**': ['scripts/judge-calibration.ts', 'test/judge-calibration.test.ts'],
'test/fixtures/judge-panel-replay-2026-10-05.json': ['test/judge-panel-median.test.ts'],
'test/fixtures/merge-train-3345/**': ['test/changelog-merge-damage.test.ts', 'test/compare-pr-version.test.ts'],
'test/fixtures/module-size-ratchet.json': ['test/helpers/module-size.ts', 'test/module-size-ratchet.test.ts'],
'test/fixtures/module-size/**': ['test/helpers/module-size.ts', 'test/module-size-ratchet.test.ts'],
'test/fixtures/multi-agent-wave/**': ['test/headless-artifacts.test.ts', 'test/helpers/autoplan-run-fixture.ts', 'test/plan-reality.test.ts'],
+2 -2
View File
@@ -68,8 +68,8 @@ export const SAFETY_RULES: readonly SafetyRule[] = [
evalId: 'safety-ios-demo-ui-only',
source: 'ios-qa/SKILL.md.tmpl',
section: '## Demo mode',
match: /demo mode overrides/i,
sha256: '8d42208c888d76af49ebe6e4d58e85537c979f53ecb32fff7e85e95e6859182a',
match: /drive every action through visible UI/i,
sha256: '0ba3230bff9de32f03719daec35c6cef762e15c550264fcffd342dde52291e21',
},
];
+15 -4
View File
@@ -9,6 +9,7 @@
* artifact downloads and check-run reads. Every call is logged, so tests can
* prove what was (and was not) dispatched.
*/
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
@@ -58,7 +59,7 @@ export function repoKey(fx: TrainFixture): string {
}
/** A same-repo PR: a branch from origin/main touching `file`, published as refs/pull/<n>/head (and /merge), known to the gh shim. */
export function openPr(fx: TrainFixture, pr: string, opts: { file?: string; text?: string; changelog?: boolean; cross?: boolean; from?: string } = {}): string {
export function openPr(fx: TrainFixture, pr: string, opts: { file?: string; text?: string; changelog?: boolean | ((text: string) => string); cross?: boolean; from?: string } = {}): string {
const { repo } = fx;
repo.git('checkout', '-q', opts.from ?? 'origin/main', '-B', `pr-${pr}`);
const file = opts.file ?? `pr-${pr}.txt`;
@@ -66,7 +67,7 @@ export function openPr(fx: TrainFixture, pr: string, opts: { file?: string; text
fs.writeFileSync(path.join(repo.work, file), opts.text ?? `change from #${pr}\n`);
if (opts.changelog !== false) {
const cl = fs.readFileSync(path.join(repo.work, 'CHANGELOG.md'), 'utf8');
fs.writeFileSync(path.join(repo.work, 'CHANGELOG.md'), cl.replace('# Changelog\n', `# Changelog\n\n## [Unreleased]\n\n- #${pr} change\n`));
fs.writeFileSync(path.join(repo.work, 'CHANGELOG.md'), typeof opts.changelog === 'function' ? opts.changelog(cl) : cl.replace('# Changelog\n', `# Changelog\n\n## [Unreleased]\n\n- #${pr} change\n`));
}
repo.git('add', '-A');
repo.git('commit', '-q', '-m', `feat #${pr}`);
@@ -76,9 +77,19 @@ export function openPr(fx: TrainFixture, pr: string, opts: { file?: string; text
return head;
}
/** The repo key of a GitHub-form origin URL: sha256 of the URL with .git and trailing slashes dropped. */
export const urlKey = (url: string) => createHash('sha256').update(url.replace(/\.git$/, '').replace(/\/+$/, '')).digest('hex').slice(0, 16);
/** Point the fixture clone's origin at a GitHub-form URL that git rewrites to the local bare origin (url.insteadOf). */
export function githubOrigin(fx: TrainFixture, url: string, cwd = fx.repo.work): void {
const git = (...args: string[]) => spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000, env: { ...process.env, ...fx.repo.env } });
git('config', `url.${fx.repo.origin}.insteadOf`, url);
git('remote', 'set-url', 'origin', url);
}
/** A READY receipt as `ready --screen|--no-screen` writes it (the lane side is tested separately). */
export function readyReceipt(fx: TrainFixture, pr: string, head: string, opts: { screen?: boolean; at?: string } = {}): void {
const key = repoKey(fx);
export function readyReceipt(fx: TrainFixture, pr: string, head: string, opts: { screen?: boolean; at?: string; key?: string } = {}): void {
const key = opts.key ?? repoKey(fx);
const file = path.join(fx.state, 'ship-queue', 'ready', key, `${pr}-${head}.json`);
fs.mkdirSync(path.dirname(file), { recursive: true });
const at = opts.at ?? '2026-10-18T08:00:00.000Z';
+193
View File
@@ -0,0 +1,193 @@
/**
* /land-and-deploy Step 3.4 VERSION check (#3318). The old step compared the
* branch VERSION with the next free patch slot, so it stopped stamp-at-merge
* PRs that share a tentative stamp, a claim-at-open PR whose sibling claimed a
* higher slot, and every MICRO bump. These tests run the template's own block
* against a real git fixture and the real gstack-ship-policy, with a stubbed
* gstack-next-version reply, and pin each verdict, including the real stops.
*/
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
const ROOT = join(import.meta.dir, '..');
const STUB = `process.stdout.write(process.env.FAKE_QUEUE_JSON ?? '');
process.exit(Number(process.env.FAKE_QUEUE_CODE ?? 0));
`;
function step34(): string {
const tmpl = readFileSync(join(ROOT, 'land-and-deploy', 'SKILL.md.tmpl'), 'utf8');
const step = tmpl.slice(tmpl.indexOf('## Step 3.4:'), tmpl.indexOf('{{SECTION:readiness-gate}}'));
const blocks = [...step.matchAll(/```bash\n([\s\S]*?)\n```/g)].map(m => m[1]);
expect(blocks).toHaveLength(1);
return blocks[0];
}
let root: string;
let dir: string;
let repo: string;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'lad-version-'));
writeFileSync(join(root, 'next-version.ts'), STUB);
});
afterEach(() => rmSync(root, { recursive: true, force: true }));
function git(...args: string[]): string {
const r = spawnSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.com', ...args], { cwd: repo, encoding: 'utf8', timeout: 15_000 });
if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);
return r.stdout.trim();
}
const changelog = (...versions: string[]) => `# Changelog\n\n${versions.map(v => `## [${v}] - 2026-10-24\n\n- entry\n`).join('\n')}`;
interface Tree { version?: string; changelog?: string; policy?: string }
function commit(tree: Tree, message: string): string {
for (const [file, body] of [['VERSION', tree.version], ['CHANGELOG.md', tree.changelog], ['.gstack/ship-policy.json', tree.policy]] as const) {
if (body === undefined) continue;
mkdirSync(join(repo, file, '..'), { recursive: true });
writeFileSync(join(repo, file), body.endsWith('\n') ? body : `${body}\n`);
}
git('add', '-A');
git('commit', '-q', '--allow-empty', '-m', message);
return git('rev-parse', 'HEAD');
}
interface Case {
mode?: 'stamp-at-merge' | 'claim-at-open' | 'none' | 'invalid';
base: Tree;
head: Tree;
queue?: object | string;
queueCode?: number;
shell?: 'bash' | 'zsh';
}
function verdict(c: Case): string {
dir = mkdtempSync(join(root, 'case-'));
repo = join(dir, 'repo');
mkdirSync(repo);
git('init', '-q', '-b', 'main');
const policy = c.mode === 'none' || c.mode === undefined ? undefined
: c.mode === 'invalid' ? '{"queue_mode": '
: JSON.stringify({ queue_mode: c.mode, bump: 'patch' });
const baseSha = commit({ ...c.base, policy }, 'base');
spawnSync('git', ['init', '-q', '--bare', join(dir, 'origin.git')], { timeout: 15_000 });
git('remote', 'add', 'origin', join(dir, 'origin.git'));
git('push', '-q', 'origin', 'main');
git('checkout', '-q', '-b', 'feature');
const head = commit(c.head, 'head');
const queue = c.queue ?? { offline: false, claimed: [], complete: true };
const block = step34()
.replaceAll('~/.claude/skills/gstack/bin/gstack-ship-policy', join(ROOT, 'bin', 'gstack-ship-policy'))
.replaceAll('~/.claude/skills/gstack/bin/gstack-next-version', join(root, 'next-version.ts'));
const r = spawnSync(c.shell ?? 'bash', ['-c', block], {
cwd: repo,
encoding: 'utf8',
timeout: 60_000,
env: {
...process.env,
PR_HEAD: head, BASE_SHA: baseSha, BASE_BRANCH: 'main', PR_NUMBER: '7',
FAKE_QUEUE_JSON: typeof queue === 'string' ? queue : JSON.stringify(queue),
FAKE_QUEUE_CODE: String(c.queueCode ?? 0),
},
});
const line = r.stdout.split('\n').find(l => l.startsWith('VERSION_CHECK: '));
if (!line) throw new Error(`no VERSION_CHECK line (exit ${r.status}):\n${r.stdout}\n${r.stderr}`);
return line;
}
const claim = (pr: number, version: string) => ({ pr, branch: `b${pr}`, version });
const BASE: Tree = { version: '1.91.186.0', changelog: changelog('1.91.186.0') };
const stamped = (version: string, below = '1.91.186.0'): Tree => ({ version, changelog: changelog(version, below) });
describe('stamp-at-merge: verify the exact head stamp, ignore claims', () => {
test('a sibling sharing the tentative stamp no longer stops the PR', () => {
expect(verdict({ mode: 'stamp-at-merge', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [claim(8, '1.91.187.0')], complete: true } }))
.toBe('VERSION_CHECK: ok (stamp-at-merge: 1.91.187.0, base 1.91.186.0)');
});
test('a numeric one-bump stamp passes (9 -> 10)', () => {
expect(verdict({ mode: 'stamp-at-merge', base: { version: '1.91.9.0', changelog: changelog('1.91.9.0') }, head: { version: '1.91.10.0', changelog: changelog('1.91.10.0', '1.91.9.0') } })).toStartWith('VERSION_CHECK: ok (stamp-at-merge:');
});
test('a MICRO stamp is one bump and passes', () => {
expect(verdict({ mode: 'stamp-at-merge', base: BASE, head: stamped('1.91.186.1') })).toStartWith('VERSION_CHECK: ok (stamp-at-merge:');
});
test('claims offline do not matter under stamp-at-merge', () => {
expect(verdict({ mode: 'stamp-at-merge', base: BASE, head: stamped('1.91.187.0'), queue: '', queueCode: 1 })).toStartWith('VERSION_CHECK: ok (stamp-at-merge:');
});
test('stops when the base already reached the stamp (a sibling landed first)', () => {
expect(verdict({ mode: 'stamp-at-merge', base: stamped('1.91.187.0'), head: stamped('1.91.187.0') }))
.toBe('VERSION_CHECK: STOP stamp stale (stamp-at-merge: 1.91.187.0, base 1.91.187.0)');
});
test('stops when the base moved under a stamp that is still one bump above it', () => {
expect(verdict({ mode: 'stamp-at-merge', base: stamped('1.91.186.1'), head: stamped('1.91.187.0') })).toStartWith('VERSION_CHECK: STOP stamp stale');
});
test('stops on an unstamped [Unreleased] entry and on a stamp more than one bump up', () => {
expect(verdict({ mode: 'stamp-at-merge', base: BASE, head: { version: '1.91.187.0', changelog: changelog('Unreleased', '1.91.186.0') } })).toStartWith('VERSION_CHECK: STOP stamp stale');
expect(verdict({ mode: 'stamp-at-merge', base: BASE, head: stamped('1.91.188.0') })).toStartWith('VERSION_CHECK: STOP stamp stale');
});
});
describe('claim-at-open: stop only on a real collision', () => {
test('versions compare numerically, and 3-digit semver works', () => {
expect(verdict({ mode: 'claim-at-open', base: { version: '1.91.9.0' }, head: { version: '1.91.10.0' } })).toStartWith('VERSION_CHECK: ok (claim-at-open:');
expect(verdict({ mode: 'claim-at-open', base: { version: '1.91.10.0' }, head: { version: '1.91.9.0' } })).toStartWith('VERSION_CHECK: STOP base is at or above it');
expect(verdict({ mode: 'claim-at-open', base: { version: '2.14.9' }, head: { version: '2.14.10' } })).toStartWith('VERSION_CHECK: ok (claim-at-open:');
expect(verdict({ mode: 'claim-at-open', base: { version: '2.14.9' }, head: { version: '2.14.9.1' } })).toStartWith('VERSION_CHECK: unavailable: bad version');
});
test('a sibling holding a higher claim no longer stops the PR', () => {
expect(verdict({ mode: 'claim-at-open', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [claim(8, '1.91.188.0')], complete: true } }))
.toBe('VERSION_CHECK: ok (claim-at-open: 1.91.187.0, base 1.91.186.0)');
});
test('a MICRO bump passes', () => {
expect(verdict({ mode: 'claim-at-open', base: BASE, head: stamped('1.91.186.1') })).toStartWith('VERSION_CHECK: ok (claim-at-open:');
});
test('stops when another open PR holds the same VERSION', () => {
expect(verdict({ mode: 'claim-at-open', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [claim(8, '1.91.187.0'), claim(9, '1.91.188.0')], complete: true } }))
.toBe('VERSION_CHECK: STOP also claimed by #8 (claim-at-open: 1.91.187.0, base 1.91.186.0)');
});
test('stops when the base is at or above the branch VERSION', () => {
expect(verdict({ mode: 'claim-at-open', base: stamped('1.91.187.0'), head: stamped('1.91.187.0') })).toStartWith('VERSION_CHECK: STOP base is at or above it');
expect(verdict({ mode: 'claim-at-open', base: stamped('1.91.188.0'), head: stamped('1.91.187.0') })).toStartWith('VERSION_CHECK: STOP base is at or above it');
});
test('a repo with no policy file gets the claim-at-open default', () => {
expect(verdict({ mode: 'none', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [claim(8, '1.91.187.0')], complete: true } })).toStartWith('VERSION_CHECK: STOP also claimed by #8');
});
test('offline claims and unreadable claims are unavailable, but a known collision still stops', () => {
expect(verdict({ mode: 'claim-at-open', base: BASE, head: stamped('1.91.187.0'), queue: { offline: true } })).toStartWith('VERSION_CHECK: unavailable: claims unread');
expect(verdict({ mode: 'claim-at-open', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [], unknown_claims: [9], complete: false } })).toStartWith('VERSION_CHECK: unavailable: claims unread');
expect(verdict({ mode: 'claim-at-open', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [claim(8, '1.91.187.0')], unknown_claims: [9], complete: false } })).toStartWith('VERSION_CHECK: STOP also claimed by #8');
});
});
describe('either mode', () => {
test.skipIf(!Bun.which('zsh'))('the block gives the same verdicts under zsh', () => {
expect(verdict({ shell: 'zsh', mode: 'stamp-at-merge', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [claim(8, '1.91.187.0')], complete: true } })).toStartWith('VERSION_CHECK: ok (stamp-at-merge:');
expect(verdict({ shell: 'zsh', mode: 'stamp-at-merge', base: stamped('1.91.186.1'), head: stamped('1.91.187.0') })).toStartWith('VERSION_CHECK: STOP stamp stale');
expect(verdict({ shell: 'zsh', mode: 'claim-at-open', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [claim(8, '1.91.187.0')], complete: true } })).toStartWith('VERSION_CHECK: STOP also claimed by #8');
});
test('no configured version source is not applicable', () => {
expect(verdict({ mode: 'stamp-at-merge', base: {}, head: {}, queue: { no_version: true, version: null } })).toStartWith('VERSION_CHECK: NO_VERSION');
});
test('a VERSION missing on one side is unavailable, not green', () => {
expect(verdict({ mode: 'claim-at-open', base: { changelog: changelog('1.91.186.0') }, head: stamped('1.91.187.0') })).toStartWith('VERSION_CHECK: unavailable: bad version');
});
test('an invalid policy is unavailable, but a base at or above the branch still stops', () => {
expect(verdict({ mode: 'invalid', base: BASE, head: stamped('1.91.187.0'), queue: { offline: false, claimed: [claim(8, '1.91.187.0')], complete: true } })).toStartWith('VERSION_CHECK: unavailable: no policy');
expect(verdict({ mode: 'invalid', base: stamped('1.91.187.0'), head: stamped('1.91.187.0') })).toStartWith('VERSION_CHECK: STOP base is at or above it');
});
});
+115
View File
@@ -243,6 +243,121 @@ describe('gate on: the mediated hand-off', () => {
}
});
test('#3359 per-remote opt-in: lifts read-only for that remote only; default, other remotes, deny and a corrupt store stay blocked', () => {
gateOn();
const policy = (...args: string[]) => spawnSync('bash', [POLICY, ...args], { env, encoding: 'utf8', timeout: 20_000 });
const store = path.join(home, '.gstack', 'gbrain-repo-policy.json');
const repos: Record<string, string> = {};
try {
for (const [name, url] of [['a', 'https://github.com/example/client-a.git'], ['b', 'https://github.com/example/client-b.git']]) {
const repo = fs.mkdtempSync(path.join(os.tmpdir(), `gstack-memo-optin-${name}-`));
spawnSync('git', ['init', '-q'], { cwd: repo, timeout: 10_000 });
spawnSync('git', ['remote', 'add', 'origin', url], { cwd: repo, timeout: 10_000 });
isolateGitRemote(repo, url);
expect(policy('set', url, 'read-only').status).toBe(0);
repos[name] = repo;
}
const hook = (name: string) => {
fs.rmSync(path.join(home, 'calls.log'), { force: true });
return runHook(JSON.stringify({ prompt: 'hello', cwd: repos[name] }), {}, repos[name]);
};
// default: read-only stays blocked
expect(hook('a').stdout).toBe('');
expect(calls()).toBe('');
expect(errLog()).toContain('memorable set <origin-url> allow');
// opt-in on client-a: recall runs there, and does not leak to client-b
expect(policy('memorable', 'set', 'https://github.com/example/client-a.git', 'allow').status).toBe(0);
expect(hook('a').stdout).toContain('remembered');
expect(calls()).toBe('hook user-prompt\n');
expect(hook('b').stdout).toBe('');
expect(calls()).toBe('');
// deny beats an opt-in, even one written into the store by hand
expect(policy('set', 'https://github.com/example/client-a.git', 'deny').status).toBe(0);
const s = JSON.parse(fs.readFileSync(store, 'utf8'));
fs.writeFileSync(store, JSON.stringify({ ...s, _memorable_recall: { 'github.com/example/client-a': 'allow' } }));
expect(hook('a').stdout).toBe('');
expect(calls()).toBe('');
// a corrupt store fails closed and is left in place (never quarantined into "no policy")
fs.writeFileSync(store, '{"_schema_version":2,"github.com/example/client-b":"read-only",');
expect(hook('b')).toEqual({ status: 0, stdout: '', stderr: '' });
expect(calls()).toBe('');
expect(errLog()).toContain('trust policy lookup failed');
expect(fs.readFileSync(store, 'utf8')).toContain('"read-only",');
expect(hook('b').stdout).toBe('');
expect(calls()).toBe('');
} finally {
for (const repo of Object.values(repos)) fs.rmSync(repo, { recursive: true, force: true });
}
});
test('#3359 review: a url.insteadOf rewrite to another host does not dodge a deny, and a dangling-symlink store fails closed', () => {
gateOn();
const url = 'https://fixture.invalid/org/denied.git';
const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-memo-rewrite-'));
try {
spawnSync('git', ['init', '-q'], { cwd: repo, timeout: 10_000 });
spawnSync('git', ['remote', 'add', 'origin', url], { cwd: repo, timeout: 10_000 });
spawnSync('git', ['config', '--local', 'url.https://mirror.invalid/.insteadOf', 'https://fixture.invalid/'], { cwd: repo, timeout: 10_000 });
expect(spawnSync('git', ['remote', 'get-url', 'origin'], { cwd: repo, encoding: 'utf8', timeout: 10_000 }).stdout.trim()).toBe('https://mirror.invalid/org/denied.git');
expect(spawnSync('bash', [POLICY, 'set', url, 'deny'], { env, encoding: 'utf8', timeout: 20_000 }).status).toBe(0);
const prompt = JSON.stringify({ prompt: 'hello', cwd: repo });
expect(runHook(prompt, {}, repo).stdout).toBe('');
expect(calls()).toBe('');
const store = path.join(home, '.gstack', 'gbrain-repo-policy.json');
fs.rmSync(store);
fs.symlinkSync(path.join(home, 'missing.json'), store);
expect(runHook(prompt, {}, repo)).toEqual({ status: 0, stdout: '', stderr: '' });
expect(calls()).toBe('');
expect(errLog()).toContain('trust policy lookup failed');
} finally {
fs.rmSync(repo, { recursive: true, force: true });
}
});
test('#3359 review: a second configured origin URL cannot dodge the first URL\'s deny, in either order', () => {
gateOn();
const denied = 'https://fixture.invalid/org/denied.git';
const other = 'https://fixture.invalid/org/unlisted.git';
expect(spawnSync('bash', [POLICY, 'set', denied, 'deny'], { env, encoding: 'utf8', timeout: 20_000 }).status).toBe(0);
for (const order of [[denied, other], [other, denied]]) {
const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-memo-multi-'));
try {
spawnSync('git', ['init', '-q'], { cwd: repo, timeout: 10_000 });
spawnSync('git', ['remote', 'add', 'origin', order[0]], { cwd: repo, timeout: 10_000 });
spawnSync('git', ['config', '--local', '--add', 'remote.origin.url', order[1]], { cwd: repo, timeout: 10_000 });
for (const u of order) spawnSync('git', ['config', '--local', `url.${u}.insteadOf`, u], { cwd: repo, timeout: 10_000 });
fs.rmSync(path.join(home, 'calls.log'), { force: true });
expect(runHook(JSON.stringify({ prompt: 'hello', cwd: repo }), {}, repo).stdout).toBe('');
expect(calls()).toBe('');
} finally {
fs.rmSync(repo, { recursive: true, force: true });
}
}
});
test('#3359 review: an origin URL with a newline or edge whitespace (valid local paths) is looked up verbatim, so its deny holds', () => {
gateOn();
for (const name of ['remote\nname.git', 'remote.git ', ' remote.git']) {
const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-memo-nl-'));
try {
const remote = path.join(parent, name);
fs.mkdirSync(remote);
expect(spawnSync('git', ['init', '-q', '--bare', remote], { timeout: 10_000 }).status).toBe(0);
const repo = path.join(parent, 'work');
fs.mkdirSync(repo);
spawnSync('git', ['init', '-q'], { cwd: repo, timeout: 10_000 });
spawnSync('git', ['remote', 'add', 'origin', remote], { cwd: repo, timeout: 10_000 });
expect(spawnSync('bash', [POLICY, 'set', remote, 'deny'], { env, encoding: 'utf8', timeout: 20_000 }).status).toBe(0);
expect(spawnSync('bash', [POLICY, 'memorable', 'get', remote], { env, encoding: 'utf8', timeout: 20_000 }).stdout).toBe('deny\toff\n');
fs.rmSync(path.join(home, 'calls.log'), { force: true });
expect([name, runHook(JSON.stringify({ prompt: 'hello', cwd: repo }), {}, repo).stdout]).toEqual([name, '']);
expect(calls()).toBe('');
} finally {
fs.rmSync(parent, { recursive: true, force: true });
}
}
});
test('gate flipped off between two runs: the second run spawns nothing (the mid-flight re-check itself cannot be interleaved from outside)', () => {
// The pre-spawn re-check reads the same store; a deterministic mid-flight flip would need a
// seam inside main(). This pins the observable contract only: once off, no spawn.
+74 -2
View File
@@ -5,12 +5,14 @@
* FINDINGS: none` for all of them. The fixtures in
* test/fixtures/outside-review-severity/codex-3105/ are synthesized from the
* forms the issue documents (it describes 13 replies but does not include them).
* #3329: that same gate then printed `clean` for a parsed advisory finding
* whose last `Verdict:` line says `not ready`. `bare-dash-p2.txt` is unchanged.
*/
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { classifyOutsideReview, type OutsideGate } from '../lib/outside-review-result';
import { classifyOutsideReview, validateOutsideReview, type OutsideGate } from '../lib/outside-review-result';
import { GATE_OUTCOMES } from '../lib/gate-outcomes';
const ROOT = path.resolve(import.meta.dir, '..');
@@ -26,7 +28,7 @@ describe('#3105 Codex reply shapes under the execution gate', () => {
for (const [name, status, stdout] of [
['plan-bold-dash.txt', 3, 'VERDICT: findings\nFINDINGS: P1\n'],
['diff-numbered-dash.txt', 3, 'VERDICT: findings\nFINDINGS: P1\n'],
['bare-dash-p2.txt', 0, 'VERDICT: clean\nFINDINGS: P2\n'],
['bare-dash-p2.txt', 3, 'VERDICT: findings\nFINDINGS: P2\n'],
['ready-one-p3.txt', 0, 'VERDICT: clean\nFINDINGS: P3\n'],
['table-p1.txt', 3, 'VERDICT: findings\nFINDINGS: P1\n'],
['not-ready-unlabeled.txt', 3, 'VERDICT: findings\nFINDINGS: unspecified\n'],
@@ -112,3 +114,73 @@ describe('#3105 severity forms are read by every gate that summarises a review',
expect(classifyOutsideReview({ text: proposal, gate: 'proposal' }).verdict).toBe('clean');
});
});
describe('#3329 a last not-ready Verdict blocks even with advisory findings', () => {
const ISSUE = '1. **P2 — The docs lag the new flag.**\n2. **P3 — Rename the helper.**\nVerdict: not ready (1 P1/P2)';
const P2 = '1. **P2 — The docs lag the new flag.**';
const textFor = (gate: OutsideGate, text: string) => gate === 'review' ? `${text}\n${REC}` : text;
const see = (text: string, gate: OutsideGate) => {
const r = classifyOutsideReview({ text: textFor(gate, text), gate });
return { verdict: r.verdict as string, highest: r.findings.highest as string | null, reason: (r.reason ?? null) as string | null, unparsed: r.unparsed ?? null };
};
test('numbered bold P2 plus P3 with not ready is findings/P2 on execution, structured and review', () => {
for (const gate of ['execution', 'structured', 'review'] as const)
expect({ gate, ...see(ISSUE, gate) }).toEqual({ gate, verdict: 'findings', highest: 'P2', reason: null, unparsed: null });
expect(validateOutsideReview(ISSUE, 'structured')).toEqual({ completed: true, gate: 'fail' });
});
test('P3-only and unlabeled not-ready replies block; P0/P1 block even when the last Verdict says ready', () => {
for (const gate of ['execution', 'structured', 'review'] as const) {
expect({ gate, ...see('1. **P3 — Rename the helper.**\nVerdict: not ready', gate) }).toEqual({ gate, verdict: 'findings', highest: 'P3', reason: null, unparsed: null });
expect({ gate, ...see('The retry path can double-send.\nVerdict: not ready', gate) }).toEqual({ gate, verdict: 'findings', highest: null, reason: null, unparsed: null });
}
expect(see('1. **P1 — The cap is ignored.**\nVerdict: ready', 'review')).toMatchObject({ verdict: 'findings', highest: 'P1' });
expect(see('**P0 — Secrets reach the log.**\nVerdict: ready', 'execution')).toMatchObject({ verdict: 'findings', highest: 'P0' });
});
test('advisory P2/P3 with ready or no Verdict stay clean', () => {
for (const text of [
`${P2}\n2. **P3 — Rename the helper.**\nVerdict: ready`,
`${P2}\n2. **P3 — Rename the helper.**`,
'1. **P3 — Rename the helper.**\nVerdict: ready (1 P3)',
]) {
const r = see(text, 'execution');
expect({ text, verdict: r.verdict, highest: r.highest }).toEqual({ text, verdict: 'clean', highest: text.includes('P2') ? 'P2' : 'P3' });
}
expect(see(`${P2}\nVerdict: ready`, 'review').verdict).toBe('clean');
expect(validateOutsideReview(`${P2}\nVerdict: ready`, 'structured')).toEqual({ completed: true, gate: 'pass' });
});
test('the last recognized Verdict wins, including supported formatting; quotes do not', () => {
expect(see(`${P2}\nVerdict: ready\nVerdict: not ready (1 P1/P2)`, 'execution')).toMatchObject({ verdict: 'findings', highest: 'P2' });
expect(see(`${P2}\nVerdict: not ready (1 P1/P2)\nVerdict: ready`, 'execution').verdict).toBe('clean');
for (const verdictLine of ['**Verdict:** not ready', '- Verdict: not ready', '### Verdict: not ready'])
expect({ verdictLine, ...see(`${P2}\n${verdictLine}`, 'execution') }).toMatchObject({ verdict: 'findings', highest: 'P2' });
expect(see(`${P2}\nVerdict: not ready\n### Verdict: ready`, 'execution').verdict).toBe('clean');
const fence = ['```', 'Verdict: not ready (2 P2)', '```'].join('\n');
expect(see(`${P2}\nVerdict: ready\n${fence}`, 'execution').verdict).toBe('clean');
expect(see(`${fence}\n${P2}\nVerdict: not ready`, 'execution')).toMatchObject({ verdict: 'findings', highest: 'P2' });
expect(see(`${P2}\nVerdict: ready\nThe rubric says \`Verdict: not ready\`.`, 'execution').verdict).toBe('clean');
expect(see(`${P2}\nThe rubric says \`Verdict: not ready\`.`, 'execution').verdict).toBe('clean');
expect(see(`No issues found.\n${fence}`, 'review').verdict).toBe('clean');
});
test('parsed P2 plus an unparsed label and not-ready still blocks and keeps the diagnostic', () => {
const text = `${P2}\n## P1/P2 findings\nVerdict: not ready`;
expect(see(text, 'execution')).toEqual({ verdict: 'findings', highest: 'P2', reason: null, unparsed: 'line 2: "## P1/P2 findings"' });
expect(see(`${P2}\n## P1/P2 findings`, 'structured')).toMatchObject({ verdict: 'unverified', reason: 'unparsed_severity', unparsed: 'line 2: "## P1/P2 findings"' });
});
test('missing markers and failed execution stay unavailable; proposal and spec ignore the verdict', () => {
expect(classifyOutsideReview({ text: `${P2}\nVerdict: not ready`, gate: 'review' }).reason).toBe('missing_markers');
const failed = classifyOutsideReview({ text: textFor('review', `${P2}\nVerdict: not ready`), gate: 'review', exit: 1, stderr: 'fatal: provider exploded' });
expect(failed.verdict).toBe('unavailable');
expect(failed.reason).toBe('execution_failed');
expect(classifyOutsideReview({ text: `${P2}\nVerdict: not ready\n${REC}`, gate: 'proposal' }).verdict).toBe('clean');
const passing = classifyOutsideReview({ text: `SCORE: 8\nAMBIGUITIES: NONE\n${P2}\nVerdict: not ready`, gate: 'spec' });
expect([passing.verdict, passing.score]).toEqual(['clean', 8]);
const failing = classifyOutsideReview({ text: 'SCORE: 6\nAMBIGUITIES: NONE\nVerdict: ready', gate: 'spec' });
expect([failing.verdict, failing.score]).toEqual(['findings', 6]);
});
});
+369
View File
@@ -0,0 +1,369 @@
/**
* C8 `lanes` for a Rust repo: a `.rs` file of a crate (the nearest Cargo.toml
* with `[package]`) is a test when it sits under `<crate>/tests/` or holds a
* `#[cfg(test)]`; every `.rs` file of a crate and its Cargo.toml select that
* crate's tests and the tests of every crate depending on it; selected tests
* run as `cargo test -p <name>` from the workspace root, judged on the summed
* `test result:` lines. The end-to-end fixture carries no workflows, so every
* selected test is a local lane on any host platform; `cargo` is a PATH shim.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import { spawnSync } from 'node:child_process';
import * as path from 'node:path';
import { bunIsolationArgs } from '../lib/bun-isolation';
import { EXIT } from '../lib/headless-artifacts';
import { parseSummary, planRuns } from '../lib/pregate/checks/lanes';
import { DEFAULT_CONFIG } from '../lib/pregate/config';
import { buildGraph, testsFor } from '../lib/pregate/import-graph';
import { draftConfig } from '../lib/pregate/init-draft';
import { cargoModel, hasCfgTest, rustEdges } from '../lib/pregate/rust';
import type { PregateContext } from '../lib/pregate/types';
import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture';
const repos: FixtureRepo[] = [];
afterEach(() => { while (repos.length) cleanup(repos.pop()!); });
const RUST_FILES: Record<string, string> = {
'engine/Cargo.toml': '[workspace]\nresolver = "3"\nmembers = ["crates/*"]\n\n[workspace.dependencies]\nalpha = { path = "crates/alpha" }\n',
'engine/crates/alpha/Cargo.toml': '[package]\nname = "alpha"\nversion = "0.1.0"\nedition = "2024"\n',
'engine/crates/alpha/src/lib.rs': 'pub mod util;\npub fn one() -> u32 { 1 }\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn one_is_one() { assert_eq!(super::one(), 1); }\n}\n',
'engine/crates/alpha/src/util.rs': 'pub fn two() -> u32 { 2 }\n',
'engine/crates/alpha/src/flags.rs': '#[cfg(feature = "test")]\npub fn only_with_the_test_feature() {}\n',
'engine/crates/alpha/tests/it.rs': '#[test]\nfn it() { assert_eq!(alpha::one(), 1); }\n',
'engine/crates/beta/Cargo.toml': '[package]\nname = "beta-core"\nversion = "0.1.0"\n\n[dependencies]\nalpha = { workspace = true } # the shared base\n',
'engine/crates/beta/src/lib.rs': 'pub fn b() -> u32 { alpha::one() }\n\n#[cfg(all(test, unix))]\nmod tests {\n #[test]\n fn b() {}\n}\n',
'engine/crates/gamma/Cargo.toml': '[package]\nname = "gamma"\nversion = "0.1.0"\n\n[target.\'cfg(unix)\'.dev-dependencies.base]\npackage = "beta-core"\npath = "../beta"\n',
'engine/crates/gamma/src/lib.rs': 'pub fn g() {}\n',
'engine/crates/gamma/tests/g.rs': '#[test]\nfn g() {}\n',
'engine/crates/lonely/Cargo.toml': '[package]\nname = "lonely"\nversion = "0.1.0"\n',
'engine/crates/lonely/src/lib.rs': 'pub fn alone() {}\n',
'standalone/Cargo.toml': '[package]\nname = "standalone"\nversion = "0.1.0"\n',
'standalone/src/main.rs': 'fn main() {}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn t() {}\n}\n',
'tools/tests/loose.rs': 'fn main() {}\n',
};
const ALPHA_TESTS = ['engine/crates/alpha/src/lib.rs', 'engine/crates/alpha/tests/it.rs'];
/** The fixture plus RUST_FILES on main, with no base policy and no workflows, so every selected test runs locally. */
function rustRepo(): FixtureRepo {
const repo = makeFixtureRepo({ pregate: null });
repos.push(repo);
commit(repo, { ...RUST_FILES, '.github/workflows/free-tests.yml': null, '.github/workflows/windows.yml': null }, 'rust');
repo.git('push', '-q', 'origin', 'HEAD:main');
repo.git('fetch', '-q', 'origin');
return repo;
}
const CARGO_OK = [
'echo "ran in $(basename "$PWD"): $*"',
'echo "running 2 tests"',
'echo "test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"',
'echo " Doc-tests $3"',
'echo "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"',
].join('\n');
/**
* A `cargo` on PATH running `body` (default: reports its cwd and argv, then two passed tests and an empty doc-test binary).
* The lane puts its Bun's directory first on PATH, and that directory can hold a real cargo (/usr/local/bin,
* /opt/homebrew/bin), so on POSIX the lane's bash puts the shim first again through BASH_ENV.
*/
function cargoShim(repo: FixtureRepo, body = CARGO_OK): Record<string, string> {
const dir = path.join(repo.root, 'shim');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'cargo'), `#!/usr/bin/env bash\n${body}\n`, { mode: 0o755 });
fs.writeFileSync(path.join(dir, 'path.sh'), `PATH='${dir}':"$PATH"\n`);
const PATH = [dir, process.env.PATH ?? ''].join(path.delimiter);
return process.platform === 'win32' ? { PATH } : { PATH, BASH_ENV: path.join(dir, 'path.sh') };
}
const rustTests = (tests: Iterable<string>) => [...tests].filter(t => t.endsWith('.rs')).sort();
describe('Rust import graph', () => {
// Value: protects=in-source `#[cfg(test)]` modules and `<crate>/tests/` files are tests only inside a crate, and a cfg naming a
// feature called "test" is not; fails_when=Rust tests are never recognised (every touched .rs is PREGATE_NO_LANE) or any
// tests/*.rs counts without a Cargo.toml; why_new=no Rust support existed; seam=none; no_claim=a Rust parser (a cfg attribute scan)
test('cfg(test) files and <crate>/tests/ files are tests; a loose tests/*.rs and a cfg(feature = "test") file are not', () => {
const g = buildGraph(rustRepo().work);
expect(rustTests(g.tests)).toEqual([...ALPHA_TESTS, 'engine/crates/beta/src/lib.rs', 'engine/crates/gamma/tests/g.rs', 'standalone/src/main.rs']);
});
// Value: protects=a src file without its own tests selects its crate's tests and, transitively, the tests of crates depending on it
// (workspace = true, a renamed target-specific dev-dependency); an in-source test selects itself; a crate with no tests stays
// no-lane; fails_when=the mapping narrows to the file, misses dependents, or invents a lane; why_new=no Rust mapping existed;
// seam=none; no_claim=cargo's own resolver (manifest dependency keys are read)
test('a crate file selects its crate and every crate depending on it; a crate without tests has no lane', () => {
const g = buildGraph(rustRepo().work);
const everyAlphaDependent = [...ALPHA_TESTS, 'engine/crates/beta/src/lib.rs', 'engine/crates/gamma/tests/g.rs'];
expect(testsFor(g, 'engine/crates/alpha/src/util.rs').tests).toEqual(everyAlphaDependent);
expect(testsFor(g, 'engine/crates/alpha/src/lib.rs').tests).toEqual(everyAlphaDependent);
expect(testsFor(g, 'engine/crates/alpha/Cargo.toml').tests).toEqual(everyAlphaDependent);
expect(testsFor(g, 'engine/crates/beta/src/lib.rs').tests).toEqual(['engine/crates/beta/src/lib.rs', 'engine/crates/gamma/tests/g.rs']);
expect(testsFor(g, 'engine/crates/gamma/src/lib.rs').tests).toEqual(['engine/crates/gamma/tests/g.rs']);
expect(testsFor(g, 'standalone/src/main.rs').tests).toEqual(['standalone/src/main.rs']);
expect(testsFor(g, 'engine/crates/lonely/src/lib.rs').tests).toEqual([]);
expect(testsFor(g, 'tools/tests/loose.rs').tests).toEqual([]);
});
// Value: protects=`gstack-pregate init` tells a Rust repo its tests run per crate (no runner to declare), and Rust does not make a
// JS selection "mixed"; fails_when=init tells the user to set a runner for Rust tests, which would override the per-crate plan;
// why_new=init grouped .rs tests as "other"; seam=none; no_claim=none beyond protects
test('init notes that Rust tests run per crate with cargo test, not that a runner must be set', () => {
const note = draftConfig(rustRepo().work).runnerNote;
expect(note).toContain('5 Rust test file(s) run per crate with cargo test -p');
expect(note).not.toContain('needs runner set');
expect(note).not.toMatch(/no runner detected for \d+ (?:other|rust)/);
});
});
describe('Rust runner and summary (pure)', () => {
// Value: protects=cargo prints one `test result:` line per test binary (unit, each integration test, doc-tests); all are summed,
// ignored and filtered tests are not runs, and an all-zero run is ZERO-RUN; fails_when=only the first or last line counts, or the
// generic `N passed` fallback reads cargo output; why_new=cargo output was unparsed (ran: null); seam=none; no_claim=a real cargo
test('cargo test: every test result line counts, doc-tests included; all zeros are a zero run', () => {
const cargo = 'cargo test -p alpha';
const ok = [
' Compiling alpha v0.1.0', ' Running unittests src/lib.rs (target/debug/deps/alpha-1)', '', 'running 2 tests', 'test tests::a ... ok', 'test tests::b ... ok', '',
'test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s', '',
' Running tests/it.rs (target/debug/deps/it-2)', '', 'running 2 tests', 'test it ... ok', 'test slow ... ignored', '',
'test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s', '',
' Doc-tests alpha', '', 'running 3 tests', 'test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.31s',
].join('\n');
expect(parseSummary(ok, cargo)).toEqual({ ran: 6, failed: 0 });
const failed = 'test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nfailures:\n tests::b\n\ntest result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s\n\nerror: test failed, to rerun pass `-p alpha --lib`';
expect(parseSummary(failed, cargo)).toEqual({ ran: 7, failed: 2 });
const zero = 'running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests alpha\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s';
expect(parseSummary(zero, cargo)).toEqual({ ran: 0, failed: 0 });
expect(parseSummary('\x1b[1m\x1b[32mtest result: ok\x1b[0m. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s', cargo)).toEqual({ ran: 5, failed: 0 });
expect(parseSummary('error[E0425]: cannot find value `x` in this scope\nerror: could not compile `alpha`', cargo)).toEqual({ ran: null, failed: null });
});
// Value: protects=each selected crate runs once as `cargo test -p <name>` from its workspace root (else its own directory), crates
// group apart, a .rs file outside any crate is unclaimed, and a missing cargo is incomplete; fails_when=.rs files reach the JS
// runner, run from the repo root, merge across crates, or a missing cargo is judged as a test failure (exit 127); why_new=no cargo
// runner existed; seam=none; no_claim=the runners themselves (plan only)
test('without a declared runner, Rust tests group by crate from the workspace root; a declared runner takes every file', () => {
const repo = rustRepo();
const ctx = { repoRoot: repo.work, config: DEFAULT_CONFIG, env: cargoShim(repo) } as unknown as PregateContext;
const files = [...ALPHA_TESTS, 'engine/crates/beta/src/lib.rs', 'standalone/src/main.rs', 'tools/tests/loose.rs'];
expect(planRuns(ctx, files)).toEqual({ groups: [
{ runner: "cargo test -p 'alpha'", cwd: 'engine', files: ['crates/alpha/src/lib.rs', 'crates/alpha/tests/it.rs'] },
{ runner: "cargo test -p 'beta-core'", cwd: 'engine', files: ['crates/beta/src/lib.rs'] },
{ runner: "cargo test -p 'standalone'", cwd: 'standalone', files: ['src/main.rs'] },
], unclaimed: ['tools/tests/loose.rs'], missing: [], noPubspec: [] });
const noCargo = { ...ctx, env: { PATH: path.join(repo.root, 'empty-path') } } as PregateContext;
expect(planRuns(noCargo, ALPHA_TESTS)).toEqual({ groups: [], unclaimed: ALPHA_TESTS, missing: ['cargo'], noPubspec: [] });
const declared = { ...ctx, config: { ...DEFAULT_CONFIG, runner: 'bash scripts/test.sh {files}' } } as PregateContext;
expect(planRuns(declared, files).groups).toEqual([{ runner: 'bash scripts/test.sh {files}', cwd: '', files }]);
});
});
/**
* Manifest shapes a line scan misreads (review of the first cut): a renamed
* dependency inherited from `[workspace.dependencies]`, TOML dotted keys, the
* `[dependencies.<name>]` table form, target-specific tables, and a crate the
* workspace excludes. Dependencies resolve by path first, then by package name.
*/
const MANIFEST_FILES: Record<string, string> = {
'Cargo.toml': '[workspace]\nmembers = ["crates/*"]\nexclude = ["crates/helper"]\n\n[workspace.dependencies]\nbase = { package = "alpha", path = "crates/a" }\n',
'crates/a/Cargo.toml': '[package]\nname = "alpha"\nversion = "0.1.0"\n',
'crates/a/src/lib.rs': 'pub fn a() {}\n',
'crates/a/tests/a.rs': '#[test]\nfn a() {}\n',
'crates/beta/Cargo.toml': '[package]\nname = "beta"\nversion = "0.1.0"\n\n[dependencies]\nbase = { workspace = true }\n',
'crates/beta/tests/b.rs': '#[test]\nfn b() {}\n',
'crates/dotted/Cargo.toml': '[package]\nname = "dotted"\nversion = "0.1.0"\n\n[dependencies]\nfoo.path = "../a"\n',
'crates/dotted/tests/d.rs': '#[test]\nfn d() {}\n',
'crates/table/Cargo.toml': '[package]\nname = "table"\nversion = "0.1.0"\n\n[dev-dependencies.whatever]\npath = "../a"\n',
'crates/table/tests/t.rs': '#[test]\nfn t() {}\n',
'crates/targeted/Cargo.toml': '[package]\nname = "targeted"\nversion = "0.1.0"\n\n[target.\'cfg(unix)\'.build-dependencies]\nrenamed = { path = "../a" }\n',
'crates/targeted/tests/x.rs': '#[test]\nfn x() {}\n',
'crates/plain/Cargo.toml': '[package]\nname = "plain"\nversion = "0.1.0"\n',
'crates/plain/tests/p.rs': '#[test]\nfn p() {}\n',
'crates/helper/Cargo.toml': '[package]\nname = "helper"\nversion = "0.1.0"\n',
'crates/helper/src/lib.rs': '#[cfg(test)]\nmod tests {\n #[test]\n fn h() {}\n}\n',
};
function manifestRepo(): FixtureRepo {
const repo = makeFixtureRepo({ pregate: null });
repos.push(repo);
commit(repo, MANIFEST_FILES, 'cargo manifests');
return repo;
}
describe('Cargo manifests are parsed as TOML', () => {
// Value: protects=every dependency spelling Cargo accepts links a crate to its dependents: an inherited renamed workspace dependency,
// a dotted `foo.path` key, a `[dev-dependencies.<name>]` table and a target-specific build dependency, all resolved by path;
// fails_when=the manifest is read by a line scan again and alpha's change misses these dependents (a false green);
// why_new=the first cut matched dependency keys against package names only; seam=none; no_claim=cargo's own resolver
test('renamed, inherited, dotted, table-form and target-specific dependencies all select the dependent crates', () => {
const g = buildGraph(manifestRepo().work);
expect(testsFor(g, 'crates/a/src/lib.rs').tests).toEqual(['crates/a/tests/a.rs', 'crates/beta/tests/b.rs', 'crates/dotted/tests/d.rs', 'crates/table/tests/t.rs', 'crates/targeted/tests/x.rs']);
});
// Value: protects=a crate the workspace excludes runs from its own directory, a member from the workspace root; fails_when=the
// nearest [workspace] is taken without checking members/exclude and `cargo test -p helper` runs where helper is no member
// (cargo fails, or tests a same-named member); why_new=membership was not read; seam=none; no_claim=a real cargo (plan only)
test('an excluded crate runs from its own directory; a member runs from the workspace root', () => {
const repo = manifestRepo();
const ctx = { repoRoot: repo.work, config: DEFAULT_CONFIG, env: cargoShim(repo) } as unknown as PregateContext;
expect(planRuns(ctx, ['crates/beta/tests/b.rs', 'crates/helper/src/lib.rs']).groups).toEqual([
{ runner: "cargo test -p 'beta'", cwd: '', files: ['crates/beta/tests/b.rs'] },
{ runner: "cargo test -p 'helper'", cwd: 'crates/helper', files: ['src/lib.rs'] },
]);
});
});
describe('Cargo membership and test detection (port review)', () => {
const inMemory = (files: Record<string, string>) => [Object.keys(files), (f: string) => files[f] ?? null] as const;
const pkg = (name: string, deps = '') => `[package]\nname = "${name}"\nversion = "0.1.0"\n${deps}`;
const dependentsOf = (files: Record<string, string>, manifest: string) => rustEdges(...inMemory(files)).edges.filter(e => e.dependency === manifest).map(e => e.dependent).sort();
// Value: protects=Cargo's member globs ([ab] classes, ** spans) admit the crates Cargo admits, so a member inherits
// [workspace.dependencies] and its tests are selected; fails_when=a character class is matched literally, the crate is
// no member, the inherited path dependency is dropped and alpha's change misses beta's tests (a false green);
// why_new=port review found classes escaped; seam=none; no_claim=cargo's own glob crate
test('a members glob with a character class or ** admits the crate, so an inherited dependency links its dependent', () => {
const files = {
'Cargo.toml': '[workspace]\nmembers = ["crates/[ab]", "nested/**/leaf", "unicode/?"]\n\n[workspace.dependencies]\nbase = { package = "alpha", path = "crates/a" }\n',
'crates/a/Cargo.toml': pkg('alpha'), 'crates/a/tests/a.rs': '#[test]\nfn a() {}\n',
'crates/b/Cargo.toml': pkg('beta', '\n[dependencies]\nbase = { workspace = true }\n'), 'crates/b/tests/b.rs': '#[test]\nfn b() {}\n',
'crates/c/Cargo.toml': pkg('gamma'),
'nested/x/y/leaf/Cargo.toml': pkg('leaf'),
'unicode/📦/Cargo.toml': pkg('boxed'),
};
const { crates } = cargoModel(...inMemory(files));
expect(['crates/a', 'crates/b', 'crates/c', 'nested/x/y/leaf', 'unicode/📦'].map(r => crates.get(r)!.workspace)).toEqual(['', '', 'crates/c', '', '']);
expect(dependentsOf(files, 'crates/a/Cargo.toml')).toEqual(['crates/a/tests/a.rs', 'crates/b/tests/b.rs']);
});
// Value: protects=a plain #[test] function or a #[tokio::test] in src is a Rust test, so a dependent crate tested that way
// runs when its dependency changes; fails_when=only cfg(test) modules and tests/ count and the dependent's failing test
// never runs (a false green); why_new=port review; seam=none; no_claim=custom [[test]] targets outside tests/
test('a plain #[test] or #[tokio::test] in src is a test; cfg(feature = "test") and #[testing] are not', () => {
expect(['#[test]\nfn a() {}', '#[tokio::test(flavor = "multi_thread")]\nasync fn a() {}', '#[ test ]\nfn a() {}'].map(hasCfgTest)).toEqual([true, true, true]);
expect(['#[cfg(feature = "test")]\nfn a() {}', '#[testing]\nfn a() {}', '// attests', '#[cfg(feature = "a]b")]\nfn a() {}'].map(hasCfgTest)).toEqual([false, false, false, false]);
expect(hasCfgTest(`#[cfg(any(test, feature = "${'f'.repeat(300)}"))]\nmod t {}`)).toBe(true);
const files = {
'a/Cargo.toml': pkg('a'), 'a/src/lib.rs': 'pub fn one() -> u32 { 1 }\n#[cfg(test)]\nmod t { #[test] fn one() {} }\n',
'b/Cargo.toml': pkg('b', '\n[dependencies]\na = { path = "../a" }\n'), 'b/src/lib.rs': 'pub fn two() -> u32 { a::one() + 1 }\n#[test]\nfn two() { assert_eq!(super::two(), 2); }\n',
};
expect(dependentsOf(files, 'a/Cargo.toml')).toEqual(['a/src/lib.rs', 'b/src/lib.rs']);
});
// Value: protects=past the members-glob size cap, where a crate's tests run is undecided, so its files are unclaimed (the
// lane incomplete) instead of running `cargo test -p <name>` from a root where a same-named member answers; fails_when=an
// oversized workspace admits every crate as runnable and the orphan's failing test is replaced by the member's passing
// ones (a false green); why_new=third port review round; seam=none; no_claim=a real cargo (plan only)
test('past the members size cap a same-named non-member is unclaimed, not run as the member', () => {
const repo = makeFixtureRepo({ pregate: null });
repos.push(repo);
commit(repo, {
'Cargo.toml': `[workspace]\nmembers = ["[${'m'.repeat(4100)}]ember"]\n`,
'member/Cargo.toml': pkg('same'), 'member/tests/m.rs': '#[test]\nfn m() {}\n',
'orphan/Cargo.toml': pkg('same'), 'orphan/tests/t.rs': '#[test]\nfn t() { panic!() }\n',
}, 'oversized members');
const ctx = { repoRoot: repo.work, config: DEFAULT_CONFIG, env: cargoShim(repo) } as unknown as PregateContext;
expect(planRuns(ctx, ['orphan/tests/t.rs'])).toEqual({ groups: [], unclaimed: ['orphan/tests/t.rs'], missing: [], noPubspec: [] });
});
// Value: protects=a hostile members glob or a file of unclosed cfg attributes cannot stall lane selection, which runs before
// any runner deadline; each probe runs in its own supervised Bun so a regression is killed and fails instead of hanging the
// file; fails_when=member globs backtrack again (an exponential '*a*a…b', or a rescan per unmatched '[') or the cfg scan
// rescans from every start (quadratic: about 80 s on 600 KB, against tens of ms now); why_new=port review; seam=none;
// no_claim=a wall-clock budget for selection (the 30 s kill only separates linear from super-linear)
const supervised = (code: string) => spawnSync(process.execPath, [...bunIsolationArgs(), '-e', `import { cargoModel, hasCfgTest } from ${JSON.stringify(path.join(import.meta.dir, '..', 'lib', 'pregate', 'rust.ts'))};\n${code}`], { encoding: 'utf8', timeout: 30_000 });
test('a hostile members glob is matched without backtracking', () => {
const r = supervised(`
const pkg = n => '[package]\\nname = "' + n + '"\\nversion = "0.1.0"\\n';
const run = (members, dirs) => { const files = { 'Cargo.toml': '[workspace]\\nmembers = ' + JSON.stringify(members) + '\\n' }; dirs.forEach((d, i) => { files[d + '/Cargo.toml'] = pkg('k' + i); }); return cargoModel(Object.keys(files), f => files[f] ?? null); };
const exp = run(['*a'.repeat(20) + 'b'], ['a'.repeat(40)]).crates.get('a'.repeat(40)).workspace;
const brackets = run(['['.repeat(1000000)], Array.from({ length: 10 }, (_, i) => 'c' + i)).crates.get('c0').workspace;
console.log(JSON.stringify([exp, brackets]));`);
expect(r.error).toBeUndefined();
expect(r.stdout.trim()).toBe(JSON.stringify(['a'.repeat(40), null]));
}, 60_000);
test('a run of unclosed cfg attributes is scanned once and counts as a test', () => {
const r = supervised(`console.log(JSON.stringify([hasCfgTest('#[cfg('.repeat(100000)), hasCfgTest('#[cfg(unix)] fn a() {}\\n'.repeat(50000))]));`);
expect(r.error).toBeUndefined();
expect(r.stdout.trim()).toBe('[true,false]');
}, 60_000);
});
describe('gstack-pregate on a Rust workspace', () => {
const run = (repo: FixtureRepo, env: Record<string, string>) => runBin(repo, 'gstack-pregate', ['--base', 'main', '--allow-repo-commands', '--stage', 'tests', '--only', 'lanes'], env);
// The cargo stand-in is a bash script the lane's Git Bash must find before the runner's real cargo; on windows-latest it
// never did (three PATH repairs, the lane still exited 1 with an empty log), so the two cases that run it are POSIX-only,
// like test/pregate-dart.test.ts's stand-ins. Selection, planning and the hostile-name case still run on Windows.
const posixShim = test.skipIf(process.platform === 'win32');
const log = (out: string) => fs.readFileSync(/log: (\S+)/.exec(out)![1]!, 'utf8');
// Value: protects=the reported case end to end: a touched src file of a workspace crate is not PREGATE_NO_LANE, its crate and the
// dependent crates run with `cargo test -p` from the workspace root, and the summed count is reported; fails_when=any link of
// graph, plan or summary regresses; why_new=no Rust run existed; seam=none; no_claim=a real cargo (PATH shim reports cwd and argv)
posixShim('a touched src file runs its crate and the crates depending on it from the workspace root', () => {
const repo = rustRepo();
commit(repo, { 'engine/crates/alpha/src/util.rs': 'pub fn two() -> u32 { 1 + 1 }\n' });
const r = run(repo, cargoShim(repo));
expect(r.out).not.toContain('has no test lane');
expect(r.out).toMatch(/^tests {6}lanes {5}pass .*6 tests ran in 4 file\(s\), exit 0/m);
expect(r.out).toContain("ran: (cd 'engine' && cargo test -p 'alpha') && (cd 'engine' && cargo test -p 'beta-core') && (cd 'engine' && cargo test -p 'gamma')");
expect(log(r.out)).toContain('ran in engine: test -p alpha');
expect(r.status).toBe(EXIT.ok);
}, 60_000);
// Value: protects=a crate whose test binaries all report 0 tests is ZERO-RUN (exit 0 is not a pass), and a failing cargo run is
// PREGATE_LANE_FAILED with its counts; fails_when=cargo's summary is unparsed (count unavailable passes) or the exit is ignored;
// why_new=the pure parser test does not run the lane; seam=none; no_claim=a real cargo (PATH shim)
posixShim('zero tests is ZERO-RUN; a failing cargo run is PREGATE_LANE_FAILED', () => {
const repo = rustRepo();
commit(repo, { 'engine/crates/gamma/src/lib.rs': 'pub fn g() { }\n' });
const zero = run(repo, cargoShim(repo, 'echo "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"'));
expect(zero.status).not.toBe(EXIT.ok);
expect(zero.out).toMatch(/^tests {6}lanes {5}fail .*ZERO-RUN: the runner reported 0 tests in \(cd 'engine' && cargo test -p 'gamma'\)/m);
const red = run(repo, cargoShim(repo, 'echo "test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"\nexit 101'));
expect(red.status).not.toBe(EXIT.ok);
expect(red.out).toMatch(/^tests {6}lanes {5}fail .*local lane exited 101 \(1 failed of 2 ran; 1 files; pipefail\)/m);
}, 60_000);
// Value: protects=a crate name is data from the repo's Cargo.toml that reaches the lane's shell and the {files} expansion,
// so a name Cargo would reject never runs (its files are unclaimed, the lane incomplete) and a valid one, Unicode
// included, still runs quoted; fails_when=the name is interpolated unchecked (`;touch` runs a command, `{files}` splices
// the quoted file list into the name); why_new=the crate runner was new; seam=none; no_claim=a real cargo (PATH shim)
test('a crate name with shell syntax or {files} never reaches the shell; a valid Unicode name still runs', () => {
const repo = rustRepo();
const lib = '#[cfg(test)]\nmod tests {\n #[test]\n fn t() {}\n}\n';
commit(repo, {
'engine/crates/evil/Cargo.toml': '[package]\nname = "evil;touch pwned-by-crate-name"\nversion = "0.1.0"\n',
'engine/crates/evil/src/lib.rs': lib,
'engine/crates/splice/Cargo.toml': '[package]\nname = "evil{files}"\nversion = "0.1.0"\n',
'engine/crates/splice/src/lib.rs': lib,
'engine/crates/uni/Cargo.toml': '[package]\nname = "naïve_crate-2"\nversion = "0.1.0"\n',
'engine/crates/uni/src/lib.rs': lib,
}, 'odd crate names');
repo.git('push', '-q', 'origin', 'HEAD:main');
repo.git('fetch', '-q', 'origin');
const env = cargoShim(repo);
const ctx = { repoRoot: repo.work, config: DEFAULT_CONFIG, env } as unknown as PregateContext;
expect(planRuns(ctx, ['engine/crates/evil/src/lib.rs', 'engine/crates/splice/src/lib.rs', 'engine/crates/uni/src/lib.rs'])).toEqual({
groups: [{ runner: "cargo test -p 'naïve_crate-2'", cwd: 'engine', files: ['crates/uni/src/lib.rs'] }],
unclaimed: ['engine/crates/evil/src/lib.rs', 'engine/crates/splice/src/lib.rs'], missing: [], noPubspec: [],
});
commit(repo, { 'engine/crates/evil/src/lib.rs': lib.replace('fn t() {}', 'fn t() { }') });
const r = run(repo, env);
expect(fs.existsSync(path.join(repo.work, 'engine', 'pwned-by-crate-name'))).toBe(false);
expect(r.out).not.toContain('cargo test -p');
expect(r.out).toContain('engine/crates/evil/src/lib.rs');
expect(r.status).not.toBe(EXIT.ok);
}, 60_000);
// Value: protects=a crate with no tests still fails closed (no lane), so the crate mapping never invents coverage;
// fails_when=crate membership alone counts as a lane; why_new=negative control for the new mapping; seam=none; no_claim=none
test('a touched file of a crate without tests still has no test lane', () => {
const repo = rustRepo();
commit(repo, { 'engine/crates/lonely/src/lib.rs': 'pub fn alone() { }\n' });
const r = run(repo, cargoShim(repo));
expect(r.status).not.toBe(EXIT.ok);
expect(r.out).toContain('FAIL lanes — engine/crates/lonely/src/lib.rs has no test lane');
}, 60_000);
});
+85 -2
View File
@@ -14,11 +14,12 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import { EXIT } from '../lib/headless-artifacts';
import { changedLiterals, constantsIn } from '../lib/pregate/checks/literals';
import { parseSummary } from '../lib/pregate/checks/lanes';
import { validateConfig } from '../lib/pregate/config';
import { parseSummary, planRuns } from '../lib/pregate/checks/lanes';
import { DEFAULT_CONFIG, validateConfig } from '../lib/pregate/config';
import { isDocsEmptyLane } from '../lib/pregate/docs-lane';
import { buildGraph, testsFor } from '../lib/pregate/import-graph';
import { CHECK_IDS } from '../lib/pregate/index';
import type { PregateContext } from '../lib/pregate/types';
import { parseWorkflow } from '../lib/pregate/workflows';
import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, runBin, write, type FixtureRepo } from './helpers/pregate-fixture';
@@ -564,3 +565,85 @@ describe('gstack-pregate (bin)', () => {
expect(runBin(repo, 'gstack-pregate', ['validate']).status).toBe(EXIT.ok);
});
});
describe('nested JS packages run their own runner from their own directory', () => {
const APP = {
'app/package.json': JSON.stringify({ name: 'app', scripts: { test: 'vitest run' }, devDependencies: { vitest: '^3.2.0' } }) + '\n',
'app/pnpm-lock.yaml': "lockfileVersion: '9.0'\n",
'app/src/sum.ts': 'export const sum = (a: number, b: number) => a + b;\n',
'app/src/sum.test.ts': "import { expect, test } from 'vitest';\nimport { sum } from './sum';\ntest('sum', () => expect(sum(1, 2)).toBe(3));\n",
};
/**
* A `pnpm` (and `yarn`) on PATH that reports its cwd and argv and prints a vitest summary for the files it is given.
* The lane puts its Bun's directory first on PATH, and that directory can hold a real pnpm (/usr/local/bin), which
* would install from the network; the lane's bash puts the shim first again through BASH_ENV.
*/
const pmShim = (repo: FixtureRepo): { PATH: string; BASH_ENV: string } => {
const dir = path.join(repo.root, 'shim');
fs.mkdirSync(dir, { recursive: true });
for (const tool of ['pnpm', 'yarn']) fs.writeFileSync(path.join(dir, tool), '#!/usr/bin/env bash\necho "ran in $(basename "$PWD"): $*"\necho " Test Files 1 passed (1)"\necho " Tests 3 passed (3)"\n', { mode: 0o755 });
fs.writeFileSync(path.join(dir, 'path.sh'), `PATH='${dir}':"$PATH"\n`);
return { PATH: `${dir}:${process.env.PATH ?? ''}`, BASH_ENV: path.join(dir, 'path.sh') };
};
const ctxFor = (repo: FixtureRepo, env: Record<string, string>) => ({ repoRoot: repo.work, config: DEFAULT_CONFIG, env }) as unknown as PregateContext;
// Value: protects=a test owned by a nested package that declares vitest runs from that package with its lockfile's package manager
// and package-relative paths, while root-owned tests keep the root runner; fails_when=the root package.json alone decides again
// (the reported `bun test` from the repo root: vi.stubGlobal missing); why_new=only root package.json detection was tested;
// seam=none; no_claim=the runners themselves (plan only)
test('a nested vitest package plans its own group with the lockfile\'s package manager; root tests keep the root runner', () => {
const repo = fixture({ pregate: null, baseFiles: APP });
const ctx = ctxFor(repo, pmShim(repo));
expect(planRuns(ctx, ['app/src/sum.test.ts', 'test/util.test.js'])).toEqual({ groups: [
{ runner: 'node --test {files}', cwd: '', files: ['test/util.test.js'] },
{ runner: 'pnpm exec vitest run {files}', cwd: 'app', files: ['src/sum.test.ts'] },
], unclaimed: [], missing: [], noPubspec: [] });
// The lockfile is found walking up, and a packageManager field outranks it.
fs.rmSync(path.join(repo.work, 'app/pnpm-lock.yaml'));
write(repo.work, 'yarn.lock', '# yarn lockfile v1\n');
expect(planRuns(ctx, ['app/src/sum.test.ts']).groups).toEqual([{ runner: 'yarn vitest run {files}', cwd: 'app', files: ['src/sum.test.ts'] }]);
write(repo.work, 'app/package.json', JSON.stringify({ name: 'app', packageManager: 'pnpm@9.15.0', devDependencies: { jest: '^29.0.0' } }) + '\n');
expect(planRuns(ctx, ['app/src/sum.test.ts']).groups).toEqual([{ runner: 'pnpm exec jest {files}', cwd: 'app', files: ['src/sum.test.ts'] }]);
// Value: protects=a package manager missing from PATH is incomplete naming it, never exit 127 judged as a test failure;
// fails_when=the PATH check is dropped; why_new=new detection path; seam=none; no_claim=a real pnpm install
expect(planRuns(ctxFor(repo, { PATH: path.join(repo.root, 'empty-path') }), ['app/src/sum.test.ts'])).toEqual({ groups: [], unclaimed: ['app/src/sum.test.ts'], missing: ['pnpm'], noPubspec: [] });
fs.rmSync(path.join(repo.work, 'yarn.lock'));
write(repo.work, 'app/package.json', JSON.stringify({ name: 'app', devDependencies: { vitest: '^3.2.0' } }) + '\n');
expect(planRuns(ctx, ['app/src/sum.test.ts']).groups).toEqual([{ runner: 'npx vitest run {files}', cwd: 'app', files: ['src/sum.test.ts'] }]);
});
// Value: protects=repos where root detection works today are unchanged: a nested package that declares no test runner stays with the
// root runner from the root, a root vitest stays `npx vitest run` from the root, and a declared runner takes every file;
// fails_when=every nested package.json splits a group or the root command changes; why_new=negative controls for the new
// nested detection; seam=none; no_claim=the runners themselves (plan only)
test('negative controls: a nested package without a test runner, a root vitest repo and a declared runner keep today\'s plan', () => {
const repo = fixture({ pregate: null, baseFiles: { ...APP, 'app/package.json': JSON.stringify({ name: 'app', scripts: { build: 'tsc' } }) + '\n' } });
const ctx = ctxFor(repo, pmShim(repo));
write(repo.work, 'bun.lock', '{}\n');
expect(planRuns(ctx, ['app/src/sum.test.ts', 'test/util.test.js']).groups).toEqual([{ runner: 'bun test {files}', cwd: '', files: ['app/src/sum.test.ts', 'test/util.test.js'] }]);
fs.rmSync(path.join(repo.work, 'bun.lock'));
write(repo.work, 'package.json', JSON.stringify({ name: 'fixture', devDependencies: { vitest: '^3.2.0' } }) + '\n');
write(repo.work, 'pnpm-lock.yaml', "lockfileVersion: '9.0'\n");
expect(planRuns(ctx, ['app/src/sum.test.ts', 'test/util.test.js']).groups).toEqual([{ runner: 'npx vitest run {files}', cwd: '', files: ['app/src/sum.test.ts', 'test/util.test.js'] }]);
const declared = { ...ctx, config: { ...DEFAULT_CONFIG, runner: 'bun test {files}' } } as PregateContext;
write(repo.work, 'app/package.json', APP['app/package.json']);
expect(planRuns(declared, ['app/src/sum.test.ts']).groups).toEqual([{ runner: 'bun test {files}', cwd: '', files: ['app/src/sum.test.ts'] }]);
});
// Value: protects=the reported case end to end: a touched source file in a nested pnpm+vitest package runs `pnpm exec vitest run`
// in that package with the package-relative path and passes on vitest's summary; fails_when=the lane runs from the repo root or
// with the root runner; why_new=no nested package run existed; seam=none; no_claim=a real pnpm or vitest (PATH shim)
test('a touched file in a nested pnpm+vitest package runs vitest there', () => {
const repo = fixture({ pregate: null, baseFiles: APP });
// No workflows, so the Windows lane's unknown matrix cannot turn the selection into a requires-remote obligation.
commit(repo, { '.github/workflows/free-tests.yml': null, '.github/workflows/windows.yml': null }, 'no workflows');
repo.git('push', '-q', 'origin', 'HEAD:main');
repo.git('fetch', '-q', 'origin');
commit(repo, { 'app/src/sum.ts': 'export const sum = (a: number, b: number) => b + a;\n' });
const r = runBin(repo, 'gstack-pregate', ['--base', 'main', '--allow-repo-commands', '--stage', 'tests', '--only', 'lanes'], pmShim(repo));
expect(r.out).toMatch(/^tests {6}lanes {5}pass .*3 tests ran in 1 file\(s\), exit 0/m);
expect(r.out).toContain("ran: (cd 'app' && pnpm exec vitest run 'src/sum.test.ts')");
expect(fs.readFileSync(/log: (\S+)/.exec(r.out)![1]!, 'utf8')).toContain('ran in app: exec vitest run src/sum.test.ts');
expect(r.status).toBe(EXIT.ok);
}, 60_000);
});
+48
View File
@@ -1,4 +1,8 @@
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { bunIsolationArgs } from '../lib/bun-isolation';
import { generateQAMethodology } from '../scripts/resolvers/utility';
import { HOST_PATHS } from '../scripts/resolvers/types';
@@ -31,3 +35,47 @@ describe('QA health rubric scoring contract', () => {
expect(rubric).toContain('Round only the final score');
});
});
const healthTmpl = fs.readFileSync(path.join(import.meta.dir, '..', 'health', 'SKILL.md.tmpl'), 'utf-8');
const gbrainSection = healthTmpl.split('**GBrain sub-score computation:**')[1] ?? '';
const gbrainScript = gbrainSection.match(/```bash\nbun --no-env-file --config=\/dev\/null -e '\n([\s\S]*?)\n'\n```/)?.[1] ?? '';
function gbrainScore(doctor: number | null, queue: number | null, pushHours: number | null): string {
const script = gbrainScript
.replace('<N|null>', String(doctor))
.replace('<N|null>', String(queue))
.replace('<N|null>', String(pushHours));
const run = spawnSync(process.execPath, [...bunIsolationArgs(), '-e', script], { encoding: 'utf-8', timeout: 30_000 });
expect(run.status).toBe(0);
return run.stdout.trim();
}
describe('/health GBrain score has one rule, computed in code (#3351)', () => {
test('the rubric row defers to the computation instead of scoring bands', () => {
const row = healthTmpl.split('\n').find(line => line.startsWith('| GBrain |')) ?? '';
expect(row).toContain('GBrain sub-score computation');
expect(row).not.toMatch(/queue\s*</);
expect(row).not.toContain('doctor=');
});
test('the issue inputs score by the formula, not the rubric column', () => {
expect(gbrainScript).not.toBe('');
expect(gbrainScore(10, 50, 2)).toBe('GBRAIN_SCORE: 9.1');
expect(gbrainScore(7, 3, 2)).toBe('GBRAIN_SCORE: 8.5');
});
test('bands are half-open at 10/100 queue lines and 24/72 hours', () => {
expect(gbrainScore(10, 9, 23.9)).toBe('GBRAIN_SCORE: 10.0');
expect(gbrainScore(10, 10, 24)).toBe('GBRAIN_SCORE: 8.5');
expect(gbrainScore(10, 99, 71.9)).toBe('GBRAIN_SCORE: 8.5');
expect(gbrainScore(10, 100, 72)).toBe('GBRAIN_SCORE: 5.0');
expect(gbrainScore(0, 100, 72)).toBe('GBRAIN_SCORE: 0.0');
expect(gbrainScore(null, 0, 1)).toBe('GBRAIN_SCORE: 5.0');
});
test('sync off gives the doctor component the whole weight', () => {
expect(gbrainScore(10, null, null)).toBe('GBRAIN_SCORE: 10.0');
expect(gbrainScore(7, null, null)).toBe('GBRAIN_SCORE: 7.0');
expect(gbrainScore(0, null, null)).toBe('GBRAIN_SCORE: 0.0');
});
});
+52 -2
View File
@@ -8,13 +8,15 @@
import { describe, expect, test } from 'bun:test';
import { DISPATCH_INPUTS, dedupeKey, dispatchPlan, findDuplicateRun, makeNonce, nonceScope, type RunSummary } from '../scripts/eval-bg';
import { DEFAULT_POLICY, TRAIN_KEYS_VERSION, validatePolicy } from '../lib/ship-policy';
import { fillDue, orderSlots, parsePins } from '../lib/ship-queue-train';
import { fillDue, orderSlots, parseOrder, parsePins, prsArgs } from '../lib/ship-queue-train';
import { gstackPaidSelection, skillOwnCases, touchedSkills } from '../lib/ship-queue-train-ready';
import type { TrainSlot } from '../lib/ship-queue-train-record';
import { normalizeRemoteUrl, repoIdentity, type TrainSlot } from '../lib/ship-queue-train-record';
import { INFRA_REDISPATCH, REBUILD_ONCE, classifyBisect, classifyGate } from '../lib/ship-queue-train-verdict';
import { EVAL_POLICY } from './helpers/periodic-exclude-data';
import { COMPLETE, FAIL, PASS, TRAIN_BLOCK } from './helpers/ship-queue-train-fixture';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
@@ -54,6 +56,54 @@ describe('ordering and fill', () => {
expect(parsePins('12')).toMatch(/entries are <pr>@<sha>/);
expect(parsePins(`12@${SHA},12@${SHA}`)).toBe('a PR appears twice in --prs');
});
test('--order (GSTA-67, #3337 docs slotted ahead of the #3343 catalog it describes): an explicit order replaces screened-first and READY order; absent, the default is unchanged', () => {
const docs = slot('3337', false, '2026-10-22T18:00:00Z');
const catalog = slot('3343', false, '2026-10-22T19:00:00Z');
expect(orderSlots([docs, catalog], 5).train.map(s => s.pr)).toEqual(['3337', '3343']);
expect(orderSlots([docs, catalog], 5, undefined).train.map(s => s.pr)).toEqual(['3337', '3343']);
const pins = [{ pr: '3337' }, { pr: '3343' }];
const order = parseOrder('3343,#3337', pins);
expect(order).toEqual(['3343', '3337']);
expect(orderSlots([docs, catalog], 5, order as string[]).train.map(s => s.pr)).toEqual(['3343', '3337']);
const screened = slot('9', true, '2026-10-22T20:00:00Z');
const over = orderSlots([docs, catalog, screened], 2, ['3343', '3337', '9']);
expect([over.train.map(s => s.pr), over.held.map(s => s.pr), over.split]).toEqual([['3343', '3337'], ['9'], false]);
expect(parseOrder(undefined, pins)).toBeUndefined();
for (const bad of ['3343', '3343,3337,3337', '3343,3337,1', '3343,x']) expect(parseOrder(bad, pins)).toEqual({ error: `--order must list every PR in --prs exactly once (--prs has #3337,#3343; got ${bad})` });
expect(prsArgs([{ pr: '3343', head: SHA }, { pr: '3337', head: SHA }], true)).toBe(`--prs 3343@${SHA},3337@${SHA} --order 3343,3337`);
expect(prsArgs([{ pr: '3343', head: SHA }], false)).toBe(`--prs 3343@${SHA}`);
});
});
describe('repo identity (GSTA-67, #3331 on 2026-10-21)', () => {
test("every URL form of one GitHub repository gives one key, the github.com key gstack's records already use", () => {
const canonical = 'https://github.com/garrytan/gstack';
for (const url of ['https://github.com/garrytan/gstack', 'https://github.com/garrytan/gstack.git', 'https://git.capy.ai/garrytan/gstack', 'https://git.capy.ai/garrytan/gstack.git/',
'git@github.com:garrytan/gstack.git', 'ssh://git@github.com/garrytan/gstack.git', 'ssh://git@ssh.github.com:443/garrytan/gstack.git', 'https://x-access-token:PASSWORD@github.com/garrytan/gstack.git',
'http://www.github.com/GarryTan/GStack']) expect(normalizeRemoteUrl(url)).toBe(canonical);
expect(normalizeRemoteUrl('https://gitlab.com/acme/widget.git')).toBe('https://gitlab.com/acme/widget');
expect(normalizeRemoteUrl('https://user:PASSWORD@gitlab.com/acme/widget.git')).toBe('https://gitlab.com/acme/widget');
expect(normalizeRemoteUrl('/tmp/fixture/origin.git')).toBe('/tmp/fixture/origin');
});
test("#3331's lane (origin https://git.capy.ai/garrytan/gstack) now writes b321d228efd2bc14, and readers still accept the 1fb5dd69740a8cf8 receipt it wrote", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'repo-identity-'));
try {
const git = (...args: string[]) => spawnSync('git', args, { cwd: dir, encoding: 'utf8', timeout: 30_000 });
git('init', '-q');
git('remote', 'add', 'origin', 'https://git.capy.ai/garrytan/gstack');
const lane = repoIdentity(dir);
expect(lane.key).toBe('b321d228efd2bc14');
expect(lane.url).toBe('https://github.com/garrytan/gstack');
expect(lane.keys).toContain('1fb5dd69740a8cf8');
git('remote', 'set-url', 'origin', 'https://github.com/garrytan/gstack.git');
const coordinator = repoIdentity(dir);
expect(coordinator.key).toBe('b321d228efd2bc14');
expect(coordinator.keys).toEqual(expect.arrayContaining(['b321d228efd2bc14', '1fb5dd69740a8cf8']));
expect(coordinator.keys[0]).toBe('b321d228efd2bc14');
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
});
describe('verdict class mapping', () => {
+122 -1
View File
@@ -19,7 +19,7 @@ import { TRAIN_HELP } from '../lib/ship-queue-train-cli';
import { BASE_POLICY, cleanup, runBin } from './helpers/restamp-fixture';
import { coordinatorClone } from './helpers/ship-queue-fixture';
import {
COMPLETE, FAIL, GREEN_GATE, PASS, RED_GATE, TRAIN_BLOCK, TRAIN_POLICY, dispatches, line, nonceOf, openPr, queue, readyReceipt, repoKey, trainFixture, trainJson,
COMPLETE, FAIL, GREEN_GATE, PASS, RED_GATE, TRAIN_BLOCK, TRAIN_POLICY, dispatches, githubOrigin, line, nonceOf, openPr, queue, readyReceipt, repoKey, trainFixture, trainJson, urlKey,
type Rule, type TrainFixture,
} from './helpers/ship-queue-train-fixture';
@@ -127,6 +127,30 @@ describe('ready under a train policy: the screen choice', () => {
expect(dispatches(fx)).toEqual([]);
}, 120_000);
test("GSTA-67: a lane whose origin is another URL form of the repository (#3331's git.capy.ai) writes its receipt under the owner/repo key", () => {
const { fx, head, pregate } = readyFixture();
githubOrigin(fx, 'https://git.capy.ai/fixture/repo.git');
const ok = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen']);
expect(ok.status).toBe(EXIT.ok);
const canonical = urlKey('https://github.com/fixture/repo');
expect(canonical).not.toBe(urlKey('https://git.capy.ai/fixture/repo'));
expect(line(ok.out, 'READY_RECEIPT:')).toContain(path.join(fx.state, 'ship-queue', 'ready', canonical, `1-${head}.json`));
}, 120_000);
test("GSTA-67: ready refuses a head the Version Gate refuses (#3345's CHANGELOG replaced a released heading)", () => {
const fx = make();
const head = openPr(fx, '1', { changelog: cl => cl.replace('## [1.2.3.0] - 2026-10-01', '## [Unreleased]\n\n- #1 change') });
fx.write(d => { d.ci[head] = [{ status: 'completed', conclusion: 'success' }]; });
const tree = runBin(fx.repo, 'gstack-wtree', []).out.trim();
const pregate = path.join(fx.repo.root, 'pregate.json');
fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree, head, verdict: 'pass', checks: [{ id: 'unit', status: 'pass' }] }));
const r = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen']);
expect(r.status).toBe(EXIT.refused);
expect(r.err).toContain(`the Version Gate refuses ${head.slice(0, 12)}: CHANGELOG.md drops released heading 1.2.3.0`);
expect(r.err).toContain('(QUEUE_NOT_READY)');
expect(fs.existsSync(path.join(fx.state, 'ship-queue', 'ready'))).toBe(false);
}, 120_000);
test('--screen dispatches one screen with the PR, its merge SHA and the policy; a repeat adopts it; a broad screen never adopts the narrow one', () => {
const { fx, head, pregate } = readyFixture();
const dry = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--screen', '--dry-run']);
@@ -207,6 +231,57 @@ describe('train build', () => {
expect(dispatches(fx)).toEqual([]);
}, 120_000);
test("GSTA-67: a PR whose CHANGELOG drops a released heading (#3345's pin 1eb7092) is a CHANGELOG conflict, never merged with the damage", () => {
const fx = make();
const h1 = openPr(fx, '1');
const h2 = openPr(fx, '2', { changelog: cl => cl.replace('## [1.2.3.0] - 2026-10-01', '## [Unreleased]\n\n- #2 change') });
readyReceipt(fx, '1', h1);
readyReceipt(fx, '2', h2);
const r = queue(fx, ['train', 'build', '--prs', `1@${h1},2@${h2}`, '--dry-run']);
expect(r.status).toBe(EXIT.fail);
expect(line(r.out, 'QUEUE_TRAIN_CONFLICT:')).toContain('stopped at #2 (conflicts: CHANGELOG.md (ours drops released heading 1.2.3.0 that the merge base carries)) after merging #1');
expect(dispatches(fx)).toEqual([]);
}, 120_000);
test("GSTA-67: READY receipts under any URL form of the repository admit (#3331's receipt was keyed on git.capy.ai, the coordinator's origin on github.com)", () => {
const fx = make();
githubOrigin(fx, 'https://github.com/fixture/repo.git');
const h1 = openPr(fx, '1');
const h2 = openPr(fx, '2');
readyReceipt(fx, '1', h1, { key: urlKey('https://git.capy.ai/fixture/repo') });
readyReceipt(fx, '2', h2, { key: urlKey('https://github.com/fixture/repo') });
const r = queue(fx, ['train', 'build', '--prs', `1@${h1},2@${h2}`, '--dry-run']);
expect(r.status).toBe(EXIT.ok);
expect(line(r.out, 'ORDER:')).toBe('ORDER: 1:#1(unscreened) 2:#2(unscreened)');
const h3 = openPr(fx, '3');
readyReceipt(fx, '3', h3, { key: urlKey('https://gitlab.com/fixture/repo') });
expect(queue(fx, ['train', 'build', '--prs', `3@${h3}`, '--dry-run']).err).toMatch(/no READY receipt for #3 .*\(QUEUE_NOT_READY\)/);
}, 120_000);
test('GSTA-67 --order: an explicit slot order (#3343 catalog before the #3337 docs that describe it) replaces READY order and carries into NEXT; the default is unchanged', () => {
const fx = make();
const docs = openPr(fx, '3337');
const catalog = openPr(fx, '3343');
readyReceipt(fx, '3337', docs, { at: '2026-10-18T07:00:00.000Z' });
readyReceipt(fx, '3343', catalog, { at: '2026-10-18T08:00:00.000Z' });
const pins = `3337@${docs},3343@${catalog}`;
expect(line(queue(fx, ['train', 'build', '--prs', pins, '--dry-run']).out, 'ORDER:')).toBe('ORDER: 1:#3337(unscreened) 2:#3343(unscreened)');
const dry = queue(fx, ['train', 'build', '--prs', pins, '--order', '3343,3337', '--dry-run']);
expect(dry.status).toBe(EXIT.ok);
expect(line(dry.out, 'ORDER:')).toBe('ORDER: 1:#3343(unscreened) 2:#3337(unscreened) (explicit --order)');
expect(dry.out).toMatch(new RegExp(`^SLOT: 1 #3343 head=${catalog} `, 'm'));
expect(next(dry.out)).toBe(`NEXT: gstack-ship-queue train build --prs 3343@${catalog},3337@${docs} --order 3343,3337`);
const partial = queue(fx, ['train', 'build', '--prs', pins, '--order', '3343']);
expect(partial.status).toBe(EXIT.refused);
expect(partial.err).toContain('--order must list every PR in --prs exactly once (--prs has #3337,#3343; got 3343)');
expect(queue(fx, ['train', 'build', '--train', 'x', '--order', '3343']).status).toBe(EXIT.usage);
fx.write(d => { d.rules['evals.yml'] = GREEN_GATE; });
const real = queue(fx, ['train', 'build', '--prs', pins, '--order', '3343,3337']);
expect(real.status).toBe(EXIT.ok);
const t = trainJson(fx, nonceOf(real.out));
expect([t.slots.map((s: any) => s.pr), t.explicit_order, t.prefixes[1].pr]).toEqual([['3343', '3337'], true, '3343']);
}, 180_000);
test('refusals: a fork PR, a moved head, a PR without READY, and a train still filling (until --urgent)', () => {
const fx = make();
const h1 = openPr(fx, '1');
@@ -557,4 +632,50 @@ describe('verify, freeze, repair and clear', () => {
expect(moved.status).toBe(EXIT.fail);
expect(moved.err).toMatch(new RegExp(`#2 moved past its pinned head ${h2.slice(0, 12)} and is not T2 modulo stamps \\(${stray.slice(0, 12)}: .*\\(QUEUE_TRAIN_MOVED\\)`));
}, 300_000);
test("GSTA-67 (#3345 at 593e61c): a merged-in head whose CHANGELOG was resolved by hand verifies even where T<i>'s mechanical CHANGELOG differs; an invented line or a head without main is still refused", () => {
const fx = make();
const h1 = openPr(fx, '1', { changelog: false });
const h2 = openPr(fx, '2', { changelog: cl => cl.replace('# Changelog\n', '# Changelog\n\n## [Unreleased]\n\n- #2 change\n').replace('## [1.2.2.0] - 2026-09-01\n\n', '') });
readyReceipt(fx, '1', h1);
readyReceipt(fx, '2', h2);
fx.write(d => { d.rules['evals.yml'] = GREEN_GATE; });
const nonce = nonceOf(queue(fx, ['train', 'build', '--prs', `1@${h1},2@${h2}`]).out);
expect(queue(fx, ['train', 'verdict', '--train', nonce]).status).toBe(EXIT.ok);
const t = trainJson(fx, nonce);
expect(fx.repo.git('show', `${t.prefixes[2].commit}:CHANGELOG.md`)).not.toContain('## [1.2.2.0]');
const coord = coordinatorClone(fx.repo);
const v = () => queue(fx, ['verify', '--pr', '2', '--train', nonce], {}, coord);
const main1 = publishMain(fx, t.prefixes[1].commit, '1.2.4.0');
const { repo } = fx;
const laneHead = (entry: string, parents: string[]) => {
repo.git('reset', '-q', '--hard');
repo.git('checkout', '-q', '-B', 'lane2', h2);
repo.git('rm', '-rq', '.');
repo.git('checkout', t.prefixes[2].commit, '--', '.');
fs.writeFileSync(path.join(repo.work, 'VERSION'), '1.2.5.0\n');
fs.writeFileSync(path.join(repo.work, 'CHANGELOG.md'), repo.git('show', `${main1}:CHANGELOG.md`).replace('# Changelog\n', `# Changelog\n\n## [1.2.5.0] - 2026-10-18\n\n${entry}\n`) + '\n');
repo.git('add', '-A');
const head = repo.git('commit-tree', repo.git('write-tree'), ...parents.flatMap(p => ['-p', p]), '-m', 'merge main into #2 (CHANGELOG by hand), stamp 1.2.5.0');
repo.git('push', '-q', '-f', 'origin', `${head}:refs/pull/2/head`);
return head;
};
const byHand = laneHead('- #2 change', [h2, main1]);
const ok = v();
expect(ok.status).toBe(EXIT.ok);
expect(ok.out).toContain(`head: ${byHand} (T2 with main merged in, same modulo stamps (1 stamp file(s)) except CHANGELOG.md, resolved as main's CHANGELOG.md plus #2's own entry)`);
expect(line(ok.out, 'MERGE_CONDITION:')).toBe(`MERGE_CONDITION: sha=${byHand}`);
const invented = laneHead('- #2 change\n- added after the gate', [h2, main1]);
const refused = v();
expect(refused.status).toBe(EXIT.fail);
expect(refused.err).toContain(`#2 moved past its pinned head ${h2.slice(0, 12)} and is not T2 modulo stamps (${invented.slice(0, 12)}: differs from T2 in CHANGELOG.md, which is not main's plus #2's own entry: the PR's entry holds a line its pin never added: "- added after the gate"; against the pin it differs: `);
expect(refused.err).toContain('(QUEUE_TRAIN_MOVED)');
const orphan = laneHead('- #2 change', [h2]);
const noMain = v();
expect(noMain.status).toBe(EXIT.fail);
expect(noMain.err).toContain(`(${orphan.slice(0, 12)}: does not contain main ${main1.slice(0, 12)}; against the pin it differs: `);
}, 300_000);
});