diff --git a/.github/workflows/weekly-release.yml b/.github/workflows/weekly-release.yml index 768dfcf4f4e..3c9ea8756a1 100644 --- a/.github/workflows/weekly-release.yml +++ b/.github/workflows/weekly-release.yml @@ -77,6 +77,8 @@ jobs: contents: write # Reads the candidate's check runs. checks: read + # Finds this workflow's own runs on the candidate, whose check runs the gate sets aside. + actions: read # A security or regression cut reads the label on the # its reason names. issues: read pull-requests: read @@ -143,6 +145,7 @@ jobs: permissions: contents: read checks: read + actions: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: diff --git a/AGENTS.md b/AGENTS.md index bbfdc843b15..ab1ff3f3bec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,6 +16,7 @@ CLIs (`gstack-ios-qa-daemon`, `gstack-ios-qa-mint`, `gstack-ios-qa-regen`) are i |-------|------| | `/office-hours` | plan | | `/plan-ceo-review` | plan | +| `/plan-eng-review` | plan | | `/plan-design-review` | plan | | `/plan-devex-review` | plan | | `/plan-tune` | plan | diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 14dea0a7750..7dc9c3546e6 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -345,12 +345,12 @@ Templates contain the workflows, tips, and examples that require human judgment. | `{{QA_METHODOLOGY}}` | `resolvers/utility.ts` | Browser-only QA methodology, conditionally loaded by /qa and /qa-only | | `{{QA_SCOPE}}, {{QA_EXPLORATORY}}, {{QA_FUNCTIONAL}}, {{QA_RESOURCE}}, {{QA_METHOD_READS}}, {{QA_REVIEW}}` | `resolvers/qa.ts` | Surface selection, checkpointed native/exploratory QA, direct conditional method reads, installed-asset references and bounded review/ship callers | | `{{DESIGN_METHODOLOGY}}` | `gen-skill-docs.ts` | Shared design audit methodology for /plan-design-review and /design-review | -| `{{SHARED_LIBS_RUBRIC}}` | `resolvers/shared-libs.ts` | Shared-code criteria for /deslop-shared-libs, /autoplan's eng phase, and /review: verified callers, existing helpers, compatibility, tests, and total savings | +| `{{SHARED_LIBS_RUBRIC}}` | `resolvers/shared-libs.ts` | Shared-code criteria for /deslop-shared-libs, /plan-eng-review, and /review: verified callers, existing helpers, compatibility, tests, and total savings | | `{{REVIEW_DASHBOARD}}` | `gen-skill-docs.ts` | Review Readiness Dashboard for /ship pre-flight | -| `{{TEST_VALUE_BAR:}}` | `resolvers/test-value.ts` | Shared test value bar (authoring gate, value card, X/Y coverage, red-first proof, low-value catalog) for /qa and /qa-only (`qa`) and /test-audit (`audit`); /autoplan's eng phase and /ship embed it through the coverage audit | +| `{{TEST_VALUE_BAR:}}` | `resolvers/test-value.ts` | Shared test value bar (authoring gate, value card, X/Y coverage, red-first proof, low-value catalog) for /qa and /qa-only (`qa`) and /test-audit (`audit`); /plan-eng-review and /ship embed it through the coverage audit | | `{{TEST_VALUE_MESSAGE:}}` | `resolvers/test-value.ts` | One degraded-mode message (problem, consequence, fix, docs anchor) from the shared constants | | `{{TEST_BOOTSTRAP}}` | `resolvers/testing.ts` | Test framework detection, bootstrap, CI/CD setup for /ship and /design-review | -| `{{CODEX_PLAN_REVIEW}}` | `resolvers/outside-voice-steps.ts` | Optional outside plan review for /plan-ceo-review and /autoplan's eng phase: Claude Code on Codex, Codex on other supported harnesses, with the caller's native subagent fallback | +| `{{CODEX_PLAN_REVIEW}}` | `resolvers/outside-voice-steps.ts` | Optional outside plan review for /plan-ceo-review and /plan-eng-review: Claude Code on Codex, Codex on other supported harnesses, with the caller's native subagent fallback | | `{{DESIGN_SETUP}}` | `resolvers/design.ts` | Discovery pattern for `$D` design binary, mirrors `{{BROWSE_SETUP}}` | | `{{DESIGN_DETECTOR}}` | `resolvers/design.ts` | Probe block + sentinel reading for the user-installed impeccable engine (`bin/gstack-design-detect.ts`); `:phase0` renders design-review's mechanical scan, `:gate` design-html's bounded slop gate | | `{{DESIGN_MD_CHECK}}` | `resolvers/design.ts` | Open DESIGN.md format check through `bin/gstack-design-md.ts`, with the one-time conversion offer persisted in the file; `:calibrate` renders the tokens-as-calibration form for /design-review | diff --git a/BROWSER.md b/BROWSER.md index 4bfc52c074a..d319829e274 100644 --- a/BROWSER.md +++ b/BROWSER.md @@ -99,7 +99,7 @@ through CDP before `goto`, as the cookbook does), and no `file://` navigation. | `/scrape` | Prototype the extraction with `aside repl`, hand back the table, list, or prices as structured data. Read-only. | | `/devex-review` | Walk the real onboarding flow and time it, carrying the cookbook inline. | | `/ship`, `/spec`, `/land-and-deploy`, `/setup-deploy`, `/office-hours` | Third-party web actions (vendor dashboards, API keys, webhooks) offered as an Aside drive across your real sessions, with the one-question consent gate for anything mutating. | -| `/plan-ceo-review`, `/plan-devex-review`, `/design-consultation`, `/review`, `/cso`, `/office-hours` | Web research runs through `aside exec` in your real browser (`{{ASIDE_RESEARCH}}`), one read-only request per question, answers treated as untrusted content. No Aside → the same queries go to the host's WebSearch tool; no WebSearch either → "Search unavailable" once and the skill proceeds on in-distribution knowledge. | +| `/plan-ceo-review`, `/plan-eng-review`, `/plan-devex-review`, `/design-consultation`, `/review`, `/cso`, `/office-hours` | Web research runs through `aside exec` in your real browser (`{{ASIDE_RESEARCH}}`), one read-only request per question, answers treated as untrusted content. No Aside → the same queries go to the host's WebSearch tool; no WebSearch either → "Search unavailable" once and the skill proceeds on in-distribution knowledge. | ### Local-HTML rendering diff --git a/CLAUDE.md b/CLAUDE.md index 83cd96c3309..35db4608f40 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -546,7 +546,7 @@ When the user's request matches an available skill, invoke it via the Skill tool Key routing rules: - Product ideas/brainstorming → invoke /office-hours - Strategy/scope → invoke /plan-ceo-review -- Architecture → invoke /autoplan +- Architecture → invoke /plan-eng-review - Design system/plan review → invoke /design-consultation or /plan-design-review - Full review pipeline → invoke /autoplan - Bugs/errors → fix them directly: one read-only check of the cause, or a focused failing test first when the cause is unclear; then fix it and run that test diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef2f645940a..42db0bdc3dd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -922,44 +922,79 @@ triaging for the maintainer posts these comments under its bot identity `gh` runs as the maintainer. The full rule, including the labels and the close reasons, is in [docs/triage.md](docs/triage.md). -## Community PR triage (wave process) - -When community PRs accumulate, batch them into themed waves: - -1. **Categorize** — group by theme (security, features, infra, docs) -2. **Deduplicate** — if two PRs fix the same thing, pick the one that - changes fewer lines. Close the other with a note pointing to the winner. -3. **Collector branch** — create `pr-wave-N`, merge clean PRs, resolve - conflicts for dirty ones, verify with `bun run test && bun run build` -4. **Close with context** — every closed PR gets a comment explaining - why and what (if anything) supersedes it. Contributors did real work; - respect that with clear communication. An agent running the wave posts - these notes under its bot identity, never the maintainer's own account. -5. **Ship as one PR** — single PR to main with all attributions preserved - in merge commits. Include a summary table of what merged and what closed. - -See [PR #205](../../pull/205) (v0.8.3) for the first wave as an example. +## Sending a report or a PR + +gstack is maintained day to day by AI agents working for Garry Tan. They triage issues +and PRs, rebuild good patches on current main, and land them with the author credited. +That's why nearly every commit on main reads as Garry's: the agents commit under his +account, and your credit is a `Co-authored-by:` trailer plus a line in the PR body. + +**What happens to your PR.** Outside code is treated as untrusted: an agent reads your +diff as text and never checks it out, runs it or builds it. Then one of three things +happens. + +- **Docs for people only** (for example the README) can be merged as + they are, after an agent checks every link, command and install step in them against + main. +- **A small fix** that is plainly correct, about 40 lines or fewer not counting its + tests, is taken even when the gain is small. An agent rebuilds it on current main + with you as co-author. We land at most one of these a day. +- **Everything else**, including anything that runs and any Markdown agents load + (`SKILL.md` files and their templates, `AGENTS.md`, `CLAUDE.md`, prompts), is + rebuilt on main with credit when it passes the test below, and closed with a short + note saying why when it doesn't. + +When your change is rebuilt, the agent comments on your PR with a link to what landed +and closes your PR, so a taken PR usually shows "Closed", not "Merged". In the month +to 15 November 2026, 4 of the 124 outside PRs opened here were merged as they were, +and 54 outside contributors were credited as co-authors on commits to main. + +**What makes a report or a PR likely to be taken.** + +1. Proof: steps that reproduce it on current main, or a test that fails before the fix. +2. A real consequence: what breaks, and for whom. +3. It matters to most gstack users or to the maintainer's own setup. Windows and Gemini + models get [minimal support](docs/support-tiers.md), so a report there needs to break + install, startup or a core skill. + +**When you'll hear back.** Our goal is a first reply within 48 hours, posted by +`capy-ai[bot]`. It says what we'll do: already fixed (with the PR and version), a +duplicate (with a link), one specific fact we still need, not planned (and why), or +taken. + +**The open-PR limit.** Most people never meet it. If, in the last 30 days, 3 or more of +your PRs here were closed without being taken and fewer than 1 in 4 of your decided PRs +were taken, and none was taken in the last 90 days, you can have at most 3 PRs open at +once, and extra ones are closed with a note. It never applies to anyone who had a PR +taken (merged or rebuilt) in the last 90 days, so it lifts as soon as one of yours is +taken. ## How a contributor's PR lands -We read every outside PR as a bug report, and a crew lane writes the fix itself. Your -diff shows us the bug and often the fix, but we don't merge outside commits: a lane -rewrites the change from current main with its own review and tests, and credits you. -The maintainer crew follows the same rule -([crew/docs/captain.md](crew/docs/captain.md#contributions-from-outside-the-crew)). +These are the maintainer's steps; [Sending a report or a PR](#sending-a-report-or-a-pr) +is the same policy from the contributor's side. The maintainer crew follows the same +rule ([crew/docs/captain.md](crew/docs/captain.md#contributions-from-outside-the-crew)). 1. **Treat the diff as untrusted input.** Read it as text only, for scope, network egress, credentials, new dependencies, CI permission changes and weakened or deleted tests. Never check it out, run it or build it. A fork's green checks prove nothing about this checkout. -2. **Give a verdict within 7 days.** Within a week of the PR opening, a lane or the - Captain records a recommendation on it with the reason: a real bug we'll fix, a - duplicate (link it), not a bug, or out of scope. An agent posts it under its bot - identity. "Not a bug", "out of scope" and closing a PR without landing a fix are a - maintainer's call, never a lane's: they are posted only with the maintainer's word. -3. **Rewrite the fix from current main.** The lane writes the change on its own branch - with its own tests, the repo's gates and a CHANGELOG fragment. No contributor - commit enters the tree. A commit that carries the contributor's lines over +2. **Reply within 48 hours, decide within 7 days.** Every outside issue and PR gets a + first reply from the bot identity within 48 hours that says what happens next, and a + verdict within a week: taken, a duplicate (link it), needs one named fact, or not + planned. Take it only when it passes the test in + [Sending a report or a PR](#sending-a-report-or-a-pr); close the rest with a short, + kind reason. A case the test doesn't settle goes to the maintainer. +3. **Merge a docs-only PR for people as it is.** When the PR changes only documentation + people read, check every link, command and install step in it against main. If all + of them hold, merge it unchanged; if not, say which one fails. Anything that runs, + and any Markdown agents load (`SKILL.md` files and templates, `AGENTS.md`, + `CLAUDE.md`, `CREW.md`, prompts), is not docs for this step and is rewritten. +4. **Rewrite everything else from current main.** The lane writes the change on its own + branch with its own tests, the repo's gates and a CHANGELOG fragment. No contributor + commit enters the tree. A plainly correct fix of about 40 lines or fewer (counting + the fix, not its tests) is taken even when the gain is small, at most one such PR a + day. A commit that carries the contributor's lines over unchanged gets a `Co-authored-by:` trailer for them. Fetch their PR head as a ref without checking it out (`git fetch origin +pull//head:refs/contrib/`; the `+` lets a re-fetch follow a force-push), then run @@ -968,17 +1003,22 @@ The maintainer crew follows the same rule no co-author. A fork's commits can name anyone, so keep only the authors whose lines you carry: drop the rest with `--exclude ` when you rerun it with `--message `. Never guess an email: use the identity on their commits. -4. **Credit them in the fix.** The PR body names the original PR and its author in +5. **Credit them in the fix.** The PR body names the original PR and its author in the first paragraph and says what differs from their diff. The CHANGELOG fragment thanks them by handle. -5. **Close the original with a specific thank-you.** After the fix lands, comment on +6. **Close the original with a specific thank-you.** After the fix lands, comment on their PR with what landed (the PR number and version), what changed from their diff and why, and thank them by name for the specific thing they found. Then close it. An agent posts that comment under its bot identity, never the maintainer's own account. +7. **Apply the open-PR limit only to chronic authors.** An author is capped at 3 open + PRs only when, in the last 30 days, 3 or more of their PRs closed untaken and fewer + than 1 in 4 of their decided PRs were taken, and none of their PRs was taken in the + last 90 days. Taken means merged, or rebuilt by the crew. Close the extra PRs with a + note that names the limit and says it lifts once one of their PRs is taken. If we won't fix what the PR reports, say why on the PR and close or park it under -[Issue triage](#issue-triage), with the maintainer's word. +[Issue triage](#issue-triage). ## Upgrade migrations diff --git a/README.md b/README.md index 9e30e702f61..e7d04738bc9 100644 --- a/README.md +++ b/README.md @@ -118,8 +118,8 @@ Claude: I'm going to push back on the framing. You said "daily briefing You: /plan-ceo-review [reads the design doc, challenges scope, runs 10-section review] -You: /autoplan - [eng phase: ASCII diagrams for data flow, state machines, error paths] +You: /plan-eng-review + [ASCII diagrams for data flow, state machines, error paths] [test matrix, failure modes, security concerns] You: Approve plan. Exit plan mode. @@ -143,12 +143,13 @@ gstack is a process, not a collection of tools. The skills run in the order a sp **Think → Plan → Build → Review → Test → Ship → Reflect** -Each skill feeds into the next. `/office-hours` writes a design doc that `/plan-ceo-review` reads. An interactive `/autoplan` run's eng phase writes a test plan that `/qa` picks up. `/review` catches bugs that `/ship` verifies are fixed. Nothing falls through the cracks because every step knows what came before it. +Each skill feeds into the next. `/office-hours` writes a design doc that `/plan-ceo-review` reads. `/plan-eng-review` writes a test plan that `/qa` picks up. `/review` catches bugs that `/ship` verifies are fixed. Nothing falls through the cracks because every step knows what came before it. | Skill | Your specialist | What they do | |-------|----------------|--------------| | `/office-hours` | **YC Office Hours** | Start here. Six forcing questions that reframe your product before you write code. Pushes back on your framing, challenges premises, generates implementation alternatives. Design doc feeds into every downstream skill. | | `/plan-ceo-review` | **CEO / Founder** | Rethink the problem. Find the 10-star product hiding inside the request. Four modes: Expansion, Selective Expansion, Hold Scope, Reduction. | +| `/plan-eng-review` | **Eng Manager** | Lock in architecture, data flow, diagrams, edge cases, and tests. Forces hidden assumptions into the open. | | `/plan-design-review` | **Senior Designer** | Rates each design dimension 0-10, explains what a 10 looks like, then edits the plan to get there. AI Slop detection. Interactive — one AskUserQuestion per design choice. | | `/plan-devex-review` | **Developer Experience Lead** | Interactive DX review: explores developer personas, benchmarks against competitors' TTHW, designs your magical moment, traces friction points step by step. Scores error messages for the agents that read them ([agent-ready errors](docs/agent-ready-errors.md)). Three modes: DX EXPANSION, DX POLISH, DX TRIAGE. 20-45 forcing questions. | | `/design-consultation` | **Design Partner** | Build a complete design system from scratch. Researches the landscape, proposes creative risks, generates realistic product mockups. Writes `DESIGN.md` in the open DESIGN.md format, so impeccable, Google Stitch, and any tool that reads it share one file. | @@ -194,7 +195,7 @@ The same `/qa` and `/qa-only` commands test CLIs, APIs, jobs, workers and webhoo |-----------------|--------------------------|----------------------------| | **End users** (UI, web app, mobile) | `/plan-design-review` | `/design-review` | | **Developers** (API, CLI, SDK, docs) | `/plan-devex-review` | `/devex-review` | -| **Architecture** (data flow, perf, tests) | `/autoplan` (eng phase) | `/review` | +| **Architecture** (data flow, perf, tests) | `/plan-eng-review` | `/review` | | **All of the above** | `/autoplan` (runs CEO → design → DX → eng, auto-detects which apply; eng always last) | — | ### Power tools diff --git a/SKILL.md b/SKILL.md index e66fed3f2d5..40d70531492 100644 --- a/SKILL.md +++ b/SKILL.md @@ -186,7 +186,7 @@ quality gates that produce better results than answering inline. - User describes a new idea, asks "is this worth building", brainstorms, pitches a concept → invoke `/office-hours` - User asks to spec something out, file an issue, write up a ticket, "turn this into a GitHub issue", "backlog item" → invoke `/spec` - User asks about strategy, scope, ambition, "think bigger", "what should we build" → invoke `/plan-ceo-review` -- User asks to review architecture, lock in the plan, "does this design make sense" → invoke `/autoplan` +- User asks to review architecture, lock in the plan, "does this design make sense" → invoke `/plan-eng-review` - User asks about design system, brand, visual identity, "how should this look" → invoke `/design-consultation` - User asks to review design of a plan → invoke `/plan-design-review` - User asks about developer experience of a plan, API/CLI/SDK design → invoke `/plan-devex-review` @@ -248,6 +248,7 @@ Generic “second opinion”, “outside review”, or “cross-model review” - Voice trigger "show me the browser" → invoke `/open-gstack-browser` - Voice trigger "pair agent", "connect agent", "share my browser", "remote browser access" → invoke `/pair-agent` - Voice trigger "dx review", "developer experience review", "devex review", "devex audit", "API design review", "onboarding review" → invoke `/plan-devex-review` +- Voice trigger "tech review", "technical review", "plan engineering review" → invoke `/plan-eng-review` - Voice trigger "quality check", "test the app", "run QA" → invoke `/qa` - Voice trigger "bug report", "just check for bugs" → invoke `/qa-only` diff --git a/SKILL.md.tmpl b/SKILL.md.tmpl index c387ef7d782..371e5683817 100644 --- a/SKILL.md.tmpl +++ b/SKILL.md.tmpl @@ -62,7 +62,7 @@ quality gates that produce better results than answering inline. - User describes a new idea, asks "is this worth building", brainstorms, pitches a concept → invoke `/office-hours` - User asks to spec something out, file an issue, write up a ticket, "turn this into a GitHub issue", "backlog item" → invoke `/spec` - User asks about strategy, scope, ambition, "think bigger", "what should we build" → invoke `/plan-ceo-review` -- User asks to review architecture, lock in the plan, "does this design make sense" → invoke `/autoplan` +- User asks to review architecture, lock in the plan, "does this design make sense" → invoke `/plan-eng-review` - User asks about design system, brand, visual identity, "how should this look" → invoke `/design-consultation` - User asks to review design of a plan → invoke `/plan-design-review` - User asks about developer experience of a plan, API/CLI/SDK design → invoke `/plan-devex-review` diff --git a/TODOS.md b/TODOS.md index abc4c831cd5..e47fc855e15 100644 --- a/TODOS.md +++ b/TODOS.md @@ -2,13 +2,9 @@ ## NEXT PRIORITY -### P2: `/plan-eng-review` retirement follow-ups (filed 2026-11-06, GST-1698 /ship review of #4108) +### P3: `/plan-eng-review` return follow-up (filed 2026-11-15, GST-2726) -- **Delete the retired `plan-eng-multi-finding-batching` case and its counter subsystem.** The case checks one interactive question per eng finding; /autoplan Phase 3 auto-decides findings, so no shipped entry reaches it. The follow-up to #4108 took it out of the weekly lane through `PERIODIC_CI_EXCLUDE` instead of deleting it, because about 20 free tests and fixtures depend on its counter (`createEngBatchingIssueCounter` in `test/helpers/eng-seeded-coverage.ts`, `test/eng-batching-saved-ledger.test.ts`, `test/detector-corpus-plan-eng-multi-finding-batching.test.ts`, the `eng-batching-*` fixtures). Retirement card: detects=an eng review that batches findings into one plan write; non_test_callers=0; stronger_proof=the ceo/design/devex finding floors keep the shared one-question-per-finding contract; unlocks=the counter helpers, their free tests and fixtures. Delete each helper only after checking it has no other caller (plan-eng-review-artifact shares `engFirstReviewAUQ`). **Effort:** M. **Priority:** P3. -- **Point the external-host methodology file's preamble Read at `gstack-autoplan`.** Every external host's `gstack-autoplan/plan-eng-review.md` says to Read `sections/preamble.md` relative to the installed `gstack-plan-eng-review` directory, which no longer exists. Normally the matching preamble id skips the reread, but after compaction late in a run the agent follows a missing path. Fixing it changes Phase 3 bytes, so it needs its own byte-pin update. **Effort:** S. **Priority:** P3. -- **Redirect `gstack-doctor --for plan-eng-review`.** It now exits 2 with "unknown skill"; map the retired name to `/autoplan`'s requirements and print a one-line redirect, so saved lane scripts keep working. **Effort:** S. **Priority:** P3. -- **Decide whether the QM edition keeps `gstack-plan`.** `hosts/qm.ts` and `qm/edition.json` still build `gstack-plan` from the `plan-eng-review` sources under another name, so the retired-name guards don't see it. Product call for Garry. **Effort:** S. **Priority:** P3. -- **Pin the retirement in two more tests.** Assert that `generateLlmsTxt` output lists no `plan-eng-review` entry (`test/llms-txt-shape.test.ts`), and that `HYBRID_SKILLS` holds none of `RETIRED_SKILLS` (`test/harness-register.test.ts`). **Effort:** S. **Priority:** P3. +- **Decide whether `plan-eng-multi-finding-batching` rejoins the weekly lane.** The cut of the standalone skill (GST-1698) took it out through `PERIODIC_CI_EXCLUDE`, because /autoplan Phase 3 auto-decides findings. The standalone `/plan-eng-review` is back (GST-2726) and asks one question per eng finding again, so the case reaches a shipped entry. Running it weekly is paid spend, so the call belongs to the measurement plan in GST-1966. The standalone paid cases deleted with the cut (`plan-eng-plan-mode`, `plan-eng-finding-floor`, `plan-eng-review-artifact-full`) are not restored either. **Effort:** S. **Priority:** P3. ### P3: clarity-judge removal follow-ups (filed 2026-11-04, GST-1371) @@ -425,10 +421,17 @@ From the approved 2026-10 test/eval/CI audit plan; the audit PR files these. - **`scripts/ship-measure.ts` on env-var hosts** — /ship's measure loop runs `$GSTACK_ROOT/scripts/ship-measure.ts`, which imports gstack's test helpers and eval harness, so a Codex/Factory/... runtime root would need most of the - development tree. It is the one `$GSTACK_ROOT` path - `test/runtime-root-assets.test.ts` defers. Either make ship-measure - self-contained or have the skill call it from the source checkout - (`.source-path`). **Effort:** M. **Priority:** P3. + development tree. `bin/gstack-model-benchmark` (/benchmark-models imports + the test tree's providers) and `bin/gstack-ship-queue` (the merge queue + imports the eval gate) have the same problem and fail to start from a + copied Windows root. `test/runtime-root-assets.test.ts` defers all three. + For each, either make it self-contained or have the skill call it from the + source checkout (`.source-path`). That test also follows static imports + only: lazy `import()` and `require()` calls (`bin/gstack-evidence` loads + `scripts/lib/shard-engine` with a fallback, and + `lib/pregate/flaky-exception.ts` requires it and a test helper), modules a + shell script launches, and bare package imports go unchecked. + **Effort:** M. **Priority:** P3. - **Rendered `SKILL.md` copies inside runtime roots are discoverable** — `office-hours/SKILL.md` (#2449) and now `plan-design-review/SKILL.md` sit in `~/.codex/skills/gstack//` because skills read them as diff --git a/USING_GBRAIN_WITH_GSTACK.md b/USING_GBRAIN_WITH_GSTACK.md index 60f60c48e27..d4a59d370e6 100644 --- a/USING_GBRAIN_WITH_GSTACK.md +++ b/USING_GBRAIN_WITH_GSTACK.md @@ -218,7 +218,8 @@ The skill re-collects a PAT (one-time, discarded after), lists every project in | `gstack-gbrain-supabase-verify` | Structural URL check. Rejects direct-connection URLs (`db.*.supabase.co:5432`) with exit 3 | | `gstack-gbrain-supabase-provision` | Management API wrapper. Subcommands: `list-orgs`, `create`, `wait`, `pooler-url`, `list-orphans`, `delete-project`. All require `SUPABASE_ACCESS_TOKEN` in env. `create` and `pooler-url` also require `DB_PASS`. `--json` mode available on every subcommand. | | `gstack-gbrain-repo-policy` | Per-remote trust triad. Subcommands: `get`, `set`, `list`, `normalize` | -| `gstack-gbrain-source-wireup` | Registers your `~/.gstack/` brain repo with gbrain as a federated source via `gbrain sources add` + `git worktree`, then runs an initial `gbrain sync`. Idempotent. Replaces the dead `consumers.json + /ingest-repo` HTTP wireup from v1.12.x. Flags: `--strict`, `--source-id `, `--no-pull`, `--uninstall`, `--probe`. | +| `gstack-gbrain-source-wireup` | Registers your `~/.gstack/` brain repo with gbrain as a federated source via `gbrain sources add` + `git worktree`, then runs an initial `gbrain sync`. Idempotent. Replaces the dead `consumers.json + /ingest-repo` HTTP wireup from v1.12.x. Flags: `--strict`, `--source-id `, `--no-pull`, `--uninstall`, `--probe`, `--advance-only`, and `--check-target` (read-only: reports `TARGET: MATCH` or `TARGET: MISMATCH` for whether an earlier run with `GBRAIN_HOME` set could have used the wrong brain; never prints a database URL). | +| `gstack-gbrain-home.sh` | Sourced, not executed. Provides `gstack_gbrain_config_path`, which prints the config.json gbrain itself reads (`$GBRAIN_HOME/.gbrain/config.json`, else `~/.gbrain/config.json`) and prints nothing for a `GBRAIN_HOME` gbrain refuses (relative, or with a `..` segment). Used by the source wireup and skill start. | ### gbrain CLI (upstream tool) @@ -240,7 +241,7 @@ Gbrain itself ships with these that gstack wraps: | Path | What lives there | |---|---| -| `~/.gbrain/config.json` | Engine (pglite/postgres), database URL or path, API keys. Mode 0600. Written by `gbrain init`. | +| `~/.gbrain/config.json` | Engine (pglite/postgres), database URL or path, API keys. Mode 0600. Written by `gbrain init`. When `GBRAIN_HOME` is set, gbrain and gstack's helpers read `$GBRAIN_HOME/.gbrain/config.json` instead. | | `~/.gstack/gbrain-repo-policy.json` | Per-remote trust triad. Schema v2. Mode 0600. | | `~/.gstack/.setup-gbrain.lock.d` | Concurrent-run lock (atomic mkdir). Released on normal exit + SIGINT. | | `~/.gstack/.brain-queue.d/` | Pending sync records for gstack memory sync — maildir-style spool, one file per record. A legacy `.brain-queue.jsonl` from older releases migrates automatically on the next drain. | diff --git a/autoplan/SKILL.md b/autoplan/SKILL.md index c9ea0b96ca0..796c5b9f459 100644 --- a/autoplan/SKILL.md +++ b/autoplan/SKILL.md @@ -2,7 +2,7 @@ name: autoplan preamble-tier: 3 version: 1.0.0 -description: "Auto-review pipeline — runs the CEO, design, eng (architecture, edge cases, failure modes, tests) and DX reviews (lean run: one reviewer), auto-deciding. (gstack)" +description: "Auto-review pipeline — runs the CEO, design, eng and DX reviews in order (lean run: one reviewer), auto-deciding. (gstack)" triggers: - run all reviews - automatic review pipeline diff --git a/autoplan/SKILL.md.tmpl b/autoplan/SKILL.md.tmpl index 2e5108f739a..f8462d149ab 100644 --- a/autoplan/SKILL.md.tmpl +++ b/autoplan/SKILL.md.tmpl @@ -3,12 +3,11 @@ name: autoplan preamble-tier: 3 version: 1.0.0 description: | - Auto-review pipeline — runs the CEO, design, eng (architecture, edge cases, failure - modes, tests) and DX reviews (lean run: one reviewer), auto-deciding. Surfaces - taste decisions (close approaches, borderline scope, outside-review disagreements) at - one approval gate. Use when asked to "auto review", "autoplan", "run all reviews", - "review this plan automatically", "review the architecture", "engineering review", or - "make the decisions for me". (gstack) + Auto-review pipeline — runs the CEO, design, eng and DX reviews in order (lean + run: one reviewer), auto-deciding. Surfaces taste decisions (close approaches, + borderline scope, outside-review disagreements) at one approval gate. Use when + asked to "auto review", "autoplan", "run all reviews", "review this plan + automatically", or "make the decisions for me". (gstack) codex_default_prompt: "Use $gstack-autoplan to run the CEO, design, DX and eng reviews over this plan in one pass, decide the routine questions itself, and stop at a single approval gate." voice-triggers: - "auto plan" diff --git a/autoplan/bin/guard-reasons.ts b/autoplan/bin/guard-reasons.ts index fde59f000c9..ad143c2d5d1 100644 --- a/autoplan/bin/guard-reasons.ts +++ b/autoplan/bin/guard-reasons.ts @@ -16,7 +16,7 @@ export type Disposition = 'fallback' | 'corrective' | 'transient' | 'unverified' export type Detail = { phase?: string | number; keys?: string[]; cause?: string; size?: string; limit?: string }; interface Reason { disposition: Disposition; text: (d: Detail) => string } -export const FALLBACK = 'Fallback: run /plan-ceo-review, then /plan-devex-review by hand; ' + +export const FALLBACK = 'Fallback: run /plan-ceo-review, then /plan-devex-review, then /plan-eng-review by hand; ' + 'or run /context-save, start a new Claude Code session (not --resume), run /context-restore, then /autoplan .'; const PUBLISH_SEPARATELY = (d: Detail) => `Publish the filled Phase ${d.phase} report as your own parent assistant text in a message ` + `whose only tool call is the Bash no-op \`true autoplan-published \`, then make this phase-entry call in a later message.`; diff --git a/bin/gstack-approvals b/bin/gstack-approvals index 3db93bf07b3..2cf9ff7320c 100755 --- a/bin/gstack-approvals +++ b/bin/gstack-approvals @@ -10,6 +10,8 @@ * gstack-approvals plan-check --plan * gstack-approvals rule --finding --head --reason --words --by [--json] * gstack-approvals rulings [--branch ] + * gstack-approvals gate --finding --gate-id --head --reason --words --by [--json] + * gstack-approvals dispositions [--branch ] * gstack-approvals lane-exception --head --files --reason --words --by [--json] * gstack-approvals list [--json] [--branch ] * gstack-approvals sync [--branch ] @@ -30,6 +32,7 @@ import { GSTACK_ACTOR, openShipRun, RULED_NOTE_SCOPE, ruledNoteRow, ruledNotes, import { resultLine } from '../lib/result-codes'; import { parsePlanLine, publicPlanLine, resolvePlan } from '../lib/plan-record'; import { TEST_LANE_EXCEPTION_SCOPE, testLaneExceptionRow } from '../lib/test-lane-exception'; +import { GATE_DISPOSITION_SCOPE, GATE_SOURCE, gateDispositionRow, gateDispositions, gateDispositionText, ONE_LINE, recordGateDisposition, validGateId } from '../lib/gate-dispositions'; const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gstack/captain.md) @@ -43,6 +46,14 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs counts that finding closed on a fix-check whose range_base..commit holds the head, and the receipt and PR body list it; refused inside this checkout's open /ship run rulings the "Ruled note: …" lines the Pre-Landing Review and the PR body carry + gate --finding --gate-id --head + --reason --words --by + the owner's disposition of a gate finding an unattended /ship logged open (docs/ship-policy.md#gate-dispositions); + it closes that fingerprint and gate_id on a review row whose range_base..commit holds the head (a first pass: its + commit), and gstack-review-read shows it kept; + finish prints it, and the receipt, PR body and READY carry it; refused while any worktree holds an open /ship run on + the branch; the lander accepts each one with gstack-ship-queue land|verify --accept-gate-disposition + dispositions the "Gate disposition: …" lines the Pre-Landing Review and the PR body carry lane-exception --head --files --reason --words --by the owner's grant that a CI-carried lane counts although exactly those files are in no run's tree.json @@ -69,7 +80,7 @@ Example: ${exitTableHelp()}`; -const VALUE_FLAGS = new Set(['--ask', '--words', '--by', '--scope', '--pending', '--outcome', '--date', '--source', '--branch', '--autoplan', '--stack', '--finding', '--reason', '--head', '--files', '--plan']); +const VALUE_FLAGS = new Set(['--ask', '--words', '--by', '--scope', '--pending', '--outcome', '--date', '--source', '--branch', '--autoplan', '--stack', '--finding', '--reason', '--head', '--files', '--plan', '--gate-id']); function parse(args: string[]): { flags: Record; bools: Set; error?: string } { const flags: Record = {}; @@ -146,7 +157,7 @@ function main(argv: string[]): number { const json = bools.has('--json'); const recorded = (where: StoreLocation) => `${where.file}${where.mirror ? ` mirror=${where.mirror}` : ''}`; - if (cmd === 'add' || cmd === 'import' || cmd === 'rule' || cmd === 'lane-exception') { + if (cmd === 'add' || cmd === 'import' || cmd === 'rule' || cmd === 'lane-exception' || cmd === 'gate') { let rows; if (cmd === 'lane-exception') { const invalid = (message: string) => fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message }); @@ -174,8 +185,25 @@ function main(argv: string[]): number { const built = buildRow({ ...ruledNoteRow(finding, head.stdout.trim(), reason), words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'] }, loc.branch); if ('code' in built) return fail(cmd, built); rows = [built]; + } else if (cmd === 'gate') { + const invalid = (message: string) => fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message }); + const finding = (flags['--finding'] ?? '').trim(), gateId = (flags['--gate-id'] ?? '').trim(), reason = (flags['--reason'] ?? '').trim(), words = (flags['--words'] ?? '').trim(), by = (flags['--by'] ?? '').trim(); + if (!finding || /\s/.test(finding) || !validGateId(gateId) || !reason) return invalid('gate needs --finding , --gate-id , both without spaces (a finding with no gate_id, or a literal undefined, cannot be dispositioned), and --reason '); + if (!words) return invalid('gate needs --words : a gate disposition is the owner\'s, in the owner\'s words'); + if (!ONE_LINE.test(reason) || !ONE_LINE.test(words) || !ONE_LINE.test(by)) return invalid('--reason, --words and --by are one line each: no newline or control character'); + const head = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${flags['--head'] ?? ''}^{commit}`], { encoding: 'utf8', timeout: 10_000 }); + if (!flags['--head'] || head.status !== 0) return invalid('gate needs --head '); + if (GSTACK_ACTOR.test(by)) return invalid('--by names gstack; a gate disposition is the owner\'s, so --by names who recorded it'); + const built = buildRow({ ...gateDispositionRow(finding, gateId, head.stdout.trim(), reason), words, by, date: flags['--date'], source: GATE_SOURCE }, loc.branch); + if ('code' in built) return fail(cmd, built); + const res = recordGateDisposition(process.cwd(), loc, built); + if ('code' in res) return fail(cmd, res); + if (json) process.stdout.write(JSON.stringify({ added: res.added.map(r => r.id), skipped: res.skipped, file: loc.file, mirror: loc.mirror ?? null }) + '\n'); + else process.stdout.write(`APPROVAL_RECORDED: ${built.id}${res.skipped ? ' (already present)' : ''} ${recorded(loc)}\n`); + return res.mirrorError ? fail(cmd, res.mirrorError) : EXIT.ok; } else if (cmd === 'add') { if (RULED_NOTE_SCOPE.test(flags['--scope'] ?? '')) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a ruled_note scope is recorded with gstack-approvals rule' }); + if (GATE_DISPOSITION_SCOPE.test(flags['--scope'] ?? '') || (flags['--source'] ?? '').trim() === GATE_SOURCE) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a gate_disposition scope is recorded with gstack-approvals gate' }); if (TEST_LANE_EXCEPTION_SCOPE.test(flags['--scope'] ?? '')) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a test_lane_exception scope is recorded with gstack-approvals lane-exception' }); const built = buildRow({ ask: flags['--ask'] ?? '', words: flags['--words'] ?? '', by: flags['--by'] ?? '', scope: flags['--scope'] ?? '', pending: flags['--pending'], outcome: flags['--outcome'], date: flags['--date'], source: flags['--source'] }, loc.branch); if ('code' in built) return fail(cmd, built); @@ -230,6 +258,11 @@ function main(argv: string[]): number { process.stdout.write(notes.length ? notes.map(n => `Ruled note: ${ruledNoteText(n)}\n`).join('') : 'RULED_NOTES: none\n'); return EXIT.ok; } + if (cmd === 'dispositions') { + const ds = gateDispositions(readRecord(loc).rows, loc.branch); + process.stdout.write(ds.length ? ds.map(d => `Gate disposition: ${gateDispositionText(d)}\n`).join('') : 'GATE_DISPOSITIONS: none\n'); + return EXIT.ok; + } if (cmd === 'sync') { const s = syncRecord(loc); process.stdout.write(`APPROVAL_SYNCED: rows=${s.rows} ${recorded(loc)}\n`); diff --git a/bin/gstack-brain-context-load.ts b/bin/gstack-brain-context-load.ts index 250341cfc68..6af90eb3f1e 100644 --- a/bin/gstack-brain-context-load.ts +++ b/bin/gstack-brain-context-load.ts @@ -540,7 +540,8 @@ async function main(): Promise { } const failures = results.filter((r) => r.failed); - if (!args.quiet && failures.length > 0 && gbrainAvailable() && existsSync(join(gbrainConfigDir(), "config.json"))) { + const configDir = gbrainConfigDir(); + if (!args.quiet && failures.length > 0 && gbrainAvailable() && configDir && existsSync(join(configDir, "config.json"))) { const reasons = [...new Set(failures.map((r) => r.reason))].join("; "); console.error(`brain context: ${failures.length}/${results.length} queries failed (${reasons})`); } diff --git a/bin/gstack-browser-ensure b/bin/gstack-browser-ensure index 5f8605f4ec2..0f87e327469 100755 --- a/bin/gstack-browser-ensure +++ b/bin/gstack-browser-ensure @@ -27,6 +27,23 @@ set -u GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v cygpath >/dev/null 2>&1; then GSTACK_BUN_CONFIG=NUL; fi ;; esac ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" || { echo "gstack-browser-ensure: cannot resolve the install root" >&2; exit 1; } +# A host runtime root (~/.codex/skills/gstack, ...) has no package.json or +# node_modules; setup records the gstack checkout it came from in .source-path. +# Use that checkout's dependencies only when the pointer is a regular file +# holding an absolute path whose real directory has gstack's own package.json +# and this helper, neither a link. Anything else keeps the root, as before. +if [ ! -e "$ROOT/package.json" ] && [ -f "$ROOT/.source-path" ] && [ ! -L "$ROOT/.source-path" ]; then + _src=$(head -1 "$ROOT/.source-path" | tr -d '\r') + case "$_src" in + /*|[A-Za-z]:/*) _src=$(cd "$_src" 2>/dev/null && pwd -P) || _src="" ;; + *) _src="" ;; + esac + if [ -n "$_src" ] && [ -f "$_src/package.json" ] && [ ! -L "$_src/package.json" ] \ + && [ -f "$_src/bin/gstack-browser-ensure" ] && [ ! -L "$_src/bin/gstack-browser-ensure" ] \ + && grep -Eq '^[[:space:]]*"name":[[:space:]]*"gstack",?[[:space:]]*$' "$_src/package.json"; then + ROOT="$_src" + fi +fi DOCS="https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#browser-ensure-failed" CHECK=0 QUIET=0 WITH_DEPS="" for _arg in "$@"; do diff --git a/bin/gstack-docs-candidate b/bin/gstack-docs-candidate index de740f9c374..de205969625 100755 --- a/bin/gstack-docs-candidate +++ b/bin/gstack-docs-candidate @@ -75,6 +75,12 @@ function git(args: string[]): string { return r.stdout; } const nul = (text: string) => text.split('\0').filter(Boolean); +/** A listed path holding a glob character is a real file (a Next.js [id] route, #4313) only when it exists from the repository root. */ +function repoFile(): (repoPath: string) => boolean { + const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 60_000 }); + const top = r.status === 0 ? r.stdout.trim() : process.cwd(); + return repoPath => fs.existsSync(path.join(top, repoPath)); +} function state(base: string) { const head = git(['rev-parse', 'HEAD']).trim(); @@ -328,11 +334,12 @@ function main(argv: string[]): void { const outDir = path.resolve(one(rest, '--out-dir')); const repairOf = optional(rest, '--repair-of'); const output = fs.readFileSync(file, 'utf8'); + const isFile = repoFile(); let check: DocsResultCheck; - if (!repairOf) check = checkDocsResult(output, auditId); + if (!repairOf) check = checkDocsResult(output, auditId, isFile); else { const original = fs.readFileSync(repairOf, 'utf8'); - const prior = checkDocsResult(original, auditId); + const prior = checkDocsResult(original, auditId, isFile); let first = true; if (!prior.ok && prior.repairable) { fs.mkdirSync(outDir, { recursive: true, mode: 0o700 }); @@ -341,7 +348,7 @@ function main(argv: string[]): void { first = false; } } - check = first ? checkDocsRepair(output, original, auditId) + check = first ? checkDocsRepair(output, original, auditId, isFile) : { ok: false, problems: ['a format repair was already used for this audit', ...(prior.ok ? [] : prior.problems)], trimmed: [], repairable: false, kept: {} }; } if (check.trimmed.length) console.log(`KEYS_TRIMMED: ${check.trimmed.map(k => JSON.stringify(k)).join(' ')}`); @@ -368,7 +375,7 @@ function main(argv: string[]): void { for (let i = 0; i < rest.length; i += 2) if (rest[i] !== '--audit-id') throw new Error(`unknown argument: ${rest[i]}`); const auditId = auditIdArg(rest); const output = fs.readFileSync(file, 'utf8'); - const check = checkDocsResult(output, auditId); + const check = checkDocsResult(output, auditId, repoFile()); if (check.ok || !check.repairable) throw new Error(`${file} is not a format-only failure of the last line, so it has no format repair: ${check.ok ? 'it is a valid result' : 'a content failure counts as an attempt (Blocked recovery, RETRY_NOTE:)'}`); process.stdout.write(docsRepairPrompt(output, auditId, check.problems)); return; diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index e84015ad76b..4a810df8abc 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -8,7 +8,7 @@ GSTACK_DOCTOR_COMPONENTS="claude codex patch codex-cli browse-bundle browser cso GSTACK_DOCTOR_CORE="runtime pins state-root privacy cores revision floor wrapper" GSTACK_DOCTOR_HOSTS="claude codex" GSTACK_DOCTOR_OPTIONAL="codex-cli cso" -GSTACK_DOCTOR_SKILLS="autoplan plan-ceo-review plan-design-review plan-devex-review plan-tune office-hours spec review ship codex cso browse qa qa-only design-review design-consultation design-html design-motion devex-review scrape skillify canary benchmark make-pdf diagram pair-agent open-gstack-browser setup-browser-cookies connect-chrome land-and-deploy benchmark-models captain careful claude-code context-restore context-save design-shotgun deslop-shared-libs document-generate document-release eval-plan freeze gstack-upgrade guard health ios-clean ios-design-review ios-fix ios-qa ios-sync landing-report learn write-skill modernize retro runaway-stopper setup-deploy setup-gbrain sync-gbrain test-audit ubicloud unfreeze verify review-voice" +GSTACK_DOCTOR_SKILLS="autoplan plan-ceo-review plan-eng-review plan-design-review plan-devex-review plan-tune office-hours spec review ship codex cso browse qa qa-only design-review design-consultation design-html design-motion devex-review scrape skillify canary benchmark make-pdf diagram pair-agent open-gstack-browser setup-browser-cookies connect-chrome land-and-deploy benchmark-models captain careful claude-code context-restore context-save design-shotgun deslop-shared-libs document-generate document-release eval-plan freeze gstack-upgrade guard health ios-clean ios-design-review ios-fix ios-qa ios-sync landing-report learn write-skill modernize retro runaway-stopper setup-deploy setup-gbrain sync-gbrain test-audit ubicloud unfreeze verify review-voice" GSTACK_BROWSER_LAZY_REASON="lazy; gstack-browser-ensure installs on first use" GSTACK_DOCTOR_HELPERS="gstack-pregate gstack-plan-reality gstack-artifact gstack-autoplan" GSTACK_DOCTOR_NOT_NEEDED="none" @@ -65,7 +65,7 @@ gstack_doctor_component_kind() { # gstack_doctor_skill_requires SKILL — the non-core ids the skill needs; returns 1 for an unknown skill. gstack_doctor_skill_requires() { case "$1" in - autoplan|plan-ceo-review|plan-design-review|plan-devex-review|plan-tune|office-hours|spec|review|ship) printf '%s' 'claude codex patch' ;; + autoplan|plan-ceo-review|plan-eng-review|plan-design-review|plan-devex-review|plan-tune|office-hours|spec|review|ship) printf '%s' 'claude codex patch' ;; codex) printf '%s' 'claude codex patch codex-cli' ;; cso) printf '%s' 'claude cso' ;; browse|qa|qa-only|design-review|design-consultation|design-html|design-motion|devex-review|scrape|skillify|canary|benchmark|make-pdf|diagram|pair-agent|open-gstack-browser|setup-browser-cookies|connect-chrome|land-and-deploy) printf '%s' 'claude codex patch browse-bundle browser' ;; @@ -78,7 +78,7 @@ gstack_doctor_skill_requires() { # gstack_doctor_skill_optional SKILL — ids that SKIP when absent; returns 1 for an unknown skill. gstack_doctor_skill_optional() { case "$1" in - autoplan|plan-ceo-review|plan-design-review|plan-devex-review|plan-tune|office-hours|spec|review|ship) printf '%s' 'codex-cli' ;; + autoplan|plan-ceo-review|plan-eng-review|plan-design-review|plan-devex-review|plan-tune|office-hours|spec|review|ship) printf '%s' 'codex-cli' ;; codex) printf '%s' '' ;; cso) printf '%s' '' ;; browse|qa|qa-only|design-review|design-consultation|design-html|design-motion|devex-review|scrape|skillify|canary|benchmark|make-pdf|diagram|pair-agent|open-gstack-browser|setup-browser-cookies|connect-chrome|land-and-deploy) printf '%s' 'codex-cli' ;; @@ -91,7 +91,7 @@ gstack_doctor_skill_optional() { # gstack_doctor_skill_pins_advisory SKILL — true for a planning-only workflow (a repo test-pin mismatch SKIPs pins). gstack_doctor_skill_pins_advisory() { case "$1" in - autoplan|plan-ceo-review|plan-design-review|plan-devex-review|office-hours) return 0 ;; + autoplan|plan-ceo-review|plan-eng-review|plan-design-review|plan-devex-review|office-hours) return 0 ;; *) return 1 ;; esac } @@ -355,6 +355,7 @@ gstack_result_anchor() { QUEUE_LAND_BASE_BUSY) printf '%s' 'queue-land-base-busy' ;; QUEUE_LAND_STAMPED) printf '%s' 'queue-land-stamped' ;; QUEUE_LAND_PIN_MOVED) printf '%s' 'queue-land-pin-moved' ;; + QUEUE_GATE_DISPOSITION) printf '%s' 'queue-gate-disposition' ;; QUEUE_LAND_CHECKS) printf '%s' 'queue-land-checks' ;; QUEUE_LAND_MERGED_CHECKS) printf '%s' 'queue-land-merged-checks' ;; QUEUE_LAND_NOT_CLEAN) printf '%s' 'queue-land-not-clean' ;; diff --git a/bin/gstack-gbrain-detect b/bin/gstack-gbrain-detect index 322eafa0ad0..7f21389f789 100755 --- a/bin/gstack-gbrain-detect +++ b/bin/gstack-gbrain-detect @@ -62,8 +62,10 @@ const CONFIG_BIN = join(SCRIPT_DIR, "gstack-config"); // GBRAIN_HOME is a parent dir, `.gbrain` is appended) — must stay consistent // with lib/gbrain-local-status's config resolution, or the detect JSON // reports gbrain_local_status "ok" alongside gbrain_config_exists false for -// relocated-home users. Both route through gbrainConfigDir. -const GBRAIN_CONFIG = join(gbrainConfigDir(), "config.json"); +// relocated-home users. Both route through gbrainConfigDir, which returns +// null for a GBRAIN_HOME gbrain refuses; that reads as no config. +const GBRAIN_CONFIG_DIR = gbrainConfigDir(); +const GBRAIN_CONFIG = GBRAIN_CONFIG_DIR ? join(GBRAIN_CONFIG_DIR, "config.json") : null; const CLAUDE_JSON = join(userHome(), ".claude.json"); function userHome(): string { @@ -106,7 +108,7 @@ function detectGbrain(): { onPath: boolean; version: string | null } { // --- gbrain config existence + engine kind --- function detectConfig(): { exists: boolean; engine: "pglite" | "postgres" | null } { - if (!existsSync(GBRAIN_CONFIG)) return { exists: false, engine: null }; + if (!GBRAIN_CONFIG || !existsSync(GBRAIN_CONFIG)) return { exists: false, engine: null }; const parsed = tryReadJSON(GBRAIN_CONFIG) as { engine?: string } | null; if (!parsed) return { exists: true, engine: null }; if (parsed.engine === "pglite" || parsed.engine === "postgres") { @@ -121,6 +123,7 @@ function detectConfig(): { exists: boolean; engine: "pglite" | "postgres" | null // a PgBouncer transaction-mode pooler (port 6543). Surfaced so /sync-gbrain // and /setup-gbrain can advise users when search may require GBRAIN_PREPARE. function detectPoolerMode(): "transaction" | "session" | "unknown" | null { + if (!GBRAIN_CONFIG) return null; const parsed = tryReadJSON(GBRAIN_CONFIG) as { database_url?: string } | null; if (!parsed?.database_url) return null; return isTransactionModePooler(parsed.database_url) ? "transaction" : "session"; @@ -289,7 +292,8 @@ function detectMcpMode(): McpMode | "none" { /** remote_mcp.mcp_url from gbrain's own config (thin-client marker, #2051). */ function readRemoteMcpUrl(): string { - const cfg = tryReadJSON(join(gbrainConfigDir(), "config.json")) as + if (!GBRAIN_CONFIG) return ""; + const cfg = tryReadJSON(GBRAIN_CONFIG) as | { remote_mcp?: { mcp_url?: string } } | null; return cfg?.remote_mcp?.mcp_url || ""; diff --git a/bin/gstack-gbrain-home.sh b/bin/gstack-gbrain-home.sh new file mode 100644 index 00000000000..242b98e966f --- /dev/null +++ b/bin/gstack-gbrain-home.sh @@ -0,0 +1,50 @@ +# gstack-gbrain-home.sh — find the config.json gbrain itself reads. +# +# This file is NOT executable; source it: +# +# . "$(dirname "$0")/gstack-gbrain-home.sh" +# +# gstack_gbrain_config_path prints the path of gbrain's config.json using +# gbrain's own configDir() rule (src/core/config.ts in garrytan/gbrain): +# GBRAIN_HOME, trimmed the way JavaScript trim() trims, is the PARENT directory +# and ".gbrain" is appended; unset or blank means $HOME/.gbrain. gbrain refuses +# a GBRAIN_HOME that is not absolute or that has a ".." segment, so for one of +# those this prints nothing and returns 1, and the caller must not fall back to +# $HOME/.gbrain (that would be a brain gbrain never reads). gbrainConfigDir() in +# lib/gbrain-exec.ts is the TypeScript twin, and test/gbrain-home-parity.test.ts +# holds both to one table. Every gstack shell read of gbrain's config goes +# through here (#4325). +# +# POSIX [[:space:]] is not trim()'s set: it misses NBSP and the BOM, and in a +# UTF-8 locale it follows the C library. So the set is spelled out as UTF-8 +# bytes: ASCII tab through carriage return and space, U+00A0, U+1680, +# U+2000-U+200A, U+2028, U+2029, U+202F, U+205F, U+3000 and U+FEFF. +gstack_gbrain_config_path() { + local home="${GBRAIN_HOME:-}" prev ws + local -a spaces=(' ' $'\t' $'\n' $'\v' $'\f' $'\r' $'\xc2\xa0' $'\xe1\x9a\x80' + $'\xe2\x80\x80' $'\xe2\x80\x81' $'\xe2\x80\x82' $'\xe2\x80\x83' $'\xe2\x80\x84' $'\xe2\x80\x85' + $'\xe2\x80\x86' $'\xe2\x80\x87' $'\xe2\x80\x88' $'\xe2\x80\x89' $'\xe2\x80\x8a' $'\xe2\x80\xa8' + $'\xe2\x80\xa9' $'\xe2\x80\xaf' $'\xe2\x81\x9f' $'\xe3\x80\x80' $'\xef\xbb\xbf') + while :; do + prev="$home" + for ws in "${spaces[@]}"; do + home="${home#"$ws"}" + home="${home%"$ws"}" + done + [ "$home" = "$prev" ] && break + done + if [ -z "$home" ]; then + printf '%s\n' "$HOME/.gbrain/config.json" + return 0 + fi + case "$home" in + /*) ;; + [A-Za-z]:[\\/]*|\\*) + case "${OSTYPE:-}" in msys*|cygwin*) ;; *) return 1 ;; esac ;; + *) return 1 ;; + esac + case "/$home/" in + */../*|*\\..\\*|*/..\\*|*\\../*) return 1 ;; + esac + printf '%s\n' "${home%/}/.gbrain/config.json" +} diff --git a/bin/gstack-gbrain-source-wireup b/bin/gstack-gbrain-source-wireup index 97cbb1b4a64..fbaa7fb8858 100755 --- a/bin/gstack-gbrain-source-wireup +++ b/bin/gstack-gbrain-source-wireup @@ -13,6 +13,7 @@ # [--database-url ] # gstack-gbrain-source-wireup --probe # gstack-gbrain-source-wireup --advance-only # daily unattended worktree advance (#2516) +# gstack-gbrain-source-wireup --check-target # read-only: could an earlier run have hit the wrong brain? (#4325) # gstack-gbrain-source-wireup --help # # Exit codes: @@ -28,9 +29,10 @@ # GSTACK_BRAIN_NO_SYNC — skip the gbrain sync step (tests; helper still # ensures source registration) # -# Defense against external rewrites of ~/.gbrain/config.json: +# Defense against external rewrites of gbrain's config.json: # At helper startup we capture the database URL ONCE — from --database-url, -# from GBRAIN_DATABASE_URL/DATABASE_URL env, or from ~/.gbrain/config.json — +# from GBRAIN_DATABASE_URL/DATABASE_URL env, or from the config.json gbrain +# itself reads ($GBRAIN_HOME/.gbrain, else ~/.gbrain; gstack-gbrain-home.sh) — # and export it as GBRAIN_DATABASE_URL for every child `gbrain` invocation. # That env var overrides whatever's in config.json (per gbrain's loadConfig # at src/core/config.ts:53), so a process that flips config.json mid-sync @@ -55,7 +57,9 @@ else REMOTE_FILE="$HOME/.gstack-brain-remote.txt" fi PLIST_PATH="$HOME/Library/LaunchAgents/com.gstack.brain-sync.plist" -GBRAIN_CONFIG="$HOME/.gbrain/config.json" +. "$SCRIPT_DIR/gstack-gbrain-home.sh" +GBRAIN_HOME_VALID=1 +GBRAIN_CONFIG=$(gstack_gbrain_config_path) || GBRAIN_HOME_VALID=0 # Git writes to $GSTACK_HOME (worktree add/prune/remove, the daily advance) # take the drain lock every gstack writer shares. A caller that already holds @@ -80,20 +84,33 @@ while [ $# -gt 0 ]; do --uninstall) MODE="uninstall"; shift ;; --probe) MODE="probe"; shift ;; --advance-only) MODE="advance-only"; shift ;; + --check-target) MODE="check-target"; shift ;; --strict) STRICT=1; shift ;; --no-pull) NO_PULL=1; shift ;; --source-id) SOURCE_ID="$2"; shift 2 ;; --database-url) DATABASE_URL_ARG="$2"; shift 2 ;; - --help|-h) sed -n '2,40p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + --help|-h) sed -n '2,42p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "Unknown flag: $1" >&2; exit 1 ;; esac done +prefix() { sed 's/^/gstack-gbrain-source-wireup: /' >&2; } +warn() { echo "$*" | prefix; } +# die [exit_code]: warn with just the message, exit with code (default 1). +die() { warn "$1"; exit "${2:-1}"; } + # ---- lock the database URL at startup ---- # Precedence: --database-url flag > existing GBRAIN_DATABASE_URL/DATABASE_URL -# env > read once from ~/.gbrain/config.json. Whichever wins gets exported as -# GBRAIN_DATABASE_URL so every child `gbrain` invocation uses THAT brain even -# if config.json is rewritten by another process during the wireup. +# env > read once from the config.json gbrain itself reads (GBRAIN_CONFIG +# above; #4325). Whichever wins gets exported as GBRAIN_DATABASE_URL so every +# child `gbrain` invocation uses THAT brain even if config.json is rewritten +# by another process during the wireup. A GBRAIN_HOME that gbrain refuses +# locks nothing: falling back to ~/.gbrain would pick a brain gbrain never reads. +if [ "$GBRAIN_HOME_VALID" = "0" ]; then + warn "GBRAIN_HOME must be an absolute path with no '..' segments (gbrain refuses this one); not reading any gbrain config" +fi +# --check-target reports the caller's URL env, before the lock below sets it. +_URL_ENV="GBRAIN_DATABASE_URL $([ -n "${GBRAIN_DATABASE_URL:-}" ] && echo set || echo unset), DATABASE_URL $([ -n "${DATABASE_URL:-}" ] && echo set || echo unset)" _locked_url="" if [ -n "$DATABASE_URL_ARG" ]; then _locked_url="$DATABASE_URL_ARG" @@ -101,7 +118,7 @@ elif [ -n "${GBRAIN_DATABASE_URL:-}" ]; then _locked_url="$GBRAIN_DATABASE_URL" elif [ -n "${DATABASE_URL:-}" ]; then _locked_url="$DATABASE_URL" -elif [ -f "$GBRAIN_CONFIG" ]; then +elif [ -n "$GBRAIN_CONFIG" ] && [ -f "$GBRAIN_CONFIG" ]; then # Python heredoc reads config.json. On JSON parse failure or any IO error, # we WARN (not silently swallow) so the user knows the URL lock fell back # to gbrain's own loadConfig (which would still read this same file). @@ -123,10 +140,6 @@ if [ -n "$_locked_url" ]; then export GBRAIN_DATABASE_URL="$_locked_url" fi -prefix() { sed 's/^/gstack-gbrain-source-wireup: /' >&2; } -warn() { echo "$*" | prefix; } -# die [exit_code]: warn with just the message, exit with code (default 1). -die() { warn "$1"; exit "${2:-1}"; } # Refuse to rm anything outside $HOME/. Defends against GSTACK_BRAIN_WORKTREE=/ # or empty-string overrides that would otherwise have line 169 / 161 nuke the @@ -452,9 +465,63 @@ do_uninstall() { echo "uninstalled source=$id worktree=$WORKTREE" } +do_check_target() { + # Read-only audit for #4325. Before the fix, a run with GBRAIN_HOME set and no + # database URL in its environment locked ~/.gbrain/config.json's database_url, + # so `sources add` and `sync` went to that brain instead of the one under + # GBRAIN_HOME. This compares the two configs and prints MATCH or MISMATCH. + # It calls no gbrain and no network, writes nothing, and never prints a + # database URL or any part of one: the URLs stay inside python3. + local id state=set + id=$(derive_source_id 2>/dev/null) || id="(unknown)" + if [ "$GBRAIN_HOME_VALID" = "0" ]; then + state=invalid + elif [ "$GBRAIN_CONFIG" = "$HOME/.gbrain/config.json" ] && [ -z "$(printf '%s' "${GBRAIN_HOME:-}" | tr -d '[:space:]')" ]; then + state=unset + fi + echo "SOURCE_ID: $id" + echo "URL_ENV: $_URL_ENV (a run with either set used that URL before and after the fix)" + CT_STATE="$state" CT_DEFAULT="$HOME/.gbrain/config.json" CT_NAMED="$GBRAIN_CONFIG" python3 -c ' +import json, os + +def read(p): + try: + with open(p) as f: + c = json.load(f) + except FileNotFoundError: + return "no file", None + except Exception: + return "unreadable", None + u = c.get("database_url") if isinstance(c, dict) else None + return ("database_url set", u) if isinstance(u, str) and u else ("no database_url", None) + +state, default, named = os.environ["CT_STATE"], os.environ["CT_DEFAULT"], os.environ["CT_NAMED"] +d_status, d_url = read(default) +print(f"GBRAIN_HOME: {state}") +print(f"DEFAULT_CONFIG: {default} ({d_status})") +if state == "set": + n_status, n_url = read(named) + print(f"GBRAIN_HOME_CONFIG: {named} ({n_status})") +if state == "unset": + verdict = "MATCH GBRAIN_HOME is unset, so the old and new rules read the same config" +elif state == "invalid": + verdict = "UNKNOWN gbrain refuses this GBRAIN_HOME (it must be absolute with no .. segments); check the value your wrapper sets" +elif d_status == "unreadable": + verdict = "UNKNOWN the default config is unreadable, so the old rule locked nothing it could report" +elif d_url is None or os.path.realpath(named) == os.path.realpath(default): + verdict = "MATCH the old rule locked nothing extra, so gbrain used the GBRAIN_HOME config itself" +elif n_url == d_url: + verdict = "MATCH both configs name the same database" +else: + verdict = "MISMATCH a run with GBRAIN_HOME set and no URL in its environment registered and synced this source in the brain named by DEFAULT_CONFIG, not GBRAIN_HOME_CONFIG; to confirm, run gbrain sources list with GBRAIN_HOME unset and look for SOURCE_ID" +print(f"TARGET: {verdict}") +' MAX_STDIN_BYTES) { // Don't even read it — fail closed at the CLI boundary. - process.stderr.write(`gstack-redact: input file too large (${st.size} bytes)\n`); + process.stderr.write(`gstack-redact: input file too large (${st.size} bytes). ${CEILING_NOTE}\n`); process.exit(3); } return fs.readFileSync(file, "utf8"); @@ -178,7 +184,7 @@ function readInput(): string { if (n === 0) break; total += n; if (total > MAX_STDIN_BYTES) { - process.stderr.write("gstack-redact: stdin too large\n"); + process.stderr.write(`gstack-redact: stdin too large. ${CEILING_NOTE}\n`); process.exit(3); } chunks.push(Buffer.from(buf.subarray(0, n))); @@ -259,7 +265,10 @@ function printUsage(code: number): never { " --self-email EMAIL --repo-public-emails PATH --auto-redact IDS\n" + " --max-bytes N\n" + "\n" + - "Exit: 0 clean · 1 usage error · 2 MEDIUM present · 3 HIGH present\n", + `--max-bytes N raises the 1 MiB scan cap. Input over ${MAX_STDIN_MIB} MiB is always refused,\n` + + "whatever --max-bytes says; split it and scan the parts.\n" + + "\n" + + "Exit: 0 clean · 1 usage error · 2 MEDIUM present · 3 HIGH present or input too large\n", ); process.exit(code); } diff --git a/bin/gstack-review-dispatch b/bin/gstack-review-dispatch index 6172bff230c..80cd9306a67 100755 --- a/bin/gstack-review-dispatch +++ b/bin/gstack-review-dispatch @@ -9,7 +9,7 @@ * gstack-review-dispatch judge --ledger --merged --judged no drop, no downgrade * gstack-review-dispatch verify --ledger [--targeted-out ] replay every hash and the judgment * gstack-review-dispatch pass --base --out --pass [-- plan flags] the pass's staged manifest - * gstack-review-dispatch show|stage|chunk|mark --manifest ... one manifest step + * gstack-review-dispatch show|stage|chunk|mark|retry --manifest ... one manifest step * gstack-review-dispatch program [--ledger ] the checked-in Capy pass program * gstack-review-dispatch audit-fetch --events [--manifest --reader ] what a reader fetched (GST-1322) * gstack-review-dispatch sweep --manifest --stage --phase start|end what a stage fetched; quarantine and rerun @@ -23,8 +23,10 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { BRIEF_ROLES, BriefError, briefFile, checkReviewedTree, checkoutRoot, checkoutTree, promptHash, renderBrief, sectionTexts, sliceDiff, sliceNote, withWorkspace, type BriefRole, type Slots, type TreeCheck } from '../lib/review-brief'; -import { cleanMarkers, collect, fixableRaises, mayBeUnavailable, parseFindings, readJsonl, readLedger, readerKey, recordJudgment, recordSent, appendEvent, verify, type JudgedLine, type MergedLine, type VerifyRow } from '../lib/review-ledger'; -import { buildManifest, chunkCount, chunkOf, manifestPath, markReader, readManifest, renderStage, withAuditModel, writeManifest, STAGES, type Extra, type Manifest, type PassReader, type ReaderState, type Stage } from '../lib/review-pass'; +import { cleanMarkers, collect, fixableRaises, mayBeUnavailable, parseFindings, parseReply, readJsonl, readLedger, readerKey, recordJudgment, recordSent, appendEvent, verify, type JudgedLine, type MergedLine, type VerdictCheck, type VerifyRow } from '../lib/review-ledger'; +import { buildManifest, chunkCount, chunkOf, manifestPath, markReader, planCyberRetry, readManifest, renderStage, withAuditModel, writeManifest, STAGES, type Extra, type Manifest, type PassReader, type ReaderState, type Stage } from '../lib/review-pass'; +import { classifyOutsideReview } from '../lib/outside-review-result'; +import { gateOutcomeLine } from '../lib/gate-outcomes'; import { diffCommand, type Dispatch } from '../lib/review-depth'; import { mayExclude, policySelection, selectFor } from '../lib/review-selection'; import { REVIEW_PLAN_TIMEOUT_MS } from '../lib/review-collect'; @@ -102,6 +104,10 @@ const HELP = `gstack-review-dispatch — verbatim reviewer briefs and loss-free specialists' merged.jsonl lines byte for byte chunk --manifest --reader --index BRIEF_CHUNK: reader=… index=i of=n sha256=…, then one JSON string line of at most 65,536 brief characters + retry --manifest --reader --error-file + the host's error for an outside voice that ended without a review, classified by lib/outside-review-result.ts: a cyber_policy + refusal plans R95's next attempt (GPT-6 Astra on the read-only brief, then Gemini 4 Carbon on the original) as RETRY: reader=..., + or RETRY: exhausted once both ran; anything else prints RETRY: none and changes nothing mark --manifest --reader --state [--path

] [--output ] [--error ] an audit reader is collected with --output, whose REVIEWED_TREE line must match its render (else failed, COLLECT_WRONG_TREE) mark --manifest --before , [--voices] the pass's reading at its first dispatch; --voices keeps Step 11's own @@ -161,7 +167,7 @@ function render(): number { const sel = base && diffBase ? standaloneSelection(readerKey(role, name), base, diffBase, readers) : { reader: readerKey(role, name), exclude: flag('--exclude'), keep: parseTail(flag('--keep')).filter(s => s !== '--'), disclosure: flag('--disclosure') }; const policyItems = parseTail(sel.exclude).filter(s => s.startsWith(':(top,exclude,glob)')); if (base && diffBase) { - const over = ceiling('gstack-review-dispatch render', base, out, [sel], diffBase, undefined); + const over = ceiling('gstack-review-dispatch render', base, out, [{ ...sel, role }], diffBase, undefined); if (over) { process.stderr.write(over.line + '\n'); return over.exit; } settleExcerpt(sel, diffBase, path.resolve(out)); if (role === 'outside-voice') diff = branchDiff(diffBase, sel); @@ -186,14 +192,14 @@ function render(): number { const workdir = checkoutRoot(); const tree = checkoutTree(workdir); if (!tree) throw new BriefError(`cannot read HEAD^{tree} and the toplevel of ${workdir}; a brief names the checkout its reply must prove`); - const text = withWorkspace(renderBrief(role, slots, sectionTexts(ROOT)), workdir, readers); + const text = withWorkspace(renderBrief(role, slots, sectionTexts(ROOT)), workdir, readers, { verdict: true }); fs.mkdirSync(out, { recursive: true, mode: 0o700 }); const file = path.join(path.resolve(out), briefFile(role, name)); fs.writeFileSync(file, text, { mode: 0o600 }); const ledger = flag('--ledger') ?? path.join(out, 'review-ledger.jsonl'); const sha = promptHash(text); const targeted = brief === undefined ? {} : { classes: parseClassList(flag('--classes')!), rules: TARGETED_RULES, brief_sha: targetedBriefSha(merged ? path.join(ROOT, 'review/specialists/targeted.md') : checklist), diff_base: diffBase ?? null, ...(diffBase ? targetedRead(process.cwd(), diffBase) : { patch_id: 'none', head: null }) }; - appendEvent(ledger, { event: 'rendered', reader: readerKey(role, name), role, name: name ?? null, file, sha256: sha, bytes: Buffer.byteLength(text), workdir, tree, ...targeted, ...(diffFile.diff_file ? { payload: { file: diffFile.diff_file, sha256: diffFile.diff_sha256 } } : {}), ...(disclosureDigest(sel.disclosure) ? { exclude: disclosureDigest(sel.disclosure) } : {}), readers: readers.digest }); + appendEvent(ledger, { event: 'rendered', reader: readerKey(role, name), role, name: name ?? null, file, sha256: sha, bytes: Buffer.byteLength(text), workdir, tree, verdict: 1, ...targeted, ...(diffFile.diff_file ? { payload: { file: diffFile.diff_file, sha256: diffFile.diff_sha256 } } : {}), ...(disclosureDigest(sel.disclosure) ? { exclude: disclosureDigest(sel.disclosure) } : {}), readers: readers.digest }); process.stdout.write(`BRIEF: reader=${readerKey(role, name)} sha256=${sha} bytes=${Buffer.byteLength(text)} file=${file}\n`); return EXIT.ok; } @@ -287,6 +293,9 @@ function sweep(): number { } const quote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`; +/** The reader's REVIEW_VERDICT line against what collect parsed (GST-2495), with the next step when they disagree or the line is malformed. */ +const verdictLine = (reader: string, v: VerdictCheck, added: string[]) => `COLLECT_VERDICT: reader=${reader} declared=${v.declared ?? v.state} parsed=${v.parsed}${v.state === 'valid' ? ` agrees=${v.agrees ? 'yes' : 'no'}` : ''}${added.length ? ` added=${added.join(',')}` : ''}${v.why ? ` why=${JSON.stringify(v.why)}` : ''}` + + (v.state === 'malformed' || v.agrees === false ? ' (next: find the declared blocker via at=, promote it and fold the added row into it; lower a summary candidate with a reason; or take the review-loop exception; docs/review-policy.md#verdict-line)\n' : '\n'); const wrongTree = (reader: string, t: TreeCheck) => `${t.moved ? 'COLLECT_TREE_MOVED' : 'COLLECT_WRONG_TREE'}: reader=${reader} reported=${JSON.stringify(t.reported)} expected=${JSON.stringify(t.expected)} (${t.moved ? 'the checkout moved after this brief was rendered' : 'the reply did not review the checkout its brief named'}; nothing merged; restore it with a fresh pass under a new --pass and --out)\n`; const PROGRAM_FILE = path.join(ROOT, 'lib', 'capy-review-pass.js'); @@ -308,13 +317,13 @@ const branchDiff = (base: string, r?: Pick & { diff_base?: string }>, diffBase: string, known: PlanExclude | undefined): { exit: number; line: string } | null { +function ceiling(context: string, base: string, outDir: string, readers: ReadonlyArray & { diff_base?: string }>, diffBase: string, known: PlanExclude | undefined): { exit: number; line: string } | null { for (const r of readers) { if (r.prompt_file) continue; const at = r.diff_base ?? diffBase; const d = selectionOf(at, r.exclude, r.keep, r.excerpt); if (!d.ok) return { exit: EXIT.fail, line: unreadableLine(context, r.reader, d, at, base, outDir) }; - if (d.bytes > REVIEW_DIFF_MAX_BYTES && r.reader !== 'outside-voice') return { exit: EXIT.refused, line: tooLargeLine(context, r.reader, d, ceilingContext(process.cwd(), base, known)).line }; + if (d.bytes > REVIEW_DIFF_MAX_BYTES && r.role !== 'outside-voice') return { exit: EXIT.refused, line: tooLargeLine(context, r.reader, d, ceilingContext(process.cwd(), base, known)).line }; } return null; } @@ -457,6 +466,21 @@ function passStep(cmd: string): number { process.stdout.write([`STAGE: ${stage} rendered=${done.length}`, ...done.map(r => readerLine(m, r))].join('\n') + '\n'); return EXIT.ok; } + if (cmd === 'retry') { + const r = m.readers.find(x => x.reader === flag('--reader')); + if (r?.role !== 'outside-voice' || !flag('--error-file')) { process.stderr.write('gstack-review-dispatch retry: --manifest --reader --error-file \n'); return EXIT.usage; } + const checked = classifyOutsideReview({ text: '', gate: 'review', exit: 1, providerError: readFile(flag('--error-file'), 'host error') }); + if (checked.reason !== 'cyber_policy_refused') { process.stdout.write(`RETRY: none reader=${r.reader} (not a cyber_policy refusal; recorded as unavailable coverage as before)\n`); return EXIT.ok; } + let voices: { laneModel?: string | null; readers?: Record } = {}; + try { voices = JSON.parse(fs.readFileSync(path.join(m.out, 'voice-models.json'), 'utf8')); } catch { voices = {}; } + const taken = [voices.laneModel, voices.readers?.['adversarial-native']?.model_id].filter((id): id is string => typeof id === 'string' && id.includes('/')).map(id => id.split('/')[0]!.toLowerCase()); + const next = planCyberRetry(m, r, taken); + writeManifest(file, m); + process.stdout.write(`${gateOutcomeLine(`Outside voice ${r.reader}`, 'cyber_policy_refused', checked.detail)}\n${next + ? `RETRY: reader=${next.reader} model=${next.model!.model_id} brief=${next.read_only ? 'read-only' : 'original'} (R95: one attempt, never the same brief on another OpenAI model)` + : `RETRY: exhausted reader=${r.reader} (R95's attempts are spent: the second-family read is missing)`}\n`); + return EXIT.ok; + } if (cmd === 'chunk') { const r = m.readers.find(x => x.reader === flag('--reader')); if (!r?.file || !r.sha256) { process.stderr.write(`gstack-review-dispatch chunk: no rendered reader ${flag('--reader')}\n`); return EXIT.usage; } @@ -558,7 +582,7 @@ function main(): number { if (cmd === 'program') return program(); if (cmd === 'audit-fetch') return auditFetch(); if (cmd === 'sweep') return sweep(); - if (['show', 'stage', 'chunk', 'mark'].includes(cmd)) return passStep(cmd); + if (['show', 'stage', 'chunk', 'mark', 'retry'].includes(cmd)) return passStep(cmd); const ledger = flag('--ledger'); if (!ledger) { process.stderr.write(`gstack-review-dispatch ${cmd}: --ledger is required\n`); return EXIT.usage; } const reader = flag('--role') ? readerKey(flag('--role')!, flag('--name')) : ''; @@ -578,10 +602,12 @@ function main(): number { const unavailable = flag('--unavailable'); if (unavailable !== undefined && !mayBeUnavailable(reader)) { process.stderr.write(`gstack-review-dispatch collect: --unavailable is for the outside voice only; ${reader}'s missing coverage leaves the review incomplete, never clean\n`); return EXIT.usage; } if (unavailable !== undefined && !unavailable.trim()) { process.stderr.write('gstack-review-dispatch collect: --unavailable needs a reason\n'); return EXIT.usage; } - if (unavailable !== undefined && parseFindings(reader, output).length) { process.stderr.write(`gstack-review-dispatch collect: ${reader}'s output holds findings; collect it without --unavailable so none is lost\n`); return EXIT.usage; } + const asked = readLedger(ledger).filter(e => e.event === 'rendered' && e.reader === reader).at(-1)?.verdict === 1; + const held = () => parseReply(reader, output, true, asked).findings.length; + if (unavailable !== undefined && held()) { process.stderr.write(`gstack-review-dispatch collect: ${reader}'s output holds findings; collect it without --unavailable so none is lost\n`); return EXIT.usage; } const rendered = readLedger(ledger).filter(e => e.event === 'rendered' && e.reader === reader).at(-1); const tree = unavailable === undefined && rendered && 'tree' in rendered ? checkReviewedTree(output, typeof rendered.tree === 'string' ? rendered.tree : null) : undefined; - if (tree && !tree.ok && mayBeUnavailable(reader) && !parseFindings(reader, output).length) { + if (tree && !tree.ok && mayBeUnavailable(reader) && !held()) { const why = `reviewed another tree: reported ${tree.reported}, expected ${tree.expected}`; const r = collect(ledger, reader, output, merged, path.resolve(outFile!), why); process.stdout.write(`COLLECT_UNAVAILABLE: reader=${reader} sha256=${r.sha} reason=${JSON.stringify(why)} (missing outside coverage: unavailable, never clean)\n`); @@ -602,6 +628,7 @@ function main(): number { return EXIT.fail; } process.stdout.write(`COLLECT: reader=${reader} findings=${r.lines.length} sha256=${r.sha} merged=${merged}\n`); + if (r.verdict) process.stdout.write(verdictLine(reader, r.verdict, r.lines.filter(l => /#(?:\d+\.)?v\d+$/.test(l.id)).map(l => l.id))); return EXIT.ok; } if (cmd === 'judge') { @@ -637,6 +664,7 @@ function main(): number { if (sel && 'digest' in sel) process.stdout.write(`REVIEW_EXCLUDE_RECORD: digest=${sel.digest} (gstack-ship-receipt write --review-exclude ${sel.digest})\n`); if (sel && 'mixed' in sel) process.stdout.write(`REVIEW_EXCLUDE_RECORD: mixed digests=${sel.mixed.join(',')} (readers read different review_exclude_paths selections; rerun the review so every reader reads HEAD's)\n`); const clean = v.clean && !(sel && 'mixed' in sel); + if (v.verdicts.asked) process.stdout.write(`VERIFY_VERDICT: agree=${v.verdicts.agree} asked=${v.verdicts.asked} (informational: a disagreeing count already counts its blockers; docs/review-policy.md#verdict-line)\n`); process.stdout.write(`VERIFY: ${clean ? 'clean' : 'dirty'} briefs=${v.briefs} outputs=${v.rows.filter(r => r.kind === 'OUTPUT').length} voided=${v.voided}${v.unavailable ? ` unavailable=${v.unavailable}` : ''}\n`); return clean ? EXIT.ok : EXIT.fail; } diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan index b90291b382a..f50c342af39 100755 --- a/bin/gstack-review-plan +++ b/bin/gstack-review-plan @@ -61,7 +61,7 @@ const HELP = `gstack-review-plan — the review depth of the next /ship step (do --gated a,b specialists the hit-rate stats tag GATE_CANDIDATE --force a,b|all specialists forced by prompt flags (--all-specialists is all): at standard and full depth they join the batched specialist's checklists, where maintainability, performance and simplification are read only when - forced; light runtime-0 and scoped passes dispatch them one reader each; targeted is no specialist and + forced; light runtime-0 docs and scoped passes dispatch them one reader each; targeted is no specialist and refuses (exit 2): the plan dispatches it itself --reviewed-numbers the numeric-claim fingerprint the outside voice already reviewed --depth-floor standard|full raise the depth to at least this (never lowers it); /ship passes its prompt flag on every run @@ -104,7 +104,7 @@ const HELP = `gstack-review-plan — the review depth of the next /ship step (do Mode (R65, the base policy's review key): review.panel all (default) keeps today's panel on every class. review.panel risk (opt-in; its one-reader shape has not passed a no-loss replay) runs lean off risk class, and review.panel off everywhere: lean runs one reader: risk class gets the merged reader on review.risk_model (the native adversarial brief plus the checklists, the Red Team and the targeted brief), non-risk code the single reader at the -lane's reasoning (cross-family when it publishes numbers), docs and tests the core read; one fix-check after fixes, never more +lane's reasoning (cross-family when it publishes numbers), docs the core read, tests one batched testing reader (R51); one fix-check after fixes, never more than 2 rounds. review.platform on (any panel): a light diff with no numeric claims whose PR carries capy-ai[bot]'s review at HEAD plans NEXT: platform and a planned SKIP for every reader. Depth (R51, risk not size): full on gate class, a risk class (money, auth, secret, security, data, review.risk_paths) or any DEPTH_ERROR; diff --git a/bin/gstack-review-read b/bin/gstack-review-read index 9b1530c6204..a030203cb28 100755 --- a/bin/gstack-review-read +++ b/bin/gstack-review-read @@ -7,7 +7,9 @@ # bin/gstack-wtree --review, or "unknown"), ---TREE--- (HEAD tree, informational) and # ---DIRTY--- (tracked-file dirty flag). Consumers grade diff-scoped review # rows using review_freshness; legacy or uncaptured diff evidence cannot fall -# back to HEAD equality. Plan rows are unchanged. +# back to HEAD equality. Plan rows are unchanged. A gate finding the owner's gstack-approvals +# gate row closes reads `kept` with its `disposition`, and the row's `gate_dispositions` lists +# those approval ids (lib/gate-dispositions.ts); values the row itself carried are discarded. set -euo pipefail GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v cygpath >/dev/null 2>&1; then GSTACK_BUN_CONFIG=NUL; fi ;; esac SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" @@ -21,14 +23,22 @@ gstack_state_root_select GSTACK_HOME="$_gstack_sr_root" WTREE=$("$SCRIPT_DIR/gstack-wtree" --review 2>/dev/null || echo "unknown") if [ -f "$GSTACK_HOME/projects/$SLUG/$BRANCH-reviews.jsonl" ]; then - GSTACK_REVIEW_LIB="$SCRIPT_DIR/../lib/review-evidence.ts" GSTACK_REVIEW_WTREE="$WTREE" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e ' + GSTACK_REVIEW_LIB="$SCRIPT_DIR/../lib/review-evidence.ts" GSTACK_GATE_LIB="$SCRIPT_DIR/../lib/gate-dispositions.ts" GSTACK_REVIEW_WTREE="$WTREE" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e ' const { reviewFreshness } = await import(process.env.GSTACK_REVIEW_LIB); + const { dispositionedOn, gateKey, readGateDispositions, showDispositioned } = await import(process.env.GSTACK_GATE_LIB); + let dispositions = []; + try { dispositions = readGateDispositions(process.cwd()); } + catch (e) { console.error("gstack-review-read: gate dispositions unreadable, none applied: " + e.message); } for (const line of (await Bun.stdin.text()).split("\n").filter(Boolean)) { try { const rec = JSON.parse(line); delete rec.review_freshness; - const freshness = reviewFreshness(rec, process.env.GSTACK_REVIEW_WTREE); + delete rec.gate_dispositions; + for (const f of Array.isArray(rec.findings) ? rec.findings : []) if (f && typeof f === "object") delete f.disposition; + const closed = dispositionedOn(process.cwd(), rec, dispositions); + const freshness = reviewFreshness(rec, process.env.GSTACK_REVIEW_WTREE, new Set(), new Set(closed.map(d => gateKey(d.finding, d.gate_id)))); if (freshness) rec.review_freshness = freshness; + showDispositioned(rec, closed); console.log(JSON.stringify(rec)); } catch { console.error("gstack-review-read: skipping malformed review row"); } } diff --git a/bin/gstack-ship-queue b/bin/gstack-ship-queue index 0b38d53ea4a..3da9e6ce931 100755 --- a/bin/gstack-ship-queue +++ b/bin/gstack-ship-queue @@ -14,7 +14,8 @@ * gstack-ship-queue gate-ahead --list --pr * gstack-ship-queue verify --pr --screen (train policy: the head's screen verdict from its run) * gstack-ship-queue verify --post-merge [--timeout ] (after a merge: main's push workflows at that commit until they settle) - * gstack-ship-queue land --pr --pin [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] (merge: direct; lib/ship-queue-land-direct.ts) + * gstack-ship-queue land --pr --pin [--accept-gate-disposition ]... [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] (merge: direct; lib/ship-queue-land-direct.ts) + * gstack-ship-queue verify --pr --pin [--accept-gate-disposition ]... (land's receipt and gate-disposition acceptance, read-only, for a lander that merges another way) * gstack-ship-queue land --pr [--dry-run] [--no-wait] [--break-lock [--break-train-lock]] (the merge step; lib/ship-queue-land.ts) * gstack-ship-queue land --pr --repair (after QUEUE_LAND_DRIFT: open the outside merge's release PR) * gstack-ship-queue land --census @@ -59,15 +60,20 @@ const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (doc gate-ahead --record --pr --attempt --exit --log bind the gate result to that attempt's gated tree; removes its worktree gate-ahead --list --pr attempts for a PR, newest last (the current one) + verify --pr --pin [--accept-gate-disposition ]... + land --pin's receipt and gate-disposition check, read-only, for a lander that merges + another way: prints each GATE_DISPOSITION line and exits 0 only when every one is accepted verify --pr --screen (train policy) the PR head's screen verdict read from its run (SCREEN_VERDICT) verify --post-merge [--timeout ] wait for every check run at a merged commit to settle: POST_MERGE: green|red|pending and one CHECK: line per workflow; resumable, default timeout 2700 s - land --pr --pin [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] + land --pr --pin [--accept-gate-disposition ]... [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] merge: direct: merge the PR at its own green head (receipt and READY at the pin, no stamp files, checks green, mergeable clean), verify the tree, write a land note; a stale base runs land.merged_checks, repo commands, only with --allow-repo-commands (never --dry-run); it holds the land lock from the re-fetch to the merge (--break-lock: a stale one); - --repair: while frozen, land the one repair PR the freeze admits (recorded under the lock) + --repair: while frozen, land the one repair PR the freeze admits (recorded under the lock); + an owner gate disposition the approval store applies at the pin merges only when the + lander passes --accept-gate-disposition (docs/ship-policy.md#gate-dispositions) land --pr [--dry-run] [--no-wait] [--timeout ] [--break-lock [--break-train-lock]] [--allow-repo-commands] the merge step: lock, merge the base, stamp (fragments folded), push the stamp commit, wait for its checks, squash with --match-head-commit, confirm the base tree; resumable @@ -89,6 +95,12 @@ function flag(args: string[], name: string): string | undefined { return i >= 0 ? args[i + 1] : undefined; } +/** Every --accept-gate-disposition value, or the first one that is not an approval id. */ +function acceptedIds(args: string[]): { ids: string[]; bad?: string } { + const ids = args.flatMap((a, i) => a === '--accept-gate-disposition' ? [args[i + 1] ?? ''] : []); + return { ids, bad: ids.find(id => !/^a-[0-9a-f]{12}$/.test(id)) }; +} + function finish(cmd: string, out: StepOutput): number { for (const line of out.lines) process.stdout.write(line + '\n'); if (out.failure) { @@ -187,7 +199,9 @@ async function main(argv: string[]): Promise { if (args.includes('--pin')) { const pin = flag(args, '--pin') ?? ''; if (!/^[0-9a-f]{40,64}$/.test(pin)) return usage('--pin needs the full head sha the READY names'); - return finish('land', (await import('../lib/ship-queue-land-direct')).landDirect(ctx, { pr, pin, dryRun: args.includes('--dry-run'), allowRepoCommands: args.includes('--allow-repo-commands'), breakLock: args.includes('--break-lock'), repair: args.includes('--repair') })); + const accept = acceptedIds(args); + if (accept.bad !== undefined) return usage(`--accept-gate-disposition needs an approval id (a-<12 hex>), not ${JSON.stringify(accept.bad)}`); + return finish('land', (await import('../lib/ship-queue-land-direct')).landDirect(ctx, { pr, pin, acceptGateDispositions: accept.ids, dryRun: args.includes('--dry-run'), allowRepoCommands: args.includes('--allow-repo-commands'), breakLock: args.includes('--break-lock'), repair: args.includes('--repair') })); } const timeout = flag(args, '--timeout'); return finish('land', l.land(ctx, { pr, repair: args.includes('--repair'), dryRun: args.includes('--dry-run'), noWait: args.includes('--no-wait'), breakLock: args.includes('--break-lock'), breakTrainLock: args.includes('--break-train-lock'), allowRepoCommands: args.includes('--allow-repo-commands'), waitTimeoutMin: timeout && /^\d+$/.test(timeout) ? Number(timeout) : undefined })); @@ -215,6 +229,13 @@ async function main(argv: string[]): Promise { failAfter: process.env.GSTACK_SHIP_QUEUE_FAIL_AFTER, })); } + if (cmd === 'verify' && args.includes('--pin')) { + const pin = flag(args, '--pin') ?? ''; + if (!/^[0-9a-f]{40,64}$/.test(pin)) return usage('--pin needs the full head sha the READY names'); + const accept = acceptedIds(args); + if (accept.bad !== undefined) return usage(`--accept-gate-disposition needs an approval id (a-<12 hex>), not ${JSON.stringify(accept.bad)}`); + return finish('verify', (await import('../lib/ship-queue-land-direct')).verifyPin(ctx, { pr, pin, acceptGateDispositions: accept.ids })); + } if (cmd === 'verify') { if (flag(args, '--train') || args.includes('--screen')) return (await import('../crew/lib/ship-queue-train-cli')).verifyMain(ctx, args, pr); const record = flag(args, '--record'); diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 17dc8bb0ef9..5709d718e39 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -58,6 +58,7 @@ import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose'; import { resolveStateRoot } from '../lib/state-root'; import { readPause, receiptBaseRed } from '../lib/base-red'; import { readRuledNotes, ruledNoteText } from '../lib/ruled-notes'; +import { appliedGateDispositions, gateDispositionText } from '../lib/gate-dispositions'; import { laneExceptionBodyLines } from '../lib/test-lane-exception'; import { readMechanicalLines } from '../lib/ship-mechanical'; import { isRegistryUnavailable, loadRegistryFromBase } from '../lib/regen'; @@ -270,6 +271,12 @@ function cmdWrite(rest: string[], json: boolean): number { const ruledNotes = readRuledNotes(repoRoot); const unlisted = bodyFile ? ruledNotes.map(n => `Ruled note: ${ruledNoteText(n)}`).find(l => !bodyText.split(/\r?\n/).some(b => b.trim() === l)) : undefined; if (unlisted) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} does not list ruled note ${JSON.stringify(unlisted)} (gstack-approvals rulings prints each line the body carries); nothing written`) + '\n'); return EXIT.fail; } + let gateDispositions: ReturnType['applied']; + try { gateDispositions = appliedGateDispositions(repoRoot, { pin: 'HEAD' }).applied; } + catch (e: any) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `the owner gate dispositions at HEAD cannot be derived (${e.message}); the receipt always records them, so an unreadable approval store or a git error writes nothing`) + '\n'); return EXIT.fail; } + if (gateDispositions.length && !bodyFile) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `the approval store applies ${gateDispositions.length} owner gate disposition(s) at HEAD (${gateDispositions.map(d => d.approval).join(', ')}), so write needs --body carrying each "Gate disposition: …" line gstack-approvals dispositions prints; nothing written`) + '\n'); return EXIT.fail; } + const undisclosed = bodyFile ? gateDispositions.map(d => `Gate disposition: ${gateDispositionText(d)}`).find(l => !bodyText.split(/\r?\n/).some(b => b.trim() === l)) : undefined; + if (undisclosed) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} does not list gate disposition ${JSON.stringify(undisclosed)} (gstack-approvals dispositions prints each line the body carries); nothing written`) + '\n'); return EXIT.fail; } const carried = ciCarried(base); const unlistedException = bodyFile ? laneExceptionBodyLines(carried).find(l => !bodyText.split(/\r?\n/).some(b => b.trim() === l)) : undefined; if (unlistedException) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} does not list ${JSON.stringify(unlistedException)} (accept's TEST_LANE_EXCEPTION: line; the body carries it as one line); nothing written`) + '\n'); return EXIT.fail; } @@ -331,7 +338,7 @@ function cmdWrite(rest: string[], json: boolean): number { policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'), ...pregate, issues: issuesFile ? receiptIssuesFrom(issuesFile) : undefined, approval: approval.kind === 'ok' ? approval.approval : undefined, review_loop: reviewLoop, ...(docs?.ok ? { docs: docs.docs } : {}), ...product, - gstack_version: installedGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, ruled_notes: ruledNotes.length ? ruledNotes : undefined, mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined, + gstack_version: installedGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, ruled_notes: ruledNotes.length ? ruledNotes : undefined, gate_dispositions: gateDispositions, mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined, design: review.frontend ? { mode: 'static', reason: 'no preview declared' } : undefined, base_red: pause ? receiptBaseRed(pause) : undefined, review_exclude: receiptExclude(review.exclude), diff --git a/bin/gstack-skill-start b/bin/gstack-skill-start index 180f6cbdef6..4c4a0fe0d6e 100755 --- a/bin/gstack-skill-start +++ b/bin/gstack-skill-start @@ -391,9 +391,11 @@ _BRAIN_CONFIG_BIN="$_BIN/gstack-config" # /sync-gbrain context-load hint. Per-worktree pin via kubectl-style # .gbrain-source at the git toplevel; empty output when gbrain is not -# configured (zero context cost for non-gbrain users). -_GBRAIN_CONFIG="$HOME/.gbrain/config.json" -if [ -f "$_GBRAIN_CONFIG" ] && command -v gbrain >/dev/null 2>&1; then +# configured (zero context cost for non-gbrain users). gbrain's config path +# comes from gstack-gbrain-home.sh, which follows GBRAIN_HOME as gbrain does +# (#4325); empty when that file is missing or gbrain would refuse GBRAIN_HOME. +_GBRAIN_CONFIG=$( . "$_BIN/gstack-gbrain-home.sh" 2>/dev/null && gstack_gbrain_config_path ) || _GBRAIN_CONFIG="" +if [ -n "$_GBRAIN_CONFIG" ] && [ -f "$_GBRAIN_CONFIG" ] && command -v gbrain >/dev/null 2>&1; then _GBRAIN_VERSION_OK=$(gbrain --version 2>/dev/null | grep -c '^gbrain ' || true) if [ "$_GBRAIN_VERSION_OK" -gt 0 ] 2>/dev/null; then _GBRAIN_PIN_PATH="" @@ -443,12 +445,12 @@ if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ] && grep -q '"gbr # matches the TS one: remote_mcp is a marker when JS-truthy, as in # gbrain's isThinClient (null, false, 0 and "" are not), and # database_url counts when non-blank after JS trim() and engine is not - # pglite. GBRAIN_HOME is the - # parent of .gbrain, as in gbrainConfigDir. test/gbrain-mcp-locality.test.ts + # pglite. The config is _GBRAIN_CONFIG above (GBRAIN_HOME is the + # parent of .gbrain, as in gbrainConfigDir). test/gbrain-mcp-locality.test.ts # runs both programs below against the TS rule. if printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -e '(.url // "") | ascii_downcase | (contains("${") | not) and test("\\Ahttps?://(localhost|127(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}|\\[::1\\])(:([0-9]{0,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?([/?#]|\\z)")' >/dev/null 2>&1 \ && jq -e '((.remote_mcp // false) | . == false or . == 0 or . == "") and .engine != "pglite" and ((.database_url // "") | (type == "string" and test("[^\\s\\x{feff}]|\\x{0085}")))' \ - "${GBRAIN_HOME:-$HOME}/.gbrain/config.json" >/dev/null 2>&1; then + "$_GBRAIN_CONFIG" >/dev/null 2>&1; then _GBRAIN_MCP_MODE="local-stdio" fi ;; @@ -688,7 +690,7 @@ When the user's request matches an available skill, invoke it via the Skill tool Key routing rules: - Product ideas/brainstorming → invoke /office-hours - Strategy/scope → invoke /plan-ceo-review -- Architecture → invoke /autoplan +- Architecture → invoke /plan-eng-review - Design system/plan review → invoke /design-consultation or /plan-design-review - Full review pipeline → invoke /autoplan - Bugs/errors → fix them directly: one read-only check of the cause, or a focused failing test first when the cause is unclear; then fix it and run that test diff --git a/bin/gstack-uninstall b/bin/gstack-uninstall index 7b35678d4bb..f88e66e00bc 100755 --- a/bin/gstack-uninstall +++ b/bin/gstack-uninstall @@ -156,17 +156,39 @@ _project_worktrees() { printf '%s\0' "${_dotgit%/.git}" done } -# Real paths of the worktrees this repository registered (all, or with -# "locked" only the locked ones). -_registered_worktrees() { - git -C "$_GIT_ROOT" worktree list --porcelain 2>/dev/null | awk -v only="${1:-}" ' - /^worktree / { if (path != "" && (only == "" || locked)) print path; path = substr($0, 10); locked = 0 } - /^locked( |$)/ { locked = 1 } - END { if (path != "" && (only == "" || locked)) print path }' | while IFS= read -r _wt; do - _real "$_wt" - done +# Fills _REGISTERED_WORKTREES with the real paths of the worktrees this +# repository registered and _LOCKED_WORKTREES with the locked ones. The list is +# read NUL-separated, so a path holding a newline stays one unquoted path. +_read_registered_worktrees() { + local _field _path="" _locked=0 + _REGISTERED_WORKTREES=() + _LOCKED_WORKTREES=() + while IFS= read -r -d '' _field; do + case "$_field" in + "worktree "*) _path="$(_real "${_field#worktree }")"; _locked=0 ;; + locked|"locked "*) _locked=1 ;; + "") + [ -n "$_path" ] || continue + _REGISTERED_WORKTREES+=("$_path") + [ "$_locked" -eq 0 ] || _LOCKED_WORKTREES+=("$_path") + _path="" + ;; + esac + done < <(_worktree_list git -C "$_GIT_ROOT") } -# git inside a registered checkout, with no config able to run a command. +# "$@" worktree list --porcelain, NUL-separated. git before 2.36 has no -z and +# fails here, so the uninstall refuses instead of reading a list it cannot split. +_worktree_list() { + "$@" worktree list --porcelain -z 2>/dev/null +} +# _in_list VALUE ITEM... — VALUE equals one of the ITEMs. +_in_list() { + local _want="$1" _item + shift + for _item in "$@"; do [ "$_item" = "$_want" ] && return 0; done + return 1 +} +# git inside a checkout, with its hooks and fsmonitor turned off. _wt_git() { local _dir="$1" shift @@ -183,7 +205,7 @@ _worktree_risk() { ""|*" "*) echo "it is not a registered worktree of this repository"; return 0 ;; esac - if ! printf '%s\n' "$_REGISTERED_WORKTREES" | grep -Fxq -- "$_dir"; then + if ! _in_list "$_dir" ${_REGISTERED_WORKTREES[@]+"${_REGISTERED_WORKTREES[@]}"}; then _is_registered_submodule "$_dir" || { echo "it is not a registered worktree of this repository"; return 0; } _local="$(_wt_git "$_dir" rev-list -n 1 --all --not --remotes 2>/dev/null)" || { echo "git cannot read its history"; return 0; } [ -z "$_local" ] || echo "it is a submodule with commits no remote-tracking branch contains" @@ -195,20 +217,18 @@ _worktree_risk() { _head="$(_wt_git "$1" rev-parse -q --verify HEAD 2>/dev/null)" || return 0 [ -n "$(git -C "$_GIT_ROOT" for-each-ref --contains "$_head" --count=1 --format=x 2>/dev/null)" ] || echo "it has commits no branch or tag contains" } -# Succeeds when checkout $1 is a submodule of the registered worktree under -# .gstack-worktrees that holds it: that worktree's index records exactly this -# path as a gitlink, so its status reports the submodule's changes. Commits only -# the submodule's own refs hold are checked by the caller. +# Succeeds when checkout $1 is a submodule of the closest checkout under +# .gstack-worktrees that holds it, and that checkout is a registered worktree or +# (for a nested submodule) itself such a submodule: its index records exactly +# this path as a gitlink, so its status reports the submodule's changes. Commits +# only the submodule's own refs hold are checked by the caller. _is_registered_submodule() { - local _wt _parent="" _base _rel _entry - _base="$(_real "$_GIT_ROOT/.gstack-worktrees")" - while IFS= read -r _wt; do - case "$_wt" in "$_base"/*) ;; *) continue ;; esac + local _wt _parent="" _rel _entry + for _wt in ${_CHECKOUTS_ON_DISK[@]+"${_CHECKOUTS_ON_DISK[@]}"}; do case "$1" in "$_wt"/*) [ ${#_wt} -gt ${#_parent} ] && _parent="$_wt" ;; esac - done </dev/null | tr '\0' '\n')" case "$_entry" in 160000\ *) ;; *) return 1 ;; esac @@ -219,15 +239,18 @@ EOF # is kept even with --force-worktrees. _worktree_refusals() { local _wt _risk - if ! git -C "$_GIT_ROOT" worktree list --porcelain >/dev/null 2>&1; then + if ! _worktree_list git -C "$_GIT_ROOT" >/dev/null; then echo "gstack-uninstall: refusing to delete $_GIT_ROOT/.gstack-worktrees/: git cannot list this repository's worktrees" return 0 fi - _REGISTERED_WORKTREES="$(_registered_worktrees)" - _LOCKED_WORKTREES="$(_registered_worktrees locked)" + _read_registered_worktrees + _CHECKOUTS_ON_DISK=() + while IFS= read -r -d '' _wt; do + _CHECKOUTS_ON_DISK+=("$(_real "$_wt")") + done < <(_project_worktrees) while IFS= read -r -d '' _wt; do [ -n "$_wt" ] || continue - if [ -n "$_LOCKED_WORKTREES" ] && printf '%s\n' "$_LOCKED_WORKTREES" | grep -Fxq -- "$(_real "$_wt")"; then + if _in_list "$(_real "$_wt")" ${_LOCKED_WORKTREES[@]+"${_LOCKED_WORKTREES[@]}"}; then _risk="it is locked (git worktree lock)" elif [ "$FORCE_WORKTREES" -eq 1 ]; then continue @@ -272,7 +295,190 @@ _check_project_keep() { exit 2 fi } +# ─── Deletion inventory ────────────────────────────────────── +CLAUDE_SKILLS="$HOME/.claude/skills" + +# Skill-name inventory (#2563 gate a): every name setup could have installed — +# each source skill's directory name, its frontmatter name, their gstack- +# prefixed variants, and the alias dirs. Built BEFORE the install root is +# removed. A real directory in ~/.claude/skills is only deletable when its +# name is in this inventory AND its SKILL.md carries the generated banner. +# The seed names below are the alias dirs setup's _install_alias_skill_md +# creates (setup: link_claude_root_skill_alias + the connect-chrome call +# sites) — keep in sync with setup if an alias is added or renamed there. +_INVENTORY=" _gstack-command connect-chrome gstack-connect-chrome " +if [ -d "$GSTACK_DIR" ]; then + for _SRC in "$GSTACK_DIR"/*/; do + [ -f "$_SRC/SKILL.md" ] || continue + _SRC_NAME=${_SRC%/}; _SRC_NAME=${_SRC_NAME##*/} + gstack_skill_md_name "$_SRC/SKILL.md"; _FM_NAME=$GSTACK_SKILL_NAME + for _N in "$_SRC_NAME" "$_FM_NAME"; do + [ -n "$_N" ] || continue + case "$_INVENTORY" in *" $_N "*) ;; *) _INVENTORY="$_INVENTORY$_N gstack-$_N " ;; esac + done + done +fi +_in_skill_inventory() { case "$_INVENTORY" in *" $1 "*) return 0 ;; *) return 1 ;; esac; } + +# Prints what the removal step does with ~/.claude/skills entry $1: unlink, +# delete, keep (listed, not provably gstack-managed), or nothing. Per-skill +# entries created by setup come in three shapes: +# 1. symlink entry (oldest installs) +# 2. real dir + SYMLINKED SKILL.md (standard Unix install) +# 3. real dir + REAL-FILE SKILL.md (Windows copy install, #2563) +# Shape 3 was skipped entirely — gstack-uninstall exited 0 and reported +# success while leaving ~52 gstack-* directories behind on Windows. +_claude_entry_action() { + local _name="${1##*/}" _target + [ "$_name" = "gstack" ] && return 0 + if [ -L "$1" ]; then + _target="$(readlink "$1" 2>/dev/null || true)" + case "$_target" in gstack/*|*/gstack/*) echo unlink ;; esac + elif [ -d "$1" ] && { [ -f "$1/SKILL.md" ] || [ -L "$1/SKILL.md" ]; }; then + if [ -L "$1/SKILL.md" ]; then + # Shape 2: provenance readable from the symlink target itself. + # Gate 1: the name must be in gstack's skill inventory (parity with + # shape 3). Gate 2: the target must contain "gstack" as an ANCHORED + # path segment (gstack/*|*/gstack/*, same pattern as shape 1) — a + # bare *gstack* substring match would wipe a user's own skill whose + # SKILL.md merely lives under e.g. ~/tools/gstack-fork/. + _target="$(readlink "$1/SKILL.md" 2>/dev/null || true)" + if _in_skill_inventory "$_name"; then + case "$_target" in gstack/*|*/gstack/*) echo delete ;; *) echo keep ;; esac + else + echo keep + fi + elif _in_skill_inventory "$_name" && grep -q ''; export const DOT_SKILLS_DIR = '/home/dot/skills'; export const ROUTER_DESCRIPTION = 'Use to review a diff or PR, debug a bug or failing test, QA test a site, plan or review architecture, ship a PR, audit security or write release docs. Load first for any coding task: lists every gstack skill and where to read it.'; /** OpenClaw hybrid mode: these task skills are listed as skills of their own; the router carries the rest. */ -export const HYBRID_SKILLS = ['review', 'qa', 'ship']; +export const HYBRID_SKILLS = ['review', 'qa', 'ship', 'plan-eng-review']; /** * OpenClaw serves a registered skill's SKILL.md whole or refuses it ("Skill instructions cannot be partially * served"), with maxBytes from resolveAdaptiveReadMaxBytes: 32,768 (DEFAULT_READ_PAGE_MAX_BYTES) when the model's diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 559896d0c3d..8436de1106f 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -128,6 +128,8 @@ export interface ShipReceipt { review_loop_exception?: { accepted_by: string; date: string; via: string; reason: string; fix_check?: { head: string; findings: number; files?: string[] }; second_pass?: { head: string; deferred: string[] } }; /** The owner's rulings that a finding ships as a disclosed note (gstack-approvals rule, lib/ruled-notes.ts); the PR body lists each one word for word (GST-1537). */ ruled_notes?: Array<{ finding: string; head: string; by: string; reason: string; at: string; approval: string }>; + /** The owner's dispositions of gate findings (gstack-approvals gate, lib/gate-dispositions.ts); the PR body lists each one word for word (GST-2491). */ + gate_dispositions?: Array<{ finding: string; gate_id: string; head: string; by: string; reason: string; words: string; at: string; approval: string }>; /** The `Mechanical retake: ()` lines /ship finish proved for this head's tree (lib/ship-mechanical.ts); the PR body lists each one word for word (GST-1560). */ mechanical?: string[]; /** The targeted pass on money, gate, auth and secret code (lib/review-targeted.ts), bound to the receipt's product_patch_id; `done` only with its output collected. */ @@ -277,6 +279,7 @@ export const ARTIFACT_SCHEMAS = { review_exclude: { type: 'object', required: ['source', 'patterns', 'applied', 'excluded', 'excluded_bytes', 'kept', 'gate_tagged', 'patterns_sha256', 'list_sha256', 'digest'], properties: { source: str, patterns: strList, applied: strList, excluded: { type: 'integer', minimum: 0 }, excluded_bytes: { type: 'integer', minimum: 0 }, kept: { type: 'integer', minimum: 0 }, gate_tagged: strList, patterns_sha256: str, list_sha256: str, digest: str } }, review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } } } }, ruled_notes: { type: 'array', items: { type: 'object', required: ['finding', 'head', 'by', 'reason', 'at', 'approval'], properties: { finding: str, head: str, by: str, reason: str, at: str, approval: str } } }, + gate_dispositions: { type: 'array', items: { type: 'object', required: ['finding', 'gate_id', 'head', 'by', 'reason', 'words', 'at', 'approval'], properties: { finding: str, gate_id: str, head: str, by: str, reason: str, words: str, at: str, approval: str } } }, mechanical: strList, design: { type: 'object', required: ['mode', 'reason'], properties: { mode: { enum: ['static'] }, reason: str } }, no_stop: { type: 'array', items: { type: 'object', required: ['class', 'reason', 'evidence'], properties: { class: { enum: [...NO_STOP_CLASSES] }, reason: str, evidence: str } } }, diff --git a/lib/outside-review-result.ts b/lib/outside-review-result.ts index 340c6a604a8..079cfda047f 100644 --- a/lib/outside-review-result.ts +++ b/lib/outside-review-result.ts @@ -20,6 +20,8 @@ export interface OutsideReviewInput { exit?: number; /** JSONL from `codex exec --json`: command events are positive execution evidence. */ events?: string; + /** The host's own error for the reviewer, such as a Capy subagent's latest_error; never a prompt echo. */ + providerError?: string; } export interface OutsideReviewClassification { @@ -62,6 +64,8 @@ function codexErrorLines(stderr: string): string[] { } /** The account's usage limit: Codex's line carries the reset time, so it is relayed verbatim. Same signature as the probe. */ export const QUOTA_FAILURE = /usage limit|insufficient_quota|exceeded your current quota|quota exceeded/i; +/** OpenAI's cyber-security refusal (R95): Capy relays it as `OpenAI key declined the request: cyber_policy: ...`; read from error lines only. */ +export const CYBER_POLICY_REFUSAL = /\bcyber_policy\b/; /** A plain HTTP 429 or rate limit: transient, so a separate reason from the quota. */ export const RATE_LIMIT_FAILURE = /rate.?limit|too many requests|(?:^|[^0-9])429(?:[^0-9]|$)/i; /** `codex review` transcript on stderr: a command that ran prints " succeeded in Nms:". */ @@ -90,10 +94,14 @@ function execution(input: OutsideReviewInput): OutsideReviewClassification['exec const stderr = input.stderr ?? ''; const exit = input.exit ?? 0; const sandbox = (output: string) => output.match(SANDBOX_FAILURE)?.[0].trim().slice(0, 240); + const cyber = (input.providerError ?? '').split(/\r?\n/).map(line => line.trim()).find(line => CYBER_POLICY_REFUSAL.test(line)); + if (cyber) return { state: 'unavailable', reason: 'cyber_policy_refused', detail: cyber.slice(0, 240) }; if (exit !== 0) { const detail = sandbox(stderr); if (detail) return { state: 'unavailable', reason: 'sandbox_unavailable', detail }; const errors = exit !== 124 ? codexErrorLines(stderr) : []; + const refusal = errors.find(line => CYBER_POLICY_REFUSAL.test(line)); + if (refusal) return { state: 'unavailable', reason: 'cyber_policy_refused', detail: refusal.slice(0, 240) }; const quota = errors.find(line => QUOTA_FAILURE.test(line)); if (quota) return { state: 'unavailable', reason: 'quota_exhausted', detail: quota.slice(0, 240) }; const rateLimit = errors.find(line => RATE_LIMIT_FAILURE.test(line)); @@ -344,7 +352,7 @@ export function validateOutsideReview(text: string, gate: OutsideGate): { comple const VERDICT_EXIT: Record = { clean: 0, findings: 3, unverified: 4, unavailable: 1 }; const GATES = ['review', 'structured', 'spec', 'execution', 'proposal']; const USAGE = `Usage: outside-review-result.ts - outside-review-result.ts --verdict [--stderr ] [--exit ] [--events ] [--label ] + outside-review-result.ts --verdict [--stderr ] [--exit ] [--events ] [--provider-error ] [--label ] Gates: ${GATES.join('|')}. Two-argument form exits 0 completed, 1 unavailable, 2 usage. Verdict form prints VERDICT: clean|findings|unverified|unavailable and exits 0, 3, 4 or 1.`; @@ -361,7 +369,7 @@ if (import.meta.main) { for (let i = 0; i < args.length; i++) { const arg = args[i]!; if (arg === '--verdict') verdictMode = true; - else if (['--stderr', '--exit', '--events', '--label'].includes(arg) && i + 1 < args.length) { flags[arg] = args[++i]!; verdictMode ||= arg !== '--label'; } + else if (['--stderr', '--exit', '--events', '--provider-error', '--label'].includes(arg) && i + 1 < args.length) { flags[arg] = args[++i]!; verdictMode ||= arg !== '--label'; } else if (arg.startsWith('--')) { console.error(USAGE); process.exit(2); } else positional.push(arg); } @@ -380,7 +388,7 @@ if (import.meta.main) { process.exit(0); } const events = await readOptional(flags['--events']); - const checked = classifyOutsideReview({ text, gate: gate as OutsideGate, exit, stderr: await readOptional(flags['--stderr']), events }); + const checked = classifyOutsideReview({ text, gate: gate as OutsideGate, exit, stderr: await readOptional(flags['--stderr']), events, providerError: await readOptional(flags['--provider-error']) }); const label = flags['--label'] ?? 'Outside review'; console.log(`VERDICT: ${checked.verdict}`); console.log(`FINDINGS: ${findingsLabel(checked)}`); diff --git a/lib/plan-record.ts b/lib/plan-record.ts index 60f3a7bf78b..279dc9865bb 100644 --- a/lib/plan-record.ts +++ b/lib/plan-record.ts @@ -42,7 +42,7 @@ export interface PlanRecord { line: string; state: 'approved' | 'exempt'; ref?: export interface PlanFailure { code: ResultCodeName; message: string; fix: string } export type PlanResolution = { ok: true; record: PlanRecord; summary: string } | { ok: false; failure: PlanFailure }; -const NOT_PLAN_ROW = /\b(ruled_note|review_loop_grant|review_loop_exception|test_lane_exception)\b/; +const NOT_PLAN_ROW = /\b(ruled_note|gate_disposition|review_loop_grant|review_loop_exception|test_lane_exception)\b/; const ROW_ID = /^a-[0-9a-f]{12}$/; const RECORD_ID = /^r-[0-9a-f]{12}$/; const LOCAL_SOURCE = 'state-root config'; diff --git a/lib/pregate/checks/lanes.ts b/lib/pregate/checks/lanes.ts index c19ab299fb5..219e3373565 100644 --- a/lib/pregate/checks/lanes.ts +++ b/lib/pregate/checks/lanes.ts @@ -43,6 +43,7 @@ import { cargoModel, type CargoModel } from '../rust'; import { adapterFor, readRange, STALL_IDLE, supervise, type Counter, type Supervised } from '../supervise'; import { ranFiles, verifyFromRun, type RunProfile } from '../../run-evidence'; import { matchesAny } from '../../ship-policy'; +import { testFileArgs } from '../../test-paths'; import type { CheckDef, CheckResult, PregateContext, RemoteObligation } from '../types'; /** The runner a `.py`-only selection gets; it needs the pytest module importable by python3 (`pytestMissing`). */ @@ -366,7 +367,7 @@ const quote = (f: string) => `'${f.replace(/'/g, `'\\''`)}'`; async function runOnce(ctx: PregateContext, env: NodeJS.ProcessEnv, g: RunGroup, files: string[], log: string, counter: Counter): Promise { // playwright test reads each file argument as a case-insensitive regex: escape it and anchor it to a path segment, so `a[1].spec.ts` runs that file, not `a1.spec.ts`. - const args = /(? `(?:^|/)${f.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) : files; + const args = /(? `(?:^|/)${f.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) : testFileArgs(g.runner, files); const joined = args.map(quote).join(' '); const run = g.runner.replace('{files}', () => joined); const command = g.cwd ? `(cd ${quote(g.cwd)} && ${run})` : run; @@ -441,6 +442,7 @@ function describe(ctx: PregateContext, sel: Selection, mode: NoLaneMode): string for (const r of sel.removed) lines.push(`removed (no lane owed): ${r.file} — ${r.note}`); if (sel.emptyLane.length) lines.push(`docs/no-tests (empty lane): ${sel.emptyLane.join(' ')}`); if (sel.inert.length) lines.push(`no-tests (assets and tool config): ${sel.inert.join(' ')}`); + for (const d of sel.declaredTier) lines.push(`declared test tree ${d.glob}: ${d.tests.length} test file(s) not run in the local lane (declared [] in ${ctx.configLabel}; the repo runs them in their own tier)`); if (sel.stampOnly.length) lines.push(`version-stamp-only (no lane needed): ${sel.stampOnly.join(' ')} — only version values changed against the merge base; a manifest whose other content changed still needs a lane`); for (const r of sel.remote) lines.push(`requires-remote ${r.lane} (${r.platform}): ${r.tests.length} test(s) — ${r.tests.slice(0, 8).join(' ')}${r.tests.length > 8 ? ' …' : ''}`); lines.push(`Tiers ran: ${sel.tiersRan.join(' ') || '(none)'}; requires-remote: ${[...new Set(sel.remote.map(r => r.platform))].join(' ') || 'none'}`); @@ -458,10 +460,10 @@ const GSTACK_ROOT = path.resolve(import.meta.dir, '..', '..', '..'); */ function remoteObligation(ctx: PregateContext, sel: Selection): RemoteObligation { const declared = ctx.config.remote_gate; - const runner = detectRunner(ctx, sel.localTests); - const command = declared ?? `${GSTACK_ROOT}/scripts/ubicloud/ubi-runner.sh run --src ${quote(ctx.repoRoot)} -- ${quote(runner ? runner.replace('{files}', sel.localTests.map(quote).join(' ')) : ' ')}`; + const runner = detectRunner(ctx, sel.gateTests); + const command = declared ?? `${GSTACK_ROOT}/scripts/ubicloud/ubi-runner.sh run --src ${quote(ctx.repoRoot)} -- ${quote(runner ? runner.replace('{files}', testFileArgs(runner, sel.gateTests).map(quote).join(' ')) : ' ')}`; const [workflow, job] = declared ? REMOTE_GATE_LANE.split('/') as [string, string] : ['test_backend', ctx.testBackend]; - return { lane: `${workflow}/${job}`, platform: 'remote', workflow, job, tests: sel.localTests, receipt: null, command }; + return { lane: `${workflow}/${job}`, platform: 'remote', workflow, job, tests: sel.gateTests, receipt: null, command }; } export const REMOTE_GATE_LANE = 'pregate.json/remote_gate'; @@ -508,7 +510,7 @@ async function runRemote(ctx: PregateContext, sel: Selection, base: CheckResult) const log = path.join(dir, 'remote.log'); const filesFile = path.join(dir, 'files.txt'); fs.writeFileSync(log, ''); - fs.writeFileSync(filesFile, sel.localTests.join('\n') + '\n'); + fs.writeFileSync(filesFile, sel.gateTests.join('\n') + '\n'); const r = await supervise({ command: obligation.command!, cwd: ctx.repoRoot, env: { ...ctx.env, PREGATE_TREE: ctx.wtree, PREGATE_FILES_FILE: filesFile, PREGATE_SPEND_CAP_USD: String(cap), PREGATE_TIMEOUT_S: String(Math.floor(ctx.timeoutMs / 1000)) }, log, deadline: Date.now() + ctx.timeoutMs, stallMs: 0, lastLine: true, label: `remote gate ${obligation.lane}`, progress: ctx.progress }); const output = readRange(log, r.start, r.end); const reported = parseRemoteReport(output); @@ -542,17 +544,18 @@ async function runSelected(ctx: PregateContext, sel: Selection, base: CheckResul : ctx.touched.length ? 'nothing touched selects a test' : 'no touched files'; return { ...base, detail }; } - if (ctx.remote && sel.localTests.length) return runRemote(ctx, sel, base); - const smallMachine = ctx.cores < SMALL_MACHINE_CORES && sel.localTests.length > 0 && (ctx.config.remote_gate || ctx.testBackend !== 'local'); + if (ctx.remote && sel.gateTests.length) return runRemote(ctx, sel, base); + const smallMachine = ctx.cores < SMALL_MACHINE_CORES && sel.gateTests.length > 0 && (ctx.config.remote_gate || ctx.testBackend !== 'local'); if (smallMachine) { const obligation = remoteObligation(ctx, sel); const route = obligation.lane === REMOTE_GATE_LANE && ctx.config.remote_gate_runs && ctx.ciCarry !== false ? `a verified CI run at this tree clears it: push, then gstack-ci-carry wait --base ${ctx.base} and rerun gstack-pregate --allow-repo-commands (a pull_request run of a branch behind its base tested the merge, another tree: dispatch the workflow on the branch); or opt in to the VM: gstack-pregate --remote --spend-cap --allow-repo-commands` : `run it, then ${clearHint(obligation.lane)}, or gstack-pregate --remote --spend-cap --allow-repo-commands`; - return { ...base, status: 'requires-remote', remote: [...sel.remote, obligation], lines: [...lines, `requires-remote ${obligation.lane}: ${ctx.cores} cores (under ${SMALL_MACHINE_CORES}); ${sel.localTests.length} local test file(s) recorded for the remote gate, not run here`, `run: ${obligation.command}`], detail: `${sel.localTests.length} local test file(s) recorded as requires-remote ${obligation.lane} (${ctx.cores} cores, under ${SMALL_MACHINE_CORES}); ${route}` }; + return { ...base, status: 'requires-remote', remote: [...sel.remote, obligation], lines: [...lines, `requires-remote ${obligation.lane}: ${ctx.cores} cores (under ${SMALL_MACHINE_CORES}); ${sel.gateTests.length} local test file(s) recorded for the remote gate, not run here`, `run: ${obligation.command}`], detail: `${sel.gateTests.length} local test file(s) recorded as requires-remote ${obligation.lane} (${ctx.cores} cores, under ${SMALL_MACHINE_CORES}); ${route}` }; } if (!ctx.allowRepoCommands) return { ...base, status: 'incomplete', code: 'REPO_COMMANDS_NOT_ALLOWED', detail: `${sel.localTests.length} local test file(s) selected but not run (pass --allow-repo-commands)`, fix: 'rerun with --allow-repo-commands (what /ship passes)' }; - if (sel.localTests.length === 0) return { ...base, status: sel.remote.length ? 'requires-remote' : 'pass', detail: `no local lane; ${sel.remote.length} requires-remote obligation(s)` }; + const tier = sel.declaredTier.reduce((n, d) => n + d.tests.length, 0); + if (sel.localTests.length === 0) return { ...base, status: sel.remote.length ? 'requires-remote' : 'pass', detail: `no local lane; ${sel.remote.length} requires-remote obligation(s)${tier ? `; ${tier} test file(s) in declared test trees not run here` : ''}` }; // Runnable groups run even when other files are unclaimed: a real failure is reported as one, and an all-green run is still incomplete. const plan = planRuns(ctx, sel.localTests); const gap = plan.unclaimed.length ? planGap(ctx, plan, sel.localTests.length) : null; @@ -636,7 +639,7 @@ async function run(ctx: PregateContext): Promise { } const reuse = ctx.fromRun ? fromRun(ctx, sel) : null; if (reuse) ctx.progress(reuse.line); - const rest = reuse?.passed.length ? { ...sel, localTests: sel.localTests.filter(t => !reuse.passed.includes(t)) } : sel; + const rest = reuse?.passed.length ? { ...sel, localTests: sel.localTests.filter(t => !reuse.passed.includes(t)), gateTests: sel.gateTests.filter(t => !reuse.passed.includes(t)) } : sel; const ran = await runSelected(ctx, rest, base); const reused = !reuse ? ran : { ...ran, lines: [reuse.line, ...(ran.lines ?? [])], ...(reuse.receipt ? { from_run: { receipt: reuse.receipt, files: reuse.passed }, detail: `${reuse.passed.length} of ${sel.localTests.length} local test file(s) passed in the --from-run run; ${ran.detail ?? ran.status}` } : {}) }; const result = withRemoved(reused); diff --git a/lib/pregate/context.ts b/lib/pregate/context.ts index c9b5038c046..597211fabcf 100644 --- a/lib/pregate/context.ts +++ b/lib/pregate/context.ts @@ -218,6 +218,7 @@ export function buildContext(o: BuildContextOptions): ContextLoad { let configLoad: ConfigLoad = loadConfigFromBase(o.repoRoot, base, o.knownChecks); const explain: string[] = []; let absentUserPolicy: string | undefined; + let headBootstrap = false; if (o.userConfigPath && !isConfigUnavailable(configLoad) && configLoad.kind === 'none') { const rejected = userConfigRejection(o.repoRoot, o.userConfigPath); const user = rejected ? null : loadConfigFromUser(o.userConfigPath, o.knownChecks); @@ -228,6 +229,7 @@ export function buildContext(o: BuildContextOptions): ContextLoad { if (isConfigUnavailable(configLoad)) return { refused: { code: 'POLICY_SOURCE_UNAVAILABLE', message: configLoad.detail } }; if (o.policyFrom === 'head' && !configLoad.errors.length) { if (o.remote && configLoad.kind === 'none') return { refused: { code: 'PREGATE_HEAD_POLICY_LOOSENS', message: '--remote under --policy-from head needs a trusted policy (the base copy or the user-owned file); with none, the head file is a bootstrap and its remote_gate cannot clear its own obligation' } }; + headBootstrap = configLoad.kind === 'none'; const head = headPolicy(o.repoRoot, configLoad, mergeBase, base, o.knownChecks ?? []); if ('loosens' in head) return { refused: { code: 'PREGATE_HEAD_POLICY_LOOSENS', message: head.loosens.join('; ') } }; configLoad = head.load; @@ -250,7 +252,7 @@ export function buildContext(o: BuildContextOptions): ContextLoad { return { ctx: { repoRoot: o.repoRoot, base, baseRef, baseSha: baseSha.out, mergeBase, head, wtree, touched: touchedFiles(o.repoRoot, mergeBase), - config, configLabel: configLoad.label, configKind: configLoad.kind, policyDeclaresLanes: configLoad.declaresLanes !== false, scratch, configFile: configLoad.kind === 'user' && o.userConfigPath ? o.userConfigPath : PREGATE_CONFIG_PATH, ...(configLoad.digest ? { configDigest: configLoad.digest } : {}), ...(absentUserPolicy ? { absentUserPolicy } : {}), registry: registryLoad.registry as Registry, registryLabel: registryLoad.source.label, + config, configLabel: configLoad.label, configKind: configLoad.kind, policyDeclaresLanes: configLoad.declaresLanes !== false, scratch, configFile: configLoad.kind === 'user' && o.userConfigPath ? o.userConfigPath : PREGATE_CONFIG_PATH, ...(configLoad.digest ? { configDigest: configLoad.digest } : {}), ...(absentUserPolicy ? { absentUserPolicy } : {}), ...(headBootstrap ? { headBootstrap } : {}), registry: registryLoad.registry as Registry, registryLabel: registryLoad.source.label, lanes, platform, allowRepoCommands: o.allowRepoCommands, timeoutMs: o.timeoutMs ?? (config.timeout_s ?? 600) * 1000, timeoutSource: o.timeoutMs !== undefined ? '--timeout' : config.timeout_s ? `timeout_s from ${configLoad.label}` : 'the 600 s default', stallTimeoutMs: o.stallTimeoutMs ?? (config.stall_timeout_s ?? DEFAULT_STALL_TIMEOUT_S) * 1000, progress: o.progress ?? (line => process.stderr.write(`${line}\n`)), diff --git a/lib/pregate/docs-only-lane.ts b/lib/pregate/docs-only-lane.ts index b10c5c9794f..cbb434837b0 100644 --- a/lib/pregate/docs-only-lane.ts +++ b/lib/pregate/docs-only-lane.ts @@ -11,6 +11,7 @@ import * as path from 'node:path'; import { bunIsolationArgs } from '../bun-isolation'; import { addedLines, brokenLinks } from '../doc-links'; import { classifyDocsOnly } from '../docs-only'; +import { explicitPath } from '../test-paths'; import type { CheckResult, PregateContext } from './types'; /** The lanes result for a docs-only change, or null when the change is not docs-only (or cannot be classified). */ @@ -34,8 +35,8 @@ export function docsOnlyLane(ctx: PregateContext, base: CheckResult): CheckResul const done = (detail: string): CheckResult => ({ ...base, lines, status: 'pass', remote: [], detail }); if (!tests.length) return done(`docs-only: ${r.files.length} file(s); links on added lines resolve; no docs reader tests; the test suites are not owed`); if (!ctx.allowRepoCommands) return { ...base, lines, status: 'incomplete', code: 'REPO_COMMANDS_NOT_ALLOWED', detail: `docs-only: ${tests.length} docs reader test file(s) selected but not run (pass --allow-repo-commands)`, fix: 'rerun with --allow-repo-commands (what /ship passes)' }; - const run = spawnSync(process.execPath, [...bunIsolationArgs(), 'test', '--timeout=30000', ...tests], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 600_000, maxBuffer: 64 * 1024 * 1024 }); + const run = spawnSync(process.execPath, [...bunIsolationArgs(), 'test', '--timeout=30000', ...tests.map(explicitPath)], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 600_000, maxBuffer: 64 * 1024 * 1024 }); const tail = `${run.stdout ?? ''}${run.stderr ?? ''}`.trim().split('\n').slice(-3).join(' | '); - if (run.status !== 0) return { ...base, lines: [...lines, tail], status: 'fail', cause: 'diff', code: 'PREGATE_LANE_FAILED', detail: `docs-only: docs reader tests failed (${run.error ? run.error.message : `exit ${run.status}`})`, fix: `bun test ${tests.join(' ')}` }; + if (run.status !== 0) return { ...base, lines: [...lines, tail], status: 'fail', cause: 'diff', code: 'PREGATE_LANE_FAILED', detail: `docs-only: docs reader tests failed (${run.error ? run.error.message : `exit ${run.status}`})`, fix: `bun test ${tests.map(explicitPath).join(' ')}` }; return done(`docs-only: ${r.files.length} file(s); links on added lines resolve; ${tests.length} docs reader test file(s) passed; the test suites are not owed`); } diff --git a/lib/pregate/lane-selection.ts b/lib/pregate/lane-selection.ts index 51f9ada0877..cf07e3b5e9b 100644 --- a/lib/pregate/lane-selection.ts +++ b/lib/pregate/lane-selection.ts @@ -23,6 +23,9 @@ import type { Lane } from './workflows'; /** Whole-tree tests every selection that runs a test must include (GST-98). Kept out of pregate.json so older readers, which reject unknown keys, keep working. */ export const ALWAYS_RUN_PATH = '.gstack/always-run.json'; +/** A glob naming a folder inside a test directory (`tests/live/**`, never `test/**` or a single file): its `[]` declaration keeps the tests under it out of the local lane. */ +const TEST_SUBTREE = /(?:^|\/)(?:test|tests|spec|__tests__)\/[^*?[{/]+\//; + /** The `tests` globs of one `.gstack/always-run.json` text; `label` names the copy in errors. */ export function parseAlwaysRun(text: string, label: string = ALWAYS_RUN_PATH): string[] { let parsed: unknown; @@ -68,10 +71,14 @@ export interface Selection { inert: string[]; /** Release manifests whose diff against the merge base changes only version values (lib/pregate/stamp-only.ts): waived, no lane needed. */ stampOnly: string[]; + /** Local-lane tests a `[]` declaration on a folder inside a test directory (TEST_SUBTREE) kept out, per glob: the repo runs them in their own tier. Never an always-run test; they stay in `tests`, `gateTests` and any remote obligation. */ + declaredTier: Array<{ glob: string; tests: string[] }>; /** Every test the touched files select, sorted. */ tests: string[]; /** Tests that run on this machine. */ localTests: string[]; + /** The local selection before declared test trees were left out: what the remote gate and `test_backend` owe, since that exclusion is local-only. */ + gateTests: string[]; /** Platform lanes this machine cannot run that select part of the set. */ remote: RemoteObligation[]; /** Tiers of the local lanes the selection touches. */ @@ -283,8 +290,10 @@ export function selectLanes(ctx: PregateContext): Selection { } noLane.push(file); } + const alwaysRun = new Set(); if (tests.size || noLane.length || seeds.has(ALWAYS_RUN_PATH)) { const always = alwaysRunTests(ctx.repoRoot, [...graph.tests].filter(t => !goneSet.has(t)), readAtMergeBase(ctx, ALWAYS_RUN_PATH, ['100644', '100755'])); + for (const t of always.tests) alwaysRun.add(t); for (const t of always.tests) if (!tests.has(t)) { tests.add(t); provenance.push(`${t} (always_run, ${always.baseOnly.includes(t) ? 'merge base ' : ''}${ALWAYS_RUN_PATH})`); } for (const glob of always.unmatched) provenance.push(`${ALWAYS_RUN_PATH}: ${glob} matches no test file`); } @@ -293,6 +302,8 @@ export function selectLanes(ctx: PregateContext): Selection { const remote: RemoteObligation[] = []; const tiers = new Set(); const selected = [...tests].sort(); + const declaredTier = ctx.headBootstrap ? [] : Object.entries(ctx.config.dependencies ?? {}).filter(([glob, list]) => list.length === 0 && TEST_SUBTREE.test(glob) && /\/\*\*?$/.test(glob)).map(([glob]) => ({ glob, tests: [] as string[] })); + const tierOf = (t: string) => alwaysRun.has(t) ? undefined : declaredTier.find(d => matchesAny([d.glob], t)); let anyLocalAll = false; for (const lane of ctx.lanes.filter(l => l.runsTests && !l.manual)) { const set = laneFileSet(ctx, lane); @@ -304,12 +315,21 @@ export function selectLanes(ctx: PregateContext): Selection { continue; } if (set === 'all') anyLocalAll = true; - if (inLane.length) { tiers.add(lane.tier === 'platform' ? 'unit' : lane.tier); for (const t of inLane) local.add(t); } + if (inLane.some(t => !tierOf(t))) tiers.add(lane.tier === 'platform' ? 'unit' : lane.tier); + for (const t of inLane) local.add(t); } if (anyLocalAll || ctx.lanes.filter(l => l.runsTests && !l.manual && l.tier !== 'platform').length === 0) for (const t of selected) local.add(t); for (const t of selected) if (!local.has(t) && !remote.some(r => r.tests.includes(t))) local.add(t); + const gateTests = [...local].sort(); + for (const t of gateTests) { + const tier = tierOf(t); + if (!tier) continue; + tier.tests.push(t); + local.delete(t); + provenance.push(`${t}: not run in the local lane; ${tier.glob} is declared [] in ${PREGATE_CONFIG_PATH} (its own tier)`); + } if (local.size && tiers.size === 0) tiers.add('unit'); - return { noLane: noLane.sort(), removed: removed.sort((a, b) => a.file.localeCompare(b.file)), emptyLane: emptyLane.sort(), inert: inert.sort(), stampOnly: stampOnly.sort(), tests: selected, localTests: [...local].sort(), remote, tiersRan: [...tiers].sort(), laneSets, provenance }; + return { noLane: noLane.sort(), removed: removed.sort((a, b) => a.file.localeCompare(b.file)), emptyLane: emptyLane.sort(), inert: inert.sort(), stampOnly: stampOnly.sort(), declaredTier: declaredTier.filter(d => d.tests.length), tests: selected, localTests: [...local].sort(), gateTests, remote, tiersRan: [...tiers].sort(), laneSets, provenance }; } export function isTest(file: string): boolean { return isTestFile(file); } diff --git a/lib/pregate/supervise.ts b/lib/pregate/supervise.ts index 37cc3210ed9..49331283dab 100644 --- a/lib/pregate/supervise.ts +++ b/lib/pregate/supervise.ts @@ -23,9 +23,10 @@ import { spawn, spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import { bashCommandInvocation } from '../script-invocation'; +import { BUN_TEST } from '../test-paths'; export type ProgressAdapter = 'bun'; -export const PROGRESS_ADAPTERS: Record = { bun: /(?:^|[\s;&|(])bun\s+test\b/ }; +export const PROGRESS_ADAPTERS: Record = { bun: BUN_TEST }; export interface Counter { done: number; total: number } diff --git a/lib/pregate/types.ts b/lib/pregate/types.ts index d1a148f77a9..f0186a33e7d 100644 --- a/lib/pregate/types.ts +++ b/lib/pregate/types.ts @@ -36,6 +36,8 @@ export interface PregateContext { configLabel: string; /** Where the policy came from: the base branch, the unreviewed head, the user-owned file, or nowhere (defaults). */ configKind: 'base' | 'head' | 'user' | 'none'; + /** A `--policy-from head` run with no base or user policy: the head file is a bootstrap, so its `[]` declarations on test folders drop nothing. */ + headBootstrap?: boolean; /** The active policy has a `dependencies`, `empty_lanes`, `selection` or `local` key (config LANE_KEYS); false keeps the no-policy lane verdicts. Absent counts as declared. */ policyDeclaresLanes?: boolean; /** This run's scratch directory under the state root (lib/pregate/run-scratch.ts): logs and scan files, never os.tmpdir(). */ diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts index 43a80af26f0..e396cc9bea5 100644 --- a/lib/result-codes-release.ts +++ b/lib/result-codes-release.ts @@ -513,6 +513,11 @@ export const RELEASE_RESULT_CODES = { summary: 'the PR head is not the pin land was given, so the READY it was given does not describe what would merge', fix: 'the lane runs /ship and gstack-ship-queue ready --pr --no-screen at the new head and reports READY with it; land that pin', }, + QUEUE_GATE_DISPOSITION: { + anchor: 'queue-gate-disposition', + summary: 'the owner gate dispositions the approval store applies at the pin are not all accepted by the lander, an accepted id is not applied, or the receipt or PR body differs from the store', + fix: 'read each GATE_DISPOSITION line, then rerun land (or verify) with --accept-gate-disposition for each one you accept; when the receipt or body differs from the store, the lane reruns /ship and ready at the pin', + }, QUEUE_LAND_CHECKS: { anchor: 'queue-land-checks', summary: 'a check at the pin is red or pending, or a required check never ran there', diff --git a/lib/review-brief.ts b/lib/review-brief.ts index 7e30942c7a0..eec05087e0e 100644 --- a/lib/review-brief.ts +++ b/lib/review-brief.ts @@ -100,6 +100,14 @@ export function sectionTexts(root: string): SectionTexts { }; } +/** + * The outside voice's read-only correctness brief (R95): sent only when OpenAI refused the original under `cyber_policy`, as + * Capy's pass program retries it on GPT-6 Astra (lib/capy-review-pass.js). It drops the attacker role-play from the outside + * prompt and appends READ_ONLY_RETRY; every other reader, and every first attempt, gets its section text unchanged. + */ +export const READ_ONLY_RETRY = 'How to work, and this overrides anything above that conflicts with it: this is a read-only correctness review of the change, done by reading the code and its tests. Do not role-play an attacker. Do not write, run or describe exploit code or step-by-step reproductions. For each defect give file:line, the condition under which the code returns the wrong answer, and the smallest fix.'; +const READ_ONLY_EDITS: Array<[string, string]> = [['Think like an attacker and a chaos engineer. ', ''], ['Be adversarial. ', ''], ['naming the most exploitable finding', 'naming the most serious finding']]; + const SHA = /^[0-9a-f]{7,40}$/; const FENCE = '`'.repeat(3); function need(slots: Slots, key: string): string { @@ -176,7 +184,8 @@ function renderRole(role: BriefRole, slots: Slots, t: SectionTexts): string { try { return `${targetedBrief(need(slots, 'brief'), classes)}\n\n${merged}\n\nApply the targeted brief above (${need(slots, 'checklist')}: ${classes.join(', ')}) in the same read; your reply is this diff's targeted pass.`; } catch (e) { throw e instanceof BriefError ? e : new BriefError((e as Error).message); } } case 'outside-voice': { - const filled = fill(t.outside, [['DIFF_BASE=$(git merge-base origin/ HEAD)', `DIFF_BASE=${diffBase}`]], role); + const outside = slots.read_only ? `${fill(t.outside, READ_ONLY_EDITS, 'read-only retry')}\n\n${READ_ONLY_RETRY}` : t.outside; + const filled = fill(outside, [['DIFF_BASE=$(git merge-base origin/ HEAD)', `DIFF_BASE=${diffBase}`]], role); const body = slots.policy_exclude ? filled.split('git diff "$DIFF_BASE".').join(`git diff "$DIFF_BASE" -- . ${slots.policy_exclude}${slots.keep ? ` and git diff "$DIFF_BASE" -- ${slots.keep}` : ''}.`) : filled; const head = [body, '', ...(slots.disclosure ? [slots.disclosure, ''] : []), `## Branch diff (git diff ${diffBase})`]; if (slots.diff_file) return [...head, `The supplied branch diff is the file ${slots.diff_file} (${need(slots, 'diff_bytes')} bytes, sha256 ${need(slots, 'diff_sha256')}). Read it from disk; it is ${slots.diff_slice ? 'the part of the diff under review' : 'the whole diff under review'}.`, ...(slots.diff_slice ? [slots.diff_slice] : [])].join('\n'); @@ -203,20 +212,27 @@ const treeCommand = (dir: string) => `cd ${quoted(dir)} && echo "REVIEWED_TREE: * follows a findings-only output format can skip a request that only closes a long brief (gpt-6.1-sol did on GST-850), and * "the line prints" was read as the command itself, so the step comes first and names the output line. */ -export function workspaceStep(dir: string): string { - return `First step, before anything else: run \`${treeCommand(dir)}\`. It outputs one line, \`REVIEWED_TREE: \`. Copy that output line, not the command, as the first line of your final reply, above everything else, even where this brief limits your output to findings or says how to end it; a reply without it, or from another checkout, does not count.`; +export function workspaceStep(dir: string, verdict = false): string { + return `First step, before anything else: run \`${treeCommand(dir)}\`. It outputs one line, \`REVIEWED_TREE: \`. Copy that output line, not the command, as the first line of your final reply, above everything else, even where this brief limits your output to findings or says how to end it; a reply without it, or from another checkout, does not count.${verdict ? ` ${VERDICT_ASK}` : ''}`; } +/** + * The verdict ask every blocking reader's brief carries right after the fingerprint step (GST-2495, lib/review-verdict.ts): one + * machine-readable count of the reply's blocking findings, which collect checks against the findings it parses. + */ +export const VERDICT_ASK = 'Put `REVIEW_VERDICT: blocking=` on the second line, right under it: n is how many findings in your reply block the merge by this brief\'s own rule, 0 when none; add ` at=:,…` for those findings that have a location. Write it once, on its own line, outside any code block; it does not replace your findings or the ending this brief asks for.'; + /** * The closing paragraphs every dispatched brief carries: the fetch rule and the readers policy (GST-1322, lib/review-fetch.ts), * then the workspace (GST-482): a reader on a shared machine starts in that machine's working directory, and every command runs * in a fresh shell, so the brief names the checkout under review and asks again for the fingerprint workspaceStep opens with. * The section's render sits between workspaceStep and these, byte for byte what renderBrief returns. */ -export function workspaceParagraph(dir: string, readers?: ReadersPolicy): string { - return `${fetchParagraph(readers)}\n\nWorkspace: the checkout under review is ${dir}. Your shell and file tools may start in another checkout, and every command runs in a fresh shell: begin each command with \`cd ${quoted(dir)} && \`, and give every file read, search, edit or write an absolute path under ${dir}. The first line of your final reply is the \`REVIEWED_TREE: \` line that \`${treeCommand(dir)}\` outputs (the output, not the command), even where this brief limits your output to findings; a reply without it, or from another checkout, does not count.`; +export function workspaceParagraph(dir: string, readers?: ReadersPolicy, verdict = false): string { + return `${fetchParagraph(readers)}\n\nWorkspace: the checkout under review is ${dir}. Your shell and file tools may start in another checkout, and every command runs in a fresh shell: begin each command with \`cd ${quoted(dir)} && \`, and give every file read, search, edit or write an absolute path under ${dir}. The first line of your final reply is the \`REVIEWED_TREE: \` line that \`${treeCommand(dir)}\` outputs (the output, not the command), even where this brief limits your output to findings; a reply without it, or from another checkout, does not count.${verdict ? ' The second line is your `REVIEW_VERDICT: blocking=` line; gstack checks that count against your findings, so do not repeat it.' : ''}`; } -export const withWorkspace = (text: string, dir: string, readers?: ReadersPolicy) => `${workspaceStep(dir)}\n\n${text}\n\n${workspaceParagraph(dir, readers)}`; +/** A blocking reader's brief (one of BRIEF_ROLES) takes the verdict ask; an audit reader, which cannot block, does not. */ +export const withWorkspace = (text: string, dir: string, readers?: ReadersPolicy, opts: { verdict?: boolean } = {}) => `${workspaceStep(dir, opts.verdict)}\n\n${text}\n\n${workspaceParagraph(dir, readers, opts.verdict)}`; /** The checkout a brief names: the toplevel of the directory the bins run in, where its diff and merge base come from. */ export function checkoutRoot(): string { const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 30_000 }); diff --git a/lib/review-depth.ts b/lib/review-depth.ts index 9547ad26661..352beca11e6 100644 --- a/lib/review-depth.ts +++ b/lib/review-depth.ts @@ -599,7 +599,11 @@ export function planReview(i: PlanInput): ReviewPlan { if (firstVoices) add('adversarial-native', 'adversarial', 'full', [], { reason: LIGHT_ADVERSARIAL_REASON }); } else { for (const n of SPECIALISTS.filter(forced)) add('specialist', n, specialist); - skipped.push('specialists, red-team and adversarial-native (light depth, runtime 0)'); + if (cls === 'docs' || dispatches.length) skipped.push('specialists, red-team and adversarial-native (light depth, runtime 0)'); + else { + add('specialist', 'batched', specialist, cls === 'tests' ? docsAndOutputs : [], { checklists: batchChecklists(cls, i, skipped) }); + skipped.push(`red-team and adversarial-native (light depth, runtime 0: one batched reader reads the ${cls} diff, R51)`); + } } if (h.fullPasses === 0 && i.numbers.publishes) add('outside-voice', 'outside-voice', 'host'); else if (numbersChanged) add('outside-voice', 'outside-voice (numbers changed)', 'host'); @@ -654,7 +658,9 @@ export function planReview(i: PlanInput): ReviewPlan { * R65's lean dispatch (docs/review-policy.md#review-depth): pass 1 runs one native adversarial reader at the lane's reasoning, on * review.reader_model (the lane's model by default: FOUN-32, ggstack#52). A risk-class diff under review.panel off gets the merged * reader: the gate-class checklists, the Red Team checklist and the targeted brief for its classes; a non-risk code diff gets the - * code-class checklists and the Red Team. Docs and tests keep the core read. A docs or tests diff with no numeric, results or prereg + * code-class checklists and the Red Team. Docs keep the core read; a tests diff, or code with no runtime lines, gets one batched + * reader on its class's checklists unless a forced specialist already reads it (R51: tests get one reviewer, so no non-docs pass 1 + * plans zero readers). A docs or tests diff with no numeric, results or prereg * claims, under review.platform on, with the platform review at HEAD, runs no reader at all (mode platform). */ /** Risk class read from the paths and lines (gate class, an R51 or review.risk_paths class, a classifier error), or a floor above light (FOUN-64 item 7: never the recorded review_depth). */ @@ -690,7 +696,9 @@ function leanPlan(i: PlanInput, c: ClassResult, depth: DepthResult, next: NextSt reader(); skipped.push(`specialists, red-team and outside-voice as their own readers (R65: the one ${risky ? 'risk-class' : 'light'} reader carries them)`); } else if (next.step === 'full') { - for (const n of SPECIALISTS.filter(forcedBy(i))) add('specialist', n, i.tiers === false ? 'host' : ROLE_EFFORT.specialist); + const effort: Effort = i.tiers === false ? 'host' : ROLE_EFFORT.specialist; + for (const n of SPECIALISTS.filter(forcedBy(i))) add('specialist', n, effort); + if (depth.class !== 'docs' && !dispatches.length) add('specialist', 'batched', effort, depth.class === 'tests' ? docsAndOutputs : [], { checklists: batchChecklists(depth.class, i, skipped) }); if (i.numbers.publishes) add('outside-voice', 'outside-voice', 'host'); else skipped.push(`outside-voice (${depth.class} class, no numeric claims)`); } else if (next.step === 'voices') reader(); diff --git a/lib/review-evidence.ts b/lib/review-evidence.ts index 01afcff02b8..b993ceb8bad 100644 --- a/lib/review-evidence.ts +++ b/lib/review-evidence.ts @@ -348,18 +348,20 @@ export const holdsOpen = (f: unknown) => !record(f) || unresolvedFinding(f) || f * rest leave nothing unresolved and the findings account for every claimed issue and critical; otherwise unchanged. An open * finding is rulable too: a fix-check that finds a CRITICAL stops for the owner (review-army decision 3.5 sends it to decision 2) * with the finding open and the row converged:false, bound `incomplete` on unchanged content, and the ruling is the owner's - * answer to that stop, so a row the rulings clear binds at the tree it read (GST-2251, harness-evals#361). + * answer to that stop, so a row the rulings clear binds at the tree it read (GST-2251, harness-evals#361). A gate finding is + * taken out the same way only when `gated` holds its ` ` key (the owner's gate_disposition rows whose + * head lies in this row's range, lib/gate-dispositions.ts, GST-2491); a ruling never closes a gate finding. */ -function withoutRuledNotes(rec: Record, ruled: ReadonlySet): Record { - const isRuled = (f: unknown) => record(f) && !f.gate && RULABLE.has(f.action) && typeof f.fingerprint === 'string' && ruled.has(f.fingerprint); - if (!ruled.size || rec.status_source === 'derived' || rec.completed !== true || !Array.isArray(rec.findings) || +function withoutRuledNotes(rec: Record, ruled: ReadonlySet, gated: ReadonlySet): Record { + const isRuled = (f: unknown) => record(f) && typeof f.fingerprint === 'string' && (f.gate ? (f.action === 'open' || f.action === 'kept') && gated.has(`${f.fingerprint} ${f.gate_id}`) : RULABLE.has(f.action) && ruled.has(f.fingerprint)); + if ((!ruled.size && !gated.size) || rec.status_source === 'derived' || rec.completed !== true || !Array.isArray(rec.findings) || !rec.findings.some(isRuled) || rec.findings.length < Number(rec.issues_found ?? 0) || rec.findings.filter(f => record(f) && isCriticalFinding(f)).length < Number(rec.critical ?? 0) || rec.findings.some(f => !isRuled(f) && holdsOpen(f))) return rec; return { ...rec, status: 'clean', issues_found: 0, critical: 0, informational: 0, findings: rec.findings.filter(f => !isRuled(f)) }; } -export function reviewFreshness(rec: Record, currentWtree: string, ruled: ReadonlySet = new Set()): { status: string; reason: string } | undefined { +export function reviewFreshness(rec: Record, currentWtree: string, ruled: ReadonlySet = new Set(), gated: ReadonlySet = new Set()): { status: string; reason: string } | undefined { if (!DIFF_REVIEWS.has(rec.skill)) return; if (rec.skill === 'ship') return { status: 'UNVERIFIED', reason: 'ship telemetry is not a review pass' }; const binding = rec.review_binding; @@ -368,7 +370,7 @@ export function reviewFreshness(rec: Record, currentWtree: string, return { status: 'STALE', reason: `content changed during review: the tree moved from ${short(binding.start_wtree)} to ${short(binding.end_wtree)} while ${rec.skill} ran (an edit, commit or merge landed before its row was logged), so the record cannot bind. Repair: freeze the checkout until every reviewer returns, then rerun the steps 11.5 names on the frozen tree; when the edit was your own fix, log it as a fix so gstack-review-plan picks the repeat depth (docs/troubleshooting.md#review-content-changed)` }; } if (rec.scope === 'fix-range') return { status: 'UNVERIFIED', reason: 'fix-range pass; only a later full pass can clear review' }; - const cleared = withoutRuledNotes(rec, ruled); + const cleared = withoutRuledNotes(rec, ruled, gated); const ruledStop = cleared !== rec && binding?.state === 'incomplete' && rec.converged === false; const wtree = ruledStop ? binding.end_wtree : rec.wtree; if ((binding?.state !== 'verified' && !ruledStop) || rec.completed !== true || (rec.converged !== true && !ruledStop) || diff --git a/lib/review-exclude.ts b/lib/review-exclude.ts index 0be1d90221c..e2e469dfcfa 100644 --- a/lib/review-exclude.ts +++ b/lib/review-exclude.ts @@ -257,9 +257,12 @@ function attributeBinaryLines(i: ExcludeInput, paths: readonly string[], unread: /** The kind of content a path holds when the policy may exclude it, or null for code (tests included). */ export type ContentKind = 'binary' | 'data' | 'docs' | 'log'; -function contentKind(i: ExcludeInput, p: string, binary: ReadonlySet): ContentKind | null { +/** One range's input with the matched files a pattern names by their file name (its last segment, with no glob character): a config name there is data. */ +type Scope = ExcludeInput & { named?: ReadonlySet }; +const config = (i: Scope, p: string) => isDataConfig(p) && !i.named?.has(p); +function contentKind(i: Scope, p: string, binary: ReadonlySet): ContentKind | null { if (binary.has(p)) return 'binary'; - if (DATA_PATH.test(p) && !isDataConfig(p)) return 'data'; + if (DATA_PATH.test(p) && !config(i, p)) return 'data'; if (/\.log$/i.test(p)) return 'log'; return classifyPath(p, i.classRoot) === 'docs' ? 'docs' : null; } @@ -272,7 +275,7 @@ function contentKind(i: ExcludeInput, p: string, binary: ReadonlySet): C const BINARY_CONTENT_EXT = /\.(?:png|jpe?g|gif|webp|bmp|ico|avif|tiff?|heic|heif|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|oga|ogv|webm|mov|avi|mkv|flac|aac|opus|pdf|docx|xlsx|pptx|odt|ods|odp|gz|tgz|zip|tar|bz2|xz|zst|7z|bin|dat|parquet|arrow|feather|avro|orc|npy|npz|h5|hdf5|sqlite3?|db|safetensors)$/i; /** Why a matched file is kept by its path, mode and lines alone; null for content the policy may exclude. A binary file readers would only see as "Binary files differ" is content unless its directory, mode, gate tags, extension or magic keep it. */ -function pathReason(i: ExcludeInput, p: string, m: Matched, binary: ReadonlySet, native: ReadonlySet): KeptReason | null { +function pathReason(i: Scope, p: string, m: Matched, binary: ReadonlySet, native: ReadonlySet): KeptReason | null { if (/^\.(gstack|github)\//.test(p)) return 'policy-dir'; if (isGatePath(p) || secretPath(p, i.added[p] ?? [])) return 'gate-path'; if (m.oldMode === '100755' || m.newMode === '100755') return 'executable'; @@ -280,14 +283,14 @@ function pathReason(i: ExcludeInput, p: string, m: Matched, binary: ReadonlySet< if (i.gateTagged?.has(p)) return 'gate-tagged'; if (binary.has(p)) return BINARY_CONTENT_EXT.test(p) && !native.has(p) ? null : 'code'; if (isAgentProse(p)) return 'agent-prose'; - if (isDataConfig(p)) return 'config'; + if (config(i, p)) return 'config'; if (contentKind(i, p, binary) === null) return 'code'; if ((i.added[p] ?? []).some(l => secretValueLine(p, l))) return 'secret-line'; return null; } /** A file whose full-path reference keeps excluded content: a code or test file (not docs, data, a .log or binary) outside the would-be-excluded set. */ -const consumer = (i: ExcludeInput, f: string, candidates: ReadonlySet) => +const consumer = (i: Scope, f: string, candidates: ReadonlySet) => !candidates.has(f) && !f.startsWith('.gstack/tmp/') && contentKind(i, f, new Set()) === null; /** @@ -299,7 +302,7 @@ const consumer = (i: ExcludeInput, f: string, candidates: ReadonlySet) = * (GST-1442: 363 chunked greps over a 192k-file tree ran 132 s). On a live tree, an entry git reads from its blob * (skip-worktree or assume-unchanged) goes into a second index grepped with --cached, as git grep itself would read it. */ -function grepFixed(i: ExcludeInput, strings: readonly string[], candidates: ReadonlySet, revs: readonly string[]): Map> | null { +function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet, revs: readonly string[]): Map> | null { const found = new Map>(); if (!strings.length) return found; const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-exclude-')); @@ -365,14 +368,16 @@ export function reviewExclude(i: ExcludeInput): Exclusion { const native = new Set(); const claimed = i.perPath.filter(e => e.binary && sel.files.has(e.path)).map(e => e.path); const binary = binaryContent(i, sel.files, new Set([...claimed, ...(bytesBinary(i, patterns) ?? sel.files.keys())]), unread, native); - const text = { ...i, added: { ...i.added, ...attributeBinaryLines(i, claimed.filter(p => !binary.has(p) && !unread.has(p)), unread) } }; + const fileName = (s: string) => s.slice(s.lastIndexOf('/') + 1); + const x: Scope = { ...i, named: new Set(patterns.flatMap(q => /[*?[\\]/.test(fileName(q)) ? [] : (sel.byPattern.get(q) ?? []).filter(f => fileName(f) === fileName(q)))) }; + const text = { ...x, added: { ...i.added, ...attributeBinaryLines(i, claimed.filter(p => !binary.has(p) && !unread.has(p)), unread) } }; const collected = new Map(i.perPath.map(e => [e.path, e])); const unseen = (p: string) => { const e = collected.get(p); return !e || (!e.binary && e.lines > 0 && !(p in text.added)); }; const reasons = new Map(); for (const [p, m] of sel.files) reasons.set(p, unread.has(p) ? 'consumer-scan-unavailable' : pathReason(text, p, m, binary, native) ?? (unseen(p) ? 'consumer-scan-unavailable' : null)); const candidates = new Set([...reasons].filter(([, r]) => r === null).map(([p]) => p)); const secretOnly = [...reasons].filter(([p, r]) => r === 'secret-line' && !p.includes('\n')).map(([p]) => p); - const named = grepFixed(i, [...candidates, ...secretOnly].filter(p => !p.includes('\n')), new Set([...candidates, ...secretOnly]), [i.mergeBase]); + const named = grepFixed(x, [...candidates, ...secretOnly].filter(p => !p.includes('\n')), new Set([...candidates, ...secretOnly]), [i.mergeBase]); for (const p of candidates) { if (i.gateTagged === null) reasons.set(p, 'gate-scan-unavailable'); else if (named === null || p.includes('\n')) reasons.set(p, 'consumer-scan-unavailable'); @@ -396,9 +401,9 @@ export function reviewExclude(i: ExcludeInput): Exclusion { const keptList = [...reasons].filter(([, r]) => r !== null).map(([p, r]) => ({ path: p, reason: r! })).sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); const sortedExcluded = [...excluded].sort(); const content: Record = { binary: 0, data: 0, docs: 0, log: 0 }; - for (const p of sortedExcluded) content[contentKind(i, p, binary)!]++; + for (const p of sortedExcluded) content[contentKind(x, p, binary)!]++; const prefixes = [...new Set(applied.map(literalPrefix).filter(Boolean))]; - const refs = grepFixed(i, prefixes, excluded, []) ?? new Map>(); + const refs = grepFixed(x, prefixes, excluded, []) ?? new Map>(); const patterns_sha256 = sha256(JSON.stringify(patterns)); const list_sha256 = sha256(JSON.stringify({ applied, excluded: sortedExcluded, kept: keptList.map(k => [k.path, k.reason]) })); const record: ExcludeRecord = { diff --git a/lib/review-ledger.ts b/lib/review-ledger.ts index a0fcd0a54be..b2d4473043f 100644 --- a/lib/review-ledger.ts +++ b/lib/review-ledger.ts @@ -18,6 +18,7 @@ import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { checkReviewedTree, isReviewedTreeLine, promptHash, type TreeCheck } from './review-brief'; +import { parseVerdict, withoutVerdictLines } from './review-verdict'; export interface LedgerEvent { event: 'rendered' | 'sent' | 'output' | 'judgment' | 'judge' | 'program' | 'quarantined' | 'fetch-sweep'; [k: string]: unknown } export const readerKey = (role: string, name?: string) => (name ? `${role}/${name}` : role); @@ -191,7 +192,7 @@ export interface MergedLine { id: string; reader: string; label: string; stated? * Severity or Blocks: yes field, the native voice's FIXABLE or INVESTIGATE, or a file:line on it or on the line it runs on from) collects * nothing; elsewhere it collects as above. A line led by a bold, unlabelled lead ("**1. Coverage:** …") is read for a closing summary after it. */ -function parseLabelled(reader: string, output: string, fixableRaises: boolean): Array<{ label: string; raw: string; shaped: boolean }> { +function parseLabelled(reader: string, output: string, fixableRaises: boolean): Array<{ label: string; raw: string; shaped: boolean; anchored: boolean }> { type Finding = { label: string; raw: string; fields: Set; list: boolean; lead?: string; fixable?: boolean; heading?: boolean; item?: boolean; nested?: boolean; closed?: boolean; section?: boolean; context?: string }; const out: Finding[] = []; let section: string | null = null; @@ -312,19 +313,51 @@ function parseLabelled(reader: string, output: string, fixableRaises: boolean): const unblocked = (f: Finding) => fixableRaises || role !== 'adversarial-native' || !(f.fixable || f.label.toUpperCase() === 'FIXABLE' || /(? { const ls = [...raw.matchAll(SEVERITY_FIELD)].flatMap(m => (m[1] ?? m[2]!).match(FIELD_LABELS)!); return ls.length === 1 && !!rank(ls[0]); }; - const shaped = (f: Finding) => f.section || f.heading || [...f.raw.split(' | '), f.context ?? ''].some(t => t.startsWith('{') || LEAD_LABEL.test(t) || META.test(t) || !!t.match(STATED_SEVERITY) || BLOCKS_YES.test(t) - || LOCUS.test(t) || PATH_LOCUS.test(t) || (role === 'adversarial-native' && /(? f.section || f.heading || [...f.raw.split(' | '), f.context ?? ''].some(t => t.startsWith('{') || LEAD_LABEL.test(t) || META.test(t) || !!t.match(STATED_SEVERITY) || BLOCKS_YES.test(t) + || LOCUS.test(t) || PATH_LOCUS.test(t) || (tag && role === 'adversarial-native' && /(? { const own = relaxed?.length === out.length && relaxed[i]!.raw === f.raw && statesNoBlocks(f.raw) && statesSeverity(f.raw) ? relaxed[i]!.label : undefined; - return { label: own ?? (unblocked(f) ? f.label : 'CRITICAL'), raw: f.raw, shaped: shaped(f) }; + return { label: own ?? (unblocked(f) ? f.label : 'CRITICAL'), raw: f.raw, shaped: shaped(f), anchored: f.list || shaped(f, false) }; }); } export function parseFindings(reader: string, output: string, fixableRaises = true): Array<{ label: string; raw: string }> { - const clean = output.split('\n').some(l => /^NO FINDINGS\.?$/.test(l.trim())); - return parseLabelled(reader, output, fixableRaises).flatMap(({ label, raw, shaped }) => { - return shaped || !clean ? [{ label, raw }] : []; - }); + return parseReply(reader, output, fixableRaises, false).findings.map(({ label, raw }) => ({ label, raw })); +} + +export interface VerdictCheck { state: 'valid' | 'missing' | 'malformed'; parsed: number; declared?: number; agrees?: boolean; why?: string } +export interface ReplyFinding { label: string; raw: string; summary?: true; synthetic?: true } +const blockingRow = (f: { label: string; raw: string }) => (rank(f.label) ?? 0) >= 4 && !statesNoBlocks(f.raw); + +/** + * A reply's findings, and with asked (its render carried the verdict ask, GST-2495) the check of its REVIEW_VERDICT line + * (lib/review-verdict.ts, docs/review-policy.md#verdict-line). A well-formed verdict line never parses as a finding, and a valid + * line lowers nothing by itself. Declared more than parsed adds CRITICAL rows, one per unmatched at= location and one for the + * rest; declared fewer marks each blocking row with no anchor (no list item, heading, field, lead label, JSON or file:line) and + * no Blocks: yes a summary candidate, whether a CRITICAL or P0 word or the native voice's FIXABLE raise made it block. It still + * blocks until lead judgment lowers it with a reason. + */ +export function parseReply(reader: string, output: string, fixableRaises = true, asked = false): { findings: ReplyFinding[]; verdict?: VerdictCheck } { + const verdict = asked ? parseVerdict(output) : undefined; + const text = asked ? withoutVerdictLines(output) : output; + const clean = text.split('\n').some(l => /^NO FINDINGS\.?$/.test(l.trim())); + const rows = parseLabelled(reader, text, fixableRaises).filter(r => r.shaped || !clean); + if (verdict?.state !== 'valid') { + const findings = rows.map(({ label, raw }) => ({ label, raw })); + return { findings, ...(verdict ? { verdict: { state: verdict.state, parsed: findings.filter(blockingRow).length, ...(verdict.state === 'malformed' ? { why: verdict.why } : {}) } } : {}) }; + } + const n = verdict.blocking; + const parsed = rows.filter(blockingRow).length; + const findings: ReplyFinding[] = rows.map(f => ({ label: f.label, raw: f.raw, ...(n < parsed && blockingRow(f) && !f.anchored && !BLOCKS_YES.test(f.raw) ? { summary: true as const } : {}) })); + if (n > parsed) { + const loci = new Set(rows.filter(blockingRow).map(f => lineLocus(f.raw))); + const unmatched = verdict.at.map(a => a.replace(/^\.\//, '')).filter(a => !loci.has(a)).slice(0, n - parsed); + const rest = n - parsed - unmatched.length; + const note = `REVIEW_VERDICT declared blocking=${n}, but collect parsed ${parsed} blocking finding${parsed === 1 ? '' : 's'} in this reply`; + for (const a of unmatched) findings.push({ label: 'CRITICAL', raw: `${a}: ${note}; this declared blocker names this location`, synthetic: true }); + if (rest > 0) findings.push({ label: 'CRITICAL', raw: `${note}; ${rest} declared blocker${rest === 1 ? '' : 's'} with no location named`, synthetic: true }); + } + return { findings, verdict: { state: 'valid', parsed, declared: n, agrees: n === parsed } }; } /** @@ -361,19 +394,23 @@ const hasCleanMarker = (reader: string, output: string) => output.replace(/\r\n/ * review: false. With unavailable (the outside voice only) the output is its failure text, recorded as missing coverage. With a * failed tree check (GST-482: the reply reviewed another checkout, or names none) nothing is merged and the output is no review. */ -export function collect(ledger: string, reader: string, output: string, mergedFile: string, outputFile?: string, unavailable?: string, tree?: TreeCheck, raises = true): { sha: string; lines: MergedLine[]; review: boolean } { +export function collect(ledger: string, reader: string, output: string, mergedFile: string, outputFile?: string, unavailable?: string, tree?: TreeCheck, raises = true): { sha: string; lines: MergedLine[]; review: boolean; verdict?: VerdictCheck } { const sha = promptHash(output); - const prior = readLedger(ledger).filter(e => e.event === 'output' && e.reader === reader).length; + const events = readLedger(ledger); + const prior = events.filter(e => e.event === 'output' && e.reader === reader).length; const wrongTree = !unavailable && tree !== undefined && !tree.ok; - const lines = unavailable || wrongTree ? [] : parseFindings(reader, output, raises).map((f, i) => { + const reply = unavailable || wrongTree ? { findings: [] } : parseReply(reader, output, raises, lastRendered(events, reader)?.verdict === 1); + let parsedNo = 0, addedNo = 0; + const lines = reply.findings.map(f => { const s = stated(f.raw); - return { id: `${reader}#${prior ? `${prior + 1}.` : ''}${i + 1}`, reader, label: f.label, ...(s ? { stated: s } : {}), ...(summaryCandidate(f.raw) ? { summary_candidate: true as const } : {}), raw: f.raw, output_sha256: sha }; + const id = `${reader}#${prior ? `${prior + 1}.` : ''}${f.synthetic ? `v${++addedNo}` : ++parsedNo}`; + return { id, reader, label: f.label, ...(s ? { stated: s } : {}), ...(f.summary || summaryCandidate(f.raw) ? { summary_candidate: true as const } : {}), raw: f.raw, output_sha256: sha }; }); const review = !unavailable && !wrongTree && (lines.length > 0 || hasCleanMarker(reader, output)); fs.appendFileSync(mergedFile, lines.map(l => JSON.stringify(l) + '\n').join(''), { mode: 0o600 }); appendEvent(ledger, { event: 'output', reader, sha256: sha, file: outputFile ? path.resolve(outputFile) : null, merged: path.resolve(mergedFile), ids: lines.map(l => l.id), review, ...(unavailable ? { unavailable } : {}), ...(raises ? {} : { fixable_raises: false }), - ...(tree && !unavailable ? { tree: tree.expected, reported_tree: tree.reported, tree_ok: tree.ok } : {}) }); - return { sha, lines, review }; + ...(tree && !unavailable ? { tree: tree.expected, reported_tree: tree.reported, tree_ok: tree.ok } : {}), ...('verdict' in reply && reply.verdict ? { verdict: reply.verdict } : {}) }); + return { sha, lines, review, ...('verdict' in reply && reply.verdict ? { verdict: reply.verdict } : {}) }; } /** The outside voice may fail without blocking (ship/sections/adversarial.md): its failure is recorded as unavailable coverage, never as a review. */ export const mayBeUnavailable = (reader: string) => reader.split('/')[0] === 'outside-voice'; @@ -401,7 +438,7 @@ export function judge(merged: MergedLine[], judged: JudgedLine[]): Judgment { const from = rank(m.label) ?? 0; const to = rank(target.severity); if (to === null) continue; - if (to < from) (!j.duplicate_of && j.reason?.trim() && (summaryCandidate(m.raw) || statedLowering(m.reader, m.raw, to)) ? res.dismissed : res.downgraded).push(m.id); + if (to < from) (!j.duplicate_of && j.reason?.trim() && (m.summary_candidate === true || summaryCandidate(m.raw) || statedLowering(m.reader, m.raw, to)) ? res.dismissed : res.downgraded).push(m.id); else if (j.duplicate_of) res.folded.push(m.id); else if (to > from) { res.promoted.push(m.id); if (!j.reason?.trim()) res.unexplained.push(m.id); } } @@ -472,6 +509,7 @@ export function ledgerBlockers(ledger: string): LedgerBlocker[] { const raws = new Map(); const readers = new Map(); const loci = new Map(); + const candidates = new Set(); const gone = quarantinedIds(events); for (const o of events.filter(e => e.event === 'output' && idsOf(e).some(id => !gone.has(id)))) { const lines = jsonLines(read(o.merged, `merged file of ${String(o.reader)}`), String(o.merged)) as MergedLine[]; @@ -480,6 +518,7 @@ export function ledgerBlockers(ledger: string): LedgerBlocker[] { ranks.set(id, rank(line.label) ?? 0); if (statesNoBlocks(line.raw)) unblocking.set(id, rank(line.label) ?? 0); raws.set(id, line.raw); + if (line.summary_candidate === true) candidates.add(id); readers.set(id, String(o.reader)); loci.set(id, lineLocus(line.raw)); } @@ -490,7 +529,7 @@ export function ledgerBlockers(ledger: string): LedgerBlocker[] { if (promptHash(text) !== verdict.judged_sha256) fail(`judged set ${String(verdict.judged)} changed since judge`); for (const j of jsonLines(text, String(verdict.judged)) as JudgedLine[]) { if (j.duplicate_of) { ranks.delete(j.id); continue; } - const dismissed = !!j.reason?.trim() && (summaryCandidate(raws.get(j.id) ?? '') || statedLowering(readers.get(j.id) ?? '', raws.get(j.id) ?? '', rank(j.severity) ?? 0)); + const dismissed = !!j.reason?.trim() && (candidates.has(j.id) || summaryCandidate(raws.get(j.id) ?? '') || statedLowering(readers.get(j.id) ?? '', raws.get(j.id) ?? '', rank(j.severity) ?? 0)); ranks.set(j.id, dismissed ? rank(j.severity) ?? 0 : Math.max(ranks.get(j.id) ?? 0, rank(j.severity) ?? 0)); if (!loci.has(j.id)) loci.set(j.id, lineLocus(j.reason ?? '')); } @@ -521,12 +560,13 @@ const collectedIds = (events: LedgerEvent[]) => { return events.filter(e => e.event === 'output').flatMap(idsOf).filter(id => !gone.has(id)); }; -export interface VerifyRow { kind: 'BRIEF' | 'OUTPUT' | 'JUDGE' | 'FETCH'; reader: string; status: string; detail: string } +export interface VerifyRow { kind: 'BRIEF' | 'OUTPUT' | 'JUDGE' | 'FETCH' | 'VERDICT'; reader: string; status: string; detail: string } /** Replay every check from a finished run's ledger: briefs dispatched as rendered, outputs merged as returned, judgment without loss. */ -export function verify(ledger: string): { rows: VerifyRow[]; clean: boolean; briefs: number; voided: number; unavailable: number } { +export function verify(ledger: string): { rows: VerifyRow[]; clean: boolean; briefs: number; voided: number; unavailable: number; verdicts: { asked: number; agree: number } } { const events = readLedger(ledger); const rows: VerifyRow[] = []; + const verdicts: VerifyRow[] = []; const short = (s: unknown) => (typeof s === 'string' ? s.slice(0, 12) : '-'); // Each render opens one dispatch of its reader (a pass); its sends and outputs run until that reader's next render. const renders = events.flatMap((e, i) => (e.event === 'rendered' ? [i] : [])); @@ -594,8 +634,13 @@ export function verify(ledger: string): { rows: VerifyRow[]; clean: boolean; bri notes.push(typeof o.file === 'string' ? 'output_file_missing' : 'output_file_unrecorded'); differs.push(...ids); } else if (promptHash(text) === o.sha256) { - const parsed = parseFindings(reader, text, o.fixable_raises !== false); - const off = ids.filter((id, k) => { const m = lines.find(l => l.id === id); return !m || m.reader !== reader || parsed[k]?.label !== m.label || parsed[k]?.raw !== m.raw; }); + const asked = render?.verdict === 1; + const reply = parseReply(reader, text, o.fixable_raises !== false, asked); + const parsed = reply.findings; + const off = ids.filter((id, k) => { const m = lines.find(l => l.id === id); return !m || m.reader !== reader || parsed[k]?.label !== m.label || parsed[k]?.raw !== m.raw + || !!(parsed[k]!.summary || summaryCandidate(m.raw)) !== (m.summary_candidate === true); }); + if (reply.verdict) verdicts.push({ kind: 'VERDICT', reader: p?.label ?? reader, status: reply.verdict.state === 'valid' ? (reply.verdict.agrees ? 'AGREES' : 'DISAGREES') : reply.verdict.state.toUpperCase(), + detail: `declared=${reply.verdict.declared ?? reply.verdict.state} parsed=${reply.verdict.parsed}${reply.verdict.why ? ` why=${JSON.stringify(reply.verdict.why)}` : ''}` }); if (unavailableOutput(o) && parsed.length) { status = 'MISMATCH'; notes.push('unavailable_output_has_findings'); } else if (!unavailableOutput(o)) { if (off.length) { status = 'MISMATCH'; notes.push(`merged_line_differs=${JSON.stringify(off)}`); differs.push(...off); } @@ -651,5 +696,7 @@ export function verify(ledger: string): { rows: VerifyRow[]; clean: boolean; bri rows.push({ kind: 'FETCH', reader: `${String(s.pass)}/${String(s.stage)}#${String(s.attempt)}`, status: s.verdict === 'violation' ? (resolved ? 'RESOLVED' : 'VIOLATION') : String(s.verdict).toUpperCase(), detail: `found=${found.length}${found.length ? ` paths=${JSON.stringify(found.map(x => x.path))}` : ''}${s.partial ? ` partial=${JSON.stringify(s.partial)}` : ''}` }); } const clean = episodes.length > 0 && rows.every(r => ['MATCH', 'OK', 'VOIDED', 'UNAVAILABLE', 'SUPERSEDED', 'CLEAN', 'PARTIAL', 'RESOLVED'].includes(r.status)); - return { rows, clean, briefs: episodes.length, voided, unavailable: rows.filter(r => r.kind === 'BRIEF' && r.status === 'UNAVAILABLE').length }; + rows.push(...verdicts); + return { rows, clean, briefs: episodes.length, voided, unavailable: rows.filter(r => r.kind === 'BRIEF' && r.status === 'UNAVAILABLE').length, + verdicts: { asked: verdicts.length, agree: verdicts.filter(r => r.status === 'AGREES').length } }; } diff --git a/lib/review-pass.ts b/lib/review-pass.ts index 4c8cae78baa..f20b1f72b40 100644 --- a/lib/review-pass.ts +++ b/lib/review-pass.ts @@ -50,6 +50,8 @@ export interface PassReader { fetch_audit?: { policy_digest: string; events: number; events_sha256: string; hits: FetchHit[]; verdict: 'clean' | 'violation'; enforced: boolean }; /** A stage rerun after a fetch violation (lib/review-sweep.ts): attempt 2 of the slot, and the reader it replaced points at it. */ attempt?: number; superseded_by?: string; + /** An outside voice retried after a cyber_policy refusal (R95, planCyberRetry): the reader it retries, and whether it gets the read-only brief. */ + retry_of?: string; read_only?: true; /** Set when the stage's sweep found a fetch: the reply's new home under /quarantine/; it is never merged, judged or returned. */ quarantined?: { file: string; at: string }; path?: string; output?: string; error?: string; state_at?: string; @@ -221,6 +223,7 @@ export function renderStage(m: Manifest, stage: Stage, t: SectionTexts, diffFor: policy_exclude: r.policy_exclude, ...(m.disclosure ? { disclosure: m.disclosure, keep: r.keep?.map(shellQuote).join(' ') } : {}), ...(m.disclosure && r.excerpt_file ? { excerpt_file: r.excerpt_file.file, excerpt_bytes: String(r.excerpt_file.bytes), excerpt_sha256: r.excerpt_file.sha256, excerpt_files: String(r.excerpt_file.files) } : {}) }; if (role === 'specialist') slots.checklist = path.join(m.checklist_root, 'review/specialists', `${r.name}.md`); + if (r.read_only) slots.read_only = '1'; let findingsSha: string | undefined; if (role === 'red-team') { const findings = specialistFindings(m.merged); @@ -250,18 +253,45 @@ export function renderStage(m: Manifest, stage: Stage, t: SectionTexts, diffFor: Object.assign(slots, { checklist, brief, classes: (r.classes ?? []).join(','), diff_base: r.diff_base ?? m.diff_base }); targeted = { classes: parseClassList(slots.classes!), rules: TARGETED_RULES, brief_sha: targetedBriefSha(checklist), diff_base: slots.diff_base, ...targetedRead(process.cwd(), slots.diff_base!) }; } - const text = withWorkspace(renderBrief(role, slots, t), workdir, m.fetch_policy); + const text = withWorkspace(renderBrief(role, slots, t), workdir, m.fetch_policy, { verdict: true }); const file = path.join(briefs, briefFile(role, r.name)); fs.writeFileSync(file, text, { mode: 0o600 }); const sha = promptHash(text); const bytes = Buffer.byteLength(text); - appendEvent(m.ledger, { event: 'rendered', reader: readerKey(role, r.name), role, name: r.name ?? null, file, sha256: sha, bytes, pass: m.pass, stage, workdir, tree, ...(findingsSha ? { findings_sha256: findingsSha } : {}), ...targeted, ...slice, ...(disclosureDigest(m.disclosure) ? { exclude: disclosureDigest(m.disclosure) } : {}), ...(m.fetch_policy ? { readers: m.fetch_policy.digest } : {}) }); + appendEvent(m.ledger, { event: 'rendered', reader: readerKey(role, r.name), role, name: r.name ?? null, file, sha256: sha, bytes, pass: m.pass, stage, workdir, tree, verdict: 1, ...(findingsSha ? { findings_sha256: findingsSha } : {}), ...targeted, ...slice, ...(disclosureDigest(m.disclosure) ? { exclude: disclosureDigest(m.disclosure) } : {}), ...(m.fetch_policy ? { readers: m.fetch_policy.digest } : {}) }); Object.assign(r, { file, sha256: sha, bytes, chunks: chunkCount(text), state: 'rendered', tree, ...(findingsSha ? { findings_sha256: findingsSha } : {}) }); done.push(r); } return done; } +/** + * R95 (2026-11-13): after OpenAI refuses the outside voice under cyber_policy, the brief goes once to GPT-6 Astra reworded as a + * read-only correctness review, then once to Gemini 4 Carbon unchanged; never the same brief to another OpenAI model. + */ +export const CYBER_RETRIES: ReadonlyArray<{ name: string; model: PassModel; read_only?: true }> = [ + { name: 'astra-read-only', model: { model_id: 'openai/gpt-6-astra', reasoning_mode: 'high' }, read_only: true }, + { name: 'gemini-4-carbon', model: { model_id: 'google/gemini-4-carbon', reasoning_mode: 'high' } }, +]; + +/** + * Plan the next R95 attempt after `refused`, which the refused reader then points at; null once the chain is spent. A step whose + * model family is in `taken` (the lane's and the native voice's, from the pass's voice-models.json) is skipped, since Step 11 refuses + * an outside voice of either family; with no step left the second-family read is missing. + */ +export function planCyberRetry(m: Manifest, refused: PassReader, taken: ReadonlyArray = []): PassReader | null { + const step = CYBER_RETRIES.slice(CYBER_RETRIES.findIndex(x => x.name === refused.name) + 1).find(x => !taken.includes(x.model.model_id.split('/')[0]!.toLowerCase())); + if (!step || refused.role !== 'outside-voice') return null; + const reader = readerKey('outside-voice', step.name); + const existing = m.readers.find(x => x.reader === reader); + if (existing) return existing.quarantined ? null : existing; + const { file: _f, sha256: _s, bytes: _b, chunks: _c, findings_sha256: _fs, tree: _t, path: _p, output: _o, error: _e, state_at: _a, quarantined: _q, fetch_audit: _fa, attempt: _at, superseded_by: _sb, model: _m, cross_family: _cf, read_only: _ro, ...plan } = refused; + const next: PassReader = { ...plan, reader, name: step.name, title: `ship ${m.pass} ${reader}`, state: 'planned', model: { ...step.model }, retry_of: refused.reader, ...(step.read_only ? { read_only: true as const } : {}) }; + refused.superseded_by = reader; + m.readers.push(next); + return next; +} + export const chunkCount = (text: string) => Math.max(1, Math.ceil(text.length / CHUNK_CHARS)); export function chunkOf(text: string, index: number): string { if (!Number.isInteger(index) || index < 0 || index >= chunkCount(text)) throw new BriefError(`chunk index ${index} is outside 0..${chunkCount(text) - 1}`); diff --git a/lib/review-verdict.ts b/lib/review-verdict.ts new file mode 100644 index 00000000000..373ccf6a1ea --- /dev/null +++ b/lib/review-verdict.ts @@ -0,0 +1,51 @@ +/** + * review-verdict: the one machine-readable line every blocking reader's reply carries (GST-2495), right under its + * REVIEWED_TREE line: `REVIEW_VERDICT: blocking=[ at=:[,:...]]`, n being how many findings + * in the reply block the merge. collect reads it only when the reader's render asked for it (the `verdict: 1` render + * event), so a reply to an older brief, or an old ledger, parses exactly as before. Lines inside fenced code blocks are + * ignored, byte-identical repeats count once, and differing repeats are malformed. docs/review-policy.md#verdict-line. + */ + +export type Verdict = { state: 'valid'; blocking: number; at: string[] } | { state: 'missing' } | { state: 'malformed'; why: string }; + +const FENCE = /^\s*(`{3,}|~{3,})/; +const LOCUS = /^[\w./-]+:\d+$/; +const GRAMMAR = /^REVIEW_VERDICT:\s*blocking=(\d+)(?:\s+at=(\S+))?$/; + +/** A line that tries to be the verdict line, wrappers removed (list marker, heading mark, whole-line bold or backticks), or null. */ +export function verdictAttempt(line: string): string | null { + let t = line.trim().replace(/^(?:[-*>]\s+|\d+[.)]\s+|#+\s+)/, ''); + for (const w of ['**', '`']) if (t.length > 2 * w.length && t.startsWith(w) && t.endsWith(w)) t = t.slice(w.length, -w.length).trim(); + t = t.replace(/^\*\*REVIEW_VERDICT:\*\*/, 'REVIEW_VERDICT:'); + return /^REVIEW_VERDICT\s*(?:[:=]|blocking\b)/i.test(t) ? t : null; +} + +/** Each line of a reply, marked when it is a verdict attempt outside a code fence. */ +function scan(output: string): Array<{ line: string; attempt: string | null }> { + let fence: string | null = null; + return output.replace(/\r\n/g, '\n').split('\n').map(line => { + const f = FENCE.exec(line)?.[1]; + if (f && (fence === null || f[0] === fence[0])) { fence = fence === null ? f : null; return { line, attempt: null }; } + return { line, attempt: fence === null ? verdictAttempt(line) : null }; + }); +} + +export function parseVerdict(output: string): Verdict { + const attempts = [...new Set(scan(output).flatMap(l => (l.attempt === null ? [] : [l.attempt])))]; + if (!attempts.length) return { state: 'missing' }; + if (attempts.length > 1) return { state: 'malformed', why: `${attempts.length} different REVIEW_VERDICT lines` }; + const m = GRAMMAR.exec(attempts[0]!); + if (!m) return { state: 'malformed', why: `not REVIEW_VERDICT: blocking=[ at=:,...]: ${JSON.stringify(attempts[0]!.slice(0, 120))}` }; + const blocking = Number(m[1]); + if (blocking > 99) return { state: 'malformed', why: `blocking=${blocking} is over 99` }; + const at = m[2] ? m[2].split(',') : []; + if (at.some(a => !LOCUS.test(a))) return { state: 'malformed', why: `at= holds something other than :: ${m[2]}` }; + if (at.length > blocking) return { state: 'malformed', why: `at= names ${at.length} locations for blocking=${blocking}` }; + return { state: 'valid', blocking, at }; +} + +/** + * The reply with every well-formed verdict line outside a code fence removed, so the line never joins or colours a neighbouring + * finding. A malformed attempt stays in the text, so a finding written on that line is still parsed and never lost. + */ +export const withoutVerdictLines = (output: string) => scan(output).filter(l => l.attempt === null || !GRAMMAR.test(l.attempt)).map(l => l.line).join('\n'); diff --git a/lib/sealed-guard.ts b/lib/sealed-guard.ts index 773671b6a3d..38ebcee6f66 100644 --- a/lib/sealed-guard.ts +++ b/lib/sealed-guard.ts @@ -41,7 +41,9 @@ * combined-diff matching; any lookup failure scans everything. */ import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; +import * as os from 'node:os'; import * as path from 'node:path'; import { sha256Hex, writeReceipt } from './egress-receipt'; import { containedRelative, globToRegExp } from './ship-policy'; @@ -88,11 +90,63 @@ export function sealedErrors(raw: unknown): Array<{ path: string; message: strin return errors; } +const GIT_TIMEOUT_MS = 120_000; + function git(repoRoot: string, args: string[], input?: string, encoding: BufferEncoding = 'utf8'): { ok: boolean; out: string; err: string } { - const r = spawnSync('git', args, { cwd: repoRoot, encoding, input, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 }); + const r = spawnSync('git', args, { cwd: repoRoot, encoding, input, timeout: GIT_TIMEOUT_MS, maxBuffer: 256 * 1024 * 1024 }); return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() }; } +/** Test seams for the streamed reads: read size, git binary and timeout. */ +export interface GitStreamOptions { chunkBytes?: number; bin?: string; timeoutMs?: number } +type GitStdin = { text: string } | { file: string } | null; + +/** Runs git with stdout written to a private temp file, so no output size meets spawnSync's maxBuffer, and passes that file to `use` only after git exits 0. A spawn error, timeout, signal or non-zero exit throws `git

Agent notes `, the `## Approvals` output (Capy) with its Plan line, -and the Pre-Landing Review section's `REVIEW_LOOP:`, `Gate edits:`, `Ruled note:`, `Review-loop exception:` +and the Pre-Landing Review section's `REVIEW_LOOP:`, `Gate edits:`, `Ruled note:`, `Gate disposition:`, `Review-loop exception:` and exception lines. `gstack-ship-receipt write` adds the receipt here; never type it.>
diff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmpl index 6ea65e08445..4fe6e0d5d70 100644 --- a/ship/sections/pr-body.md.tmpl +++ b/ship/sections/pr-body.md.tmpl @@ -107,7 +107,7 @@ ZERO-RUN lane never reaches this body unresolved.> ## Pre-Landing Review +with its ruler and reason; each `Gate disposition: …` line `gstack-approvals dispositions` prints, verbatim; finish's `MECHANICAL: x` as `Mechanical retake: x` and its `UID_SIDECAR: x (beside y)` as `Godot UID sidecar: x (beside y)`. `gstack-ship-receipt write --body` refuses a body missing one.>
Agent notes `, the `## Approvals` output (Capy) with its Plan line, -and the Pre-Landing Review section's `REVIEW_LOOP:`, `Gate edits:`, `Ruled note:`, `Review-loop exception:` +and the Pre-Landing Review section's `REVIEW_LOOP:`, `Gate edits:`, `Ruled note:`, `Gate disposition:`, `Review-loop exception:` and exception lines. `gstack-ship-receipt write` adds the receipt here; never type it.>
diff --git a/spec/SKILL.md b/spec/SKILL.md index e2e9d924f9b..5bd89c8e06f 100644 --- a/spec/SKILL.md +++ b/spec/SKILL.md @@ -622,7 +622,8 @@ Add to the standard template: route them to `/office-hours` first. `/spec` is for work that has already passed the "is this worth building" bar. - **After `/spec`:** if the spec describes architectural or design risk that - needs review before implementation starts, suggest `/autoplan`. + needs review before implementation starts, suggest `/plan-eng-review` (or + `/autoplan` for the full review gauntlet). - **For implementation:** the issue itself is the handoff. The implementer can open it and execute without re-asking the user. **Implementation model:** relay model/source from `"$HOME/.claude/skills/gstack/bin/gstack-models" resolve --role implementation --provider anthropic`. gstack cannot change this session. Recommend only; no spawn or config edits unless asked. On error, relay its repair, not a model. [Policy setup](https://github.com/garrytan/gstack/blob/main/docs/model-policy.md). diff --git a/spec/SKILL.md.tmpl b/spec/SKILL.md.tmpl index 58b8eb7d293..aad712c2220 100644 --- a/spec/SKILL.md.tmpl +++ b/spec/SKILL.md.tmpl @@ -474,7 +474,8 @@ Add to the standard template: route them to `/office-hours` first. `/spec` is for work that has already passed the "is this worth building" bar. - **After `/spec`:** if the spec describes architectural or design risk that - needs review before implementation starts, suggest `/autoplan`. + needs review before implementation starts, suggest `/plan-eng-review` (or + `/autoplan` for the full review gauntlet). - **For implementation:** the issue itself is the handoff. The implementer can open it and execute without re-asking the user. {{IMPLEMENTATION_MODEL_HANDOFF}} diff --git a/test-audit/SKILL.md b/test-audit/SKILL.md index 5574e5e9174..e86c478586b 100644 --- a/test-audit/SKILL.md +++ b/test-audit/SKILL.md @@ -102,7 +102,7 @@ it — it never blocks the workflow. Find existing tests that cost more than they protect, prove it with evidence, and retire them only in approved batches. Optimize for confidence, not deletion count; a few well-evidenced candidates beat a large speculative list, and none is a valid -result. `/review`, `/ship`, `/qa` and `/autoplan` apply the same bar to new +result. `/review`, `/ship`, `/qa` and `/plan-eng-review` apply the same bar to new tests in a diff; this skill is the whole-repo sweep for tests that already exist. Usage: `/test-audit [path ...] [--since ] [--max-candidates N]` (default: whole diff --git a/test-audit/SKILL.md.tmpl b/test-audit/SKILL.md.tmpl index 4c66b7b7c71..b063cd16d72 100644 --- a/test-audit/SKILL.md.tmpl +++ b/test-audit/SKILL.md.tmpl @@ -26,7 +26,7 @@ allowed-tools: Find existing tests that cost more than they protect, prove it with evidence, and retire them only in approved batches. Optimize for confidence, not deletion count; a few well-evidenced candidates beat a large speculative list, and none is a valid -result. `/review`, `/ship`, `/qa` and `/autoplan` apply the same bar to new +result. `/review`, `/ship`, `/qa` and `/plan-eng-review` apply the same bar to new tests in a diff; this skill is the whole-repo sweep for tests that already exist. Usage: `/test-audit [path ...] [--since ] [--max-candidates N]` (default: whole diff --git a/test/autoplan-bounded-journal.test.ts b/test/autoplan-bounded-journal.test.ts index 087a7500909..768d50c2a28 100644 --- a/test/autoplan-bounded-journal.test.ts +++ b/test/autoplan-bounded-journal.test.ts @@ -77,7 +77,7 @@ describe('A2: the guard decides on a journal larger than its shrunk bounds', () const output = await bounded(() => f.hook(input), RECORD, 4 * 1024); expect(codeOf(output)).toBe('oversized_invocation'); expect(denial(output)).toContain('retained-data bound'); - expect(denial(output)).toContain('/plan-ceo-review, then /plan-devex-review by hand'); + expect(denial(output)).toContain('/plan-ceo-review, then /plan-devex-review, then /plan-eng-review'); expect(f.log().at(-1)).toMatchObject({ decision: 'deny', disposition: 'fallback', code: 'oversized_invocation' }); await bounded(() => expect(ownedRetainedLimit()).toBe(OWNED_RETAINED_MAX_BYTES), RECORD, OWNED_RETAINED_MAX_BYTES * 4); }); @@ -157,7 +157,7 @@ describe('A2: append-tolerant reads with prefix identity', () => { test('a journal that shrinks between two reads is an identity denial', async () => { const { output } = await twoReads(file => fs.truncateSync(file, Math.floor(fs.statSync(file).size / 2))); expect(codeOf(output)).toBe('identity'); - expect(denial(output)).toContain('/plan-ceo-review, then /plan-devex-review by hand'); + expect(denial(output)).toContain('/plan-ceo-review, then /plan-devex-review, then /plan-eng-review'); }); test('the reader itself: a changed prefix is rewritten, fewer bytes than the prefix is identity', () => { diff --git a/test/autoplan-guard-reasons.test.ts b/test/autoplan-guard-reasons.test.ts index 39963056b2f..6154d918f98 100644 --- a/test/autoplan-guard-reasons.test.ts +++ b/test/autoplan-guard-reasons.test.ts @@ -30,7 +30,7 @@ describe('guard reason inventory', () => { if (reason.disposition === 'unverified') expect(text).toContain('Phase-report enforcement was skipped for this call'); if (reason.disposition === 'corrective') expect(text).not.toContain(FALLBACK); } - expect(FALLBACK).toContain('/plan-ceo-review, then /plan-devex-review by hand'); + expect(FALLBACK).toContain('/plan-ceo-review, then /plan-devex-review, then /plan-eng-review'); expect(FALLBACK).toContain('/context-save'); expect(FALLBACK).toContain('/context-restore, then /autoplan '); }); diff --git a/test/autoplan-methodology-names.test.ts b/test/autoplan-methodology-names.test.ts index deda7685753..91f29c3d056 100644 --- a/test/autoplan-methodology-names.test.ts +++ b/test/autoplan-methodology-names.test.ts @@ -4,7 +4,7 @@ import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rm import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { createSnapshot, prepareMethodology } from '../bin/gstack-autoplan-snapshot'; -import { RETIRED_SKILLS } from '../scripts/discover-skills'; +import { AUTOPLAN_SIBLING_METHODOLOGIES } from '../scripts/discover-skills'; const ROOT = resolve(import.meta.dir, '..'); const owned: string[] = []; @@ -23,16 +23,16 @@ function fixture(phase: string, layout: string) { }); expect(generated.status, generated.stderr).toBe(0); } - // A retired skill's external render is a methodology file beside /autoplan. - const retiredInline = layout === 'inlineCodex' && RETIRED_SKILLS.includes(skill); - const source = layout === 'inlineCodex' ? join(dir, '.agents/skills', retiredInline ? 'gstack-autoplan' : `gstack-${skill}`) : join(ROOT, skill); - const fileName = retiredInline ? `${skill}.md` : 'SKILL.md'; - const target = join(dir, retiredInline ? 'gstack-autoplan' : skill); + // /autoplan reads a sibling methodology file beside its own SKILL.md on external hosts. + const siblingInline = layout === 'inlineCodex' && AUTOPLAN_SIBLING_METHODOLOGIES.includes(skill); + const source = layout === 'inlineCodex' ? join(dir, '.agents/skills', siblingInline ? 'gstack-autoplan' : `gstack-${skill}`) : join(ROOT, skill); + const fileName = siblingInline ? `${skill}.md` : 'SKILL.md'; + const target = join(dir, siblingInline ? 'gstack-autoplan' : skill); mkdirSync(target); cpSync(join(source, fileName), join(target, fileName)); // C4: Codex carves plan-ceo-review too, so an install that has sections/ copies it. // Every tier 2+ skill ships sections/preamble.md; carving is the review section. - const carved = !retiredInline && existsSync(join(source, 'sections', 'review-sections.md')); + const carved = !siblingInline && existsSync(join(source, 'sections', 'review-sections.md')); if (existsSync(join(source, 'sections'))) cpSync(join(source, 'sections'), join(target, 'sections'), { recursive: true }); if (layout === 'patchedClaude') { const result = spawnSync('bash', [join(ROOT, 'bin/gstack-patch-names'), dir, 'true'], { encoding: 'utf8', timeout: 10_000 }); diff --git a/test/autoplan-publication-hook.test.ts b/test/autoplan-publication-hook.test.ts index da97d11eea5..9635e38faff 100644 --- a/test/autoplan-publication-hook.test.ts +++ b/test/autoplan-publication-hook.test.ts @@ -156,7 +156,7 @@ describe('Autoplan hook journal-root verdicts', () => { const reason: string = output.hookSpecificOutput.permissionDecisionReason; expect(reason).toContain(`code ${code}`); expect(reason).toContain('Claude Code 2.1.284'); - expect(reason).toContain('/plan-ceo-review, then /plan-devex-review by hand'); + expect(reason).toContain('/plan-ceo-review, then /plan-devex-review, then /plan-eng-review'); expect(reason).toContain('docs/autoplan-guard-troubleshooting.md'); expect(reason).not.toContain('no missing-publication conclusion'); const records = fs.readFileSync(s.log, 'utf8').trim().split('\n').map(line => JSON.parse(line)); diff --git a/test/autoplan-publication-payload.test.ts b/test/autoplan-publication-payload.test.ts index 4716497054b..0515e426f0e 100644 --- a/test/autoplan-publication-payload.test.ts +++ b/test/autoplan-publication-payload.test.ts @@ -156,7 +156,7 @@ describe('Publication flush: a report counts only once a later journaled record f.report(f.nextMessage()); f.journal(); const output = await f.hook(next(f)); expect(codeOf(output)).toBe('publication_repeat'); - expect(denial(output)).toContain('/plan-ceo-review, then /plan-devex-review by hand'); + expect(denial(output)).toContain('/plan-ceo-review, then /plan-devex-review, then /plan-eng-review'); }); test('a denied call after the report proves the report was journaled, so the next attempt counts it', async () => { diff --git a/test/autoplan-review-discovery.test.ts b/test/autoplan-review-discovery.test.ts index 24215662c77..e701dab7711 100644 --- a/test/autoplan-review-discovery.test.ts +++ b/test/autoplan-review-discovery.test.ts @@ -8,12 +8,12 @@ import { ALL_HOST_CONFIGS } from '../hosts'; import { generateAutoplanReviewFile } from '../scripts/resolvers/composition'; import { HOST_PATHS, type TemplateContext } from '../scripts/resolvers/types'; import { E2E_TOUCHFILES } from './helpers/touchfiles'; -import { RETIRED_SKILLS } from '../scripts/discover-skills'; +import { AUTOPLAN_SIBLING_METHODOLOGIES } from '../scripts/discover-skills'; const ROOT = path.resolve(import.meta.dir, '..'); const REVIEWS = ['plan-ceo-review', 'plan-design-review', 'plan-devex-review', 'plan-eng-review']; -/** External hosts: a retired review ships beside gstack-autoplan/SKILL.md as .md (GST-1698). */ -const externalRef = (review: string) => RETIRED_SKILLS.includes(review) ? `${review}.md` : `../gstack-${review}/SKILL.md`; +/** External hosts: /autoplan reads a sibling methodology beside gstack-autoplan/SKILL.md as .md (GST-1698). */ +const externalRef = (review: string) => AUTOPLAN_SIBLING_METHODOLOGIES.includes(review) ? `${review}.md` : `../gstack-${review}/SKILL.md`; let owned: string; let rendered: string; @@ -78,8 +78,8 @@ describe('autoplan reads installed host methodology', () => { // Read the path actually emitted in the entrypoint. Resolving it from // the installed entrypoint works for copied installs and symlinked ones. const refs = [...body.matchAll(/`(\.\.\/gstack-plan-[a-z-]+\/SKILL\.md)`/g)].map(match => match[1]!); - expect([...new Set(refs)].sort()).toEqual(REVIEWS.filter(name => !RETIRED_SKILLS.includes(name)).map(externalRef).sort()); - for (const name of REVIEWS.filter(review => RETIRED_SKILLS.includes(review))) { + expect([...new Set(refs)].sort()).toEqual(REVIEWS.filter(name => !AUTOPLAN_SIBLING_METHODOLOGIES.includes(name)).map(externalRef).sort()); + for (const name of REVIEWS.filter(review => AUTOPLAN_SIBLING_METHODOLOGIES.includes(review))) { expect(body).toContain(`the file \`${name}.md\` in the installed \`/autoplan\` SKILL.md directory`); expect(body).not.toContain(`gstack-${name}/SKILL.md`); } diff --git a/test/carve-section-sharding.test.ts b/test/carve-section-sharding.test.ts index f9be6a12b1c..0f239b41394 100644 --- a/test/carve-section-sharding.test.ts +++ b/test/carve-section-sharding.test.ts @@ -18,7 +18,10 @@ describe('carved-skill cases each get a complete paid process budget', () => { const cases = [...source.matchAll(/test\('carve-section-loading-([a-z-]+)', \(\) => runCarveSectionCase\('([a-z-]+)'\), CAPTURE_LONG_MS\)/g)] .map(match => ({ id: `carve-section-loading-${match[1]}`, skill: match[2]! })); // A retired skill keeps its carve guard (its methodology still renders) but no section-loading case. - const generic = Object.values(CARVE_GUARDS).filter(guard => (guard.behavioral === 'plan' || guard.behavioral === 'prompt') && !RETIRED_SKILLS.includes(guard.skill)).map(guard => guard.skill).sort(); + // plan-eng-review's case was deleted with the GST-1698 cut; the skill came back in GST-2726 without + // it, and whether the paid case returns is the GST-1966 measurement plan's call. + const NO_LOADING_CASE = [...RETIRED_SKILLS, 'plan-eng-review']; + const generic = Object.values(CARVE_GUARDS).filter(guard => (guard.behavioral === 'plan' || guard.behavioral === 'prompt') && !NO_LOADING_CASE.includes(guard.skill)).map(guard => guard.skill).sort(); test('every generic registry entry has exactly one periodic case, under its own case id, and no external entry does', () => { expect(source).toContain("describeE2ETier('periodic')"); diff --git a/test/cso-registry-socket.test.ts b/test/cso-registry-socket.test.ts index 02352e3a049..a311d644122 100644 --- a/test/cso-registry-socket.test.ts +++ b/test/cso-registry-socket.test.ts @@ -80,7 +80,9 @@ posixDescribe('short supervised CSO registry sockets', () => { }, 15_000); test('deadline cleanup removes the whole per-call socket root without a global temp sweep', async () => { - const doomed = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 150 }); + // The watchdog takes whole seconds and cleans as soon as the deadline passes, so a deadline inside the ~1 s startup + // handshake fails it on a slow start (Free Tests 42772387147): expire it after the handshake instead. + const doomed = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 2_000 }); const survivor = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 10_000 }); const broker = new RegistryEgressBroker(doomed.socketPath, ['registry.npmjs.org'], Date.now() + 10_000, 1024 * 1024); try { diff --git a/test/cso-snapshot-state.test.ts b/test/cso-snapshot-state.test.ts index a18799a73fb..3357e8b5407 100644 --- a/test/cso-snapshot-state.test.ts +++ b/test/cso-snapshot-state.test.ts @@ -17,7 +17,7 @@ const read=fs.readdirSync.bind(fs);spyOn(fsModule,'readdirSync').mockImplementat spyOn(fsModule,'writeFileSync').mockImplementation(((target,data,...args)=>{const name=path.basename(String(target));if(name.includes('.decision.tmp.')){let decision;try{decision=JSON.parse(String(data));}catch{}if(decision?.kind==='ticket'&&decision.token===token){try{mark('choice-'+id,decision.ticket);}catch{}if(mode==='pause-before-decision'&&!triggered){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}}if(decision?.kind==='withdraw'&&mode==='pause-before-withdraw'&&!triggered){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}}return write(target,data,...args);}) as typeof fs.writeFileSync); const link=fs.linkSync.bind(fs);spyOn(fsModule,'linkSync').mockImplementation(((source,target)=>{const name=path.basename(String(target));if(mode==='wait-active'&&!triggered&&name.includes('.active.')){triggered=true;mark('doorway-'+id);waitFor('paused-H');}return link(source,target);}) as typeof fs.linkSync); const unlink=fs.unlinkSync.bind(fs);spyOn(fsModule,'unlinkSync').mockImplementation(((target)=>{const result=unlink(target),name=path.basename(String(target)),candidateToken=name.endsWith('.json')?name.slice(0,-5):'';if((mode==='pause-decision'||mode==='pause-ticket')&&!triggered&&name.includes('.decision.tmp.')&&(!token||name.startsWith(token+'.decision.tmp.'))){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}if((mode==='pause-after-candidate-cleanup'||mode==='pause-withdraw-cleanup')&&!triggered&&/^[a-f0-9]{32}$/.test(candidateToken)&&(!token||candidateToken===token)&&fs.existsSync(path.join(leases,candidateToken+'.decision'))){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}return result;}) as typeof fs.unlinkSync); -const {withLock}=await import(${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state.ts'))});let outcome='success';try{withLock(dir,()=>{const active=path.join(barrier,'work-active');try{write(active,id,{flag:'wx'});}catch{fs.appendFileSync(path.join(barrier,'overlap'),'overlap\\n');}mark('entered-'+id);if(process.env.RACE_HOLD==='1')waitFor('release-'+id);try{if(fs.readFileSync(active,'utf8')===id)fs.unlinkSync(active);}catch{}});}catch(error){outcome=String(error?.code??error);}write(path.join(barrier,'result-'+id),outcome);`;} +const {withLock}=await import(${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state.ts'))});let outcome='success';try{withLock(dir,()=>{const active=path.join(barrier,'work-active');try{write(active,id,{flag:'wx'});}catch{fs.appendFileSync(path.join(barrier,'overlap'),'overlap\\n');}mark('entered-'+id);if(process.env.RACE_HOLD==='1')waitFor('release-'+id);try{if(fs.readFileSync(active,'utf8')===id)fs.unlinkSync(active);}catch{}});}catch(error){outcome=String(error?.code??error);}const result=path.join(barrier,'result-'+id);write(result+'.tmp',outcome);fs.renameSync(result+'.tmp',result);`;} describe('CSO dirty snapshot boundary',()=>{ test('captures tracked modifications and nonignored untracked source without changing Git state',async()=>{const p=repo();fs.writeFileSync(path.join(p,'tracked.txt'),'dirty\n');fs.writeFileSync(path.join(p,'new.txt'),'untracked\n');fs.writeFileSync(path.join(p,'.gitignore'),'ignored.txt\n');fs.writeFileSync(path.join(p,'ignored.txt'),'ignored\n');const before=git(p,'status','--porcelain=v1','-z'),run=newRun(p),m=await capture(p,run.dir,'HEAD');expect(fs.readFileSync(path.join(run.dir,'snapshot','tracked.txt'),'utf8')).toBe('dirty\n');expect(fs.readFileSync(path.join(run.dir,'snapshot','new.txt'),'utf8')).toBe('untracked\n');expect(fs.existsSync(path.join(run.dir,'snapshot','ignored.txt'))).toBe(false);expect(git(p,'status','--porcelain=v1','-z')).toBe(before);expect(m.changedPaths).toContain('new.txt');}); test('records an untracked nested repository as one boundary entry instead of failing the run',async()=>{const p=repo(),inner=path.join(p,'inner');fs.mkdirSync(inner);git(inner,'init','-q');git(inner,'config','user.email','fixture@example.test');git(inner,'config','user.name','Fixture');fs.writeFileSync(path.join(inner,'f.txt'),'x\n');git(inner,'add','.');git(inner,'commit','-qm','inner');const run=newRun(p),manifest=await capture(p,run.dir,'HEAD');assertSnapshot(run.dir,manifest);const entry=manifest.entries.find(e=>e.path==='inner');expect(entry?.transformation).toBe(NESTED_REPOSITORY);expect(entry?.originalHash).toBe('not-read');expect(manifest.entries.map(e=>e.path).filter(p=>p==='tracked.txt'||p.startsWith('inner'))).toEqual(['inner','tracked.txt']);expect(manifest.changedPaths).toContain('inner');expect(fs.existsSync(path.join(run.dir,'snapshot','inner'))).toBe(false);expect(fs.existsSync(path.join(run.dir,'readable','inner'))).toBe(false);}); diff --git a/test/docs-audit-result.test.ts b/test/docs-audit-result.test.ts index 067c2607782..af056f51c52 100644 --- a/test/docs-audit-result.test.ts +++ b/test/docs-audit-result.test.ts @@ -16,8 +16,9 @@ function scratch() { return root; } -function result(output: string, auditId: string, repairOf?: { file: string; out: string }) { +function result(output: string, auditId: string, repairOf?: { file: string; out: string }, files: string[] = []) { const root = scratch(); + for (const f of files) { fs.mkdirSync(path.dirname(path.join(root, f)), { recursive: true }); fs.writeFileSync(path.join(root, f), ''); } const file = path.join(root, 'child.txt'); fs.writeFileSync(file, output); const out = repairOf?.out ?? path.join(root, 'record'); @@ -82,6 +83,58 @@ describe('gstack-docs-candidate result', () => { expect(r.written).toEqual([]); }); + test.each([ + ['a Next.js dynamic route', 'app/api/items/[id]/route.ts'], + ['a catch-all route', 'app/blog/[...slug]/page.tsx'], + ['an optional catch-all route', 'app/shop/[[...opt]]/page.tsx'], + ['a route group around a dynamic segment', 'app/(marketing)/blog/[slug]/page.tsx'], + ['a SvelteKit route', 'src/routes/blog/[slug]/+page.svelte'], + ...(process.platform === 'win32' ? [] : [['a file named with * and ?', 'docs/what-is-*this*?.md']]), + ])('%s that names a real file is a path, not a glob (#4313)', (_name, file) => { + const r = result(line({ documentation_section: SECTION, files_reviewed: ['README.md', file] }) + '\n', 'ship352b-docs-1', undefined, ['README.md', file]); + expect([r.status, r.stderr]).toEqual([0, '']); + expect(r.stdout).toContain('DOCS_RESULT: ok status=current'); + expect(JSON.parse(fs.readFileSync(path.join(r.out, 'ship352b-docs-1-result.json'), 'utf8')).files_reviewed).toEqual(['README.md', file]); + }); + + test('a route group alone was never read as a glob', () => { + const r = result(line({ documentation_section: SECTION, files_reviewed: ['app/(group)/page.tsx'] }) + '\n', 'ship352b-docs-1'); + expect(r.status).toBe(0); + }); + + test('an updated bracketed route file is accepted in files_updated too', () => { + const file = 'app/api/items/[id]/route.ts'; + const r = result(line({ documentation_section: SECTION, status: 'updated', files_updated: [file], files_reviewed: [file] }) + '\n', 'ship352b-docs-1', undefined, [file]); + expect([r.status, r.stderr]).toEqual([0, '']); + expect(r.stdout).toContain('DOCS_RESULT: ok status=updated files_updated=1'); + }); + + test.each([ + ['a bracketed path that names no file', 'app/api/items/[id]/route.ts', []], + ['a glob even when it would match a file', 'docs/*.md', ['docs/a.md']], + ['a character class even when it would match a file', 'docs/[ab].md', ['docs/a.md']], + ])('%s is still refused as a glob', (_name, listed, files) => { + const r = result(line({ documentation_section: SECTION, files_reviewed: [listed] }) + '\n', 'ship352b-docs-1', undefined, files); + expect(r.status).toBe(1); + expect(r.stdout).toContain('(DOCS_RESULT_INVALID)'); + expect(r.stdout).toContain('"files_reviewed" must list unique repo-relative files, not globs'); + expect(r.written).toEqual([]); + }); + + test('a bracketed path is looked up from the repository root when result runs in a subdirectory', () => { + const file = 'app/api/items/[id]/route.ts'; + const root = scratch(); + expect(spawnSync('git', ['init', '-q', root], { encoding: 'utf8', timeout: 20_000 }).status).toBe(0); + fs.mkdirSync(path.join(root, path.dirname(file)), { recursive: true }); + fs.writeFileSync(path.join(root, file), ''); + const sub = path.join(root, 'sub'); + fs.mkdirSync(sub); + const output = path.join(sub, 'child.txt'); + fs.writeFileSync(output, line({ documentation_section: SECTION, files_reviewed: [file] }) + '\n'); + const r = spawnSync(BIN, ['result', output, '--audit-id', 'ship352b-docs-1', '--out-dir', path.join(sub, 'record')], { cwd: sub, encoding: 'utf8', timeout: 20_000 }); + expect([r.status, r.stderr]).toEqual([0, '']); + }); + test('two keys that trim to the same name are refused, not merged', () => { const r = result(line({ documentation_section: SECTION }).replace(/}$/, ',"documentation_section ":"second"}'), 'ship352b-docs-1'); expect(r.status).toBe(1); diff --git a/test/docsync-command-grammar.test.ts b/test/docsync-command-grammar.test.ts index 0a26c7266a7..ad9743cff87 100644 --- a/test/docsync-command-grammar.test.ts +++ b/test/docsync-command-grammar.test.ts @@ -258,6 +258,29 @@ test('the docs-candidate result command is admitted only with a private output f expect(docsNativeInterface(fixture)).toContain(`${fixture.skills.split(path.sep).join('/')}/bin/gstack-docs-candidate result --audit-id --out-dir <`); }); +// Census 42748129558 (ship-docsync-store): Step 14.5 counts each launch with `gstack-docs-candidate attempt` (#4192), which +// this interface did not declare, so the parent correctly stopped before launching any audit. +test('the docs-candidate attempt command is admitted only with a private child output and a private --state .json', () => { + const helper = path.join(fixture.skills, 'bin/gstack-docs-candidate'); + const output = path.join(fixture.home, 'audit-1-output.md'); + const state = path.join(fixture.home, 'docs-attempts.json'); + for (const command of [`${helper} attempt ${output} --state ${state}`, `${helper} attempt --help`]) + expect(docsCommandAllowed(command, fixture), command).toBe(true); + for (const command of [ + `${helper} attempt ${output} --state ${path.join(fixture.repo, '.gstack/tmp/docs-attempts.json')}`, + `${helper} attempt ${output} --state ${path.join(fixture.home, 'docs-attempts.md')}`, + `${helper} attempt ${output} --state ${path.join(fixture.skills, 'bin/docs-attempts.json')}`, + `${helper} attempt ${path.join(fixture.repo, 'out.md')} --state ${state}`, + `${helper} attempt ${output}`, + `${helper} attempt --state ${state} ${output}`, + `${helper} attempt ${output} --state ${state} --exec rm`, + `${helper} attempt ${output} --out ${state}`, + `${helper} attempt --help extra`, + `~/.claude/skills/gstack/bin/gstack-docs-candidate attempt ${output} --state ${state}`, + ]) expect(docsCommandAllowed(command, fixture), command).toBe(false); + expect(docsNativeInterface(fixture)).toContain(`${fixture.skills.split(path.sep).join('/')}/bin/gstack-docs-candidate attempt --state and attempt --help`); +}); + // Train gate 39904966815 and GSTA-63's focused run joined the candidate's --help onto a line of reads; v1.91.185.0 moved the // own-call rule into the sentence naming --help and the slip came back four times (JOINED_READ_LINES below). The --help only // prints usage, so it now joins a line of reads like a Git read; every other own-call command stays alone. diff --git a/test/e2e-harness-audit.test.ts b/test/e2e-harness-audit.test.ts index 41bcd15e388..64d68b59aee 100644 --- a/test/e2e-harness-audit.test.ts +++ b/test/e2e-harness-audit.test.ts @@ -67,14 +67,15 @@ function findInteractiveSkills(): string[] { /** * Scan a test file's contents for any of the supported real-interactive * coverage patterns. Either: direct canUseTool usage in runAgentSdkTest, - * the legacy plan-mode-helpers wrapper, or the new real-PTY observation - * helper. + * the legacy plan-mode-helpers wrapper, or a real-PTY helper that answers + * the skill's native questions (observation or counting). */ function hasCanUseToolCoverage(testFile: string): boolean { const content = fs.readFileSync(testFile, 'utf-8'); if (content.includes('canUseTool')) return true; if (content.includes('runPlanModeSkillTest')) return true; if (content.includes('runPlanSkillObservation')) return true; + if (content.includes('runPlanSkillCounting')) return true; return false; } diff --git a/test/eng-review-routing.test.ts b/test/eng-review-routing.test.ts index 92215bfd9a6..6c8372d7d8b 100644 --- a/test/eng-review-routing.test.ts +++ b/test/eng-review-routing.test.ts @@ -158,7 +158,7 @@ describe('engineering review routing contracts', () => { test('#3106: an unpersisted review gets no saved credit; /ship names the PERSIST: line or a rerun', () => { const ctx = (skillName: string) => ({ skillName, tmplPath: `${skillName}/SKILL.md.tmpl`, host: 'claude', paths: HOST_PATHS.claude } as TemplateContext); const ship = compact(generateReviewDashboard(ctx('ship'))); - expect(ship).toContain('With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only eng review printed, or rerun /autoplan"'); + expect(ship).toContain('With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only /plan-eng-review printed, or rerun it"'); expect(ship).toContain('docs/troubleshooting.md#plan-eng-review-not-persisted'); expect(generateReviewDashboard(ctx('plan-eng-review'))).not.toContain('PERSIST:'); const gate = compact(generateExitPlanModeGate(ctx('plan-eng-review'))); diff --git a/test/fixtures/cyber-policy/README.md b/test/fixtures/cyber-policy/README.md new file mode 100644 index 00000000000..b79906fa16a --- /dev/null +++ b/test/fixtures/cyber-policy/README.md @@ -0,0 +1,5 @@ +# cyber_policy refusal fixtures + +`capy-latest-error.txt` is the `latest_error` Capy reported, verbatim, for GBRA-392's /ship outside voice +(subagent 7, "ship ship-8903-1-p2 outside-voice", openai/gpt-6.1-sol, status `failed`, 2026-11-13). The same +string came back for every Sol and Astra refusal in the org drive's handoffs/review-refusals-2026-11-13. diff --git a/test/fixtures/cyber-policy/capy-latest-error.txt b/test/fixtures/cyber-policy/capy-latest-error.txt new file mode 100644 index 00000000000..d6d2d3c3ec1 --- /dev/null +++ b/test/fixtures/cyber-policy/capy-latest-error.txt @@ -0,0 +1 @@ +OpenAI key declined the request: cyber_policy: This content was flagged for possible cybersecurity risk. If this seems wrong, try rephrasing your request. If you’re doing authorized security work that requires more cyber permissive safeguards, apply for Daybreak access via https://platform.openai.com/settings/organization/status-and-access before retrying. diff --git a/test/fixtures/golden/agy-ship-SKILL.md b/test/fixtures/golden/agy-ship-SKILL.md index 5f1f969a619..9cfd1db8b2c 100644 --- a/test/fixtures/golden/agy-ship-SKILL.md +++ b/test/fixtures/golden/agy-ship-SKILL.md @@ -396,7 +396,7 @@ and outside_status; retain partial coverage. These details do not clear Eng Revi **3. Choose the historical verdict.** CLEARED requires the selected Eng Review to be `clean`, within 7 days and fresh under step 2. Otherwise report NOT CLEARED -and its missing, stale or open-issue reason. With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only eng review printed, or rerun /autoplan" (docs/troubleshooting.md#plan-eng-review-not-persisted). If `skip_eng_review` is true, show +and its missing, stale or open-issue reason. With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only /plan-eng-review printed, or rerun it" (docs/troubleshooting.md#plan-eng-review-not-persisted). If `skip_eng_review` is true, show "SKIPPED (global)" for Eng Review and CLEARED for this dashboard. This verdict never skips Step 9 or its finding, approval and convergence gates. Continue Step 1 even when history is NOT CLEARED. @@ -424,7 +424,7 @@ VERDICT: {CLEARED or NOT CLEARED} — {reason} An outside review with status `unverified` or `unavailable` is missing coverage, never a pass. -Over 200 lines, `DIFF:` recommends `/autoplan`. `SCOPE: frontend=true` (from +Over 200 lines, `DIFF:` recommends `/plan-eng-review` or `/autoplan`. `SCOPE: frontend=true` (from `gstack-diff-scope `) (Lit or htm templates in .ts/.js count) with no design review: mention "Design Review: static (no preview declared) — Step 9 runs the lite check only; consider /design-review on a served page for a visual audit." Continue to Step 2 without asking; Step 9 applies the review gates. diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md index a1e64ae47ad..1ddec86b5e4 100644 --- a/test/fixtures/golden/claude-ship-SKILL.md +++ b/test/fixtures/golden/claude-ship-SKILL.md @@ -395,7 +395,7 @@ and outside_status; retain partial coverage. These details do not clear Eng Revi **3. Choose the historical verdict.** CLEARED requires the selected Eng Review to be `clean`, within 7 days and fresh under step 2. Otherwise report NOT CLEARED -and its missing, stale or open-issue reason. With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only eng review printed, or rerun /autoplan" (docs/troubleshooting.md#plan-eng-review-not-persisted). If `skip_eng_review` is true, show +and its missing, stale or open-issue reason. With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only /plan-eng-review printed, or rerun it" (docs/troubleshooting.md#plan-eng-review-not-persisted). If `skip_eng_review` is true, show "SKIPPED (global)" for Eng Review and CLEARED for this dashboard. This verdict never skips Step 9 or its finding, approval and convergence gates. Continue Step 1 even when history is NOT CLEARED. @@ -423,7 +423,7 @@ VERDICT: {CLEARED or NOT CLEARED} — {reason} An outside review with status `unverified` or `unavailable` is missing coverage, never a pass. -Over 200 lines, `DIFF:` recommends `/autoplan`. `SCOPE: frontend=true` (from +Over 200 lines, `DIFF:` recommends `/plan-eng-review` or `/autoplan`. `SCOPE: frontend=true` (from `gstack-diff-scope `) (Lit or htm templates in .ts/.js count) with no design review: mention "Design Review: static (no preview declared) — Step 9 runs the lite check only; consider /design-review on a served page for a visual audit." Continue to Step 2 without asking; Step 9 applies the review gates. diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.md index 8575222df20..c85fa5297a6 100644 --- a/test/fixtures/golden/codex-ship-SKILL.md +++ b/test/fixtures/golden/codex-ship-SKILL.md @@ -395,7 +395,7 @@ and outside_status; retain partial coverage. These details do not clear Eng Revi **3. Choose the historical verdict.** CLEARED requires the selected Eng Review to be `clean`, within 7 days and fresh under step 2. Otherwise report NOT CLEARED -and its missing, stale or open-issue reason. With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only eng review printed, or rerun /autoplan" (docs/troubleshooting.md#plan-eng-review-not-persisted). If `skip_eng_review` is true, show +and its missing, stale or open-issue reason. With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only /plan-eng-review printed, or rerun it" (docs/troubleshooting.md#plan-eng-review-not-persisted). If `skip_eng_review` is true, show "SKIPPED (global)" for Eng Review and CLEARED for this dashboard. This verdict never skips Step 9 or its finding, approval and convergence gates. Continue Step 1 even when history is NOT CLEARED. @@ -423,7 +423,7 @@ VERDICT: {CLEARED or NOT CLEARED} — {reason} An outside review with status `unverified` or `unavailable` is missing coverage, never a pass. -Over 200 lines, `DIFF:` recommends `/autoplan`. `SCOPE: frontend=true` (from +Over 200 lines, `DIFF:` recommends `/plan-eng-review` or `/autoplan`. `SCOPE: frontend=true` (from `gstack-diff-scope `) (Lit or htm templates in .ts/.js count) with no design review: mention "Design Review: static (no preview declared) — Step 9 runs the lite check only; consider /design-review on a served page for a visual audit." Continue to Step 2 without asking; Step 9 applies the review gates. diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.md index 8ede1f6b195..60d57ecfc89 100644 --- a/test/fixtures/golden/factory-ship-SKILL.md +++ b/test/fixtures/golden/factory-ship-SKILL.md @@ -397,7 +397,7 @@ and outside_status; retain partial coverage. These details do not clear Eng Revi **3. Choose the historical verdict.** CLEARED requires the selected Eng Review to be `clean`, within 7 days and fresh under step 2. Otherwise report NOT CLEARED -and its missing, stale or open-issue reason. With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only eng review printed, or rerun /autoplan" (docs/troubleshooting.md#plan-eng-review-not-persisted). If `skip_eng_review` is true, show +and its missing, stale or open-issue reason. With no Eng Review record, say "no saved Eng Review: run the `PERSIST:` line a read-only /plan-eng-review printed, or rerun it" (docs/troubleshooting.md#plan-eng-review-not-persisted). If `skip_eng_review` is true, show "SKIPPED (global)" for Eng Review and CLEARED for this dashboard. This verdict never skips Step 9 or its finding, approval and convergence gates. Continue Step 1 even when history is NOT CLEARED. @@ -425,7 +425,7 @@ VERDICT: {CLEARED or NOT CLEARED} — {reason} An outside review with status `unverified` or `unavailable` is missing coverage, never a pass. -Over 200 lines, `DIFF:` recommends `/autoplan`. `SCOPE: frontend=true` (from +Over 200 lines, `DIFF:` recommends `/plan-eng-review` or `/autoplan`. `SCOPE: frontend=true` (from `gstack-diff-scope `) (Lit or htm templates in .ts/.js count) with no design review: mention "Design Review: static (no preview declared) — Step 9 runs the lite check only; consider /design-review on a served page for a visual audit." Continue to Step 2 without asking; Step 9 applies the review gates. diff --git a/test/fixtures/review-ledger/verdict-controls.json b/test/fixtures/review-ledger/verdict-controls.json new file mode 100644 index 00000000000..33df6496c8b --- /dev/null +++ b/test/fixtures/review-ledger/verdict-controls.json @@ -0,0 +1,43 @@ +{ + "source": "GST-2495 negative controls: handoffs/GSTA-521/probes.md lines; FOUN-298 (founderstar#926) native output with project names genericized; #3901 pass-2 excerpt; CAPY-1's qm #3567 fix-check paragraph and qm #3589 red-team sentence with identifiers reworded", + "probes": [ + "I found nothing that blocks. There are three Low findings, all FIXABLE, and none can change outcomes, draws or save replay.", + "CRITICAL: the token leak in log.ts:3 ships the API key.", + "1. **The cache key drops the tree (key.ts:3).** FIXABLE: key on the tree hash.", + "I found nothing that blocks except the token leak, and it is FIXABLE. There are two Low findings.", + "Apart from the token leak, nothing that blocks; three Low findings, all FIXABLE.", + "Nothing that blocks, but the cache key drops the tree; three Low findings, all FIXABLE.", + "I found one blocker. There are three Low findings, all FIXABLE.", + "Nothing else blocks. Blocks: the cache key drops the tree, all FIXABLE.", + "I found nothing that blocks. One finding blocks the merge: three Low findings, all FIXABLE.", + "I found nothing that blocks. The cache key drops the reviewed tree, FIXABLE.", + "I found nothing that blocks. Three Low findings, all FIXABLE; the token leak in log.ts:3 is FIXABLE.", + "I found nothing that blocks. There are two Low findings, all FIXABLE. Blocks: yes", + "I found nothing that blocks. There are three Low findings, all FIXABLE, with one exception: the migration drops user rows.", + "I found nothing that blocks. However, the API key is logged in plain text. There are two Low findings, all FIXABLE.", + "Nothing blocks, though the API key is logged; two Low findings, all FIXABLE.", + "There are two Low findings, all FIXABLE, and none of them matter though the key is logged.", + "I found nothing that blocks. The migration drops user rows on retry. There are two Low findings, all FIXABLE.", + "The migration drops user rows, but nothing blocks; two Low findings, all FIXABLE.", + "I reviewed the migration, and apart from the dropped user rows\nnothing that blocks; two Low findings, all FIXABLE.", + "Nothing blocking an unauthenticated caller from the admin route; two Low findings, all FIXABLE.", + "There are two Low findings, all FIXABLE, and nothing blocking an unauthenticated caller from the admin route.", + "Probably nothing blocks; two Low findings, all FIXABLE.", + "I think nothing should block. There are two Low findings, all FIXABLE.", + "I found one blocker, and two Low findings, all FIXABLE, none of which would block.", + "I found nothing that blocks. There are two Low findings, all FIXABLE, and one blocking issue.", + "Nothing blocks, but there is one security issue; two Low findings, all FIXABLE.", + "Nothing blocks; one critical regression and two Low findings, all FIXABLE.", + "Nothing blocks; one data-loss bug and two Low findings, all FIXABLE.", + "There are two Low findings, all FIXABLE, and nothing stops an unauthenticated caller from reading every user token.", + "All nine fixes hold under the design you gave me. I didn't find any CRITICAL defects. These are the parts I checked against the code at the reviewed head. The tree is still clean.", + "The findings are all INFORMATIONAL and none CRITICAL." + ], + "outputs": { + "foun298": "REVIEWED_TREE: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb /workspace/app\n\nI found nothing that blocks. There are three Low findings, all FIXABLE, and none can change outcomes, draws or save replay.\n\n**Scope.** I read the full source diff against 0000000a (src/content.ts, game.ts, meeting.ts, the two docs) and checked the data with scripts: ideas.json typed lines, raise_meetings.json takes, flavor.json Demo Day takes, people.json, and data/overlays/was_idea_lines.json. The four test files (tests/core_test.ts, content_lint.ts, dana_fit_check.ts, was_overlay.ts) were reviewed in summary mode only, so coverage there is reduced on purpose:\n- core_test adds tests that the new lines move no outcome (on three sets of ideas, including pivots), that typed lines are no longer than stock, and that draws still come from the stock pool.\n- content_lint now loads was_idea_lines.\n- was_overlay.ts learns path lookup for overlays.\n\n**What I checked and found correct:**\n- `typed_line` makes the same `_fresh` call as before: same pool name, key, laps, and the same default `once=false`. The callback still gets laps 0, so `used` and the rng keys don't change.\n- Below `idea_lines`, the typed lines, meeting takes and Demo Day takes are all switched off (`rule_number` check, and `take_industry()` returns \"\").\n- was_idea_lines restores the default old wants correctly. For accountants, big_cos and cities, which had no `want` before, the overlay's restored value is exactly the default own `want`, so the old screen text comes back the same.\n- No stock pool (`calls.*`, `evidence.*`, Demo Day in/out) has duplicate lines. Every typed line and take is no longer than the line it replaces, and the slots and tokens match.\n- I ran the targeted tests: `ONLY=test_idea_lines_*,test_investor_voice*` core_test PASSED with 0 failures, and content_lint was all ok.\n\n**Findings**\n\n1. **A meeting take is checked against a different line than the one it replaces at runtime.** `_validate_takes` (content.ts ~1160) compares a take's slots with the voice's `lines.open`, using a regex that allows `{Caller}`-style uppercase tokens. At runtime, `Meeting._line` (meeting.ts:36-38) runs `voiced(stock open_, take)` with `Meeting.slots`, whose regex is lowercase only. So a take can pass lint and still be dropped. When that happens the code returns the stock line, which skips the investor's own voiced `open` as well, and the player sees a generic opener with no warning. No take has slots today, so this can't happen yet. FIXABLE: validate takes against each stock `open_*` line with `Meeting.slots`, and when `voiced` rejects a take, fall through to the voice's `open` instead of returning stock. Severity: Low. Blocks: no.\n\n2. **Which typed line shows depends on the stock line's text being unique.** Both `typed_line` (game.ts ~7101) and `_demo_line` (game.ts ~12476) find the drawn line's position with `stock.find(line)`. If someone later adds a duplicate line to a stock pool, the typed line at the second copy's position never shows, and the first copy's typed line shows in its place. Nothing checks for this, so it would fail silently. There are no duplicates today. FIXABLE: reject duplicate stock lines in `_validate_shadow`, or have `_fresh` return the index it drew. Severity: Low. Blocks: no.\n\n3. **Some new support has no content behind it.** `TYPED_POOLS` and five call sites send `sideways`, `polite`, `maybe`, `paid` and `callback` through `typed_line`, but no customer type in ideas.json has lines for those pools. Only `open` and `evidence.*` are filled in. The code is harmless and is validated, but nothing uses it yet. INVESTIGATE: either fill these pools in a content follow-up or drop them from `TYPED_POOLS` until lines exist. Severity: Low. Blocks: no.\n\nRecommendation: Ship as-is because the strongest finding is the take-validation mismatch at meeting.ts:36, which can't trigger with today's slot-free takes and at worst shows a stock opener, never a wrong outcome.", + "pr3901": "REVIEWED_TREE: 7be72149fbd6d1b8e713c7c42ef4cd9ba6373e20 /workspace/gstack\n\nI found no blocking defects in this range. There are three low-severity findings, all FIXABLE, and none blocks.\n\n### Findings\n\n1. **The remote-gate route hint ignores `--no-ci-carry`** (`lib/pregate/checks/lanes.ts`, the `route` condition). The hint prints whenever `remote_gate_runs` is declared. FIXABLE. Severity: Low. Blocks: no.\n\nRecommendation: Ship as-is.", + "capy1_fix_check": "REVIEWED_TREE: cccccccccccccccccccccccccccccccccccccccc /workspace/app\n{\"severity\":\"INFORMATIONAL\",\"confidence\":7,\"path\":\"src/sync.ts\",\"line\":41,\"category\":\"fix-check\",\"summary\":\"The retry comment still names the old helper.\"}\n\nAll nine fixes hold under the design you gave me. I didn't find any CRITICAL defects. These are the parts I checked against the code at the reviewed head. The tree is still clean.", + "capy1_red_team": "REVIEWED_TREE: cccccccccccccccccccccccccccccccccccccccc /workspace/app\n{\"severity\":\"INFORMATIONAL\",\"confidence\":6,\"path\":\"src/queue.ts\",\"line\":88,\"category\":\"red-team\",\"summary\":\"A slow consumer delays the next poll by one tick.\"}\n\nThe findings are all INFORMATIONAL and none CRITICAL.", + "native_relabel_loss": "REVIEWED_TREE: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb /workspace/app\nREVIEW_VERDICT: blocking=1\n\nThe migration deletes the old rows before the copy, so a failed copy loses every note. FIXABLE.\n\nNo other CRITICAL issues.\n\nRecommendation: Fix the migration because a failed copy loses every note." + } +} diff --git a/test/fixtures/review-pins/files/lib/review-depth.ts.json b/test/fixtures/review-pins/files/lib/review-depth.ts.json index 8b2a7293c6e..9a556d9b5ba 100644 --- a/test/fixtures/review-pins/files/lib/review-depth.ts.json +++ b/test/fixtures/review-pins/files/lib/review-depth.ts.json @@ -1 +1 @@ -{"sha":"a21071a64f90bc38781fd7d6b9a65b0fe78a0466cfd1e22238bc2dc4d5f4872c","replay":"GST-1833"} +{"sha":"057c5f84b5227d6ad8c6010447875ac9f031e35a4e6ef1aaaf17726cdd797ae6","replay":"GST-2547"} diff --git a/test/fixtures/review-pins/replays/GST-2547.json b/test/fixtures/review-pins/replays/GST-2547.json new file mode 100644 index 00000000000..70fae860c76 --- /dev/null +++ b/test/fixtures/review-pins/replays/GST-2547.json @@ -0,0 +1 @@ +{"replay":"GST-2547","justification":"GST-2547 (R51: a tests-only diff gets one reviewer): lib/review-depth.ts is main's GST-1833 bytes plus one rule in planReview's light, runtime-0 branch and in leanPlan's matching branch: a tests diff, or a code diff with no runtime lines (only registered outputs), that has no forced specialist reading it gets one batched reader on its class's checklists (Testing for tests, which leaves docs and outputs out of its diff; the code checklists over the whole diff for outputs-only), so only a docs diff plans zero readers on pass 1. Preregistered no-loss criterion (written before the replay ran): over the grid below, no case loses a dispatch main planned, lowers class, depth or step depth, or changes the next step; every heavier case is a light full step on a tests or outputs-only diff that adds exactly one batched reader. Deterministic no-loss replay, no paid run, old module from origin/main bc858ffc against the new one: planReview over 186,624 cases (18 diff fixtures including docs, docs with numbers, tests, tests plus docs, a tests file on an eval path, outputs-only code, light code, gate, declared security, auth, migrations, a harness pin, unconsumed data, forced specialists and targeted gate; 6 review shapes: none, panel all, risk and off, platform on with and without the review at HEAD; 3 depth floors; the GST-967 history grid; tiers on and off): 0 lighter, 184,232 identical, 2,392 heavier, all of them one added batched reader (Testing on 1,784 tests cases, testing and security on 608 outputs-only cases). A first version merged forced specialists into that reader; this replay caught it (588 lighter cases) and the forced specialists now keep their own dispatch, as on main. No reviewer brief or checklist changes; the GST-967 and GST-972 grids hash to main's plans with the added Testing reader read back out."} diff --git a/test/fixtures/skill-md-size-allowlist.json b/test/fixtures/skill-md-size-allowlist.json index 2fa14e7d7cb..7a207307c5e 100644 --- a/test/fixtures/skill-md-size-allowlist.json +++ b/test/fixtures/skill-md-size-allowlist.json @@ -2,55 +2,55 @@ "_comment": "Generated SKILL.md files over the limit, pinned at their exact character count (#3199). test/skill-md-size-guard.test.ts fails when a pinned skill grows past its pin or shrinks below it: lower the pin when a skill shrinks and delete it once the skill is within the limit. Raising a pin is an owner decision. The shared-preamble hoist (GSTA-96) moved every tier 2+ skill's shared preamble into sections/preamble.md; the pins below are what remains.", "limit": 100000, "pins": { - "agy/gstack-autoplan": 109480, - "agy/gstack-plan-design-review": 109036, - "agy/gstack-plan-devex-review": 114864, + "agy/gstack-autoplan": 109389, + "agy/gstack-plan-design-review": 109043, + "agy/gstack-plan-devex-review": 114884, "agy/gstack-plan-eng-review": 143520, "agy/gstack-review": 104675, - "codex/gstack-autoplan": 108223, - "codex/gstack-plan-design-review": 110393, - "codex/gstack-plan-devex-review": 116372, + "codex/gstack-autoplan": 108132, + "codex/gstack-plan-design-review": 110400, + "codex/gstack-plan-devex-review": 116392, "codex/gstack-plan-eng-review": 144685, "codex/gstack-review": 104059, - "copilot/gstack-autoplan": 108923, - "copilot/gstack-plan-design-review": 109302, - "copilot/gstack-plan-devex-review": 114326, + "copilot/gstack-autoplan": 108832, + "copilot/gstack-plan-design-review": 109309, + "copilot/gstack-plan-devex-review": 114346, "copilot/gstack-plan-eng-review": 143685, "copilot/gstack-review": 104256, - "cursor/gstack-autoplan": 108155, - "cursor/gstack-plan-design-review": 107844, - "cursor/gstack-plan-devex-review": 113596, + "cursor/gstack-autoplan": 108064, + "cursor/gstack-plan-design-review": 107851, + "cursor/gstack-plan-devex-review": 113616, "cursor/gstack-plan-eng-review": 142275, "cursor/gstack-review": 122728, - "factory/gstack-autoplan": 110433, - "factory/gstack-plan-design-review": 110942, - "factory/gstack-plan-devex-review": 116959, + "factory/gstack-autoplan": 110342, + "factory/gstack-plan-design-review": 110949, + "factory/gstack-plan-devex-review": 116979, "factory/gstack-plan-eng-review": 145383, "factory/gstack-review": 126501, - "gbrain/gstack-autoplan": 108562, + "gbrain/gstack-autoplan": 108471, "gbrain/gstack-plan-eng-review": 124903, - "gemini/gstack-autoplan": 108713, - "gemini/gstack-plan-design-review": 109130, - "gemini/gstack-plan-devex-review": 114154, + "gemini/gstack-autoplan": 108622, + "gemini/gstack-plan-design-review": 109137, + "gemini/gstack-plan-devex-review": 114174, "gemini/gstack-plan-eng-review": 143518, "gemini/gstack-review": 104078, - "hermes/gstack-autoplan": 108516, + "hermes/gstack-autoplan": 108476, "hermes/gstack-plan-eng-review": 124939, - "kiro/gstack-autoplan": 107929, - "kiro/gstack-plan-design-review": 107690, - "kiro/gstack-plan-devex-review": 113448, + "kiro/gstack-autoplan": 107838, + "kiro/gstack-plan-design-review": 107697, + "kiro/gstack-plan-devex-review": 113468, "kiro/gstack-plan-eng-review": 142137, "kiro/gstack-review": 122552, - "openclaw/gstack-autoplan": 108385, + "openclaw/gstack-autoplan": 108294, "openclaw/gstack-plan-eng-review": 123418, - "opencode/gstack-autoplan": 108904, - "opencode/gstack-plan-design-review": 109158, - "opencode/gstack-plan-devex-review": 114204, + "opencode/gstack-autoplan": 108813, + "opencode/gstack-plan-design-review": 109165, + "opencode/gstack-plan-devex-review": 114224, "opencode/gstack-plan-eng-review": 143544, "opencode/gstack-review": 123350, - "slate/gstack-autoplan": 108042, - "slate/gstack-plan-design-review": 107767, - "slate/gstack-plan-devex-review": 113522, + "slate/gstack-autoplan": 107951, + "slate/gstack-plan-design-review": 107774, + "slate/gstack-plan-devex-review": 113542, "slate/gstack-plan-eng-review": 142206, "slate/gstack-review": 122640 } diff --git a/test/gbrain-detect-shape.test.ts b/test/gbrain-detect-shape.test.ts index 761b7326bcf..7cb0c6d1265 100644 --- a/test/gbrain-detect-shape.test.ts +++ b/test/gbrain-detect-shape.test.ts @@ -307,6 +307,23 @@ exit 0 } }); + it("a GBRAIN_HOME gbrain refuses reads no config, with no ~/.gbrain fallback, and still prints JSON", () => { + const tmp = mkdtempSync(join(tmpdir(), "detect-refused-")); + try { + mkdirSync(join(tmp, ".gbrain"), { recursive: true }); + writeFileSync(join(tmp, ".gbrain", "config.json"), JSON.stringify({ engine: "pglite" })); + for (const refused of ["relative/home", "/srv/../brain"]) { + const parsed = JSON.parse( + runDetect({ HOME: tmp, PATH: "/usr/bin:/bin", GSTACK_HOME: tmp, GSTACK_DETECT_NO_CACHE: "1", GBRAIN_HOME: refused }), + ) as DetectShape; + expect(parsed.gbrain_config_exists).toBe(false); + expect(parsed.gbrain_engine).toBeNull(); + } + } finally { + rmSync(tmp, { recursive: true, force: true }); + } + }); + it("exit code agrees with the JSON gbrain_local_status (no skew)", () => { // Run both surfaces against the same env and assert they never disagree. const tmp = mkdtempSync(join(tmpdir(), "detect-isok-")); diff --git a/test/gbrain-home-parity.test.ts b/test/gbrain-home-parity.test.ts new file mode 100644 index 00000000000..771a486aff9 --- /dev/null +++ b/test/gbrain-home-parity.test.ts @@ -0,0 +1,162 @@ +/** + * gbrain's config home, resolved two ways (#4325, GST-2625): bin/gstack-gbrain-home.sh for + * shell helpers and gbrainConfigDir() in lib/gbrain-exec.ts for TypeScript. Both follow + * gbrain's configDir() (src/core/config.ts in garrytan/gbrain): GBRAIN_HOME trimmed with + * JavaScript trim(), unset or blank means ~/.gbrain, and a relative value or one with a ".." + * segment is refused with no ~/.gbrain fallback. One table drives both resolvers so they + * cannot drift, and lib/checks.ts health selection is checked against two distinct homes. + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { buildGbrainEnv, gbrainConfigDir } from '../lib/gbrain-exec'; +import { healthDimensions } from '../lib/checks'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const HELPER = path.join(ROOT, 'bin', 'gstack-gbrain-home.sh'); +const HOME = '/home/fixture'; +const DEFAULT = `${HOME}/.gbrain/config.json`; + +// Every code point JavaScript trim() removes, read from the runtime rather than listed by hand. +const TRIM_SET: string[] = []; +for (let c = 0; c <= 0x10ffff; c++) { + if (c >= 0xd800 && c <= 0xdfff) continue; + if (String.fromCodePoint(c).trim() === '') TRIM_SET.push(String.fromCodePoint(c)); +} +const hex = (s: string) => [...s].map(ch => 'U+' + ch.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')).join(' '); + +const TABLE: Array<[string, string | undefined, string | null]> = [ + ['unset', undefined, DEFAULT], + ['empty', '', DEFAULT], + ['ASCII blank', ' \t\n\r\v\f ', DEFAULT], + ['NBSP only', '\u00a0', DEFAULT], + ['BOM only', '\ufeff', DEFAULT], + ['mixed Unicode blank', '\u00a0\ufeff\u2003\u3000\u2028 ', DEFAULT], + ...TRIM_SET.map((ch): [string, string, string] => [`trim() blank ${hex(ch)}`, ch, DEFAULT]), + ['NEL is not trim() whitespace', '\u0085', null], + ['zero-width space is not trim() whitespace', '\u200b', null], + ['ordinary', '/srv/brain', '/srv/brain/.gbrain/config.json'], + ['ASCII padded', ' /srv/brain \t', '/srv/brain/.gbrain/config.json'], + ['Unicode padded', '\u00a0\ufeff/srv/brain\u3000\u00a0', '/srv/brain/.gbrain/config.json'], + ['trailing slash', '/srv/brain/', '/srv/brain/.gbrain/config.json'], + ['trailing slashes', '/srv/brain///', '/srv/brain/.gbrain/config.json'], + ['root', '/', '/.gbrain/config.json'], + ['relative', 'relative/home', null], + ['dot relative', './brain', null], + ['tilde is not expanded', '~/brain', null], + ['padded relative', '\u00a0relative/home ', null], + ['parent segment', '/srv/../brain', null], + ['trailing parent segment', '/srv/brain/..', null], + ['bare parent', '..', null], + ['backslash parent segment', '/srv\\..\\brain', null], + ['drive path off Windows', 'C:\\brain', null], +]; + +function shellResolve(gbrainHome: string | undefined): string | null { + const env: Record = { PATH: process.env.PATH ?? '', HOME, LC_ALL: 'C.UTF-8' }; + if (gbrainHome !== undefined) env.GBRAIN_HOME = gbrainHome; + const r = spawnSync('bash', ['-c', '. "$1" && gstack_gbrain_config_path', 'helper', HELPER], { env, encoding: 'utf8', timeout: 10_000 }); + if (r.status === 1 && r.stdout === '') return null; + expect(r.status).toBe(0); + // The shell helper does not collapse repeated separators; they name the same file. + return path.posix.normalize(r.stdout.replace(/\n$/, '')); +} + +function tsResolve(gbrainHome: string | undefined): string | null { + const env: NodeJS.ProcessEnv = { HOME }; + if (gbrainHome !== undefined) env.GBRAIN_HOME = gbrainHome; + const dir = gbrainConfigDir(env); + return dir && path.join(dir, 'config.json'); +} + +// The expected paths are POSIX paths, and the shell helper is sourced through bash. +describe.skipIf(process.platform === 'win32')('GBRAIN_HOME parity: shell and TypeScript resolvers', () => { + test('the runtime trim() set includes NBSP and the BOM', () => { + expect(TRIM_SET).toContain('\u00a0'); + expect(TRIM_SET).toContain('\ufeff'); + }); + + for (const [name, value, expected] of TABLE) { + test(`${name}`, () => { + expect({ ts: tsResolve(value), shell: shellResolve(value) }).toEqual({ ts: expected, shell: expected }); + }); + } +}); + +const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-home-parity-')); +afterAll(() => fs.rmSync(tmp, { recursive: true, force: true })); +const stubs = path.join(tmp, 'stubs'); +fs.mkdirSync(stubs); +fs.writeFileSync(path.join(stubs, 'gbrain'), '#!/bin/sh\nexit 0\n'); +fs.chmodSync(path.join(stubs, 'gbrain'), 0o755); +function home(name: string, config?: object): string { + const dir = path.join(tmp, name); + fs.mkdirSync(path.join(dir, '.gbrain'), { recursive: true }); + if (config) fs.writeFileSync(path.join(dir, '.gbrain', 'config.json'), JSON.stringify(config)); + return dir; +} +const named = home('named', { database_url: 'postgresql://postgres:postgres@localhost:5432/named' }); +const fallback = home('default', { database_url: 'postgresql://postgres:postgres@localhost:5432/default' }); +const bare = home('bare'); +const repo = path.join(tmp, 'repo'); +fs.mkdirSync(repo); + +// The gbrain stub is an extensionless #!/bin/sh file, which windows-latest cannot launch. +describe.skipIf(process.platform === 'win32')('lib/checks.ts health selection follows GBRAIN_HOME', () => { + const gbrain = (env: NodeJS.ProcessEnv) => { + const d = healthDimensions(repo, { PATH: stubs, ...env }); + return { check: d.checks.find(c => c.dimension === 'gbrain'), missing: d.missing.find(m => m.dimension === 'gbrain')?.reason }; + }; + + test('GBRAIN_HOME names the brain that has a config, the default home has none: selected', () => { + expect(gbrain({ HOME: bare, GBRAIN_HOME: named }).check).toEqual({ + dimension: 'gbrain', command: 'timeout 5s gbrain doctor --json', source: 'PATH, $GBRAIN_HOME/.gbrain/config.json', + }); + }); + + test('GBRAIN_HOME names a brain with no config while the default home has one: not selected', () => { + expect(gbrain({ HOME: fallback, GBRAIN_HOME: bare })).toEqual({ + check: undefined, missing: 'gbrain is not on PATH or $GBRAIN_HOME/.gbrain/config.json is absent', + }); + }); + + test('a GBRAIN_HOME gbrain refuses selects nothing, with no ~/.gbrain fallback', () => { + expect(gbrain({ HOME: fallback, GBRAIN_HOME: 'relative/home' })).toEqual({ + check: undefined, missing: 'GBRAIN_HOME is relative or has a ".." segment, which gbrain refuses', + }); + }); + + test('a Unicode-blank GBRAIN_HOME means the default home', () => { + expect(gbrain({ HOME: fallback, GBRAIN_HOME: '\u00a0\ufeff' }).check?.source).toBe('PATH, ~/.gbrain/config.json'); + }); + + test('negative control: GBRAIN_HOME unset keeps the ~/.gbrain selection and wording', () => { + expect(gbrain({ HOME: fallback }).check).toEqual({ dimension: 'gbrain', command: 'timeout 5s gbrain doctor --json', source: 'PATH, ~/.gbrain/config.json' }); + expect(gbrain({ HOME: named }).check?.source).toBe('PATH, ~/.gbrain/config.json'); + expect(gbrain({ HOME: bare })).toEqual({ check: undefined, missing: 'gbrain is not on PATH or ~/.gbrain/config.json is absent' }); + }); +}); + +describe('buildGbrainEnv follows the same GBRAIN_HOME rule', () => { + const url = (env: NodeJS.ProcessEnv) => buildGbrainEnv({ baseEnv: env }).DATABASE_URL; + + test('GBRAIN_HOME selects its own brain over the default one', () => { + expect(url({ HOME: fallback, GBRAIN_HOME: named })).toBe('postgresql://postgres:postgres@localhost:5432/named'); + }); + + test('a Unicode-blank GBRAIN_HOME means the default brain', () => { + expect(url({ HOME: fallback, GBRAIN_HOME: '\u00a0' })).toBe('postgresql://postgres:postgres@localhost:5432/default'); + }); + + test('a refused GBRAIN_HOME seeds nothing, with no ~/.gbrain fallback', () => { + for (const refused of [path.relative(process.cwd(), named), `${named}/../named`, ` ${path.relative(process.cwd(), named)} `]) { + expect(url({ HOME: fallback, GBRAIN_HOME: refused })).toBeUndefined(); + } + }); + + test('negative control: GBRAIN_HOME unset seeds the default brain', () => { + expect(url({ HOME: fallback })).toBe('postgresql://postgres:postgres@localhost:5432/default'); + }); +}); diff --git a/test/gen-skill-docs.test.ts b/test/gen-skill-docs.test.ts index dbfa0b6a369..343fac44763 100644 --- a/test/gen-skill-docs.test.ts +++ b/test/gen-skill-docs.test.ts @@ -916,13 +916,13 @@ describe('REVIEW_DASHBOARD resolver', () => { }); } - test('plan-ceo-review chaining mentions eng (via /autoplan) and design reviews', () => { + test('plan-ceo-review chaining mentions eng and design reviews', () => { // Carved skill: the chaining prose lives in sections/*.md. (It used to // pass against the skeleton only because the preamble's routing-injection // rules incidentally named these skills — that prose moved into // bin/gstack-skill-start in token-reduction Phase 2.) const content = readSkillUnion('plan-ceo-review'); - expect(content).toContain('Run /autoplan next (eng review)'); + expect(content).toContain('/plan-eng-review'); expect(content).toContain('/plan-design-review'); }); @@ -932,9 +932,9 @@ describe('REVIEW_DASHBOARD resolver', () => { expect(content).toContain('/plan-ceo-review'); }); - test('plan-design-review chaining mentions eng (via /autoplan), ceo, and design skills', () => { + test('plan-design-review chaining mentions eng, ceo, and design skills', () => { const content = readSkillUnion('plan-design-review'); - expect(content).toContain('Run /autoplan next (eng review)'); + expect(content).toContain('/plan-eng-review'); expect(content).toContain('/plan-ceo-review'); expect(content).toContain('/design-shotgun'); expect(content).toContain('/design-html'); @@ -1302,7 +1302,7 @@ describe('PLAN_FILE_REVIEW_REPORT resolver', () => { expect(content).toContain('Findings'); expect(content).toContain('VERDICT'); expect(content).toContain('/plan-ceo-review'); - expect(content).toContain('| Eng Review | `/autoplan` |'); + expect(content).toContain('/plan-eng-review'); expect(content).toContain('/plan-design-review'); expect(content).toContain('/codex review'); }); diff --git a/test/gstack-browser-ensure.test.ts b/test/gstack-browser-ensure.test.ts index 31f2a684e64..4e4d9a71c7b 100644 --- a/test/gstack-browser-ensure.test.ts +++ b/test/gstack-browser-ensure.test.ts @@ -57,6 +57,97 @@ function fixture(opts: { playwright?: boolean } = {}) { const lastLine = (s: string) => s.trim().split('\n').at(-1); +// Value: protects=a runtime root with no package.json (~/.codex/skills/gstack and +// the other host roots) probes the dependencies of the gstack checkout its +// .source-path names, and only of a real gstack checkout; fails_when=the +// helper ignores the pointer, or follows an empty, stale, relative, linked or +// non-gstack one, or lets a pointer override a root's own package.json, or +// --check writes anything; why_new=no fixture had a .source-path; +// seam=none; no_claim=a real Chromium launch (Playwright is a stub). +describe('gstack-browser-ensure in a runtime root without package.json', () => { + const playwrightStub = (version: string) => + `module.exports.chromium = { launch: async () => ({ version: () => ${JSON.stringify(version)}, close: async () => {}, newPage: async () => ({ setContent: async () => {}, title: async () => "gstack smoke test" }) }) };\n`; + function runtime(checkoutName = 'checkout') { + const f = fixture({ playwright: false }); + const checkout = path.join(f.base, checkoutName); + write(path.join(checkout, 'package.json'), '{\n "name": "gstack",\n "version": "0.0.0"\n}\n'); + write(path.join(checkout, 'bin/gstack-browser-ensure'), '#!/usr/bin/env bash\n', 0o755); + write(path.join(checkout, 'node_modules/playwright/index.js'), playwrightStub('141.1.0')); + const point = (text: string) => write(path.join(f.root, '.source-path'), text); + const tree = () => walkFiles(f.base).filter(p => !p.startsWith(path.join(f.base, 'stub'))).sort(); + return { ...f, checkout, point, tree }; + } + const walkFiles = (dir: string): string[] => fs.readdirSync(dir, { withFileTypes: true }) + .flatMap(e => e.isDirectory() ? walkFiles(path.join(dir, e.name)) : [path.join(dir, e.name)]); + const unavailable = (root: string) => `BROWSER_UNAVAILABLE playwright is not installed under ${root}/node_modules`; + + for (const [label, name, eol] of [ + ['the recorded checkout', 'checkout', '\n'], + ['a checkout path with spaces', 'gstack checkout', '\n'], + ['a CRLF pointer', 'checkout', '\r\n'], + ] as const) { + test(`--check probes ${label} and writes nothing`, () => { + const f = runtime(name); + f.point(f.checkout + eol); + const files = f.tree(); + const r = f.run(['--check']); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(lastLine(r.stdout)).toBe('BROWSER_OK node 141.1.0'); + expect(f.tree()).toEqual(files); + expect(f.calls()).toBe(''); + }); + } + + test('without --check a valid pointer is a probe only, and a link to the checkout resolves to it', () => { + const f = runtime(); + const link = path.join(f.base, 'checkout-link'); + fs.symlinkSync(f.checkout, link); + f.point(link + '\n'); + const r = f.run(); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(lastLine(r.stdout)).toBe('BROWSER_OK node 141.1.0'); + expect(fs.existsSync(path.join(f.root, 'node_modules'))).toBe(false); + expect(f.calls()).toBe(''); + }); + + const refused: Array<[string, (f: ReturnType) => void]> = [ + ['an empty pointer', f => f.point('\n')], + ['a stale pointer', f => f.point(path.join(f.base, 'gone') + '\n')], + ['a relative pointer', f => f.point(path.relative(process.cwd(), f.checkout) + '\n')], + ['a pointer file that is a link', f => { write(path.join(f.base, 'elsewhere'), f.checkout + '\n'); fs.symlinkSync(path.join(f.base, 'elsewhere'), path.join(f.root, '.source-path')); }], + ['a directory whose package.json is not gstack\'s', f => { write(path.join(f.checkout, 'package.json'), '{\n "name": "left-pad"\n}\n'); f.point(f.checkout + '\n'); }], + ['a directory whose package.json is a link', f => { + write(path.join(f.base, 'real-package.json'), fs.readFileSync(path.join(f.checkout, 'package.json'), 'utf8')); + fs.rmSync(path.join(f.checkout, 'package.json')); + fs.symlinkSync(path.join(f.base, 'real-package.json'), path.join(f.checkout, 'package.json')); + f.point(f.checkout + '\n'); + }], + ['a directory without gstack-browser-ensure', f => { fs.rmSync(path.join(f.checkout, 'bin'), { recursive: true }); f.point(f.checkout + '\n'); }], + ]; + for (const [label, setUp] of refused) { + test(`--check ignores ${label} and reports the runtime root, as before`, () => { + const f = runtime(); + setUp(f); + const files = f.tree(); + const r = f.run(['--check']); + expect(r.status, r.stdout + r.stderr).toBe(1); + expect(lastLine(r.stdout)).toBe(unavailable(f.root)); + expect(f.tree()).toEqual(files); + expect(f.calls()).toBe(''); + }); + } + + test('a root with its own package.json keeps its own dependencies over a valid pointer', () => { + const f = runtime(); + write(path.join(f.root, 'package.json'), '{\n "name": "gstack"\n}\n'); + write(path.join(f.root, 'node_modules/playwright/index.js'), playwrightStub('142.2.0')); + f.point(f.checkout + '\n'); + const r = f.run(['--check']); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(lastLine(r.stdout)).toBe('BROWSER_OK node 142.2.0'); + }); +}); + describe('gstack-browser-ensure', () => { test('--check never installs: unavailable Chromium is BROWSER_UNAVAILABLE, exit 1, with the fix line and code', () => { const f = fixture(); diff --git a/test/gstack-gbrain-source-wireup.test.ts b/test/gstack-gbrain-source-wireup.test.ts index c792ff196d6..c969247ae5e 100644 --- a/test/gstack-gbrain-source-wireup.test.ts +++ b/test/gstack-gbrain-source-wireup.test.ts @@ -606,3 +606,186 @@ describe('gstack-gbrain-source-wireup without jq (B8)', () => { }); }); + +// #4325: the lock and every database call must follow GBRAIN_HOME the way +// gbrain's configDir() does. Two homes hold different database_urls; the +// GBRAIN_HOME one is the brain gbrain itself would use. +describe('gstack-gbrain-source-wireup — GBRAIN_HOME (#4325)', () => { + const DEFAULT_URL = 'postgresql://postgres:postgres@localhost:5432/default_brain'; + const NAMED_URL = 'postgresql://postgres:postgres@localhost:5433/named_brain'; + let gbrainHome: string; + + function writeConfig(dir: string, config: Record) { + fs.mkdirSync(path.join(dir, '.gbrain'), { recursive: true }); + fs.writeFileSync(path.join(dir, '.gbrain', 'config.json'), JSON.stringify(config)); + } + + function databaseCalls(): string[] { + return gbrainCalls().filter((c) => c.includes('sources add') || /^gbrain sync --source/.test(c)); + } + + beforeEach(() => { + gbrainHome = path.join(tmpHome, 'named-home'); + writeConfig(tmpHome, { engine: 'postgres', database_url: DEFAULT_URL }); + writeConfig(gbrainHome, { engine: 'postgres', database_url: NAMED_URL }); + setupGstackRepo('git@github.com:user/gstack-brain-user.git'); + makeFakeGbrain({}); + }); + + test('GBRAIN_HOME set: sources add and sync carry the GBRAIN_HOME brain, never the default one', () => { + const r = run([], { env: { GBRAIN_DATABASE_URL: '', DATABASE_URL: '', GBRAIN_HOME: gbrainHome } }); + expect(r.status).toBe(0); + const calls = databaseCalls(); + expect(calls.length).toBe(2); + for (const c of calls) { + expect(c).toContain(`[GBRAIN_DATABASE_URL=${NAMED_URL}]`); + expect(c).not.toContain(DEFAULT_URL); + } + }); + + test('negative control: GBRAIN_HOME unset still locks the default brain', () => { + const r = run([], { env: { GBRAIN_DATABASE_URL: '', DATABASE_URL: '' } }); + expect(r.status).toBe(0); + const calls = databaseCalls(); + expect(calls.length).toBe(2); + for (const c of calls) expect(c).toContain(`[GBRAIN_DATABASE_URL=${DEFAULT_URL}]`); + }); + + test('GBRAIN_HOME with surrounding whitespace resolves as gbrain trims it', () => { + const r = run([], { + env: { GSTACK_BRAIN_NO_SYNC: '1', GBRAIN_DATABASE_URL: '', DATABASE_URL: '', GBRAIN_HOME: ` ${gbrainHome} ` }, + }); + expect(r.status).toBe(0); + expect(databaseCalls()[0]).toContain(`[GBRAIN_DATABASE_URL=${NAMED_URL}]`); + }); + + test('GBRAIN_HOME config without a database_url exports nothing, so gbrain picks its own brain', () => { + writeConfig(gbrainHome, { engine: 'pglite' }); + const r = run([], { + env: { GSTACK_BRAIN_NO_SYNC: '1', GBRAIN_DATABASE_URL: '', DATABASE_URL: '', GBRAIN_HOME: gbrainHome }, + }); + expect(r.status).toBe(0); + const calls = databaseCalls(); + expect(calls.length).toBe(1); + expect(calls[0]).not.toContain('GBRAIN_DATABASE_URL='); + }); + + test('a relative GBRAIN_HOME (gbrain refuses it) never falls back to the default brain', () => { + const r = run([], { + env: { GSTACK_BRAIN_NO_SYNC: '1', GBRAIN_DATABASE_URL: '', DATABASE_URL: '', GBRAIN_HOME: 'relative/home' }, + }); + expect(r.stderr).toContain('GBRAIN_HOME'); + for (const c of gbrainCalls()) expect(c).not.toContain(DEFAULT_URL); + }); + + test('the ZeroEntropy advisory reads the GBRAIN_HOME config', () => { + writeConfig(gbrainHome, { engine: 'postgres', database_url: NAMED_URL, embedding: { recipe: 'zeroentropyai' } }); + const r = run([], { + env: { GSTACK_BRAIN_NO_SYNC: '1', GBRAIN_DATABASE_URL: '', DATABASE_URL: '', GBRAIN_HOME: gbrainHome }, + }); + expect(r.status).toBe(0); + expect(r.stderr).toContain('ZeroEntropy'); + }); +}); + +// #4325 audit: --check-target tells an operator whether an earlier wireup run +// with GBRAIN_HOME set could have written to the default brain. Read-only, and +// it never prints a database URL or any part of one. +describe('gstack-gbrain-source-wireup --check-target (#4325)', () => { + const DEFAULT_URL = 'postgresql://postgres:postgres@localhost:5432/default_brain'; + const NAMED_URL = 'postgresql://postgres:postgres@localhost:5433/named_brain'; + let gbrainHome: string; + + function writeConfig(dir: string, config: Record) { + fs.mkdirSync(path.join(dir, '.gbrain'), { recursive: true }); + fs.writeFileSync(path.join(dir, '.gbrain', 'config.json'), JSON.stringify(config)); + } + + function check(env: Record) { + const r = run(['--check-target'], { env: { GBRAIN_DATABASE_URL: '', DATABASE_URL: '', ...env } }); + const out = r.stdout + r.stderr; + for (const secret of [DEFAULT_URL, NAMED_URL, 'postgres:postgres', 'localhost', ':5432', ':5433', 'default_brain', 'named_brain', 'postgresql://']) { + expect(out).not.toContain(secret); + } + expect(gbrainCalls()).toEqual([]); + return r; + } + + beforeEach(() => { + gbrainHome = path.join(tmpHome, 'named-home'); + writeConfig(tmpHome, { engine: 'postgres', database_url: DEFAULT_URL }); + writeConfig(gbrainHome, { engine: 'postgres', database_url: NAMED_URL }); + makeFakeGbrain({}); + }); + + test('two brains with different URLs under GBRAIN_HOME → MISMATCH', () => { + const r = check({ GBRAIN_HOME: gbrainHome }); + expect(r.status).toBe(0); + expect(r.stdout).toMatch(/^TARGET: MISMATCH /m); + expect(r.stdout).toMatch(/^URL_ENV: GBRAIN_DATABASE_URL unset, DATABASE_URL unset /m); + }); + + test('GBRAIN_HOME unset → MATCH', () => { + const r = check({}); + expect(r.status).toBe(0); + expect(r.stdout).toMatch(/^TARGET: MATCH /m); + }); + + test('same URL in both configs → MATCH', () => { + writeConfig(gbrainHome, { engine: 'postgres', database_url: DEFAULT_URL }); + expect(check({ GBRAIN_HOME: gbrainHome }).stdout).toMatch(/^TARGET: MATCH /m); + }); + + test('default config without a database_url → MATCH (the old rule locked nothing)', () => { + writeConfig(tmpHome, { engine: 'pglite' }); + expect(check({ GBRAIN_HOME: gbrainHome }).stdout).toMatch(/^TARGET: MATCH /m); + }); + + test('GBRAIN_HOME has no config but the default brain has a URL → MISMATCH', () => { + fs.rmSync(path.join(gbrainHome, '.gbrain'), { recursive: true, force: true }); + expect(check({ GBRAIN_HOME: gbrainHome }).stdout).toMatch(/^TARGET: MISMATCH /m); + }); + + test('writes nothing: configs unchanged, no gstack state, no worktree', () => { + const configs = [tmpHome, gbrainHome].map((d) => path.join(d, '.gbrain', 'config.json')); + const before = configs.map((p) => fs.readFileSync(p, 'utf-8')); + check({ GBRAIN_HOME: gbrainHome }); + expect(configs.map((p) => fs.readFileSync(p, 'utf-8'))).toEqual(before); + for (const dir of [tmpHome, gbrainHome]) expect(fs.readdirSync(path.join(dir, '.gbrain'))).toEqual(['config.json']); + expect(fs.existsSync(gstackHome)).toBe(false); + expect(fs.existsSync(worktreeDir)).toBe(false); + }); +}); + +// The shared helper itself (#4325): every gstack shell read of gbrain's config +// resolves through bin/gstack-gbrain-home.sh, which follows gbrain's configDir(). +describe('bin/gstack-gbrain-home.sh (#4325)', () => { + const HELPER = path.join(ROOT, 'bin/gstack-gbrain-home.sh'); + + function configPath(gbrainHome?: string) { + const env: Record = { PATH: HERMETIC_PATH, HOME: '/home/fixture' }; + if (gbrainHome !== undefined) env.GBRAIN_HOME = gbrainHome; + const r = spawnSync('bash', ['-c', '. "$1" && gstack_gbrain_config_path', 'helper', HELPER], { + env, + encoding: 'utf8', + timeout: 10_000, + }); + return { status: r.status, out: r.stdout }; + } + + test('unset or blank GBRAIN_HOME means ~/.gbrain', () => { + for (const home of [undefined, '', ' ']) { + expect(configPath(home)).toEqual({ status: 0, out: '/home/fixture/.gbrain/config.json\n' }); + } + }); + + test('GBRAIN_HOME is trimmed and is the parent of .gbrain', () => { + expect(configPath(' /srv/brain/ ')).toEqual({ status: 0, out: '/srv/brain/.gbrain/config.json\n' }); + }); + + test('a GBRAIN_HOME gbrain refuses prints nothing and fails, with no ~/.gbrain fallback', () => { + for (const home of ['relative/home', '/srv/../brain', '/srv/brain/..']) { + expect(configPath(home)).toEqual({ status: 1, out: '' }); + } + }); +}); diff --git a/test/gstack-redact-cli.test.ts b/test/gstack-redact-cli.test.ts index 703b2a45a8e..b583e0bd961 100644 --- a/test/gstack-redact-cli.test.ts +++ b/test/gstack-redact-cli.test.ts @@ -102,6 +102,39 @@ describe("gstack-redact oversize fails closed", () => { expect(code).toBe(3); expect(stdout).toContain("too large"); }); + + // #4351: input over the 16 MiB ceiling is refused before --max-bytes is + // consulted, so --help and both errors have to say so. + test("--help names the 16 MiB ceiling that --max-bytes can't raise", () => { + const { code, stdout } = run(["--help"], ""); + expect(code).toBe(0); + expect(stdout).toContain("Input over 16 MiB is always refused"); + expect(stdout).toContain("3 HIGH present or input too large"); + }); + + test("a --from-file input over 16 MiB names the ceiling even with a bigger --max-bytes", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "redact-ceiling-")); + try { + const f = path.join(dir, "big.txt"); + fs.writeFileSync(f, ""); + fs.truncateSync(f, 16 * 1024 * 1024 + 1); + const proc = Bun.spawnSync(["bun", BIN, "--from-file", f, "--max-bytes", "33554432"], { + timeout: 30_000, + }); + expect(proc.exitCode).toBe(3); + expect(proc.stderr.toString()).toContain( + "input file too large (16777217 bytes). The limit is 16 MiB and --max-bytes can't raise it.", + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + test("stdin over 16 MiB names the ceiling even with a bigger --max-bytes", () => { + const { code, stderr } = run(["--max-bytes", "33554432"], "a".repeat(16 * 1024 * 1024 + 1)); + expect(code).toBe(3); + expect(stderr).toContain("stdin too large. The limit is 16 MiB and --max-bytes can't raise it."); + }); }); describe("gstack-redact argv dispatch", () => { diff --git a/test/gstack-ship-receipt-docs.test.ts b/test/gstack-ship-receipt-docs.test.ts index 927ab01fbab..d7b310d46bc 100644 --- a/test/gstack-ship-receipt-docs.test.ts +++ b/test/gstack-ship-receipt-docs.test.ts @@ -145,7 +145,7 @@ describe('E11: the documentation audit record and the doc caps', () => { const receipt = extractReceipt(fs.readFileSync(body, 'utf8')); expect(receipt.errors).toEqual([]); expect((receipt.receipt as any).docs).toEqual({ status: 'blocked', scope: 'docs/', exception: { accepted_by: 'owner', date: '2026-10-26', via: 'PR #9 review', reason: 'removed page republished in the next release' } }); - expect(Object.keys(receipt.receipt!).slice(-2)).toEqual(['docs', 'review_loop']); + expect(Object.keys(receipt.receipt!).slice(-3)).toEqual(['docs', 'review_loop', 'gate_dispositions']); expect(runBin(repo, 'gstack-ship-receipt', ['read', '--body', body]).status).toBe(EXIT.ok); const malformed = runBin(repo, 'gstack-ship-receipt', [...common, '--docs', '{"status":"done","scope":"docs/"}']); expect(malformed.status).toBe(EXIT.fail); diff --git a/test/gstack-ship-receipt.test.ts b/test/gstack-ship-receipt.test.ts index 3f0fe847910..509897ebae6 100644 --- a/test/gstack-ship-receipt.test.ts +++ b/test/gstack-ship-receipt.test.ts @@ -48,7 +48,7 @@ describe('gstack-ship-receipt write', () => { const parsed = extractReceipt(ok.out); expect(parsed.found).toBe(true); expect(parsed.errors).toEqual([]); - expect(Object.keys(parsed.receipt!)).toEqual(['schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'spend_usd', 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history', 'head_tree', 'product_patch_id', 'gstack_version', 'review_depth']); + expect(Object.keys(parsed.receipt!)).toEqual(['schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'spend_usd', 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history', 'head_tree', 'product_patch_id', 'gstack_version', 'review_depth', 'gate_dispositions']); expect(parsed.receipt).toMatchObject({ schema_version: 1, pr: 42, head, version: '1.2.4.0', base: 'main', tree: 'same-modulo-stamps', spend_usd: 0.42, ci: { checks: { pass: 3 } } }); expect(parsed.receipt!.head_tree).toBe(repo.git('rev-parse', 'HEAD^{tree}')); expect(parsed.receipt!.product_patch_id).toMatch(/^([0-9a-f]{40}|none)$/); @@ -714,7 +714,7 @@ describe('review_loop receipt input (harness lane E: the factory scorecard count expect(extractReceipt(withLoop.out).receipt).toMatchObject({ pr: 42, review_loop: { passes: 2, blocking_found: 1, deferred: 1, noted: 3, fixed: 1, scope: 'frozen' } }); const written = extractReceipt(fs.readFileSync(loopBody, 'utf8')); expect(written.errors).toEqual([]); - expect(Object.keys(written.receipt!).slice(-1)).toEqual(['review_loop']); + expect(Object.keys(written.receipt!).slice(-2)).toEqual(['review_loop', 'gate_dispositions']); }); test('parseReviewLoop keeps integer counters and drops the rest; write --review-loop refuses a malformed record and writes nothing', () => { diff --git a/test/gstack-skill-start.test.ts b/test/gstack-skill-start.test.ts index 6a183fb8b34..be5ce7c82c0 100644 --- a/test/gstack-skill-start.test.ts +++ b/test/gstack-skill-start.test.ts @@ -638,6 +638,30 @@ describe('gstack-skill-start behavior', () => { expect(out).toMatch(/^ARTIFACTS_SYNC: off$/m); }); + test('the /sync-gbrain hint follows GBRAIN_HOME the way gbrain resolves its config (#4325)', () => { + const bin = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ss-gbrain-bin-')); + const named = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ss-gbrain-home-')); + const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ss-gbrain-empty-')); + try { + fs.writeFileSync(path.join(bin, 'gbrain'), '#!/bin/sh\necho "gbrain 0.0.0"\n', { mode: 0o755 }); + fs.mkdirSync(path.join(named, '.gbrain')); + fs.writeFileSync(path.join(named, '.gbrain', 'config.json'), '{}\n'); + const env = { PATH: `${bin}${path.delimiter}${process.env.PATH}` }; + expect(runStart([], env)).not.toContain('GBrain configured'); + expect(runStart([], { ...env, GBRAIN_HOME: named })).toContain('GBrain configured'); + fs.mkdirSync(path.join(tmpHome, '.gbrain')); + fs.writeFileSync(path.join(tmpHome, '.gbrain', 'config.json'), '{}\n'); + try { + expect(runStart([], env)).toContain('GBrain configured'); + expect(runStart([], { ...env, GBRAIN_HOME: empty })).not.toContain('GBrain configured'); + } finally { + fs.rmSync(path.join(tmpHome, '.gbrain'), { recursive: true, force: true }); + } + } finally { + for (const dir of [bin, named, empty]) fs.rmSync(dir, { recursive: true, force: true }); + } + }); + test('artifacts-sync consent is asked before any artifacts egress, and only in interactive sessions', () => { const gh = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ss-privacy-')); const bin = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ss-privacy-bin-')); diff --git a/test/helpers/autoplan-preconfigured-fixture.ts b/test/helpers/autoplan-preconfigured-fixture.ts index 758bd086c13..f5c426221ce 100644 --- a/test/helpers/autoplan-preconfigured-fixture.ts +++ b/test/helpers/autoplan-preconfigured-fixture.ts @@ -9,7 +9,7 @@ When the user's request matches an available skill, invoke it via the Skill tool Key routing rules: - Product ideas/brainstorming → invoke /office-hours - Strategy/scope → invoke /plan-ceo-review -- Architecture → invoke /autoplan +- Architecture → invoke /plan-eng-review - Design system/plan review → invoke /design-consultation or /plan-design-review - Full review pipeline → invoke /autoplan - Bugs/errors → fix them directly: one read-only check of the cause, or a focused failing test first when the cause is unclear; then fix it and run that test diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.ts index 40393984f21..5971f0d454d 100644 --- a/test/helpers/carve-guards.ts +++ b/test/helpers/carve-guards.ts @@ -161,7 +161,7 @@ export const CARVE_GUARDS: Record = { }, behavioral: 'external', externalTest: 'test/skill-e2e-ship-section-loading.test.ts', - maxSkeletonBytes: 61_420, // GSTA-152 token cap (2026-10-29, Garry's "Do it" on plan v3): the skeleton's Budget paragraph (the --token-cap, --resume and --continue flags, start/check/close, the budget-handoff pointer) and the section index's budget-handoff line; measured 61,420 (before: 60,958 on edf4c2e). Before that: GSTA-131 token efficiency (2026-10-27, Garry's D1): Step 1's delta carry (dry run, pregate at HEAD, then carry --pregate) and Step 11.5's fix-check and planned-skip binding, +60 bytes after tightening Step 1 and the Review policy paragraph; measured 60,960 (before: 60,900 on 10b77de4). Before that: GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): the hoisted skeleton (59,706) plus this PR's growth, keeping the hoist's 65-byte headroom; measured 60,848. Before: + v2.0 {{ASIDE_RESEARCH}} (Aside first, WebSearch fallback); measured 78_275. + gate integrity (HONEST_WORK_GATE_INTEGRITY W3): Step 16 stage 4 ZERO-RUN/unknown receipt rows, stage 5 honesty inventory, Step 17 open-gate ready-PR gate; measured 80,540 (2026-10-10). + rule 22 / GBRA-108 (2026-10-25): Step 22's terminal line (gstack-ship-receipt result, the GSTACK_RESULT line a parent greps) and Step 18's unattended routing (an open PR at HEAD gets its body updated, else handoff), offset in part by tightening Steps 14, 16, 18 and 20 prose after the 2026-10-14 tightening left 2 bytes of headroom; measured 81,535. + harness lane E (2026-10-26, issue row 3: four Captains re-ran /ship on identical product code): Step 1's carry check (gstack-ship-receipt carry binds an earlier receipt to HEAD when the product patch-id is unchanged); measured 82,165. + the Review policy paragraph (the blocking floor, pass structure and cap, NO FINDINGS, the review_loop receipt counters, the review_scope knob), stated in the skeleton because gstack is the canonical holder of its review policy (docs/review-policy.md); measured 82,645. + maxSkeletonBytes: 61_438, // GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): Step 1's DIFF hint and the no-Eng-Review line name /plan-eng-review again, the wording GST-1698 removed; measured 61,438 (before: 61,417 on 81fb900). Before that: GSTA-152 token cap (2026-10-29, Garry's "Do it" on plan v3): the skeleton's Budget paragraph (the --token-cap, --resume and --continue flags, start/check/close, the budget-handoff pointer) and the section index's budget-handoff line; measured 61,420 (before: 60,958 on edf4c2e). Before that: GSTA-131 token efficiency (2026-10-27, Garry's D1): Step 1's delta carry (dry run, pregate at HEAD, then carry --pregate) and Step 11.5's fix-check and planned-skip binding, +60 bytes after tightening Step 1 and the Review policy paragraph; measured 60,960 (before: 60,900 on 10b77de4). Before that: GSTA-96 hoist merged with GSTA-92 phase 2 (2026-10-26): the hoisted skeleton (59,706) plus this PR's growth, keeping the hoist's 65-byte headroom; measured 60,848. Before: + v2.0 {{ASIDE_RESEARCH}} (Aside first, WebSearch fallback); measured 78_275. + gate integrity (HONEST_WORK_GATE_INTEGRITY W3): Step 16 stage 4 ZERO-RUN/unknown receipt rows, stage 5 honesty inventory, Step 17 open-gate ready-PR gate; measured 80,540 (2026-10-10). + rule 22 / GBRA-108 (2026-10-25): Step 22's terminal line (gstack-ship-receipt result, the GSTACK_RESULT line a parent greps) and Step 18's unattended routing (an open PR at HEAD gets its body updated, else handoff), offset in part by tightening Steps 14, 16, 18 and 20 prose after the 2026-10-14 tightening left 2 bytes of headroom; measured 81,535. + harness lane E (2026-10-26, issue row 3: four Captains re-ran /ship on identical product code): Step 1's carry check (gstack-ship-receipt carry binds an earlier receipt to HEAD when the product patch-id is unchanged); measured 82,165. + the Review policy paragraph (the blocking floor, pass structure and cap, NO FINDINGS, the review_loop receipt counters, the review_scope knob), stated in the skeleton because gstack is the canonical holder of its review policy (docs/review-policy.md); measured 82,645. minUnionBytes: 181_000, // token-reduction Phases 1-2 (v1.69.x branch); measured union 201,464 mustContain: ['VERSION', 'CHANGELOG', 'review', 'merge', 'PR'], // v1.58.5.0: pre-push-guard install (#2077) stacks on the shared first-run-guidance preamble. @@ -359,7 +359,7 @@ do not launch the downstream skill or open a browser.`, maxSkeletonBytes: 43_885, // GSTA-134 skill diet (2026-10-28): lowered from 80_533 to the measured skeleton after the second opinion and visual design moved to sections, 43,885. Before: GSTA-96 hoist (2026-10-26): lowered from 95_900 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 952 bytes; measured 79,581. Before: Office-hours + sketch outside voices include host guards and completion checks. + v1.91.19.0 wave: Q open-question prose form (#2729, approved Q3), DESIGN_READY --version probe (B4), Aside ~/.local/bin fallback (E7), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting (#3022) merged in; measured 89,684 (2026-10-03). + Oct 6 fix wave A3/CEO-12: free text reaches commands only through agent-written mktemp files (mktemp block, write rule, path rebuild and refusal at each posting, prompt and brief site); skeleton measured 92,590 (2026-10-06). + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; skeleton measured 92,869 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; skeleton measured 92,930 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; skeleton measured 92,756 (2026-10-07). Merged with the guard area: measured skeleton 93,099 (2026-10-07). + fix wave PR D: the Phase 4.5 builder-profile read before the session log (#2801) and the pre-telemetry design-doc check (#1049); measured skeleton 94,877 (2026-10-07). + Honest Work wave merged (W2/W3 gate integrity in review/ship, W4 kernel + DONE line in every tier-2+ skill, W5/W7 in spec/ship): re-measured on the integrated tree (2026-10-10). minUnionBytes: 115_800, // Phase 4 wave 4; measured union 118,175 mustContain: ['design doc', 'problem statement'], - maxSizeRatio: 1.1921, // GSTA-134 (2026-10-28, raised from 1.1796 by GStack Minder as merge-queue owner): +1,662 B union: second-opinion question moved into the main file while CODEX_SECOND_OPINION keeps its copy; per-run load 73,248→43,885 B; measured 156,286 / 131,110 = 1.19202, rounded up. Before: + Oct 6 fix wave A3/CEO-12: free text reaches commands only through agent-written mktemp files (mktemp block, write rule, path rebuild and refusal at each posting, prompt and brief site); measured 149,758 / 131,110 = 1.1422 (2026-10-06). + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 150,037 / 131,110 = 1.1444 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; measured 150,098 / 131,110 = 1.1448 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; measured 150,011 / 131,110 = 1.1442 (2026-10-07). Merged with the guard area: measured 150,354 / 131,110 = 1.1468 (2026-10-07). + fix wave PR D: builder-profile read before the session log with Phase 6 using the carried values (#2801), the inline design doc before approval (#879) and the pre-telemetry design-doc check (#1049); measured 153,206 / 131,110 = 1.1685 (2026-10-07). + empty LAST_ASSIGNMENT/LAST_PROJECT guards in the welcome_back and regular greetings (backfilled profiles); measured 153,469 / 131,110 = 1.1705 (2026-10-08). + Honest Work wave merged (W2/W3 gate integrity in review/ship, W4 kernel + DONE line in every tier-2+ skill, W5/W7 in spec/ship): re-measured on the integrated tree (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file and its own copies of shared sections; measured 160,989 / 131,110 = 1.2279 (2026-10-25). Before: 1.18. - GSTA-96 dedupe: the Q open-question form is office-hours' own appended subsection, so its copies of the shared Format and fallback subsections go; measured 154,653 / 131,110 = 1.1796 (2026-10-26), 154,624 = 1.1793 after the main merge. Before: 1.2279. + maxSizeRatio: 1.1922, // GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the handoff menu, its default and the design-doc line name /plan-eng-review again, +42 B union; measured 156,298 / 131,110 = 1.19211, rounded up (before: 156,256 = 1.19179 on 81fb900). Before that: GSTA-134 (2026-10-28, raised from 1.1796 by GStack Minder as merge-queue owner): +1,662 B union: second-opinion question moved into the main file while CODEX_SECOND_OPINION keeps its copy; per-run load 73,248→43,885 B; measured 156,286 / 131,110 = 1.19202, rounded up. Before: + Oct 6 fix wave A3/CEO-12: free text reaches commands only through agent-written mktemp files (mktemp block, write rule, path rebuild and refusal at each posting, prompt and brief site); measured 149,758 / 131,110 = 1.1422 (2026-10-06). + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 150,037 / 131,110 = 1.1444 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; measured 150,098 / 131,110 = 1.1448 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; measured 150,011 / 131,110 = 1.1442 (2026-10-07). Merged with the guard area: measured 150,354 / 131,110 = 1.1468 (2026-10-07). + fix wave PR D: builder-profile read before the session log with Phase 6 using the carried values (#2801), the inline design doc before approval (#879) and the pre-telemetry design-doc check (#1049); measured 153,206 / 131,110 = 1.1685 (2026-10-07). + empty LAST_ASSIGNMENT/LAST_PROJECT guards in the welcome_back and regular greetings (backfilled profiles); measured 153,469 / 131,110 = 1.1705 (2026-10-08). + Honest Work wave merged (W2/W3 gate integrity in review/ship, W4 kernel + DONE line in every tier-2+ skill, W5/W7 in spec/ship): re-measured on the integrated tree (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file and its own copies of shared sections; measured 160,989 / 131,110 = 1.2279 (2026-10-25). Before: 1.18. - GSTA-96 dedupe: the Q open-question form is office-hours' own appended subsection, so its copies of the shared Format and fallback subsections go; measured 154,653 / 131,110 = 1.1796 (2026-10-26), 154,624 = 1.1793 after the main merge. Before: 1.2279. }, 'document-release': { skill: 'document-release', @@ -733,7 +733,7 @@ do not launch the downstream skill or open a browser.`, gateAfterStop: undefined, }, behavioral: 'prompt', - maxSkeletonBytes: 51_622, // GSTA-96 hoist (2026-10-26): lowered from 73_450 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 937 bytes; measured 50,685. Before: + v1.78 AUQ spawned-trigger objectivity (explicit declaration + interactive fence); measured 73_059 + maxSkeletonBytes: 51_626, // GST-2726 (2026-11-15, Garry: bring /plan-eng-review back): the EUREKA example names /plan-eng-review again; measured 51,626 (before: 51,619 on 81fb900). Before that: GSTA-96 hoist (2026-10-26): lowered from 73_450 by the shared preamble that moved to sections/preamble.md, keeping the pre-hoist headroom of 937 bytes; measured 50,685. Before: + v1.78 AUQ spawned-trigger objectivity (explicit declaration + interactive fence); measured 73_059 minUnionBytes: 66_000, // measured union 73,496 mustContain: ['retrospective', '45-minute gap', 'Ship of the week', 'Praise'], }, diff --git a/test/helpers/docsync-interface.ts b/test/helpers/docsync-interface.ts index 90113471f26..485fa3becd6 100644 --- a/test/helpers/docsync-interface.ts +++ b/test/helpers/docsync-interface.ts @@ -15,7 +15,7 @@ export const docsCapsCommand = (skills: string) => `${skills}/bin/gstack-ship-re export function docsNativeInterface(fixture: Pick, 'home' | 'repo' | 'skills'> & Partial, 'env'>>, scripts: string[] = [], transport = false, insert = false, file?: string): string { const skills = fixture.skills.split(path.sep).join('/'); const state = fixture.env?.GSTACK_HOME ?? path.join(fixture.home, 'state'); - return `Fixture observation interface (applies to parent and every child; ${file ? `saved at ${file}: each child prompt tells the child to Read that file first instead of copying this text` : 'include this interface in child prompts'}): Bash may execute only separate literal pwd, ls, cat, stat, sha256sum and Git read commands (status, diff, show, log, ls-files, ls-tree, check-ignore, rev-parse, merge-base, hash-object without -w, branch listings with no operand and only --show-current, -a/--all, -r/--remotes, -v/--verbose, -l/--list, --no-color or --no-abbrev (no --merged, --sort, --format or --contains), tag listings with no operand and only -l/--list, describe with only --tags, --always, --abbrev= or --exact-match and at most one revision). Bash may also run each of the following as its own Bash call, with nothing joined before or after it by ;, &&, || or a pipe (one exception follows the read grammar below): the exact generated Preamble block with its spawned prefix, literal installed gstack-skill-start/gstack-skill-end commands for document-release (start requires GSTACK_SESSION_KIND=spawned) or their own --help, or the literal installed ${skills}/bin/gstack-docs-candidate snapshot (its --out a private .json under ${fixture.home}), compare and --help commands, the literal installed ${skills}/bin/gstack-docs-candidate result --audit-id --out-dir <${fixture.home} or a new directory directly under it> and result --help, and /ship Step 14.5's three own-tree housekeeping commands exactly as written, each on its own line: the shared .gstack/tmp exclude line (the one &&-joined housekeeping line this interface admits) + return `Fixture observation interface (applies to parent and every child; ${file ? `saved at ${file}: each child prompt tells the child to Read that file first instead of copying this text` : 'include this interface in child prompts'}): Bash may execute only separate literal pwd, ls, cat, stat, sha256sum and Git read commands (status, diff, show, log, ls-files, ls-tree, check-ignore, rev-parse, merge-base, hash-object without -w, branch listings with no operand and only --show-current, -a/--all, -r/--remotes, -v/--verbose, -l/--list, --no-color or --no-abbrev (no --merged, --sort, --format or --contains), tag listings with no operand and only -l/--list, describe with only --tags, --always, --abbrev= or --exact-match and at most one revision). Bash may also run each of the following as its own Bash call, with nothing joined before or after it by ;, &&, || or a pipe (one exception follows the read grammar below): the exact generated Preamble block with its spawned prefix, literal installed gstack-skill-start/gstack-skill-end commands for document-release (start requires GSTACK_SESSION_KIND=spawned) or their own --help, or the literal installed ${skills}/bin/gstack-docs-candidate snapshot (its --out a private .json under ${fixture.home}), compare and --help commands, the literal installed ${skills}/bin/gstack-docs-candidate result --audit-id --out-dir <${fixture.home} or a new directory directly under it> and result --help, the literal installed ${skills}/bin/gstack-docs-candidate attempt --state and attempt --help, and /ship Step 14.5's three own-tree housekeeping commands exactly as written, each on its own line: the shared .gstack/tmp exclude line (the one &&-joined housekeeping line this interface admits) ${DOCS_TMP_EXCLUDE} then ${DOCS_AUDIT_RESET} diff --git a/test/helpers/docsync-observer.ts b/test/helpers/docsync-observer.ts index 0630b1facf2..00ac6a56a74 100644 --- a/test/helpers/docsync-observer.ts +++ b/test/helpers/docsync-observer.ts @@ -414,8 +414,10 @@ function literalDocsCommandAllowed(text: string, fixture: ReturnType !!file && path.isAbsolute(file) && /\.json$/i.test(file) && docsPrivateArtifact(file, fixture, scripts); if (rest.length === 1 && rest[0] === '--help') return true; - if (rest.length === 2 && (rest[0] === 'snapshot' || rest[0] === 'compare' || rest[0] === 'result') && rest[1] === '--help') return true; + if (rest.length === 2 && ['snapshot', 'compare', 'result', 'attempt'].includes(rest[0]) && rest[1] === '--help') return true; if (rest[0] === 'compare') return rest.length === 2 && privateJson(rest[1]); + if (rest[0] === 'attempt') return rest.length === 4 && path.isAbsolute(rest[1]) && docsPrivateArtifact(rest[1], fixture, scripts) && + rest[2] === '--state' && privateJson(rest[3]); if (rest[0] === 'result') { if (rest.length !== 6 || !path.isAbsolute(rest[1]) || !docsPrivateArtifact(rest[1], fixture, scripts)) return false; const flags = [rest[2], rest[4]]; diff --git a/test/helpers/free-fixtures-data.ts b/test/helpers/free-fixtures-data.ts index 3f78417b250..13a6830af3c 100644 --- a/test/helpers/free-fixtures-data.ts +++ b/test/helpers/free-fixtures-data.ts @@ -59,6 +59,7 @@ export const FREE_FIXTURES: Readonly> = { 'test/fixtures/codex-review-sandbox-unavailable-37158847998.json': ['test/outside-voice-evidence.test.ts'], 'test/fixtures/codex-review/**': ['test/codex-hardening.test.ts', 'test/outside-review-severity.test.ts', 'test/outside-voice-evidence.test.ts', 'test/skill-validation.test.ts'], 'test/fixtures/codex-sandbox/**': ['test/codex-eval-recording.test.ts', 'test/codex-model-probe.test.ts', 'test/outside-review-result.test.ts', 'test/outside-voice-invocation.test.ts'], + 'test/fixtures/cyber-policy/**': ['test/outside-review-cyber-policy.test.ts', 'test/review-pass.test.ts'], 'test/fixtures/context-bill/**': ['test/context-bill.test.ts', 'test/context-budget-ratchet.test.ts'], 'test/fixtures/context-budget.json': ['test/helpers/capture-context-budget.ts', 'test/test-value-bar.test.ts'], 'test/fixtures/context-restore-fragment-match-captures.json': ['test/context-restore-fragment-verdict.test.ts'], diff --git a/test/helpers/office-hours-completion.ts b/test/helpers/office-hours-completion.ts index ead28775d32..9a4960f0e08 100644 --- a/test/helpers/office-hours-completion.ts +++ b/test/helpers/office-hours-completion.ts @@ -223,7 +223,7 @@ export function validateOfficeHoursCompletion(evidence: OfficeHoursCompletionEvi const handoff = sectionBody(evidence.output, ['handoff', 'handoff — the relationship closing', 'handoff - the relationship closing']) || sectionBody(evidence.output, ['relationship closing']); if (!substantive(handoff)) fail('REPORT.md lacks a substantive Handoff'); - if (!/\/(?:autoplan|plan-(?:ceo|design|devex)-review)\b/.test(handoff)) fail('Handoff lacks the next-skill recommendation'); + if (!/\/(?:autoplan|plan-(?:ceo|eng|design|devex)-review)\b/.test(handoff)) fail('Handoff lacks the next-skill recommendation'); if (!/\b(?:declined|deferred|not now|later)\b/i.test(handoff)) fail('Handoff does not record the declined downstream launch'); // The caller separately checks actual tool calls for downstream launch; // recording the user's choice here is not proof that it was respected. diff --git a/test/helpers/periodic-exclude-data.ts b/test/helpers/periodic-exclude-data.ts index 70f6b6bee97..515b4ced481 100644 --- a/test/helpers/periodic-exclude-data.ts +++ b/test/helpers/periodic-exclude-data.ts @@ -24,8 +24,8 @@ export const PERIODIC_CI_EXCLUDE: Record { expect(browseNavigatedTo(bash(`$B goto ${url}`, `Error: page.goto: net::ERR_FILE_NOT_FOUND at ${url}`), url)).toBe(false); expect(browseNavigatedTo(bash(`$B goto ${url}`, `Navigated to ${url} (404)`), url)).toBe(false); }); + + test('a goto with its stdout sent to /dev/null is credited only when the call proves it exited 0 (PR #4223 outside-voice#1)', () => { + const { url } = trials[0]!; + const cwd = url.replace(/^file:\/\//, '').replace(/\/fixture\.html$/, ''); + const html = '
  • Alpha 12
'; + const credited = (command: string, output = html) => browseNavigatedTo(bash(command, output), url, cwd); + for (const command of ['B=/x/browse; $B goto "file://$PWD/fixture.html" >/dev/null && $B html', + `$B goto ${url} >/dev/null 2>&1 && $B text`, `"$B" goto '${url}' > /dev/null &&\n $B html`, + '/x/browse/dist/browse goto "file://${PWD}/fixture.html" &>/dev/null && /x/browse/dist/browse html']) + expect(credited(command), command).toBe(true); + expect(browseNavigatedTo(bash(`cd ${cwd} && $B goto file://$PWD/fixture.html >/dev/null && $B html`, html), url)).toBe(true); + expect(browseNavigatedTo([...bash(`cd ${cwd}`, ''), ...bash('$B goto "file://$PWD/fixture.html" >/dev/null && $B html', html)], url)) + .toBe(true); + for (const command of ['$B goto "file://$PWD/fixture.html" >/dev/null; $B html', + '$B goto "file://$PWD/fixture.html" >/dev/null || $B html', '$B goto "file://$PWD/fixture.html" >/dev/null & $B html', + '$B goto "file://$PWD/fixture.html" >/dev/null && $B html; echo done', '$B goto "file://$PWD/fixture.html" && $B html', + "$B goto 'file://$PWD/fixture.html' >/dev/null && $B html", '$B goto "file://$PWD/other.html" >/dev/null && $B html', + 'cd /tmp/elsewhere && $B goto "file://$PWD/fixture.html" >/dev/null && $B html', + 'cd "$HOME" && $B goto "file://$PWD/fixture.html" >/dev/null && $B html', + `echo "$B goto ${url}" >/dev/null && $B html`, `$B text goto ${url} >/dev/null && $B html`, + '$B status >/dev/null || $B goto "file://$PWD/fixture.html" >/dev/null && $B html', + `cd ${cwd} && $B status || $B goto "file://$PWD/fixture.html" >/dev/null && $B html`, + 'true || echo | $B goto "file://$PWD/fixture.html" >/dev/null && $B html']) + expect(credited(command), command).toBe(false); + for (const command of [`test -d ${cwd} || exit 1; $B goto "file://$PWD/fixture.html" >/dev/null && $B html`, + '[ -x "$B" ] || B=/x/browse && $B goto "file://$PWD/fixture.html" >/dev/null && $B html']) + expect(credited(command), command).toBe(true); + const http = 'http://127.0.0.1:9/missing'; + expect(browseNavigatedTo(bash(`$B goto ${http} >/dev/null && $B html`, 'Not Found'), http)).toBe(false); + const goto = '$B goto "file://$PWD/fixture.html" >/dev/null && $B html'; + expect(browseNavigatedTo(bash(goto, html), url)).toBe(false); + for (const output of [`Exit code 1\n${html}`, `Error: page.goto: net::ERR_FILE_NOT_FOUND at ${url}`, 'denied']) + expect(credited(goto, output), output).toBe(false); + }); }); diff --git a/test/helpers/session-runner.ts b/test/helpers/session-runner.ts index 0d5f36f91c3..6a0fad87922 100644 --- a/test/helpers/session-runner.ts +++ b/test/helpers/session-runner.ts @@ -92,13 +92,45 @@ export function scanBrowseErrors(text: string): string[] { }); } -/** True when a Bash `goto` printed browse's success line for exactly this URL with a 2xx status. */ -export function browseNavigatedTo(toolCalls: Array<{ tool: string; input: any; output: string }>, url: string): boolean { - return toolCalls.some(call => call.tool === 'Bash' && /\bgoto\b/.test(String(call.input?.command ?? '')) - && String(call.output ?? '').split('\n').some(line => { +/** + * True when a Bash `goto` reached exactly this URL: it printed browse's success line for the URL with a 2xx status, or + * it sent its stdout to /dev/null (`$B goto "" >/dev/null && $B html`) and the call proves it exited 0. That proof + * is a call that did not fail (no leading `Exit code N` or tool error, no `Error` or `net::ERR_` line) where no `||` + * directly before the goto's pipeline could skip it and every command after the goto is joined by `&&`, so none of them ran + * unless it succeeded. Only a file:// URL qualifies: goto exits 0 on any HTTP status, so exit 0 proves no 2xx load of + * an http URL. The goto's target must be the URL + * itself, or `$PWD`/`${PWD}` under a known working directory (`cwd`, followed through literal `cd ` commands in + * call order; any other `cd` makes it unknown). The goto must be the segment's own browse command (`$B goto`, + * `${B} goto` or `/browse goto`), not text inside another command. + */ +export function browseNavigatedTo(toolCalls: Array<{ tool: string; input: any; output: string }>, url: string, cwd?: string): boolean { + let pwd = cwd; + for (const call of toolCalls) { + if (call.tool !== 'Bash') continue; + const command = String(call.input?.command ?? ''); + const output = String(call.output ?? ''); + if (/\bgoto\b/.test(command) && output.split('\n').some(line => { const match = line.trim().match(/^Navigated to (\S+) \((\d+)\)$/); return match?.[1] === url && match[2]!.startsWith('2'); - })); + })) return true; + const failed = /^\s*(?:Exit code [1-9]|)/.test(output) || /^\s*Error\b|net::ERR_/m.test(output); + const parts = command.replace(/\\\n/g, ' ').replace(/(&&|\|\|)\s*\n/g, '$1 ').trim().split(/(&&|\|\||(?&])&(?![>&])|[;|\n])/); + for (let i = 0; i < parts.length; i += 2) { + const segment = parts[i]!.trim(); + const cd = segment.match(/^cd\s+(\S+)$/); + if (cd) pwd = /^\/[^$`'"]*$/.test(cd[1]!) ? cd[1] : undefined; + const goto = segment.match(/^(?:\w+=\S*\s+)*(?:"?\$\{?B\}?"?|\S*\bbrowse)\s+goto\s+("[^"]*"|'[^']*'|[^\s'"]+)(.*)$/); + if (failed || !goto || !url.startsWith('file://') || !/(?:^|\s)(?:1?>|&>)\s*\/dev\/null(?:\s|$)/.test(goto[2]!)) continue; + if (parts.slice(i + 1).some((separator, j) => j % 2 === 0 && separator !== '&&')) continue; + const before = parts.slice(0, i).filter((_, j) => j % 2 === 1); + if (before[before.findLastIndex(separator => separator !== '|')] === '||') continue; + const raw = goto[1]!; + const target = raw.startsWith("'") ? raw.slice(1, -1) + : (raw.startsWith('"') ? raw.slice(1, -1) : raw).replace(/\$\{PWD\}|\$PWD\b/g, () => pwd ?? '\u0000'); + if (target === url) return true; + } + } + return false; } // --- Testable NDJSON parser --- diff --git a/test/helpers/third-party-actions.ts b/test/helpers/third-party-actions.ts index 8220e897cf7..426c6020287 100644 --- a/test/helpers/third-party-actions.ts +++ b/test/helpers/third-party-actions.ts @@ -34,6 +34,13 @@ export function letteredOptions(text: string): string[] { return options; } +/** + * A mention that says Aside is missing ("since Aside isn't available", "Aside was not detected", "with no Aside + * installed") names the browser the option does not use, so it never makes a drive option an Aside drive (gate + * 42748129558: "I drive it in gstack's own visible browser (recommended, since Aside isn't available)"). + */ +const ASIDE_UNAVAILABLE = /\bAside(?:['’]s)?(?:\s+(?:browser|app))?\s+(?:is|was)(?:n['’]t|\s+not)\b|\bAside(?:\s+(?:browser|app))?\s+(?:is|was)\s+(?:unavailable|missing|absent)\b|\b(?:no|without)\s+(?:the\s+|your\s+)?Aside\b/gi; + /** Inspect lettered consent options, not narration that quotes an unavailable option. */ export function asideDriveOptions(text: string): string[] { return letteredOptions(text).filter(option => { @@ -41,7 +48,7 @@ export function asideDriveOptions(text: string): string[] { /\b(?:I|we)(?:['’]ll| will) (?:re[- ]?ask|ask again)(?: (?:you|this question))? with (?:the )?(?:"[^"]+"|“[^”]+”|[\w -]+?) option(?: included)?\b/gi, '', ); - return /\bAside\b/.test(option) && (/\b(?:drive|driving|browse|browsing|navigate|click)\b/i.test(currentOffer) + return /\bAside\b/.test(option.replace(ASIDE_UNAVAILABLE, '')) && (/\b(?:drive|driving|browse|browsing|navigate|click)\b/i.test(currentOffer) || /\bI(?:['’]ll| will)? (?:do|handle|create|complete) (?:it|this)\b/i.test(currentOffer)); }); } @@ -65,13 +72,22 @@ export const offersDriveOption = (text: string): boolean => letteredOptions(text * waiting on you", "I refuse to mark this step as blocked on you", "otherwise I'll mark this step as blocked on you", * "if you skip it, I'll mark this step as blocked on you", "the step is not blocked on you" and "nothing stays blocked * on you" do not count, and neither does "waiting on you to approve it". + * + * Marking the step is what choosing the option does, so that clause counts on its own. The stays/remains/is predicate + * only describes the step's state, which any option can mention, so it counts only after an earlier part of the same + * option puts the step off ("later", "not yet", "not now"): "Later. This step remains waiting on you." counts, but "Sign + * in yourself. Until then the step stays blocked on you.", "Approve it in the dashboard. The step is waiting on you." + * and "Do it now, not later. The step stays blocked on you." do not. */ -const DEFER_OUTCOME = /(?:^|[.!?;:]\s+|\s-+\s+|[\u2013\u2014]\s*)(?:(?!\b(?:not|never|no|nothing|nobody|none|neither|nor|without|cannot|refus\w*|declin\w*|avoid\w*|rather|instead|if|unless|otherwise|else)\b|n['\u2019]t\b)[^.!?;:\u2013\u2014])*?\b(?:(?:I|we)(?:['\u2019]ll| will) |I |we )?(?:(?:mark|leave|keep)\w* (?:this|it|the)(?: [\w-]+)?(?: step)? (?:as )?|(?:stays|remains|is) )(?:blocked|waiting) on you(?=\s*(?:[.!?;:]|[-\u2013\u2014]|$))/i; +const DEFER_OUTCOME = /(?:^|[.!?;:]\s+|\s-+\s+|[\u2013\u2014]\s*)(?:(?!\b(?:not|never|no|nothing|nobody|none|neither|nor|without|cannot|refus\w*|declin\w*|avoid\w*|rather|instead|if|unless|otherwise|else)\b|n['\u2019]t\b)[^.!?;:\u2013\u2014])*?\b(?:(?:I|we)(?:['\u2019]ll| will) |I |we )?(?:(?:mark|leave|keep)\w* (?:this|it|the)(?: [\w-]+)?(?: step)? (?:as )?|(?(?:stays|remains|is) ))(?:blocked|waiting) on you(?=\s*(?:[.!?;:]|[-\u2013\u2014]|$))/gi; +const PUT_OFF = /(? [...option.matchAll(DEFER_OUTCOME)] + .some(match => !match.groups?.status || PUT_OFF.test(option.slice(0, match.index + match[0].lastIndexOf(match.groups.status)))); export const offersDefer = (text: string): boolean => letteredOptions(text).some(option => /\b(?:defer\w*|postpone\w*|put (?:this|it)(?: step)? off|skip (?:this|it)(?: step)? for now|come back to (?:this|it)(?: step)? later|leave (?:this|it)(?: step)? for (?:now|later))\b/i.test(option) || !/drive|browse|Aside/i.test(option) && (/(?:^|[.!?;:]\s+)(?:(?:we|I|let['\u2019]s) )?(?:wait|hold off)(?: on (?:this|it)(?: step)?)? for now\b(?=\s*(?:[.!?;:]|[-\u2013\u2014]|$))/i.test(option) - || !offersManualSteps(option) && DEFER_OUTCOME.test(option))); + || !offersManualSteps(option) && offersDeferOutcome(option))); /** The manual option: "manual", or one sentence offering instructions or steps the user follows themselves. */ export function offersManualSteps(text: string): boolean { diff --git a/test/office-hours-completion.test.ts b/test/office-hours-completion.test.ts index 5b11d4047ec..41bede449db 100644 --- a/test/office-hours-completion.test.ts +++ b/test/office-hours-completion.test.ts @@ -392,17 +392,17 @@ describe('office-hours fixture completion', () => { expect(() => validateOfficeHoursCompletion({ ...completed(), output: noDecline })).toThrow('declined downstream launch'); }); - test('accepts every next skill the handoff menu offers and rejects the retired /plan-eng-review', () => { - // #4108 moved the default recommendation to /autoplan; run 42371706491 failed a - // correct /autoplan handoff against the old list. + test('accepts every next skill the handoff menu offers, and /autoplan', () => { + // Run 42371706491 failed a correct handoff against a stale list; the menu + // offers /plan-eng-review again since GST-2726, and /autoplan stays valid. const menu = fs.readFileSync(path.join(import.meta.dir, '..', 'office-hours', 'sections', 'design-and-handoff.md'), 'utf8'); const offered = [...menu.matchAll(/^[A-C]\) Run (\/[\w-]+) now/gm)].map(match => match[1]); - expect(offered).toEqual(['/autoplan', '/plan-ceo-review', '/plan-design-review']); - for (const skill of offered) { + expect(offered).toEqual(['/plan-eng-review', '/plan-ceo-review', '/plan-design-review']); + for (const skill of [...offered, '/autoplan']) { expect(() => validateOfficeHoursCompletion({ ...completed(), output: report.replace('Next: /autoplan', `Next: ${skill}`) })).not.toThrow(); } - const retired = report.replace('Next: /autoplan', 'Next: /plan-eng-review'); - expect(() => validateOfficeHoursCompletion({ ...completed(), output: retired })).toThrow('next-skill recommendation'); + const unknown = report.replace('Next: /autoplan', 'Next: /plan-qa-review'); + expect(() => validateOfficeHoursCompletion({ ...completed(), output: unknown })).toThrow('next-skill recommendation'); }); }); diff --git a/test/outside-review-cyber-policy.test.ts b/test/outside-review-cyber-policy.test.ts new file mode 100644 index 00000000000..3e3b8f606ad --- /dev/null +++ b/test/outside-review-cyber-policy.test.ts @@ -0,0 +1,97 @@ +/** + * R95 (2026-11-13): OpenAI refuses some review briefs under its cyber-security policy (`cyber_policy`). That refusal + * is its own outcome, cyber_policy_refused, never a generic failure, so Capy's /ship can retry it on GPT-6 Astra with + * the read-only correctness brief (lib/review-brief.ts) and then Gemini 4 Carbon (lib/capy-review-pass.js). + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { classifyOutsideReview } from '../lib/outside-review-result'; +import { GATE_OUTCOMES, gateOutcomeLine } from '../lib/gate-outcomes'; +import { READ_ONLY_RETRY, renderBrief, sectionTexts } from '../lib/review-brief'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const LIB = path.join(ROOT, 'lib', 'outside-review-result.ts'); +const CAPY_ERROR = fs.readFileSync(path.join(ROOT, 'test/fixtures/cyber-policy/capy-latest-error.txt'), 'utf8'); +const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'cyber-policy-')); +afterAll(() => fs.rmSync(TMP, { recursive: true, force: true })); +const REVIEW = 'Recommendation: ship as-is because no finding survived\nVERDICT: CLEAN'; + +describe('a cyber_policy refusal is its own outcome (R95)', () => { + // Value: protects=the captured Capy refusal (GBRA-392's outside voice) classifies as cyber_policy_refused with the provider's line as detail, so /ship can tell it apart from auth, timeout and empty replies; fails_when=the host error is ignored, or the refusal falls into execution_failed or review_refused; + // why_new=R95; seam=lib/outside-review-result.ts execution(); no_claim=how often OpenAI refuses + test("Capy's captured latest_error is cyber_policy_refused, with the provider's line as detail", () => { + const c = classifyOutsideReview({ text: '', gate: 'review', exit: 1, providerError: CAPY_ERROR }); + expect(c).toMatchObject({ verdict: 'unavailable', reason: 'cyber_policy_refused' }); + expect(c.detail!.startsWith('OpenAI key declined the request: cyber_policy:')).toBe(true); + expect(GATE_OUTCOMES.cyber_policy_refused.state).toBe('unavailable'); + const line = gateOutcomeLine('Outside voice', 'cyber_policy_refused', c.detail); + expect(line).toContain('missing coverage, not a pass'); + expect(line).toContain('docs/troubleshooting.md#outside-review-cyber-policy'); + }); + + // Value: protects=Codex's own trailing ERROR line with cyber_policy is the refusal, while a prompt echo that merely quotes cyber_policy is not; fails_when=the classifier reads the whole stderr (Codex echoes the prompt, and this PR's own diff names cyber_policy); + // why_new=R95; seam=lib/outside-review-result.ts codexErrorLines; no_claim=Codex's exact wording, which is synthetic here + test("Codex's ERROR line is read; a prompt echo that quotes cyber_policy is not", () => { + const echo = 'user\nReview this diff: + if (/cyber_policy/.test(err)) retry()\n'; + const refused = classifyOutsideReview({ text: '', gate: 'review', exit: 1, stderr: echo + 'ERROR: {"error":{"code":"cyber_policy","message":"This content was flagged for possible cybersecurity risk."}}\n' }); + expect(refused.reason).toBe('cyber_policy_refused'); + const auth = classifyOutsideReview({ text: '', gate: 'review', exit: 1, stderr: echo + 'ERROR: 401 Unauthorized: invalid API key\n' }); + expect(auth.reason).toBe('execution_failed'); + }); + + // Value: protects=auth, timeout, empty, quota and plain failures keep their reasons, and a host error without cyber_policy changes nothing; fails_when=the new check swallows another failure or a non-refusal host error starts a retry; + // why_new=R95 (non-refusal failures unchanged); seam=lib/outside-review-result.ts execution(); no_claim=none + test('non-refusal failures keep their reasons', () => { + const cases: Array<[Parameters[0], string]> = [ + [{ text: '', gate: 'review', exit: 124, stderr: 'killed' }, 'timeout'], + [{ text: '', gate: 'review', exit: 0 }, 'empty_response'], + [{ text: '', gate: 'review', exit: 1, stderr: 'ERROR: You exceeded your current quota\n' }, 'quota_exhausted'], + [{ text: '', gate: 'review', exit: 1, stderr: 'ERROR: 401 Unauthorized\n' }, 'execution_failed'], + [{ text: '', gate: 'review', exit: 1, providerError: 'OpenAI key declined the request: invalid_api_key' }, 'execution_failed'], + [{ text: 'I cannot review this change.', gate: 'review', exit: 0 }, 'review_refused'], + ]; + for (const [input, reason] of cases) expect(classifyOutsideReview(input).reason).toBe(reason as never); + }); + + // Value: protects=a completed review that discusses cyber_policy, with or without cyber_policy on stderr after a clean exit, still counts as the review it is, while the host's own error (providerError) naming cyber_policy is the refusal whatever the reply says; fails_when=any mention of cyber_policy in the reply or on stderr makes it a refusal, or a host refusal is read as a clean review; + // why_new=R95 negative control; seam=lib/outside-review-result.ts; no_claim=none + test('a normal review is never a refusal', () => { + const text = 'The new check matches cyber_policy in the error.\n' + REVIEW; + expect(classifyOutsideReview({ text, gate: 'review', exit: 0 })).toMatchObject({ verdict: 'clean' }); + expect(classifyOutsideReview({ text, gate: 'review', exit: 0, stderr: 'cyber_policy\n' })).toMatchObject({ verdict: 'clean' }); + expect(classifyOutsideReview({ text, gate: 'review', exit: 0, providerError: CAPY_ERROR }).reason).toBe('cyber_policy_refused'); + }); + + // Value: protects=the CLI the Capy pass program calls reads --provider-error and prints REASON: cyber_policy_refused; fails_when=the flag is refused as usage or ignored; + // why_new=R95; seam=outside-review-result.ts --verdict; no_claim=none + test('the --verdict CLI reads --provider-error', () => { + const err = path.join(TMP, 'err.txt'), reply = path.join(TMP, 'reply.txt'); + fs.writeFileSync(err, CAPY_ERROR); + fs.writeFileSync(reply, ''); + const r = spawnSync(process.execPath, [LIB, '--verdict', '--provider-error', err, '--exit', '1', '--label', 'Outside voice', 'review', reply], { encoding: 'utf8', timeout: 10_000 }); + expect(r.status).toBe(1); + expect(r.stdout).toContain('REASON: cyber_policy_refused'); + expect(r.stderr).toContain('Outside voice unavailable: OpenAI declined the review under its cyber-security policy (cyber_policy)'); + }); +}); + +describe('the read-only retry brief (R95)', () => { + const t = sectionTexts(ROOT); + const slots = { diff_base: 'abc1234', diff: '+x' }; + // Value: protects=the retry brief drops attacker role-play, asks for file:line, the wrong-answer condition and the smallest fix, and keeps every marker collect needs, while the default outside brief is unchanged; fails_when=the retry text leaks into the default brief, or the retry loses the Recommendation/VERDICT markers; + // why_new=R95 (reworded only on the retry); seam=lib/review-brief.ts outside-voice; no_claim=that the retry finds what the original would + test('only the retry render is reworded, and it keeps the reply markers', () => { + const plain = renderBrief('outside-voice', slots, t); + const retry = renderBrief('outside-voice', { ...slots, read_only: '1' }, t); + expect(plain).toContain('Think like an attacker and a chaos engineer.'); + expect(plain).not.toContain(READ_ONLY_RETRY); + expect(retry).toContain(READ_ONLY_RETRY); + for (const gone of ['Think like an attacker', 'Be adversarial.', 'most exploitable']) expect(retry).not.toContain(gone); + for (const kept of ['Severity: Critical|High|Medium|Low', 'Recommendation: because', 'VERDICT: CLEAN', 'git diff "$DIFF_BASE"']) expect(retry).toContain(kept); + expect(READ_ONLY_RETRY).toContain('For each defect give file:line, the condition under which the code returns the wrong answer, and the smallest fix'); + expect(() => renderBrief('outside-voice', { ...slots, read_only: '1' }, { ...t, outside: t.outside.replace('Be adversarial. ', '') })).toThrow(/placeholder Be adversarial/); + }); +}); diff --git a/test/outside-voice-routing.test.ts b/test/outside-voice-routing.test.ts index 257d550674c..2dddae92efa 100644 --- a/test/outside-voice-routing.test.ts +++ b/test/outside-voice-routing.test.ts @@ -5,7 +5,6 @@ import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { ALL_HOST_CONFIGS } from '../hosts'; import { ALL_MODEL_NAMES } from '../scripts/models'; -import { RETIRED_SKILLS } from '../scripts/discover-skills'; import { HOST_PATHS, type TemplateContext } from '../scripts/resolvers/types'; import { outsideVoiceFor, outsideVoiceCommand } from '../scripts/resolvers/outside-voice'; import { RESOLVERS } from '../scripts/resolvers'; @@ -82,7 +81,7 @@ describe('generated automatic review coverage', () => { for (const skill of skills) { test(`Codex /${skill} invokes Claude Code, including lazy sections`, () => { const host = ALL_HOST_CONFIGS.find(h => h.name === 'codex')!; - const text = RETIRED_SKILLS.includes(skill) ? readFileSync(join(skillDir(host, 'autoplan'), `${skill}.md`), 'utf8') : readUnion(skillDir(host, skill)); + const text = readUnion(skillDir(host, skill)); expect(text).toContain('gstack-claude-code'); // Prose about the CLI is permitted; executable codex review commands are not. expect(shellLines(text).filter(line => /\bcodex\s+(?:exec|review)\b/.test(line))).toEqual([]); diff --git a/test/plan-review-cases.test.ts b/test/plan-review-cases.test.ts index 9e830187e23..90e91c63509 100644 --- a/test/plan-review-cases.test.ts +++ b/test/plan-review-cases.test.ts @@ -265,12 +265,12 @@ describe('plan report persistence precedes completion logging', () => { || artifact.relativePath.endsWith(`/gstack-${skill}/sections/review-sections.md`)); const carved = new Set(generated.artifacts.filter(isSection).map(a => `${a.host}:${a.relativePath.replace(/\/sections\/review-sections\.md$/, '')}`)); const carriers = generated.artifacts.filter(artifact => isSection(artifact) - || (artifact.kind === 'skill' && plans.some(skill => artifact.relativePath.endsWith(`/gstack-${skill}/SKILL.md`) || artifact.relativePath.endsWith(`/gstack-autoplan/${skill}.md`)) + || (artifact.kind === 'skill' && plans.some(skill => artifact.relativePath.endsWith(`/gstack-${skill}/SKILL.md`)) && !carved.has(`${artifact.host}:${artifact.relativePath.replace(/\/SKILL\.md$/, '')}`))); expect(carriers).toHaveLength(plans.length * ALL_HOST_CONFIGS.length); for (const carrier of carriers) { const content = readFileSync(join(outputRoot, carrier.relativePath), 'utf8'); - if (carrier.relativePath.includes('plan-eng-review')) { + if (carrier.relativePath.includes('plan-eng-review/')) { const dispatch = compactProse(content.slice(content.indexOf('**Pending-record checkpoint.**'), content.indexOf('## Scope Challenge'))); ordered(dispatch, ['AskUserQuestion({ questions: [currentDecision] })', /stop until the actual answer arrives/i, '### Record the answer', 'For the next choice']); } @@ -280,7 +280,7 @@ describe('plan report persistence precedes completion logging', () => { const dashboard = content.indexOf('\n## Review Readiness Dashboard\n'); expect({ carrier: carrier.relativePath, ordered: 0 < report && report < readback && readback < log && log < dashboard }).toMatchObject({ ordered: true }); expect(content.slice(report, readback)).toContain('current Completion Summary'); - expect(content.slice(readback, log)).toMatch(carrier.relativePath.includes('plan-eng-review') + expect(content.slice(readback, log)).toMatch(carrier.relativePath.includes('plan-eng-review/') ? /follow \*\*Blocked outcome\*\* before Review Log or decision logging/i : /stop before Review Log or decision logging/i); } diff --git a/test/policy-floor-stable.test.ts b/test/policy-floor-stable.test.ts index b840f7c0f3c..b90af5d2908 100644 --- a/test/policy-floor-stable.test.ts +++ b/test/policy-floor-stable.test.ts @@ -10,7 +10,8 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { EXIT } from '../lib/headless-artifacts'; -import { runningGstackVersion, validatePolicy } from '../lib/ship-policy'; +import { BUMP_NEVER_KEY_VERSION, POLICY_KEY_INTRODUCED, runningGstackVersion, TRAIN_GATES_KEY_VERSION, validatePolicy } from '../lib/ship-policy'; +import { cmpVersion, parseVersion } from '../lib/version-source'; import { useDoctorCleanup, REPO, makeFixture, doctor, write as writeFile } from './helpers/doctor-fixture'; import { cleanup as cleanupPregate, commit, makeFixtureRepo as makePregateRepo, runBin as runPregateBin, type FixtureRepo as PregateRepo } from './helpers/pregate-fixture'; import { cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; @@ -187,12 +188,13 @@ describe('gstack-doctor --check floor row', () => { test('an unstamped main checkout gets the verdict validatePolicy gives: the newest policy key it knows counts', () => { const f = makeFixture(); fs.copyFileSync(path.join(REPO, 'lib/ship-policy-keys.ts'), path.join(f.root, 'lib/ship-policy-keys.ts')); - const known = runningGstackVersion(); + const newer = (a: string, b: string) => cmpVersion(parseVersion(a)!, parseVersion(b)!) > 0; + const known = [...Object.values(POLICY_KEY_INTRODUCED), BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION].reduce((a, b) => (newer(b, a) ? b : a)); const dir = project(f, known); const at = floorRow(f, dir); expect(validatePolicy({ min_gstack_version: known })).toEqual([]); expect(at.status, at.line).toBe('PASS'); - expect(at.line).toBe(known === VERSION ? `PASS floor ${known} declared by ${dir}/.gstack/ship-policy.json (installed ${VERSION})` : `PASS floor ${known} declared by ${dir}/.gstack/ship-policy.json (installed ${VERSION}, reads policies as ${known})`); + expect(at.line).toBe(!newer(known, VERSION) ? `PASS floor ${known} declared by ${dir}/.gstack/ship-policy.json (installed ${VERSION})` : `PASS floor ${known} declared by ${dir}/.gstack/ship-policy.json (installed ${VERSION}, reads policies as ${known})`); // A checkout whose VERSION lags a key it carries reads the key's floor (validatePolicy agrees), so the row passes. writeFile(path.join(f.root, 'VERSION'), '1.0.0.0\n'); const lagging = floorRow(f, project(f, known)); diff --git a/test/pregate-declared-test-tree.test.ts b/test/pregate-declared-test-tree.test.ts new file mode 100644 index 00000000000..30a8b4ff731 --- /dev/null +++ b/test/pregate-declared-test-tree.test.ts @@ -0,0 +1,129 @@ +/** + * GST-2500: a `[]` declaration on a folder inside a test directory + * (`tests/live/**`, never the whole `test/**`) keeps the selected tests under it + * out of the local lane, and pregate says so. alphaclaw's tests/live/** and + * tests/container/** need their own tier; before this the lane ran them and the + * repo's runner found no test files. Fixture code only, never alphaclaw's. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { lanesCheck } from '../lib/pregate/checks/lanes'; +import { buildContext } from '../lib/pregate/context'; +import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; + +const TIER_TEST = "const test = require('node:test');\nconst { v } = require('./fixture');\ntest('needs the live tier', () => { throw new Error('tier test ran in the local lane ' + v); });\n"; +const OUTSIDE_TEST = "const test = require('node:test');\nconst { v } = require('../tests/live/fixture');\ntest('reads the live fixture', () => { if (v !== 1) throw new Error('bad'); });\n"; +const SCRIPT_TEST = "const test = require('node:test');\ntest('a test under a non-test glob', () => { throw new Error('script test ran'); });\n"; +const BASE_FILES = { 'tests/live/fixture.js': 'exports.v = 1;\n', 'tests/live/x.test.js': TIER_TEST, 'test/outside.test.js': OUTSIDE_TEST, 'scripts/z.test.js': SCRIPT_TEST }; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); +const fixture = (declared: Record) => { + const repo = makeFixtureRepo({ pregate: { ...BASE_PREGATE, dependencies: { ...BASE_PREGATE.dependencies, ...declared } }, baseFiles: BASE_FILES }); + repos.push(repo); + return repo; +}; +const lanes = (repo: FixtureRepo) => runBin(repo, 'gstack-pregate', ['--base', 'main', '--allow-repo-commands', '--only', 'lanes', '--explain']); +const LINE = /lanes: declared test tree tests\/live\/\*\*: 1 test file\(s\) not run in the local lane \(declared \[\] in origin\/main@[0-9a-f]{12}:\.gstack\/pregate\.json; the repo runs them in their own tier\)/; + +describe('declared test trees', () => { + test('a touched test under a [] test-tree glob is not run and the drop is printed and recorded', () => { + const repo = fixture({ 'tests/live/**': [] }); + commit(repo, { 'tests/live/x.test.js': TIER_TEST + '\n' }); + const r = lanes(repo); + expect(r.out).not.toContain('tier test ran in the local lane'); + expect(r.status).toBe(EXIT.ok); + expect(r.out).toMatch(LINE); + const recorded = JSON.parse(fs.readFileSync(path.join(repo.work, '.gstack', 'tmp', 'pregate.json'), 'utf8')).checks.find((c: { id: string }) => c.id === 'lanes'); + expect(recorded.lines.map((l: string) => `lanes: ${l}`).join('\n')).toMatch(LINE); + expect(r.out).toContain('tests/live/x.test.js: not run in the local lane; tests/live/** is declared [] in .gstack/pregate.json (its own tier)'); + expect(r.out).toContain('no local lane; 0 requires-remote obligation(s); 1 test file(s) in declared test trees not run here'); + expect(r.out).not.toContain('has no test lane'); + }); + + test('a test outside the glob that imports a file inside it still runs; the tier test it shares the file with does not', () => { + const repo = fixture({ 'tests/live/**': [] }); + commit(repo, { 'tests/live/fixture.js': 'exports.v = 1; \n' }); + const r = lanes(repo); + expect(r.status).toBe(EXIT.ok); + expect(r.out).toContain('test/outside.test.js ← tests/live/fixture.js'); + expect(r.out).toMatch(LINE); + expect(r.out).toContain("ran: node --test 'test/outside.test.js'"); + expect(r.out).not.toContain('tier test ran in the local lane'); + }); + + test('with no declaration, a glob that does not match, or a [] on the whole test directory, the tier test is still selected and run', () => { + for (const declared of [{}, { 'tests/container/**': [] }, { 'tests/**': [] }, { 'tests/live/x.test.js': [] }] as Array>) { + const repo = fixture(declared); + commit(repo, { 'tests/live/x.test.js': TIER_TEST + '\n' }); + const r = lanes(repo); + expect(r.status).not.toBe(EXIT.ok); + expect(r.out).toContain('tests/live/x.test.js (itself a test)'); + expect(r.out).not.toContain('declared test tree'); + } + }); + + test('touching only a declared-tier test still runs the always_run tests', () => { + const repo = makeFixtureRepo({ pregate: { ...BASE_PREGATE, dependencies: { ...BASE_PREGATE.dependencies, 'tests/live/**': [] } }, baseFiles: { ...BASE_FILES, 'test/tree-tripwire.test.js': "const test = require('node:test');\ntest('scans the tree', () => {});\n", '.gstack/always-run.json': JSON.stringify({ tests: ['test/*-tripwire.test.js'] }) } }); + repos.push(repo); + commit(repo, { 'tests/live/x.test.js': TIER_TEST + '\n' }); + const r = lanes(repo); + expect(r.status).toBe(EXIT.ok); + expect(r.out).toContain('test/tree-tripwire.test.js (always_run, .gstack/always-run.json)'); + expect(r.out).toContain("ran: node --test 'test/tree-tripwire.test.js'"); + expect(r.out).toMatch(LINE); + expect(r.out).not.toContain('tier test ran in the local lane'); + }); + + test('a [] for a test folder added only on the branch is refused under --policy-from head', () => { + const repo = fixture({}); + commit(repo, { '.gstack/pregate.json': JSON.stringify({ ...BASE_PREGATE, dependencies: { ...BASE_PREGATE.dependencies, 'tests/live/**': [] } }) + '\n', 'tests/live/x.test.js': TIER_TEST + '\n' }); + const r = runBin(repo, 'gstack-pregate', ['--base', 'main', '--allow-repo-commands', '--only', 'lanes', '--policy-from', 'head']); + expect(r.status).toBe(EXIT.refused); + expect(r.err).toContain('(PREGATE_HEAD_POLICY_LOOSENS'); + }); + + test('an always_run test inside the declared tree still runs, whether always_run added it or the diff selected it first', () => { + for (const touched of >>[{ 'lib/util.js': 'exports.add = (a, b) => a + b + 0;\n' }, { 'tests/live/x.test.js': TIER_TEST + '\n' }]) { + const repo = makeFixtureRepo({ pregate: { ...BASE_PREGATE, dependencies: { ...BASE_PREGATE.dependencies, 'tests/live/**': [] } }, baseFiles: { ...BASE_FILES, '.gstack/always-run.json': JSON.stringify({ tests: ['tests/live/**'] }) } }); + repos.push(repo); + commit(repo, touched); + const r = lanes(repo); + expect(r.status).not.toBe(EXIT.ok); + expect(r.out).toContain('tier test ran in the local lane'); + expect(r.out).not.toContain('declared test tree'); + } + }); + + test('with no base or user policy, a [] the branch adds in its bootstrap policy drops nothing under --policy-from head', () => { + const repo = makeFixtureRepo({ pregate: null, baseFiles: BASE_FILES }); + repos.push(repo); + commit(repo, { '.gstack/pregate.json': JSON.stringify({ ...BASE_PREGATE, dependencies: { ...BASE_PREGATE.dependencies, 'tests/live/**': [] } }) + '\n', 'tests/live/x.test.js': TIER_TEST + '\n' }); + const r = runBin(repo, 'gstack-pregate', ['--base', 'main', '--allow-repo-commands', '--only', 'lanes', '--policy-from', 'head']); + expect(r.status).not.toBe(EXIT.ok); + expect(r.out).toContain('tier test ran in the local lane'); + expect(r.out).not.toContain('declared test tree'); + }); + + test('on a small machine the remote gate still owes a declared-tree test: the exclusion is local-only', async () => { + const repo = makeFixtureRepo({ pregate: { ...BASE_PREGATE, remote_gate: 'node scripts/remote-gate.js', dependencies: { ...BASE_PREGATE.dependencies, 'tests/live/**': [] } }, baseFiles: BASE_FILES }); + repos.push(repo); + commit(repo, { 'tests/live/x.test.js': TIER_TEST + '\n' }); + const loaded = buildContext({ repoRoot: repo.work, base: 'main', policyFrom: 'base', allowRepoCommands: true, env: { ...process.env, ...repo.env }, progress: () => {}, cores: 4, testBackend: 'local' }); + if (!('ctx' in loaded)) throw new Error('fixture context refused'); + const r = await lanesCheck.run(loaded.ctx); + expect(r.status).toBe('requires-remote'); + expect(r.remote?.find(o => o.lane === 'pregate.json/remote_gate')?.tests).toEqual(['tests/live/x.test.js']); + }); + + test('a [] declaration on a glob that names no test directory keeps running the tests under it', () => { + const repo = fixture({ 'scripts/**': [] }); + commit(repo, { 'scripts/z.test.js': SCRIPT_TEST + '\n' }); + const r = lanes(repo); + expect(r.status).not.toBe(EXIT.ok); + expect(r.out).toContain('scripts/z.test.js (itself a test)'); + expect(r.out).not.toContain('declared test tree'); + }); +}); diff --git a/test/pregate-hidden-folder-paths.test.ts b/test/pregate-hidden-folder-paths.test.ts new file mode 100644 index 00000000000..3252a13ae4b --- /dev/null +++ b/test/pregate-hidden-folder-paths.test.ts @@ -0,0 +1,113 @@ +/** + * GST-2640 (gbrain #3965): the lanes check ran `bun test {files}` with bare repo-relative paths. Bun 1.4.4 reads a bare + * path as a name filter whose search skips hidden folders, so a selected test under .github/scripts/ ran nothing, Bun + * exited 1 and the lane failed with PREGATE_LANE_FAILED on a green test. The fixture repo has its test under + * .github/scripts/; the failing control proves the lane still judges that test instead of passing it unrun. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { buildContext } from '../lib/pregate/context'; +import { runPregate } from '../lib/pregate/index'; +import { explicitPath, testFileArgs } from '../lib/test-paths'; +import { runAt } from '../lib/base-red'; +import { perFileCommand } from '../lib/ci-carry'; +import { execFileSync } from 'node:child_process'; +import { cleanup, commit, makeFixtureRepo, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); + +const TEST = '.github/scripts/select.test.mjs'; +const GREEN = "import { expect, test } from 'bun:test';\nimport { pick } from './select.mjs';\ntest('picks the first lane', () => expect(pick(['a', 'b'])).toBe('a'));\n"; +const RED = "import { expect, test } from 'bun:test';\nimport { pick } from './select.mjs';\ntest('picks the last lane', () => expect(pick(['a', 'b'])).toBe('b'));\n"; +const DETECTED = { $schema: 'https://github.com/garrytan/gstack/docs/pregate.md#pregate-v1', dependencies: { '.github/scripts/**': [TEST], 'docs/**': [], 'README.md': [] } }; +const DECLARED = { ...DETECTED, runner: 'bun test {files}' }; + +async function lanes(policy: Record, files: Record, unlink: string[] = [], machine: { cores: number; testBackend: string } = { cores: 64, testBackend: 'local' }) { + const repo = makeFixtureRepo({ pregate: policy, baseFiles: { 'bun.lock': '' } }); + repos.push(repo); + commit(repo, { '.github/scripts/select.mjs': 'export const pick = (lanes) => lanes[0];\n', ...files }, 'add the lane selector'); + for (const rel of unlink) fs.rmSync(path.join(repo.work, rel)); + const loaded = buildContext({ repoRoot: repo.work, base: 'main', policyFrom: 'base', allowRepoCommands: true, env: { ...process.env, ...repo.env }, progress: () => {}, ...machine } as never); + if (!('ctx' in loaded)) throw new Error('fixture context refused'); + const file = await runPregate(loaded.ctx, { stage: 'tests', only: ['lanes'] }); + return file.checks.find(c => c.id === 'lanes')!; +} + +describe('explicit test paths for bun test', () => { + // Value: protects=every relative test path reaches bun test as a path; fails_when=a bare path (Bun's name filter) or a doubled ./ is passed; + // why_new=GST-2640; seam=the pure helper the lanes, remote-gate, docs-only, base-red and CI-carry commands share + test('adds ./ to a bare relative path, keeps explicit ones, and leaves other runners alone', () => { + expect(['.github/scripts/x.test.mjs', 'test/a.test.ts', './b.test.ts', '../c.test.ts', '/abs/d.test.ts'].map(explicitPath)) + .toEqual(['./.github/scripts/x.test.mjs', './test/a.test.ts', './b.test.ts', '../c.test.ts', '/abs/d.test.ts']); + expect(testFileArgs('bun test --timeout=30000 {files}', ['.github/x.test.ts'])).toEqual(['./.github/x.test.ts']); + expect(testFileArgs('bun --no-env-file --config=/dev/null test {files}', ['.github/x.test.ts'])).toEqual(['./.github/x.test.ts']); + expect(testFileArgs('npx vitest run {files}', ['.github/x.test.ts'])).toEqual(['.github/x.test.ts']); + }); + + // Value: protects=perFileCommand single-quotes each path after anchoring it with one ./; fails_when=quoting runs before the prefix, ./ doubles, or an absolute path gains ./; + // why_new=no test called perFileCommand after it moved to explicitPath; seam=none; no_claim=bash execution of the command (string only) + test('perFileCommand anchors and quotes per-file paths', () => { + expect(perFileCommand('bun test {files}', [".github/it's.test.ts", './a.test.ts', '/abs/b.test.ts'])) + .toBe("bun test './.github/it'\\''s.test.ts' './a.test.ts' '/abs/b.test.ts'"); + }); +}); + +describe.skipIf(process.platform === 'win32')('lanes check on a test under a hidden folder', () => { + // Value: protects=a green test under .github/ passes the lane, with the runner detected from bun.lock or declared; + // fails_when=bun test gets the bare path, runs nothing and exits 1 (PREGATE_LANE_FAILED); + // why_new=GST-2640, gbrain #3965 blocked /ship on bun 1.4.4; seam=runPregate --only lanes on a fixture repo that runs bun test + for (const [name, policy] of [['detected', DETECTED], ['declared', DECLARED]] as const) { + test(`a green hidden-folder test passes the lane (${name} runner)`, async () => { + const result = await lanes(policy, { [TEST]: GREEN }); + expect(result.lines).toContainEqual(expect.stringContaining("bun test './.github/scripts/select.test.mjs'")); + // The fixture's windows.yml claims every test, so the green local lane leaves a windows obligation instead of a bare pass. + expect(result).toMatchObject({ status: 'requires-remote', detail: '1 tests ran in 1 file(s), exit 0; 1 requires-remote obligation(s)' }); + }, 120_000); + } + + // Value: protects=the remote-gate command a small machine records carries ./-prefixed bun paths; fails_when=remoteObligation drops testFileArgs and records the bare .github path; + // why_new=only the local lane was tested; seam=none (runPregate on a 4-core ubicloud-backend context); no_claim=the remote VM run itself + test('a small machine records the remote-gate command with ./ paths', async () => { + const result = await lanes(DETECTED, { [TEST]: GREEN }, [], { cores: 4, testBackend: 'ubicloud' }); + expect(result.status).toBe('requires-remote'); + const run = result.lines?.find(l => l.startsWith('run: ')) ?? ''; + expect(run).toContain('./.github/scripts/select.test.mjs'); + expect(run).not.toMatch(/'\.github\/scripts/); + }, 120_000); + + // Value: protects=the lane still runs and judges a hidden-folder test; fails_when=the fix passes the lane without running the test + test('a failing hidden-folder test still fails the lane', async () => { + const result = await lanes(DETECTED, { [TEST]: RED }); + expect(result).toMatchObject({ status: 'fail', code: 'PREGATE_LANE_FAILED', detail: expect.stringContaining('1 failed of 1 ran') }); + }, 120_000); + + // Value: protects=AGENTS.md's rule that a missing test file never reaches Bun, which drops a missing ./ path beside a present one + // without an error; fails_when=selection hands bun test a path the working tree no longer has + test('a declared test file missing from the working tree is never passed to bun test', async () => { + const gone = '.github/scripts/gone.test.mjs'; + const result = await lanes({ ...DETECTED, dependencies: { ...DETECTED.dependencies, '.github/scripts/**': [TEST, gone] } }, { [TEST]: GREEN, [gone]: GREEN }, [gone]); + expect(result.lines).toContain("ran: bun test './.github/scripts/select.test.mjs'"); + expect(result.lines?.join('\n')).not.toContain('gone.test.mjs'); + }, 120_000); +}); + +describe.skipIf(process.platform === 'win32')('base-red select anchors bun test paths', () => { + // Value: protects=runAt hands a bun select ./-prefixed, quoted paths; fails_when=runAt drops testFileArgs and passes the bare .github path; + // why_new=no test reached runAt's select string; seam=none (runAt's existing Runner parameter); no_claim=bun execution (recording runner) + test('runAt passes ./-prefixed paths to a bun select', () => { + const repo = makeFixtureRepo({ pregate: DETECTED }); + repos.push(repo); + const prev = process.env.GSTACK_STATE_ROOT; + process.env.GSTACK_STATE_ROOT = path.join(repo.work, '..', 'state'); + try { + const seen: string[] = []; + const sha = execFileSync('git', ['-C', repo.work, 'rev-parse', 'HEAD'], { encoding: 'utf8', timeout: 10_000 }).trim(); + runAt(repo.work, sha, { select: 'bun test {files}', timeout_sec: 30 } as never, [TEST, 'test/a.test.ts'], (_d, cmd) => { seen.push(cmd); return { status: 0, out: '' }; }); + expect(seen).toEqual(["bun test './.github/scripts/select.test.mjs' './test/a.test.ts'"]); + } finally { + if (prev === undefined) delete process.env.GSTACK_STATE_ROOT; else process.env.GSTACK_STATE_ROOT = prev; + } + }); +}); diff --git a/test/retired-skills.test.ts b/test/retired-skills.test.ts index f465b796d98..790f44aa329 100644 --- a/test/retired-skills.test.ts +++ b/test/retired-skills.test.ts @@ -1,11 +1,11 @@ /** - * GST-1698: /plan-eng-review is cut. Its source stays as /autoplan's eng-phase - * methodology, and no host registers it. setup and gstack-relink treat it as a - * disabled skill that config cannot re-enable (GSTACK_RETIRED_SKILLS), so an - * existing gstack-owned entry is removed on the next setup or upgrade and a - * user's own same-name skill stays. External hosts carry the methodology beside - * gstack-autoplan/SKILL.md as plan-eng-review.md (Codex and Copilot register - * every nested SKILL.md). + * Retired skills: no host registers them, and setup and gstack-relink treat + * each as a disabled skill that config cannot re-enable (GSTACK_RETIRED_SKILLS), + * so an existing gstack-owned entry is removed on the next setup or upgrade and + * a user's own same-name skill stays. /investigate is retired (GST-1717). + * /plan-eng-review was retired in GST-1698 and came back in GST-2726: every host + * registers it again, and external hosts still carry its methodology beside + * gstack-autoplan/SKILL.md as plan-eng-review.md for /autoplan's eng phase. */ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { spawnSync } from 'child_process'; @@ -18,13 +18,13 @@ import { runGeneration } from '../scripts/gen-skill-docs'; const ROOT = path.resolve(import.meta.dir, '..'); const REGISTRY = path.join(ROOT, 'bin', 'gstack-install-registry.sh'); const BINS = ['gstack-config', 'gstack-relink', 'gstack-patch-names', 'gstack-skill-name.sh', 'gstack-state-root.sh', 'gstack-install-registry.sh']; -const PLAN_ENG = 'plan-eng-review'; // pregate-literal: GSTACK_RETIRED_SKILLS=plan-eng-review still retired; GST-1717 appended investigate to the list +const PLAN_ENG = 'plan-eng-review'; // pregate-literal: GST-2726 took plan-eng-review off GSTACK_RETIRED_SKILLS; investigate stays retired test('setup and gstack-relink retire the same skills as the generator', () => { const r = spawnSync('bash', ['-c', '. "$1" && printf %s "$GSTACK_RETIRED_SKILLS"', '_', REGISTRY], { encoding: 'utf8', timeout: 10_000 }); expect(r.status, r.stderr).toBe(0); expect(r.stdout.split(/\s+/).filter(Boolean)).toEqual(RETIRED_SKILLS); - expect(RETIRED_SKILLS.join(' ')).toBe('plan-eng-review investigate'); + expect(RETIRED_SKILLS.join(' ')).toBe('investigate'); }); describe('gstack-relink after an upgrade removed /investigate (GST-1717)', () => { @@ -104,7 +104,7 @@ describe('gstack-relink after an upgrade removed /investigate (GST-1717)', () => }); }); -describe('gstack-relink on an install that still has /plan-eng-review', () => { +describe('gstack-relink after /plan-eng-review returned (GST-2726)', () => { let tmp: string; let install: string; let skills: string; @@ -137,27 +137,17 @@ describe('gstack-relink on an install that still has /plan-eng-review', () => { }); afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); - test('an upgrade removes the old gstack-owned entry and keeps the methodology source', () => { - setRegistry(''); - const before = relink(); - expect(before.status, before.stderr).toBe(0); - expect(fs.existsSync(path.join(skills, PLAN_ENG, 'SKILL.md'))).toBe(true); - - setRegistry(PLAN_ENG); - const after = relink(); - expect(after.status, after.stderr).toBe(0); + test('an install whose upgrade removed the entry gets /plan-eng-review back on the next relink', () => { + setRegistry(`${PLAN_ENG} investigate`); + const cut = relink(); + expect(cut.status, cut.stderr).toBe(0); expect(fs.lstatSync(path.join(skills, PLAN_ENG), { throwIfNoEntry: false })).toBeUndefined(); - expect(fs.existsSync(path.join(skills, 'ship', 'SKILL.md'))).toBe(true); - expect(fs.existsSync(path.join(install, PLAN_ENG, 'SKILL.md'))).toBe(true); - expect(after.stdout).not.toContain('Disabled (gstack-config disabled_skills'); - }); - test('a gstack-plan-eng-review entry from a prefixed install goes too', () => { - fs.mkdirSync(path.join(skills, 'gstack-plan-eng-review'), { recursive: true }); - fs.symlinkSync(path.join(install, PLAN_ENG, 'SKILL.md'), path.join(skills, 'gstack-plan-eng-review', 'SKILL.md')); - const r = relink(); - expect(r.status, r.stderr).toBe(0); - expect(fs.lstatSync(path.join(skills, 'gstack-plan-eng-review'), { throwIfNoEntry: false })).toBeUndefined(); + fs.copyFileSync(REGISTRY, path.join(install, 'bin', 'gstack-install-registry.sh')); + const back = relink(); + expect(back.status, back.stderr).toBe(0); + expect(fs.readFileSync(path.join(skills, PLAN_ENG, 'SKILL.md'), 'utf8')).toContain(`# ${PLAN_ENG}`); + expect(fs.existsSync(path.join(skills, 'ship', 'SKILL.md'))).toBe(true); }); test("a user's own plan-eng-review skill is left alone", () => { @@ -179,29 +169,35 @@ describe('setup prunes external-host entries for a retired skill whose source st return SETUP_SRC.slice(start, end + 2); }; - test('the old gstack-plan-eng-review render and its host link are removed, live skills stay', () => { + const pruneScript = (src: string, gen: string, host: string, retired?: string) => [ + 'set -e', 'log() { echo "$@"; }', `. "${REGISTRY}"`, ...(retired ? [`GSTACK_RETIRED_SKILLS="${retired}"`] : []), + ...['_gstack_link_target_abs', '_gstack_target_is_ours', '_gstack_generated_header', '_backup_skill_md', '_cleanup_weak_dir', + '_owned_for_windows_refresh', '_skill_source_exists', '_prune_stale_generated'].map(extractFn), + `_prune_stale_generated "${src}" "${gen}" "${host}"`, + ].join('\n'); + const pruneFixture = (t: string, live: string[]) => { + const src = path.join(t, 'src'), gen = path.join(t, 'gen'), host = path.join(t, 'host'); + for (const s of live) { + fs.mkdirSync(path.join(src, s), { recursive: true }); + fs.writeFileSync(path.join(src, s, 'SKILL.md.tmpl'), `---\nname: ${s}\n---\nx\n`); + } + fs.mkdirSync(host); + for (const s of live) { + const g = `gstack-${s}`; + fs.mkdirSync(path.join(gen, g), { recursive: true }); + fs.writeFileSync(path.join(gen, g, 'SKILL.md'), `\n# ${g}\n`); + fs.symlinkSync(path.join(gen, g) + '/', path.join(host, g)); + } + return { src, gen, host }; + }; + + test('a retired skill whose source still exists loses its render and host link, live skills stay', () => { const t = fs.mkdtempSync(path.join(os.tmpdir(), 'retired-prune-')); try { - const src = path.join(t, 'src'), gen = path.join(t, 'gen'), host = path.join(t, 'host'); - for (const s of [PLAN_ENG, 'autoplan']) { - fs.mkdirSync(path.join(src, s), { recursive: true }); - fs.writeFileSync(path.join(src, s, 'SKILL.md.tmpl'), `---\nname: ${s}\n---\nx\n`); - } - for (const g of ['gstack-plan-eng-review', 'gstack-autoplan']) { - fs.mkdirSync(path.join(gen, g), { recursive: true }); - fs.writeFileSync(path.join(gen, g, 'SKILL.md'), `\n# ${g}\n`); - } - fs.mkdirSync(host); - for (const g of ['gstack-plan-eng-review', 'gstack-autoplan']) fs.symlinkSync(path.join(gen, g) + '/', path.join(host, g)); - const script = [ - 'set -e', 'log() { echo "$@"; }', `. "${REGISTRY}"`, - ...['_gstack_link_target_abs', '_gstack_target_is_ours', '_gstack_generated_header', '_backup_skill_md', '_cleanup_weak_dir', - '_owned_for_windows_refresh', '_skill_source_exists', '_prune_stale_generated'].map(extractFn), - `_prune_stale_generated "${src}" "${gen}" "${host}"`, - ].join('\n'); - const r = spawnSync('bash', ['-c', script], { encoding: 'utf-8', timeout: 30_000 }); + const { src, gen, host } = pruneFixture(t, ['old-review', 'autoplan']); + const r = spawnSync('bash', ['-c', pruneScript(src, gen, host, 'old-review investigate')], { encoding: 'utf-8', timeout: 30_000 }); expect(r.status, r.stderr).toBe(0); - expect(r.stdout).toContain('pruned retired skill: gstack-plan-eng-review'); + expect(r.stdout).toContain('pruned retired skill: gstack-old-review'); expect(fs.readdirSync(gen)).toEqual(['gstack-autoplan']); expect(fs.readdirSync(host)).toEqual(['gstack-autoplan']); } finally { @@ -209,6 +205,20 @@ describe('setup prunes external-host entries for a retired skill whose source st } }); + test('the gstack-plan-eng-review render and its host link stay now that the skill is back (GST-2726)', () => { + const t = fs.mkdtempSync(path.join(os.tmpdir(), 'retired-prune-back-')); + try { + const { src, gen, host } = pruneFixture(t, [PLAN_ENG, 'autoplan']); + const r = spawnSync('bash', ['-c', pruneScript(src, gen, host)], { encoding: 'utf-8', timeout: 30_000 }); + expect(r.status, r.stderr).toBe(0); + expect(r.stdout).not.toContain('pruned retired skill'); + expect(fs.readdirSync(gen).sort()).toEqual(['gstack-autoplan', 'gstack-plan-eng-review']); + expect(fs.readdirSync(host).sort()).toEqual(['gstack-autoplan', 'gstack-plan-eng-review']); + } finally { + fs.rmSync(t, { recursive: true, force: true }); + } + }); + test('a copied gstack-investigate whose source is gone: an edited SKILL.md is backed up, a pristine copy goes (GST-1717)', () => { const t = fs.mkdtempSync(path.join(os.tmpdir(), 'retired-prune-gone-')); try { @@ -271,24 +281,28 @@ describe('setup prunes external-host entries for a retired skill whose source st }); }); -test('no host renders a plan-eng-review skill; external hosts get the methodology beside gstack-autoplan', async () => { +test('every host renders /plan-eng-review; external hosts also keep the same methodology beside gstack-autoplan', async () => { const out = fs.mkdtempSync(path.join(os.tmpdir(), 'retired-gen-')); try { const result = await runGeneration({ host: 'all', outputRoot: out }); expect(result.diagnostics.filter(d => d.kind === 'error'), JSON.stringify(result.diagnostics.filter(d => d.kind === 'error'))).toEqual([]); const paths = result.artifacts.map(a => a.relativePath); - expect(paths.filter(p => /gstack-plan-eng-review\//.test(p))).toEqual([]); expect(paths).toContain('plan-eng-review/SKILL.md'); const external = result.artifacts.filter(a => a.host && a.host !== 'claude' && a.kind === 'skill'); const hosts = new Set(external.map(a => a.host)); + expect(hosts.size).toBeGreaterThan(5); for (const host of hosts) { - const copy = external.find(a => a.host === host && a.relativePath.endsWith('/skills/gstack-autoplan/plan-eng-review.md')); - expect(copy, host).toBeDefined(); - expect(fs.readFileSync(path.join(out, copy!.relativePath), 'utf8')).toMatch(/^---\nname: (gstack-)?plan-eng-review\n/); + const standalone = external.find(a => a.host === host && a.relativePath.endsWith('/skills/gstack-plan-eng-review/SKILL.md')); + const sibling = external.find(a => a.host === host && a.relativePath.endsWith('/skills/gstack-autoplan/plan-eng-review.md')); + expect(standalone, host).toBeDefined(); + expect(sibling, host).toBeDefined(); + const body = fs.readFileSync(path.join(out, standalone!.relativePath), 'utf8'); + expect(body).toMatch(/^---\nname: (gstack-)?plan-eng-review\n/); + expect(fs.readFileSync(path.join(out, sibling!.relativePath), 'utf8')).toBe(body); } const router = fs.readFileSync(path.join(out, 'SKILL.md'), 'utf8'); - expect(router).not.toContain('/plan-eng-review'); - expect(fs.readFileSync(path.join(out, 'gstack', 'llms.txt'), 'utf8')).not.toContain(PLAN_ENG); + expect(router).toContain('→ invoke `/plan-eng-review`'); + expect(fs.readFileSync(path.join(out, 'gstack', 'llms.txt'), 'utf8')).toContain('[/plan-eng-review](plan-eng-review/SKILL.md)'); expect(paths.filter(p => /(^|\/)(gstack-)?investigate\//.test(p))).toEqual([]); expect(router).not.toContain('/investigate'); expect(fs.readFileSync(path.join(out, 'gstack', 'llms.txt'), 'utf8')).not.toContain('/investigate'); diff --git a/test/review-depth.test.ts b/test/review-depth.test.ts index 0033e55f4d0..86a1c63e6ce 100644 --- a/test/review-depth.test.ts +++ b/test/review-depth.test.ts @@ -196,8 +196,19 @@ describe('GST-967 invariant: no gate-class owner exit before Step 11\'s voices; * takes none). The brief bodies lib/review-brief.ts cuts from the ship sections hash to MAIN_SECTIONS: main's bodies plus * GST-508's exclude-pathspec placeholders (replay 'GST-508+GST-464+GST-967': the merged bodies minus main's are the wave's minus fc292e22f), * then GST-1821's last-line VERDICT request in the outside brief (replay 'GST-1821'). + * GST-2547 (R51) adds one reader and drops none: a light runtime-0 full step on the tests diff dispatches one batched reader on + * the Testing checklist where main dispatched nothing; asMainBeforeR51 checks that reader and reads the plan back as main's. */ +const R51_SKIP = 'red-team and adversarial-native (light depth, runtime 0: one batched reader reads the tests diff, R51)'; +function asMainBeforeR51(p: ReturnType): { dispatches: typeof p.dispatches; skipped: string[]; added: boolean } { + if (!(p.class === 'tests' && p.next.step === 'full' && p.stepDepth === 'light')) return { dispatches: p.dispatches, skipped: p.skipped, added: false }; + expect(p.dispatches[0]).toEqual({ role: 'specialist', name: 'batched', effort: ROLE_EFFORT.specialist, exclude: [], checklists: ['testing'] }); + const at = p.skipped.indexOf('specialists except testing (tests class)'); + expect(p.skipped.slice(at, at + 2)).toEqual(['specialists except testing (tests class)', R51_SKIP]); + return { dispatches: p.dispatches.slice(1), skipped: [...p.skipped.slice(0, at), 'specialists, red-team and adversarial-native (light depth, runtime 0)', ...p.skipped.slice(at + 2)], added: true }; +} const MAIN_PLANS = '9d13d6bae86bfc9207ce7e0cec8da5b33db2518c1653e8e009160a98b0f04c89'; +const R51_CASES = 28; const MAIN_SECTIONS = '7eb6b4c2dd31edbd7c69f02bd31f8884407187fac8ace4e796632d60957b6bbb'; describe('GST-967 dispatch-superset no-loss check', () => { // Value: protects=the no-loss rule for review-depth changes: GST-967 drops, renames and re-efforts no reviewer main dispatches on any grid case, and changes no brief body; fails_when=a non-stop plan changes, a voices step appears off gate class or after Step 11, it dispatches anything but the three voices, or a brief body moves; @@ -213,19 +224,22 @@ describe('GST-967 dispatch-superset no-loss check', () => { }; const rows: unknown[] = []; let voices = 0; + let r51 = 0; for (const [name, f] of Object.entries(fixtures)) for (const fullPasses of [0, 1, 2]) for (const last of ['none', 'full', 'fix-check'] as const) for (let bits = 0; bits < 16; bits++) for (const adversarialRan of [false, true]) { const history = { fullPasses, last, fixedBlocking: !!(bits & 1), fixedBelow: !!(bits & 2), blockingOpen: !!(bits & 4), touchedGate: !!(bits & 8) }; const p = planReview({ ...f, numbers: none, history, adversarialRan } as PlanInput); let { step, reason } = p.next; - let dispatches = p.dispatches; + const back = asMainBeforeR51(p); + if (back.added) r51++; + let dispatches = back.dispatches; if (step === 'voices') { voices++; expect([p.class, adversarialRan, dispatches.map(d => `${d.role}:${d.effort}`)]).toEqual(['gate', false, ['adversarial-native:full', 'outside-voice:host', 'targeted:full']]); [step, reason, dispatches] = ['stop', reason.slice(reason.indexOf('--adversarial-ran (') + '--adversarial-ran ('.length, -1), []]; } - rows.push({ name, fullPasses, last, bits, adversarialRan, class: p.class, step, reason, dispatches, skipped: p.skipped }); + rows.push({ name, fullPasses, last, bits, adversarialRan, class: p.class, step, reason, dispatches, skipped: back.skipped }); } - expect([rows.length, voices, sha(rows)]).toEqual([1440, 71, MAIN_PLANS]); + expect([rows.length, voices, r51, sha(rows)]).toEqual([1440, 71, R51_CASES, MAIN_PLANS]); expect(sha(sectionTexts(ROOT))).toBe(MAIN_SECTIONS); }); }); @@ -276,7 +290,7 @@ describe('GST-972 follow-up no-loss check', () => { for (const [name, c] of Object.entries(cases)) for (const fullPasses of [0, 1, 2]) for (const last of ['none', 'full', 'fix-check'] as const) for (let bits = 0; bits < 16; bits++) for (const adversarialRan of [false, true]) { const history = { fullPasses, last, fixedBlocking: !!(bits & 1), fixedBelow: !!(bits & 2), blockingOpen: !!(bits & 4), touchedGate: !!(bits & 8) }; const p = planReview({ paths: c[pick], scope: c[2], gateTagged: 0, diffLines: 40, consumed: [], numbers: none, history, adversarialRan }); - rows.push({ name, fullPasses, last, bits, adversarialRan, class: p.class, depth: p.depth, step: p.next.step, dispatches: p.dispatches.map(d => ({ role: d.role, name: d.name, effort: d.effort, checklists: d.checklists ?? [] })) }); + rows.push({ name, fullPasses, last, bits, adversarialRan, class: p.class, depth: p.depth, step: p.next.step, dispatches: (pick ? asMainBeforeR51(p).dispatches : p.dispatches).map(d => ({ role: d.role, name: d.name, effort: d.effort, checklists: d.checklists ?? [] })) }); } return rows; }; @@ -305,6 +319,50 @@ describe('GST-972 follow-up no-loss check', () => { }); }); +describe('GST-2547: a tests-only diff gets one reader (R51)', () => { + // Value: protects=R51's one reviewer on a tests diff and the rule that only a human-docs diff (R81) may plan zero readers on pass 1; fails_when=a tests diff, or code with no runtime lines, plans no dispatch, a tests diff plans more than one reader or a second round after a clean pass, or the docs, code, gate and security plans move; + // why_new=HARN-1 (harness-evals#425): a tests-only diff printed dispatches=0 and the only review was the author's core read; seam=planReview; no_claim=what the reader finds + const off: PlanInput['shape'] = { panel: 'off', readerModel: 'lane', platform: 'off', head: 'h', platformReview: null }; + const tests = { paths: ['test/clock.test.ts'], scope: { SCOPE_TESTS: 'true' }, diffLines: 12 }; + test.each([['panel all', undefined], ['review.panel off', off]] as const)('%s: one batched Testing reader on pass 1, then done after a clean pass or below-floor fixes', (_, shape) => { + const p = planReview(base({ ...tests, shape })); + expect([p.class, p.depth, roles(p), batch(p)]).toEqual(['tests', 'light', ['specialist:batched:medium'], ['testing']]); + const after = (h: Partial) => planReview(base({ ...tests, shape, history: { fullPasses: 1, last: 'full', ...h } })).next.step; + expect([after({}), after({ fixedBelow: true, rangeRuntimeLines: 0 })]).toEqual(['done', 'done']); + }); + test('only a docs diff plans zero readers on pass 1, under every panel and depth floor', () => { + const fixtures: Record> = { + tests, + 'outputs-only code': { paths: ['src/gen.ts'], perPath: [{ path: 'src/gen.ts', lines: 30, binary: false }], registry: { sha: 'a', outputs: ['src/gen.ts'] } }, + code: {}, gate: { gateTagged: 1 }, security: { declared: ['security'] }, + }; + for (const shape of [undefined, off, { ...off, panel: 'risk' as const }, { ...off, panel: 'all' as const }]) for (const floor of [undefined, 'standard', 'full'] as const) { + for (const [name, f] of Object.entries(fixtures)) expect([name, shape?.panel, floor, planReview(base({ ...f, shape, floor })).dispatches.length > 0]).toEqual([name, shape?.panel, floor, true]); + expect(planReview(base({ paths: ['README.md'], scope: {}, gateTagged: null, shape })).dispatches).toEqual([]); + } + }); + test('a forced specialist on a tests diff stays its own reader and is the one reader, as on main', () => { + const p = planReview(base({ ...tests, force: ['performance'] })); + expect([roles(p), p.skipped[0]]).toEqual([['specialist:performance:medium'], 'specialists, red-team and adversarial-native (light depth, runtime 0)']); + }); + test('code with no runtime lines (registered outputs only) gets one batched reader on the code checklists over the whole diff', () => { + const p = planReview(base({ paths: ['src/gen.ts'], perPath: [{ path: 'src/gen.ts', lines: 30, binary: false }], registry: { sha: 'a', outputs: ['src/gen.ts'] } })); + expect([p.class, p.runtimeLines, p.dispatches]).toEqual(['code', 0, [{ role: 'specialist', name: 'batched', effort: 'medium', exclude: [], checklists: ['testing', 'security'] }]]); + }); + test('controls: the docs, code, gate and security plans are main\'s', () => { + const plan = (o: Partial) => { const p = planReview(base(o)); return [p.class, p.depth, p.dispatches.map(d => `${d.role}:${d.name}:${d.effort}${d.checklists ? `[${d.checklists.join(',')}]` : ''}`)]; }; + expect(plan({ paths: ['docs/howto.md'], scope: {}, gateTagged: null })).toEqual(['docs', 'light', []]); + expect(plan({ paths: ['docs/howto.md'], scope: {}, gateTagged: null, shape: off })).toEqual(['docs', 'light', []]); + expect(plan({})).toEqual(['code', 'light', ['specialist:batched:full[testing,security,red-team]', 'adversarial-native:adversarial:full']]); + expect(plan({ shape: off })).toEqual(['code', 'light', ['adversarial-native:single:full[testing,security,red-team]']]); + const panel = ['specialist:batched:medium[testing,security]', 'red-team:red-team:full', 'adversarial-native:adversarial:full', 'outside-voice:outside-voice:host']; + expect(plan({ gateTagged: 1, targeted: { classes: ['gate'] } })).toEqual(['gate', 'full', [...panel, 'targeted:targeted:full']]); + expect(plan({ gateTagged: 1, shape: off })).toEqual(['gate', 'full', ['adversarial-native:merged:full[testing,security,red-team]']]); + expect(plan({ declared: ['security'] })).toEqual(['code', 'full', panel]); + expect(plan({ declared: ['security'], shape: off })).toEqual(['code', 'full', ['adversarial-native:merged:full[testing,security,red-team]']]); + }); +}); + describe('scanNumbers', () => { test('finds claims and fingerprints them', () => { const a = scanNumbers({ 'docs/bench.md': ['Median dropped 48% to 1.2s', 'no numbers here'] }); @@ -328,10 +386,10 @@ describe('planReview', () => { const p = planReview(base({ paths: ['docs/bench.md'], scope: {}, numbers: scanNumbers({ 'docs/bench.md': ['3x faster'] }) })); expect(roles(p)).toEqual(['outside-voice:outside-voice:host']); }); - test('tests class: runtime 0 is light, core only (Behavior changes: no Testing specialist)', () => { + test('tests class: runtime 0 is light, one batched reader on the Testing checklist (R51, GST-2547)', () => { const p = planReview(base({ paths: ['test/a.test.ts'], scope: { SCOPE_TESTS: 'true' } })); expect(p.depth).toBe('light'); - expect(roles(p)).toEqual([]); + expect([roles(p), batch(p)]).toEqual([['specialist:batched:medium'], ['testing']]); }); test('non-risky code pass 1 is light at any size (R51): one batched reader carrying the Red Team prompt and the native adversarial', () => { const p = planReview(base({ diffLines: 900 })); @@ -455,9 +513,9 @@ const mixed = (o: Partial = {}) => base({ paths: Object.keys(o.perPat const err = (code: DepthError['code'], result?: DepthError['result']): DepthError => ({ code, detail: 'd', input: 'i', repair: 'r', ...(result ? { result } : {}) }); describe('review depth: the matrix', () => { - test('runtime 0 (tests and docs only) is light: core only, nothing dispatched', () => { + test('runtime 0 (tests and docs only) is light: one batched Testing reader that leaves the docs out (R51, GST-2547)', () => { const p = planReview(mixed({ perPath: per({ 'test/a.test.ts': 300, 'docs/a.md': 40 }), diffLines: 340 })); - expect([p.depth, p.runtimeLines, p.dispatches]).toEqual(['light', 0, []]); + expect([p.depth, p.runtimeLines, p.dispatches]).toEqual(['light', 0, [{ role: 'specialist', name: 'batched', effort: 'medium', exclude: [':(exclude)docs/a.md'], checklists: ['testing'] }]]); }); test('runtime 1-50 is light plus one batched specialist: the fixed set, scope picks and the Red Team in one context', () => { const p = planReview(mixed({ perPath: per({ 'src/app.ts': 48, 'test/a.test.ts': 190, 'docs/a.md': 9 }), diffLines: 247 })); diff --git a/test/review-dispatch.test.ts b/test/review-dispatch.test.ts index 3301e3a1a1e..b069e6afd21 100644 --- a/test/review-dispatch.test.ts +++ b/test/review-dispatch.test.ts @@ -956,7 +956,7 @@ describe('the workspace paragraph (GST-482)', () => { const r = run(['render', '--role', role, '--out', out, ...(role === 'fix-check' ? [] : ['--diff-base', SHA]), ...args]); expect(r.status, role + ': ' + r.stderr).toBe(0); const main = renderBrief(role as Parameters[0], { diff_base: role === 'fix-check' ? undefined : SHA, ...slots }, t); - expect(fs.readFileSync(field(r.stdout, 'file'), 'utf8'), role).toBe(workspaceStep(top) + '\n\n' + main + '\n\n' + workspaceParagraph(top)); + expect(fs.readFileSync(field(r.stdout, 'file'), 'utf8'), role).toBe(workspaceStep(top, true) + '\n\n' + main + '\n\n' + workspaceParagraph(top, undefined, true)); } expect(workspaceParagraph(top)).toContain(`begin each command with \`cd '${top}' && \``); expect(workspaceParagraph(top)).toContain(`absolute path under ${top}`); diff --git a/test/review-exclude.test.ts b/test/review-exclude.test.ts index 959aab08fd1..14c5e585c24 100644 --- a/test/review-exclude.test.ts +++ b/test/review-exclude.test.ts @@ -94,6 +94,36 @@ describe('what review_exclude_paths excludes and keeps', () => { for (const f of KEPT) expect(read.has(f)).toBe(true); }, 120_000); + // Value: protects=a results manifest the base policy names by file name leaves the reviewers' diff, and stops keeping the + // receipts it lists, while config files under a broader pattern stay; fails_when=a pattern whose last segment is + // manifest.json keeps the manifest as config, the manifest's full-path list keeps the receipts as named-by-code, or a + // package.json or manifest.json matched only by data/** is excluded; why_new=a large eval results PR stopped at + // REVIEW_DIFF_TOO_LARGE on a 1.42 MB manifest its base policy named; seam=bin/gstack-review-plan and git running the printed commands + test('a config-named data file is excluded when a pattern names its file name, and kept under a broader pattern', () => { + const named = 'docs/bench/run1/results-a/x/manifest.json'; + const repo = makeFixtureRepo({ prefix: 'gstack-exclude-', baseFiles: { '.gstack/ship-policy.json': policyText(['data/**', 'docs/bench/*/results*/**/manifest.json']) } }); + repos.push(repo); + commit(repo, { + [named]: JSON.stringify({ trials: ['data/r1.json', 'data/r2.json'] }) + '\n', + 'data/r1.json': '{"ok": true}\n', + 'data/r2.json': '{"ok": false}\n', + 'data/manifest.json': '{"name": "data"}\n', + 'data/package.json': '{"scripts": {"postinstall": "node x.js"}}\n', + 'docs/bench/run1/package.json': '{"name": "bench"}\n', + }); + const p = JSON.parse(plan(repo, ['--json']).out); + expect(p.review_exclude.kept_files).toEqual([ + { path: 'data/manifest.json', reason: 'config' }, + { path: 'data/package.json', reason: 'config' }, + ]); + expect(p.review_exclude).toMatchObject({ state: 'active', excluded: 3, content: { binary: 0, data: 3, docs: 0, log: 0 } }); + const mb = mergeBase(repo); + const cmds = plan(repo).out.split('\n').filter(l => /^DIFF_(CMD|KEEP): /.test(l)).map(l => l.replace(/^DIFF_(CMD|KEEP): \S+ /, '')); + const read = new Set(cmds.flatMap(c => pathsRead(repo, c, mb))); + for (const f of [named, 'data/r1.json', 'data/r2.json']) expect(read.has(f)).toBe(false); + for (const f of ['data/manifest.json', 'data/package.json', 'docs/bench/run1/package.json']) expect(read.has(f)).toBe(true); + }, 120_000); + // Value: protects=the Red Team, the security specialist, the adversarial pass and the outside voice read the same selection // as the plan, including through the fixture-handling command; fails_when=any brief's git diff command (or the embedded // outside-voice diff) shows an excluded file, or a kept file is unreachable from a brief; why_new=task 8 (the fixture diff --git a/test/review-pass.test.ts b/test/review-pass.test.ts index f7f52a3e849..fbda28eb5d5 100644 --- a/test/review-pass.test.ts +++ b/test/review-pass.test.ts @@ -7,8 +7,8 @@ import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { promptHash, sectionTexts, withWorkspace, workspaceParagraph, workspaceStep } from '../lib/review-brief'; -import { CHUNK_CHARS, PARENT_ONLY_QA, buildManifest, chunkCount, chunkOf, markReader, renderStage, specialistFindings, type Manifest } from '../lib/review-pass'; +import { READ_ONLY_RETRY, promptHash, sectionTexts, withWorkspace, workspaceParagraph, workspaceStep } from '../lib/review-brief'; +import { CHUNK_CHARS, PARENT_ONLY_QA, buildManifest, chunkCount, chunkOf, markReader, planCyberRetry, renderStage, specialistFindings, type Manifest } from '../lib/review-pass'; import type { Dispatch } from '../lib/review-depth'; import { FIXTURE_MARKER } from '../lib/fixture-marker'; @@ -137,7 +137,7 @@ function repo(): { dir: string; env: NodeJS.ProcessEnv } { return { dir, env }; } -interface Sub { title: string; prompt: string; status: string; polls: number; model?: unknown; summary?: string; late?: boolean } +interface Sub { title: string; prompt: string; status: string; polls: number; model?: unknown; summary?: string; late?: boolean; error?: string } /** A fake Capy host: the shell is real (the repository's bins), subagents are scripted. */ const cleanReply = (title: string) => (title.endsWith('outside-voice') ? 'Recommendation: ship as-is because no finding survived' : 'NO FINDINGS'); /** The REVIEWED_TREE line a reader prints from dir (its brief's checkout when it follows the workspace paragraph); '' outside a checkout. */ @@ -148,7 +148,7 @@ function treeLine(dir: string): string { return tree.status === 0 && top.status === 0 ? `REVIEWED_TREE: ${tree.stdout.trim()} ${top.stdout.trim()}\n` : ''; } const briefDir = (prompt: string) => /Workspace: the checkout under review is (.+?)\. Your shell and file tools/.exec(prompt)?.[1] ?? ''; -function host(dir: string, env: NodeJS.ProcessEnv, o: { output?: (title: string) => string; reportFrom?: (title: string) => string; fail?: (title: string) => boolean; reject?: (title: string) => boolean; createThrows?: (title: string) => 'before' | 'after' | undefined; pollsToFinish?: number; lateSummary?: boolean; hang?: (title: string) => boolean; stopped?: (title: string) => boolean; keepSummary?: boolean; epoch?: number } = {}) { +function host(dir: string, env: NodeJS.ProcessEnv, o: { output?: (title: string) => string; reportFrom?: (title: string) => string; fail?: (title: string) => boolean; reject?: (title: string) => boolean; createThrows?: (title: string) => 'before' | 'after' | undefined; pollsToFinish?: number; lateSummary?: boolean; hang?: (title: string) => boolean; stopped?: (title: string) => boolean; keepSummary?: boolean; epoch?: number; error?: (title: string) => string | undefined } = {}) { let clock = 0; const subs = new Map(); const creates: Sub[] = []; @@ -160,7 +160,8 @@ function host(dir: string, env: NodeJS.ProcessEnv, o: { output?: (title: string) if (s.late && !s.summary) { s.summary = reply(s); continue; } if (s.status !== 'working' || o.hang?.(s.title)) continue; if (++s.polls < (o.pollsToFinish ?? 1)) continue; - if (o.stopped?.(s.title)) { s.status = 'stopped'; if (o.keepSummary) s.summary = reply(s); } + if (o.error?.(s.title)) { s.status = 'failed'; s.error = o.error(s.title); if (o.keepSummary) s.summary = reply(s); } + else if (o.stopped?.(s.title)) { s.status = 'stopped'; if (o.keepSummary) s.summary = reply(s); } else if (o.fail?.(s.title)) { s.status = 'failed'; if (o.keepSummary) s.summary = reply(s); } else if (o.lateSummary && !s.late) { s.status = 'done'; s.late = true; } else { s.status = 'done'; s.summary = reply(s); } @@ -190,7 +191,7 @@ function host(dir: string, env: NodeJS.ProcessEnv, o: { output?: (title: string) }, start: async ({ indices, model }: { indices: number[]; model?: unknown }) => { starts.push(indices); for (const i of indices) { const s = subs.get(String(i))!; s.status = 'working'; if (model) s.model = model; } return { started: indices.map(index => ({ index })), rejected: [] }; }, list: async () => { advance(); return { tasks: [...subs].map(([p, s]) => ({ path: p, title: s.title, status: s.status })), total: subs.size }; }, - get: async ({ path: p }: { path: string }) => ({ path: p, status: subs.get(p)!.status, summary: subs.get(p)!.summary }), + get: async ({ path: p }: { path: string }) => ({ path: p, status: subs.get(p)!.status, summary: subs.get(p)!.summary, ...(subs.get(p)!.error ? { latest_error: subs.get(p)!.error } : {}) }), stop: async ({ paths }: { paths: string[] }) => { stops.push(...paths); for (const p of paths) subs.get(p)!.status = 'stopped'; return { results: paths.map(p => ({ path: p, ok: true })) }; }, }, thread: { get: async () => ({ cost: { tokens: 1000 + clock, credits: 1 + clock / 1000 } }) }, @@ -630,6 +631,133 @@ describe('Capy pass program (fake host, real bins)', () => { expect(v.stdout).not.toContain('NOT_REVIEWED'); }, 300_000); + // R95 (2026-11-13): a cyber_policy refusal of the outside voice is retried once on GPT-6 Astra with the read-only brief, then on Gemini 4 Carbon with the original brief; when every attempt fails the second-family read is missing, disclosed, and Step 11 goes on. + const CYBER = fs.readFileSync(path.join(ROOT, 'test/fixtures/cyber-policy/capy-latest-error.txt'), 'utf8').trim(); + const voiceReply = (t: string) => (t.includes('outside-voice') ? 'Recommendation: ship as-is because no finding survived' : cleanReply(t)); + async function refusedVoices(pass: string, error: (title: string) => string | undefined, lane: Record = {}) { + const { dir, env } = repo(); + const out = path.join(dir, '.state/run/p1'); + const h = host(dir, env, { error, output: voiceReply, epoch: Date.now() }); + const base = { base: 'main', out, pass, planFlags: ['--depth-floor', 'full'], ...lane }; + expect(await runPass(h, base)).toContain('NEXT: judge (Phase 4)'); + let res = '', all = ''; + for (let i = 0; i < 12; i++) { + res = await runPass(h, { ...base, stage: 'voices', stuckMs: 60_000 }); + all += res + '\n'; + if (!res.includes('NEXT: poll')) break; + } + const created = (suffix: string) => h.creates.find(c => c.title === 'ship ' + pass + ' ' + suffix); + const verify = bin(dir, env, ['verify', '--ledger', path.join(out, 'review-ledger.jsonl')]).stdout; + return { res, all, h, created, verify, base }; + } + + // Value: protects=R95 on the real pass program: Capy's captured cyber_policy refusal of the Sol outside voice is recorded unavailable with its own reason and retried once on openai/gpt-6-astra with the read-only brief, whose review is the Step 11 outside record; fails_when=the refusal is recorded as a plain failure with no retry, the retry resends the original brief, or the original's unavailable record replaces the retry's; + // why_new=R95; seam=lib/capy-review-pass.js ended outside voice; no_claim=that Astra finishes a real refused brief (one live smoke in GSTA-537) + test('a cyber_policy refusal is retried once on Astra with the read-only brief (R95)', async () => { + const { res, all, h, created, verify } = await refusedVoices('x40p1', t => (t.endsWith(' outside-voice') ? CYBER : undefined)); + expect(res).not.toContain('STOP:'); + expect(all).toContain('RETRY: reader=outside-voice/astra-read-only model=openai/gpt-6-astra brief=read-only'); + expect(all).toMatch(/COLLECT_UNAVAILABLE: reader=outside-voice .*/); + const astra = created('outside-voice/astra-read-only')!; + expect(astra.model).toEqual({ model_id: 'openai/gpt-6-astra', reasoning_mode: 'high' }); + expect(astra.prompt).toContain(READ_ONLY_RETRY); + expect(astra.prompt).not.toContain('Think like an attacker'); + expect(created('outside-voice')!.prompt).toContain('Think like an attacker and a chaos engineer.'); + expect(created('outside-voice/gemini-4-carbon')).toBeUndefined(); + expect(res).toContain('OUTSIDE_RECORD: "outside_provider":"host-subagent","outside_model":"openai/gpt-6-astra","outside_status":"completed","outside_note":"second-family read by openai/gpt-6-astra on the read-only retry brief after cyber_policy refused openai/gpt-6.1-sol"'); + expect(res).not.toContain('"outside_model":"openai/gpt-6.1-sol"'); + expect(res).toContain('NEXT: judge the voices'); + expect(verify).toMatch(/^BRIEF outside-voice UNAVAILABLE/m); + expect(verify).toMatch(/^OUTPUT outside-voice UNAVAILABLE .*reason=".*cyber_policy/m); + expect(verify).toMatch(/^BRIEF outside-voice\/astra-read-only MATCH/m); + expect(verify).not.toContain('MISMATCH'); + expect(verify).toMatch(/^VERIFY: .* unavailable=1$/m); + expect(h.creates.filter(c => c.title.includes('outside-voice')).length).toBe(2); + }, 600_000); + + // Value: protects=an Astra refusal of the retry falls through to google/gemini-4-carbon with the original brief byte for byte, and a refusal or failure there records the second-family read as missing (a disclosed gap, not a pass) while Step 11 goes on to the native voice; fails_when=a fourth attempt starts, Gemini gets the reworded brief, or the exhausted chain STOPs the pass; + // why_new=R95; seam=lib/capy-review-pass.js retry chain; no_claim=Gemini's availability under another organization's model policy + test('an Astra refusal falls through to Gemini 4 Carbon with the original brief, then the second-family read is missing (R95)', async () => { + const { res, all, h, created, verify } = await refusedVoices('x41p1', t => (/outside-voice(\/astra-read-only|\/gemini-4-carbon)?$/.test(t) ? CYBER : undefined)); + expect(res).not.toContain('STOP:'); + expect(all).toContain('RETRY: reader=outside-voice/astra-read-only model=openai/gpt-6-astra brief=read-only'); + expect(all).toContain('RETRY: reader=outside-voice/gemini-4-carbon model=google/gemini-4-carbon brief=original'); + expect(all).toContain('RETRY: exhausted'); + const gemini = created('outside-voice/gemini-4-carbon')!; + expect(gemini.model).toEqual({ model_id: 'google/gemini-4-carbon', reasoning_mode: 'high' }); + expect(gemini.prompt).toBe(created('outside-voice')!.prompt); + expect(h.creates.filter(c => c.title.includes('outside-voice')).length).toBe(3); + expect(res).toContain('"outside_model":"google/gemini-4-carbon","outside_status":"unavailable","outside_note":"second-family read missing: cyber_policy refused openai/gpt-6.1-sol, openai/gpt-6-astra (read-only retry brief) and google/gemini-4-carbon"'); + expect(res).toContain('first write this voice its own adversarial-review row'); + expect(res).toContain('NEXT: judge the voices'); + expect(verify).not.toContain('MISMATCH'); + expect(verify).toMatch(/^BRIEF outside-voice\/gemini-4-carbon UNAVAILABLE/m); + expect(verify).toMatch(/^VERIFY: .* unavailable=3$/m); + }, 900_000); + + // Value: protects=on a Google-family lane the Gemini step is skipped (Step 11 refuses an outside voice of the lane's family), so two OpenAI refusals record the second-family read as missing and a resume finishes instead of stopping; fails_when=Gemini is planned beside a Google lane and familyStop stops every resume; + // why_new=GSTA-537 /ship outside-voice finding (lib/review-pass.ts:274), fixed under the Captain's scoped fix-check grant; seam=planCyberRetry via gstack-review-dispatch retry; no_claim=which outside voice a Google lane should use + test('a Google-family lane skips the Gemini retry and records the second-family read missing, with no STOP on resume (R95)', async () => { + const lane = { laneModel: 'google/gemini-4-argon', models: { 'outside-voice': { model_id: 'openai/gpt-6.1-sol', reasoning_mode: 'medium' } } }; + const { res, all, h, created, base } = await refusedVoices('x45p1', t => (/outside-voice(\/astra-read-only)?$/.test(t) ? CYBER : undefined), lane); + expect(all).not.toContain('STOP:'); + expect(all).toContain('RETRY: reader=outside-voice/astra-read-only model=openai/gpt-6-astra brief=read-only'); + expect(all).toContain('RETRY: exhausted reader=outside-voice/astra-read-only'); + expect(created('outside-voice/gemini-4-carbon')).toBeUndefined(); + expect(res).toContain('"outside_status":"unavailable","outside_note":"second-family read missing: cyber_policy refused openai/gpt-6.1-sol and openai/gpt-6-astra (read-only retry brief)"'); + expect(res).toContain('NEXT: judge the voices'); + const again = await runPass(h, { ...base, stage: 'voices', stuckMs: 60_000 }); + expect(again).not.toContain('STOP:'); + }, 600_000); + + // Value: protects=planCyberRetry skips only the steps whose family the lane or native voice holds: an Anthropic lane still gets Astra then Gemini, a Google lane gets Astra and then nothing; fails_when=the family check drops Gemini for every lane or keeps it beside a Google lane; + // why_new=GSTA-537 scoped fix-check (control for the Google-lane case); seam=lib/review-pass.ts planCyberRetry; no_claim=none + test('planCyberRetry keeps Gemini for an Anthropic lane and skips it for a Google lane (R95)', () => { + const chain = (taken: string[]) => { + const m = { pass: 'u1', readers: [{ reader: 'outside-voice', role: 'outside-voice', stage: 'voices', state: 'collected' }] } as unknown as Manifest; + const astra = planCyberRetry(m, m.readers[0]!, taken); + return [astra?.reader, astra ? planCyberRetry(m, astra, taken)?.reader ?? null : null]; + }; + expect(chain(['anthropic'])).toEqual(['outside-voice/astra-read-only', 'outside-voice/gemini-4-carbon']); + expect(chain(['google'])).toEqual(['outside-voice/astra-read-only', null]); + }); + + // Value: protects=only cyber_policy starts a retry: a failed voice whose host error is another provider failure, and a voice that reviews normally, each run exactly one outside voice; fails_when=any failure, or a success, dispatches an Astra or Gemini reader; + // why_new=R95 (no new retries for anything else; negative control); seam=lib/capy-review-pass.js; no_claim=none + test('a non-refusal failure and a normal review never retry (R95)', async () => { + const failed = await refusedVoices('x42p1', t => (t.endsWith(' outside-voice') ? 'OpenAI key declined the request: invalid_api_key: Incorrect API key provided.' : undefined)); + expect(failed.res).not.toContain('STOP:'); + expect(failed.all).toContain('RETRY: none'); + expect(failed.res).toContain('"outside_model":"openai/gpt-6.1-sol","outside_status":"unavailable"'); + expect(failed.h.creates.filter(c => c.title.includes('outside-voice')).length).toBe(1); + const clean = await refusedVoices('x43p1', () => undefined); + expect(clean.all).not.toContain('RETRY:'); + expect(clean.res).toContain('"outside_model":"openai/gpt-6.1-sol","outside_status":"completed"'); + expect(clean.res).not.toContain('outside_note'); + expect(clean.h.creates.filter(c => c.title.includes('outside-voice')).length).toBe(1); + }, 600_000); + + // Value: protects=a voice that the host marks refused under cyber_policy but that still wrote a review is collected as that review, with its own outside record, and starts no retry; fails_when=the retry is planned before the program knows the voice left findings, so a redundant Astra reader runs and the collected voice's OUTSIDE_RECORD is dropped; + // why_new=GSTA-537 /ship red-team finding (capy-review-pass.js refusal before collect); seam=lib/capy-review-pass.js ended outside voice; no_claim=how often a refused voice leaves a review + test('a cyber_policy refusal that still left a review is collected and never retried (R95)', async () => { + const { dir, env } = repo(); + const out = path.join(dir, '.state/run/p1'); + const h = host(dir, env, { error: t => (t.endsWith(' outside-voice') ? CYBER : undefined), keepSummary: true, output: t => (t.endsWith('outside-voice') ? '1. **A guard fails open** - `src/a.ts:1` accepts any input. Severity: Medium. Blocks: no.\n\nRecommendation: fix the guard because it fails open' : cleanReply(t)), epoch: Date.now() }); + const base = { base: 'main', out, pass: 'x44p1', planFlags: ['--depth-floor', 'full'] }; + expect(await runPass(h, base)).toContain('NEXT: judge (Phase 4)'); + let res = '', all = ''; + for (let i = 0; i < 6; i++) { + res = await runPass(h, { ...base, stage: 'voices', stuckMs: 60_000 }); + all += res + '\n'; + if (!res.includes('NEXT: poll')) break; + } + expect(res).not.toContain('STOP:'); + expect(all).not.toContain('RETRY:'); + expect(h.creates.filter(c => c.title.includes('outside-voice')).length).toBe(1); + expect(res).toContain('OUTSIDE_RECORD: "outside_provider":"host-subagent","outside_model":"openai/gpt-6.1-sol","outside_status":"completed"'); + expect(fs.readFileSync(path.join(out, 'merged.jsonl'), 'utf8')).toContain('A guard fails open'); + }, 300_000); + test('an audit reader marked first settles before any specialist starts; its output is returned, never merged', async () => { const { dir, env } = repo(); const out = path.join(dir, '.state/run/p1'); @@ -1270,7 +1398,10 @@ describe('readers on a shared machine review the checkout the pass ships (GST-48 expect(res).not.toContain('STOP:'); expect(res).toContain('NEXT: judge (Phase 4)'); expect(h.creates.length).toBeGreaterThan(2); - for (const c of h.creates) expect([c.prompt.startsWith(workspaceStep(wt) + '\n\n'), c.prompt.endsWith('\n\n' + workspaceParagraph(wt))], c.title).toEqual([true, true]); + for (const c of h.creates) { + const verdict = !c.title.includes(' audit/'); + expect([c.prompt.startsWith(workspaceStep(wt, verdict) + '\n\n'), c.prompt.endsWith('\n\n' + workspaceParagraph(wt, undefined, verdict))], c.title).toEqual([true, true]); + } expect(bin(wt, env, ['verify', '--ledger', path.join(out, 'review-ledger.jsonl')]).stdout).not.toContain('wrong_tree'); }, 240_000); diff --git a/test/review-plan-cli.test.ts b/test/review-plan-cli.test.ts index a62313a7d91..b4836f30f2d 100644 --- a/test/review-plan-cli.test.ts +++ b/test/review-plan-cli.test.ts @@ -52,6 +52,14 @@ describe('gstack-review-plan', () => { expect(plan.status).toBe(0); expect(plan.stdout).toContain('REVIEW_PLAN: class=docs pass=1 next=full dispatches=0 numbers=no'); }); + // Value: protects=R51's one reviewer on a tests-only diff at the CLI /ship runs; fails_when=it prints dispatches=0 or any reader but the batched Testing one; + // why_new=HARN-1 (harness-evals#425, GST-2547): a test getting a scripted clock planned zero readers; seam=gstack-review-plan on a real repo; no_claim=what the reader finds + test('a tests-only diff plans one batched Testing reader (R51)', () => { + const r = run(repo({ 'test/clock.test.ts': "import { test, expect, setSystemTime } from 'bun:test';\ntest('clock', () => { setSystemTime(new Date(0)); expect(Date.now()).toBe(0); setSystemTime(); });\n" }), []); + expect(r.status).toBe(0); + expect(r.stdout).toContain('REVIEW_PLAN: class=tests pass=1 next=full dispatches=1 numbers=no'); + expect(r.stdout.split('\n').filter(l => l.startsWith('DISPATCH: '))).toEqual(['DISPATCH: specialist batched effort=medium checklists=testing']); + }); test('a docs diff that publishes numbers keeps the outside voice', () => { const r = run(repo({ 'docs/bench.md': 'Median latency fell 42% to 180 ms.\n' }), []); expect(r.stdout).toContain('DISPATCH: outside-voice outside-voice effort=host'); diff --git a/test/review-reader-selection.test.ts b/test/review-reader-selection.test.ts index 091199dc780..d3c2a4d75b2 100644 --- a/test/review-reader-selection.test.ts +++ b/test/review-reader-selection.test.ts @@ -185,3 +185,39 @@ describe('every reader path builds its diff from the base policy\'s selection', expect(sub).toBe(root); }, 120_000); }); + +describe('the review-size ceiling on a standalone render', () => { + /** A plain change beside about 2.5 MB of data with no base policy, so every reader's selection is over the 2 MB ceiling. */ + function large() { + const repo = makeFixtureRepo({ prefix: 'gstack-sel-big-' }); + repos.push(repo); + const files: Record = { 'lib/a.ts': 'export const a = 1;\n' }; + for (let k = 0; k < 6; k++) files['data/t' + k + '.json'] = ('{"x": "' + 'y'.repeat(200) + '"}\n').repeat(2000); + commit(repo, files); + return { repo, mb: repo.git('merge-base', 'origin/main', 'HEAD') }; + } + + // Value: protects=the outside voice rendered on its own keeps its exemption from the 2 MB ceiling and gets a sliced diff; + // fails_when=render's selection carries no role, so the ceiling's outside-voice exemption never matches and the render + // stops at REVIEW_DIFF_TOO_LARGE (#4350 regression, GST-2632); why_new=GST-2632; seam=gstack-review-dispatch render on a + // real repository; no_claim=the pass manifest's voices stage + test('the outside voice renders over the ceiling with a sliced diff', () => { + const { repo, mb } = large(); + const out = path.join(repo.root, 'ov'); + const r = render(repo, mb, out, 'outside-voice'); + expect({ status: r.status, err: r.err }).toEqual({ status: EXIT.ok, err: '' }); + expect(fs.statSync(path.join(out, 'outside-voice.diff')).size).toBeLessThanOrEqual(REVIEW_DIFF_MAX_BYTES); + }, 120_000); + + // Value: protects=every other reader on the same standalone path is still refused over the ceiling; fails_when=the + // outside voice's exemption widens to the reader rendered beside it; why_new=GST-2632; seam=gstack-review-dispatch render + // on a real repository; no_claim=the wording of the refusal + test('a reader that is not the outside voice is still refused over the ceiling', () => { + const { repo, mb } = large(); + const out = path.join(repo.root, 'rt'); + const r = render(repo, mb, out, 'red-team', ['--findings-file', empty(repo), '--specialists', '1']); + expect(r.status).toBe(EXIT.refused); + expect(r.err).toContain('REVIEW_DIFF_TOO_LARGE'); + expect(fs.existsSync(path.join(out, 'red-team.prompt.md'))).toBe(false); + }, 120_000); +}); diff --git a/test/review-verdict.test.ts b/test/review-verdict.test.ts new file mode 100644 index 00000000000..da1b9abf1f5 --- /dev/null +++ b/test/review-verdict.test.ts @@ -0,0 +1,212 @@ +/** + * GST-2495: every blocking reader's reply carries `REVIEW_VERDICT: blocking=[ at=:,...]`, and collect checks it + * against the findings it parses instead of inferring "nothing blocks" from prose (docs/review-policy.md#verdict-line). The + * controls are test/fixtures/review-ledger/verdict-controls.json: the GSTA-521 probe lines, FOUN-298's native reply + * (founderstar#926), #3901's verdict line and CAPY-1's fix-check (qm #3567) and red-team (qm #3589) summaries. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { BRIEF_ROLES, promptHash, VERDICT_ASK, withWorkspace } from '../lib/review-brief'; +import { appendEvent, collect, judge, parseFindings, parseReply, rank, readJsonl, recordJudgment, recordSent, statesNoBlocks, verify, type MergedLine } from '../lib/review-ledger'; +import { parseVerdict, withoutVerdictLines } from '../lib/review-verdict'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const CONTROLS = JSON.parse(fs.readFileSync(path.join(ROOT, 'test/fixtures/review-ledger/verdict-controls.json'), 'utf8')) as { probes: string[]; outputs: Record }; +const TREE = `REVIEWED_TREE: ${'a'.repeat(40)} /workspace/app`; +const blocking = (fs: Array<{ label: string; raw: string }>) => fs.filter(f => (rank(f.label) ?? 0) >= 4 && !statesNoBlocks(f.raw)).length; +const reply = (body: string, line?: string) => [TREE, ...(line === undefined ? [] : [line]), '', body].join('\n'); +const asked = (role: string, out: string, raises = true) => parseReply(role, out, raises, true); + +describe('the REVIEW_VERDICT line', () => { + test('grammar: count, optional locations, wrappers; fenced lines ignored; identical repeats count once, differing ones are malformed', () => { + expect(parseVerdict('REVIEW_VERDICT: blocking=0')).toEqual({ state: 'valid', blocking: 0, at: [] }); + expect(parseVerdict('x\n**REVIEW_VERDICT: blocking=2 at=lib/a.ts:3,b.md:9**')).toEqual({ state: 'valid', blocking: 2, at: ['lib/a.ts:3', 'b.md:9'] }); + expect(parseVerdict('- `REVIEW_VERDICT: blocking=1`')).toEqual({ state: 'valid', blocking: 1, at: [] }); + expect(parseVerdict('REVIEW_VERDICT: blocking=1\nREVIEW_VERDICT: blocking=1')).toEqual({ state: 'valid', blocking: 1, at: [] }); + expect(parseVerdict('no line here').state).toBe('missing'); + expect(parseVerdict('```\nREVIEW_VERDICT: blocking=0\n```').state).toBe('missing'); + for (const bad of ['REVIEW_VERDICT: blocking=two', 'REVIEW_VERDICT: blocking=0 at=lib/a.ts:3', 'REVIEW_VERDICT: blocking=100', 'REVIEW_VERDICT: none', + 'REVIEW_VERDICT: blocking=1 at=somewhere', 'REVIEW_VERDICT: blocking=0\nREVIEW_VERDICT: blocking=1', 'review_verdict: blocking=0 trailing words']) expect(parseVerdict(bad).state, bad).toBe('malformed'); + expect(withoutVerdictLines('a\nREVIEW_VERDICT: blocking=0\n```\nREVIEW_VERDICT: blocking=9\n```')).toBe('a\n```\nREVIEW_VERDICT: blocking=9\n```'); + }); + + test('the ask: every blocking role\'s brief carries it after the fingerprint step and in the closing paragraph; an audit reader\'s does not', () => { + const w = withWorkspace('BODY', '/work/repo', undefined, { verdict: true }); + expect(w.split('\n\n')[0]).toContain(VERDICT_ASK); + expect(w.endsWith('gstack checks that count against your findings, so do not repeat it.')).toBe(true); + expect(withWorkspace('BODY', '/work/repo')).not.toContain('REVIEW_VERDICT'); + expect(BRIEF_ROLES.length).toBe(7); + }); +}); + +describe('negative controls on every blocking role, both review classes', () => { + // A valid line lowers nothing by itself (Captain ruling D1, 2026-11-14): no probe line, role or line state stops blocking. + for (const role of BRIEF_ROLES) for (const raises of [true, false]) { + test(`${role} ${raises ? 'gate' : 'relaxed'} class`, () => { + const lowered: number[] = []; + for (const [i, p] of CONTROLS.probes.entries()) { + const main = parseFindings(role, reply(p), raises); + for (const line of [undefined, 'REVIEW_VERDICT: blocking=none', 'REVIEW_VERDICT: blocking=0\nREVIEW_VERDICT: blocking=1']) { + expect(asked(role, reply(p, line), raises).findings.map(f => [f.label, f.raw]), `${i} ${line}`).toEqual(main.map(f => [f.label, f.raw])); + } + // A declared blocker the parser missed always blocks; unlocated ones share one row, so blocking_found counts them once. + for (const n of [1, 2]) expect(blocking(asked(role, reply(p, `REVIEW_VERDICT: blocking=${n}`), raises).findings), `${i} blocking=${n}`).toBeGreaterThanOrEqual(1); + const zero = asked(role, reply(p, 'REVIEW_VERDICT: blocking=0'), raises).findings; + if (blocking(main) && !blocking(zero)) lowered.push(i); + } + expect(lowered).toEqual([]); + }); + } + + test('FOUN-298: blocking=0 keeps CRITICAL,Low,Low,Low and makes the summary row a candidate the lead may lower; with no line nothing is flagged', () => { + const out = CONTROLS.outputs.foun298!; + const at = out.replace(/^(REVIEWED_TREE: .*)$/m, '$1\nREVIEW_VERDICT: blocking=0'); + for (const raises of [true, false]) { + const r = asked('adversarial-native', at, raises); + expect(r.findings.map(f => [f.label, f.summary ?? false])).toEqual([['CRITICAL', true], ['Low', false], ['Low', false], ['Low', false]]); + expect(r.verdict).toEqual({ state: 'valid', parsed: 1, declared: 0, agrees: false }); + expect(asked('adversarial-native', out, raises).findings.some(f => f.summary)).toBe(false); + expect(asked('adversarial-native', out, raises).findings.map(f => f.label)).toEqual(['CRITICAL', 'Low', 'Low', 'Low']); + expect(asked('adversarial-native', at.replace('blocking=0', 'blocking=1'), raises).verdict).toMatchObject({ declared: 1, parsed: 1, agrees: true }); + } + }); + + test('#3901: without a line every role parses as on main', () => { + for (const role of BRIEF_ROLES) for (const raises of [true, false]) expect(asked(role, CONTROLS.outputs.pr3901!, raises).findings).toEqual(parseFindings(role, CONTROLS.outputs.pr3901!, raises)); + }); + + test('CAPY-1 (qm #3567 fix-check, qm #3589 red-team): blocking=0 keeps the CRITICAL row but makes it a summary candidate; no line keeps it a plain CRITICAL', () => { + for (const key of ['capy1_fix_check', 'capy1_red_team']) for (const role of BRIEF_ROLES) { + const out = CONTROLS.outputs[key]!; + const zero = asked(role, out.replace(/^(REVIEWED_TREE: .*)$/m, '$1\nREVIEW_VERDICT: blocking=0')); + expect(zero.findings.map(f => [f.label, f.summary ?? false]), `${key} ${role}`).toEqual([['INFORMATIONAL', false], ['CRITICAL', true]]); + expect(zero.verdict).toMatchObject({ declared: 0, parsed: 1, agrees: false }); + expect(asked(role, out).findings.map(f => [f.label, f.summary ?? false])).toEqual([['INFORMATIONAL', false], ['CRITICAL', false]]); + expect(asked(role, out.replace(/^(REVIEWED_TREE: .*)$/m, '$1\nREVIEW_VERDICT: blocking=1')).findings.map(f => [f.label, f.summary ?? false])).toEqual([['INFORMATIONAL', false], ['CRITICAL', false]]); + } + }); + + test('positive phrasings under blocking=0 still block, as summary candidates the lead may lower with a reason', () => { + const one = (p: string) => asked('adversarial-native', reply(p, 'REVIEW_VERDICT: blocking=0')).findings.map(f => [f.label, f.summary ?? false]); + expect(one('Nothing that blocks: one Medium and two Low findings, all FIXABLE.')).toEqual([['CRITICAL', true]]); + expect(one('Nothing that blocks: three High findings, all FIXABLE.')).toEqual([['CRITICAL', true]]); + expect(one('Nothing that blocks: two CRITICAL findings, all FIXABLE.')).toEqual([['CRITICAL', true]]); + }); + + test('a real unanchored FIXABLE blocker beside a denial line keeps blocking when the count agrees (Step 11 rerun at 1acb0d5)', () => { + const out = CONTROLS.outputs.native_relabel_loss!; + for (const raises of [true, false]) { + const r = asked('adversarial-native', out, raises); + expect(r.findings[0]!.label, `raises=${raises}`).toBe(raises ? 'CRITICAL' : parseFindings('adversarial-native', out, raises)[0]!.label); + expect(r.findings.map(f => [f.label, f.raw])).toEqual(parseFindings('adversarial-native', out, raises).map(f => [f.label, f.raw])); + } + const gate = asked('adversarial-native', out); + expect(blocking(gate.findings)).toBe(2); + expect(gate.verdict).toMatchObject({ declared: 1, parsed: 2, agrees: false }); + expect(gate.findings.map(f => f.summary ?? false)).toEqual([true, true]); + }); +}); + +describe('declared more blockers than parsed', () => { + test('one row per unmatched location and one for the rest, appended after the parsed rows', () => { + const out = reply('1. **Cache key (key.ts:3).** FIXABLE: key on the tree. Severity: Low. Blocks: no.', 'REVIEW_VERDICT: blocking=3 at=key.ts:3,lib/auth.ts:10'); + const r = asked('adversarial-native', out); + expect(r.findings.map(f => [f.label, !!f.synthetic])).toEqual([['Low', false], ['CRITICAL', true], ['CRITICAL', true], ['CRITICAL', true]]); + expect(r.findings[1]!.raw.startsWith('key.ts:3: REVIEW_VERDICT declared blocking=3, but collect parsed 0')).toBe(true); + expect(r.findings[2]!.raw.startsWith('lib/auth.ts:10: ')).toBe(true); + expect(r.findings[3]!.raw).toContain('1 declared blocker with no location named'); + expect(asked('adversarial-native', out.replace('blocking=3 at=key.ts:3,lib/auth.ts:10', 'blocking=1 at=key.ts:3')).findings.map(f => f.raw.split(':')[0])).toEqual(['1. **Cache key (key.ts', 'key.ts']); + }); +}); + +describe('the line never colours its neighbour', () => { + test('in an asked render it is skipped; main\'s parser (no ask) still raises the shapes it always did', () => { + const next = 'I found no Critical findings and two Low findings.'; + const out = `${TREE}\nREVIEW_VERDICT: blocking=0\n${next}`; + expect(asked('fix-check', out).findings).toEqual(parseFindings('fix-check', `${TREE}\n${next}`)); + expect(parseFindings('fix-check', `${TREE}\n${next}`).map(f => f.label)).toEqual(['Low']); + const pinned = parseFindings('fix-check', out).map(f => f.label); + expect(pinned).toEqual(parseFindings('fix-check', out).map(f => f.label)); + for (const role of BRIEF_ROLES) for (const p of CONTROLS.probes) { + const without = parseFindings(role, reply(p)); + const withLine = parseFindings(role, reply(p, 'REVIEW_VERDICT: blocking=0')); + expect(blocking(withLine), `${role} ${p}`).toBeGreaterThanOrEqual(blocking(without)); + } + }); +}); + +describe('a finding line that names REVIEW_VERDICT is never stripped', () => { + test('prose about the token is no attempt, and a malformed attempt keeps its line for the parser', () => { + const finding = '1. REVIEW_VERDICT parsing in lib/a.ts:3 drops findings. CRITICAL. Blocks: yes'; + const r = asked('specialist/testing', reply(finding, 'REVIEW_VERDICT: blocking=1 at=lib/a.ts:3')); + expect(r.findings.filter(f => f.label === 'CRITICAL').length).toBeGreaterThanOrEqual(1); + expect(r.verdict?.state).toBe('valid'); + expect(r.verdict?.agrees).toBe(true); + const malformed = '- REVIEW_VERDICT: lines in lib/a.ts:3 are dropped. CRITICAL. Blocks: yes'; + const m = asked('specialist/testing', reply(malformed)); + expect(m.verdict?.state).toBe('malformed'); + expect(blocking(m.findings)).toBe(blocking(parseFindings('specialist/testing', reply(malformed)))); + expect(blocking(m.findings)).toBeGreaterThanOrEqual(1); + }); +}); + +describe('a ledger round trip', () => { + const dirs: string[] = []; + afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); + const run = (verdict: boolean, outputs: string[]) => { + const d = fs.mkdtempSync(path.join(os.tmpdir(), 'review-verdict-')); dirs.push(d); + const ledger = path.join(d, 'review-ledger.jsonl'), merged = path.join(d, 'merged.jsonl'); + fs.writeFileSync(merged, ''); + for (const [k, out] of outputs.entries()) { + const brief = path.join(d, `brief${k}.md`), text = `brief ${k}`; + fs.writeFileSync(brief, text); + appendEvent(ledger, { event: 'rendered', reader: 'adversarial-native', role: 'adversarial-native', name: null, file: brief, sha256: promptHash(text), bytes: text.length, ...(verdict ? { verdict: 1 } : {}) }); + recordSent(ledger, 'adversarial-native', text); + const file = path.join(d, `out${k}.md`); + fs.writeFileSync(file, out); + collect(ledger, 'adversarial-native', out, merged, file); + } + const rows = readJsonl(merged); + const judged = rows.map(m => ({ id: m.id, severity: m.label })); + fs.writeFileSync(path.join(d, 'judged.jsonl'), judged.map(j => JSON.stringify(j)).join('\n') + '\n'); + recordJudgment(ledger, rows, judged, path.join(d, 'judged.jsonl'), merged); + return { ledger, merged, rows, v: verify(ledger) }; + }; + const declared = reply('1. **Cache key (key.ts:3).** FIXABLE: key on the tree. Severity: Low. Blocks: no.', 'REVIEW_VERDICT: blocking=1'); + + test('re-rendered twice: ids keep the per-output prefix, synthetic rows survive verify, and verify counts the verdicts', () => { + const { rows, v } = run(true, [declared, declared]); + expect(rows.map(r => r.id)).toEqual(['adversarial-native#1', 'adversarial-native#v1', 'adversarial-native#2.1', 'adversarial-native#2.v1']); + expect(v.rows.filter(r => r.kind !== 'VERDICT').map(r => r.status).every(s => s === 'MATCH' || s === 'OK')).toBe(true); + expect(v.clean).toBe(true); + expect(v.verdicts).toEqual({ asked: 2, agree: 0 }); + }); + + test('an edited summary flag or verdict makes verify dirty; a render that never asked ignores the line', () => { + const capy = CONTROLS.outputs.capy1_fix_check!.replace(/^(REVIEWED_TREE: .*)$/m, '$1\nREVIEW_VERDICT: blocking=0'); + const a = run(true, [capy]); + expect(a.rows.map(r => r.summary_candidate ?? false)).toEqual([false, true]); + fs.writeFileSync(a.merged, a.rows.map(r => JSON.stringify({ ...r, summary_candidate: undefined })).join('\n') + '\n'); + expect(verify(a.ledger).clean).toBe(false); + const b = run(false, [declared]); + expect(b.rows.map(r => r.id)).toEqual(['adversarial-native#1']); + expect(b.v.verdicts).toEqual({ asked: 0, agree: 0 }); + }); + + test('a summary flag edited onto a real CRITICAL makes verify dirty even when the render never asked', () => { + const c = run(false, [reply('1. CRITICAL: token leak in auth.ts:3. Blocks: yes')]); + expect(c.v.clean).toBe(true); + expect(c.rows.map(r => [r.label, r.summary_candidate ?? false])).toEqual([['CRITICAL', false]]); + fs.writeFileSync(c.merged, c.rows.map(r => JSON.stringify({ ...r, summary_candidate: true })).join('\n') + '\n'); + expect(verify(c.ledger).clean).toBe(false); + }); + + test('lead judgment lowers a verdict summary candidate only with a reason', () => { + const rows = run(true, [CONTROLS.outputs.capy1_red_team!.replace(/^(REVIEWED_TREE: .*)$/m, '$1\nREVIEW_VERDICT: blocking=0')]).rows; + const lower = (reason?: string) => judge(rows, rows.map(m => ({ id: m.id, severity: m.summary_candidate ? 'INFORMATIONAL' : m.label, ...(reason ? { reason } : {}) }))); + expect(lower('the reader\'s own verdict line says nothing blocks').dismissed).toEqual([rows[1]!.id]); + expect(lower().downgraded).toEqual([rows[1]!.id]); + }); +}); diff --git a/test/runtime-root-assets.test.ts b/test/runtime-root-assets.test.ts index d18eed0beef..be5647d4725 100644 --- a/test/runtime-root-assets.test.ts +++ b/test/runtime-root-assets.test.ts @@ -20,6 +20,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { HOST_CONFIG_MAP } from '../hosts'; +import { bunIsolationArgs } from '../lib/bun-isolation'; import { runGeneration } from '../scripts/gen-skill-docs'; const ROOT = path.resolve(import.meta.dir, '..'); @@ -43,7 +44,9 @@ const ROOT_BUILDERS: Record = { // Deferred, with the reason recorded in TODOS.md: /ship's measure loop runs // scripts/ship-measure.ts, which imports gstack's test helpers and eval // harness; a runtime root would need the whole development tree. -const DEFERRED = new Set(['scripts/ship-measure.ts']); +// gstack-model-benchmark (/benchmark-models) and the merge queue's +// gstack-ship-queue are deferred the same way: both import that tree. +const DEFERRED = new Set(['scripts/ship-measure.ts', 'bin/gstack-model-benchmark', 'bin/gstack-ship-queue']); // Compiled outputs: the stub source carries placeholder binaries, so a fresh // checkout without a build still exercises the links to them. @@ -97,17 +100,52 @@ function makeSource(): void { } } -function buildRoot(host: string): { root: string; stderr: string; status: number | null } { - const root = path.join(tmp, 'home', host, 'skills', 'gstack'); +// windows: setup's IS_WINDOWS=1 arm, where bin/, lib/ and the runtime dists +// are real copies instead of links, so a module they import resolves only if +// setup copied it beside them. It copies from the checkout itself, because +// cp -R copies the stub source's top-level links as links. +function buildRoot(host: string, windows = false): { root: string; stderr: string; status: number | null } { + const root = path.join(tmp, windows ? 'home-windows' : 'home', host, 'skills', 'gstack'); fs.mkdirSync(path.dirname(root), { recursive: true }); const functions = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_copy_skill_md', '_sidecar_root_user_owned', '_gstack_generated_header', ROOT_BUILDERS[host]!] .filter(name => SETUP_SRC.includes(`\n${name}() {`)).map(extractFunction).join('\n'); - const r = spawnSync('bash', ['-c', `set -e\nIS_WINDOWS=0\n${functions}\n${ROOT_BUILDERS[host]} "${src}" "${root}"`], + const r = spawnSync('bash', ['-c', `set -e\nIS_WINDOWS=${windows ? 1 : 0}\n${functions}\n${ROOT_BUILDERS[host]} "${windows ? ROOT : src}" "${root}"`], { encoding: 'utf8', timeout: 30_000, env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: path.join(tmp, 'home') } }); return { root, stderr: r.stderr, status: r.status }; } +const transpiler = new Bun.Transpiler({ loader: 'ts' }); +function isBunSource(file: string): boolean { + if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return false; + return /\.(ts|js|mjs)$/.test(file) || (!path.extname(file) && /^#!.*\bbun\b/.test(fs.readFileSync(file, 'utf8'))); +} + +/** + * Static imports reachable from the code a host's skills run that do not + * resolve inside its runtime root. Paths resolve from where the root holds + * each file, never through its links, which is how a copied root loads them. + */ +function importsOutsideRoot(host: string, root: string): string[] { + const queue = [...referencedPaths(host)].filter(rel => !DEFERRED.has(rel)).map(rel => path.join(root, rel)).filter(isBunSource); + const seen = new Set(); + const outside = new Set(); + while (queue.length) { + const file = queue.pop()!; + if (seen.has(file)) continue; + seen.add(file); + for (const { path: spec, kind } of transpiler.scanImports(fs.readFileSync(file, 'utf8').replace(/^#!.*/, ''))) { + if (kind !== 'import-statement' || !spec.startsWith('.')) continue; + const target = path.resolve(path.dirname(file), spec); + const found = [target, target.replace(/\.js$/, '.ts'), `${target}.ts`, `${target}.js`, path.join(target, 'index.ts')] + .find(c => c.startsWith(root + path.sep) && fs.existsSync(c) && fs.statSync(c).isFile()); + if (!found) outside.add(`${path.relative(root, file)} -> ${path.relative(root, target)}`); + else if (isBunSource(found)) queue.push(found); + } + } + return [...outside].sort(); +} + beforeAll(async () => { const result = await runGeneration({ host: 'all', outputRoot: renderDir }); if (result.exitCode !== 0) throw new Error(result.diagnostics.filter(d => d.kind === 'error').map(d => d.message).join('\n')); @@ -139,6 +177,49 @@ describe.skipIf(process.platform === 'win32')('runtime roots carry every $GSTACK }); } + for (const host of Object.keys(ROOT_BUILDERS)) { + test(`${host}: every module the skills' commands import is inside the runtime root`, () => { + const { root, status } = buildRoot(host); + expect(status).toBe(0); + expect(importsOutsideRoot(host, root)).toEqual([]); + }); + } + + test('the review planner starts from a copied (Windows) runtime root', () => { + const { root, stderr, status } = buildRoot('codex', true); + expect(stderr).toBe(''); + expect(status).toBe(0); + expect(fs.lstatSync(path.join(root, 'bin')).isSymbolicLink()).toBe(false); + const r = spawnSync(process.execPath, [...bunIsolationArgs(), path.join(root, 'bin', 'gstack-review-plan'), '--help'], + { cwd: tmp, encoding: 'utf8', timeout: 30_000, env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: path.join(tmp, 'home-windows') } }); + expect(r.stderr).not.toContain('Cannot find module'); + expect(r.status).toBe(0); + expect(r.stdout).toContain('--fix-check-prompt'); + }); + + // Value: protects=the question helper's --check and --signal-keys start from a + // runtime root, linked or copied; fails_when=setup's asset list drops + // scripts/one-way-doors.ts or scripts/psychographic-signals.ts; + // why_new=the helper imports them inside a bash-quoted bun -e, which the + // static import walk above cannot see; seam=none; no_claim=native Windows. + for (const windows of [false, true]) { + test(`the question helper's checks start from a ${windows ? 'copied (Windows)' : 'linked'} runtime root`, () => { + const { root, stderr, status } = buildRoot('codex', windows); + expect(stderr).toBe(''); + expect(status).toBe(0); + const home = path.join(tmp, windows ? 'home-windows' : 'home'); + for (const [args, expected] of [[['--check', 'land-and-deploy-merge'], 'ASK_NORMALLY'], [['--signal-keys'], 'scope-appetite']] as const) { + const r = spawnSync('bash', [path.join(root, 'bin', 'gstack-question-preference'), ...args], { + cwd: tmp, encoding: 'utf8', timeout: 30_000, + env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home, GSTACK_STATE_ROOT: path.join(home, 'question-state') }, + }); + expect(r.stderr).not.toContain('Cannot find module'); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(r.stdout).toContain(expected); + } + }); + } + test('a runtime root never gains a whole skill directory beside the rendered copies', () => { const { root } = buildRoot('codex'); for (const dir of ['plan-design-review', 'office-hours']) { diff --git a/test/sealed-stream.test.ts b/test/sealed-stream.test.ts new file mode 100644 index 00000000000..e78d2ddad46 --- /dev/null +++ b/test/sealed-stream.test.ts @@ -0,0 +1,254 @@ +/** + * GST-2494: the sealed guard streams its two large git reads. textFindings + * (`diff-tree --cc -p --unified=0`) and landedOnBase (`diff-tree -p | patch-id`) + * used to buffer git's whole stdout under spawnSync's 256 MiB maxBuffer; a PR + * with ~4M lines of generated fixtures overflowed it and the guard refused with + * an empty-stderr "git diff-tree -p failed:". Now git's stdout goes to a + * private temp file and is read one line at a time after git exits 0. + * + * Parity: the pre-fix buffered functions (copied verbatim below, maxBuffer + * injectable) and the streamed ones give equal findings and landed maps on + * small fixtures, at every read size. Negative controls: a non-zero exit, a + * signal, a timeout, a missing binary and an unreadable object all throw (and + * refuse at evaluateSealed), naming the exit code or signal. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { evaluateSealed, gitLines, landedOnBase, renderSealed, textFindings, type SealedFinding, type SealedPolicy } from '../lib/sealed-guard'; + +const roots: string[] = []; +afterEach(() => { while (roots.length) fs.rmSync(roots.pop()!, { recursive: true, force: true }); }); + +const POLICY: SealedPolicy = { paths: [], transcripts: [], answer_markers: ['SEALED ANSWER:'], seed_patterns: ['seed=\\d+', '\uFFFD', 'é'], local_paths: false, allow_paths: [], case_insensitive: false, label_keys: [], identifier_keys: [] }; + +function tmp(prefix: string): string { + const d = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix))); + roots.push(d); + return d; +} + +function repo() { + const root = tmp('sealed-stream-'); + const dir = path.join(root, 'work'); + fs.mkdirSync(dir); + const env = { ...process.env, HOME: root, GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' }; + fs.writeFileSync(env.GIT_CONFIG_GLOBAL, '[user]\n\tname = t\n\temail = t@example.com\n[commit]\n\tgpgsign = false\n[init]\n\tdefaultBranch = main\n'); + const run = (args: string[]) => spawnSync('git', args, { cwd: dir, encoding: 'utf8', timeout: 30_000, env }); + const git = (...args: string[]) => { + const r = run(args); + if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); + return (r.stdout ?? '').trim(); + }; + const write = (files: Record, msg: string) => { + for (const [rel, body] of Object.entries(files)) { + const abs = path.join(dir, rel); + if (body === null) { fs.rmSync(abs, { force: true }); continue; } + fs.mkdirSync(path.dirname(abs), { recursive: true }); + fs.writeFileSync(abs, body); + } + git('add', '-A'); git('commit', '-q', '--allow-empty', '-m', msg); + return git('rev-parse', 'HEAD'); + }; + git('init', '-q', '-b', 'main'); + return { dir, git, run, write }; +} + +// ---- The pre-fix buffered path (lib/sealed-guard.ts at 0ead11c), verbatim but for the injectable maxBuffer. ---- +const HEX = /^[0-9a-f]{40,64}$/; +function oldGit(repoRoot: string, args: string[], maxBuffer: number, input?: string, encoding: BufferEncoding = 'utf8') { + const r = spawnSync('git', args, { cwd: repoRoot, encoding, input, timeout: 120_000, maxBuffer }); + return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() }; +} +function oldTextFindings(repoRoot: string, commits: string[], p: SealedPolicy, maxBuffer: number): SealedFinding[] { + const rules: Array<[SealedFinding['rule'], RegExp]> = [ + ...p.answer_markers.map(r => ['sealed.answer', new RegExp(r)] as [SealedFinding['rule'], RegExp]), + ...p.seed_patterns.map(r => ['sealed.seed', new RegExp(r)] as [SealedFinding['rule'], RegExp]), + ]; + const r = oldGit(repoRoot, ['-c', 'core.quotePath=false', 'diff-tree', '--stdin', '-r', '--root', '-M', '-C', '--cc', '-p', '--unified=0', '--no-color', '--no-ext-diff', '--no-textconv'], maxBuffer, commits.join('\n') + '\n'); + if (!r.ok) throw new Error(`git diff-tree -p failed: ${r.err.slice(0, 200)}`); + const out: SealedFinding[] = []; + let commit = ''; let file = ''; let inHunk = false; let parents = 1; let next = 0; + for (const line of r.out.split('\n')) { + if (HEX.test(line)) { commit = line; inHunk = false; continue; } + if (line.startsWith('diff --')) { inHunk = false; file = ''; continue; } + if (line.startsWith('@@')) { inHunk = true; parents = (/^@+/.exec(line)?.[0].length ?? 2) - 1; next = Number(/ \+(\d+)(?:,\d+)? @+/.exec(line)?.[1] ?? 0); continue; } + if (!inHunk) { if (line.startsWith('+++ ')) file = line.startsWith('+++ b/') ? line.slice(6) : ''; continue; } + const prefix = line.slice(0, parents); + if (line.startsWith('\\') || prefix.includes('-')) continue; + const n = next++; + if (!prefix.includes('+')) continue; + const text = line.slice(parents); + for (const [rule, re] of rules) if (re.test(text)) out.push({ rule, file, line: n, commit }); + } + return out; +} +const patchBody = (diff: string) => diff.split('\n').filter(l => !HEX.test(l) && !l.startsWith('index ')).map(l => l.replace(/^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@/, '@@')).join('\n'); +function oldLanded(repoRoot: string, baseCommits: string[], rest: string[], maxBuffer: number): Map { + const out = new Map(); + const diffArgs = ['diff-tree', '-r', '--root', '-p', '--no-color', '--no-ext-diff', '--no-textconv']; + const ids = (list: string[]): string[][] => { + const d = oldGit(repoRoot, [...diffArgs, '--stdin'], maxBuffer, list.join('\n') + '\n', 'latin1'); + if (!d.ok) throw new Error(`git diff-tree -p failed: ${d.err.slice(0, 200)}`); + const p = oldGit(repoRoot, ['patch-id', '--verbatim'], maxBuffer, d.out, 'latin1'); + if (!p.ok) throw new Error(`git patch-id failed: ${p.err.slice(0, 200)}`); + return p.out.split('\n').map(l => l.split(' ')).filter(f => f.length === 2); + }; + const byId = new Map(); + for (const [id, c] of ids(baseCommits)) if (!byId.has(id!)) byId.set(id!, c!); + const body = (c: string) => { const r = oldGit(repoRoot, [...diffArgs, c], maxBuffer, undefined, 'latin1'); return r.ok && r.out.trim() ? patchBody(r.out) : null; }; + for (const [id, c] of ids(rest)) { + const b = byId.get(id!); + if (!b) continue; + const mine = body(c!); + if (mine !== null && mine === body(b)) out.set(c!, b); + } + return out; +} +// ---- end of the pre-fix path ---- + +const BIG = Array.from({ length: 3000 }, (_, i) => `generated fixture row ${i} ${i % 97 === 0 ? 'SEALED ANSWER: x' : 'plain'} é ünïcode`).join('\n') + '\n'; +const lines20 = (edit = (i: number) => '') => Array.from({ length: 20 }, (_, i) => `line ${i}${edit(i)}`).join('\n') + '\n'; + +/** Roots, renames, copies, a binary, CRLF, a missing final newline, invalid UTF-8, a quoted file name, a --cc merge resolution and a ~200 KB file. */ +function textFixture() { + const r = repo(); + r.write({ 'a.txt': 'one\nSEALED ANSWER: 42\nseed=1234\n', 'keep.txt': 'k1\nk2\nk3\nk4\nk5\nk6\n' }, 'root'); + r.write({ 'b.txt': 'crlf line\r\nSEALED ANSWER: crlf\r\nno final newline SEALED ANSWER: nl', 'dir/ü file.txt': 'héllo SEALED ANSWER: é\n' }, 'unicode'); + r.write({ 'bad.txt': Buffer.concat([Buffer.from('before\n'), Buffer.from([0xff, 0xfe, 0x20, 0xe2, 0x82]), Buffer.from('\nSEALED ANSWER: \xe9 latin\n', 'latin1'), Buffer.from([0xf0, 0x9f, 0x98]), Buffer.from(' seed=7\n')]) }, 'invalid utf8'); + r.write({ 'bin.dat': Buffer.concat([Buffer.from('SEALED ANSWER: 1\n'), Buffer.from([0, 1, 2, 0])]) }, 'binary'); + r.write({ 'a.txt': null, 'a-renamed.txt': 'one\nSEALED ANSWER: 42\nseed=1234\nadded SEALED ANSWER: 43\n', 'keep-copy.txt': 'k1\nk2\nk3\nk4\nk5\nk6\nSEALED ANSWER: copy\n' }, 'rename and copy'); + r.write({ 'big.txt': BIG }, 'big'); + r.git('checkout', '-q', '-b', 'side', 'HEAD~1'); + r.write({ 'keep.txt': 'k1\nside SEALED ANSWER: s\nk3\nk4\nk5\nk6\n' }, 'side'); + r.git('checkout', '-q', 'main'); + r.write({ 'keep.txt': 'k1\nmain SEALED ANSWER: m\nk3\nk4\nk5\nk6\n' }, 'main edit'); + r.run(['merge', '-q', 'side', '-m', 'merge']); + fs.writeFileSync(path.join(r.dir, 'keep.txt'), 'k1\nresolved SEALED ANSWER: r seed=99\nk3\nk4\nk5\nk6\n'); + r.git('add', '-A'); r.git('commit', '-q', '--no-edit'); + return { ...r, commits: r.git('rev-list', 'HEAD').split('\n') }; +} + +/** Feature commits, some cherry-picked onto main (one at an offset, one with latin1 bytes, one large), a whitespace near-miss and one never landed. */ +function landedFixture() { + const r = repo(); + r.write({ 'f.txt': lines20(), 'big.txt': BIG }, 'root'); + const mb = r.git('rev-parse', 'HEAD'); + r.git('checkout', '-q', '-b', 'feature'); + const picked = r.write({ 'f.txt': lines20(i => (i === 10 ? ' changed' : '')) }, 'change line 10'); + const latin = r.write({ 'l.txt': Buffer.from('caf\xe9 \xff\xfe bytes\n', 'latin1') }, 'latin1 bytes'); + const nearMiss = r.write({ 'n.txt': 'path /home/alice/x\n' }, 'near miss'); + const bigEdit = r.write({ 'big.txt': BIG.replace('row 1500 ', 'row 1500 edited '), 'big2.txt': BIG }, 'big edit'); + const never = r.write({ 'z.txt': 'never landed\n' }, 'never'); + r.git('checkout', '-q', 'main'); + r.write({ 'f.txt': 'top\n' + lines20() }, 'offset'); + r.git('cherry-pick', picked); r.git('cherry-pick', latin); r.git('cherry-pick', bigEdit); + r.write({ 'n.txt': 'path /home/ alice/x\n' }, 'near miss differs'); + const baseCommits = r.git('rev-list', '--no-merges', 'main', `^${mb}`).split('\n'); + return { ...r, mb, baseCommits, rest: [picked, latin, nearMiss, bigEdit, never], landed: [picked, latin, bigEdit] }; +} + +const OLD_LIMIT = 256 * 1024 * 1024; +const opts = (dir: string) => ({ repoRoot: dir, targets: [], baseRef: 'main', remoteUrl: null, target: 't' }); + +describe('streamed reads match the pre-fix buffered path', () => { + test('textFindings: equal findings at every read size', () => { + const f = textFixture(); + const old = oldTextFindings(f.dir, f.commits, POLICY, OLD_LIMIT); + expect(old.length).toBeGreaterThan(40); + expect(new Set(old.map(o => o.file))).toEqual(new Set(['a.txt', 'b.txt', 'dir/ü file.txt\t', 'bad.txt', 'a-renamed.txt', 'keep-copy.txt', 'big.txt', 'keep.txt'])); + expect(old.some(o => o.rule === 'sealed.seed' && o.file === 'bad.txt')).toBe(true); + for (const chunkBytes of [1, 2, 3, 7, 64, 4096, undefined]) expect(JSON.stringify(textFindings(f.dir, f.commits, POLICY, { chunkBytes }))).toBe(JSON.stringify(old)); + }); + + test('landedOnBase: equal skips at every read size', () => { + const f = landedFixture(); + const old = oldLanded(f.dir, f.baseCommits, f.rest, OLD_LIMIT); + expect([...old.keys()].sort()).toEqual([...f.landed].sort()); + for (const chunkBytes of [1, 3, 7, 64, undefined]) { + const notes: string[] = []; + expect([...landedOnBase(opts(f.dir), f.rest, [f.mb], notes, { chunkBytes })]).toEqual([...old]); + expect(notes).toEqual([]); + } + }); + + test('the old buffer limit no longer applies (a 4 KiB maxBuffer reproduces the empty-stderr refusal)', () => { + const t = textFixture(); + expect(() => oldTextFindings(t.dir, t.commits, POLICY, 4096)).toThrow(/^git diff-tree -p failed: $/); + expect(JSON.stringify(textFindings(t.dir, t.commits, POLICY, { chunkBytes: 64 }))).toBe(JSON.stringify(oldTextFindings(t.dir, t.commits, POLICY, OLD_LIMIT))); + const l = landedFixture(); + expect(() => oldLanded(l.dir, l.baseCommits, l.rest, 4096)).toThrow(/^git diff-tree -p failed: $/); + expect([...landedOnBase(opts(l.dir), l.rest, [l.mb], [], { chunkBytes: 64 })]).toEqual([...oldLanded(l.dir, l.baseCommits, l.rest, OLD_LIMIT)]); + }); +}); + +describe('streamed reads still fail closed, and say why', () => { + const fake = (body: string) => { + const bin = path.join(tmp('sealed-fake-git-'), 'git'); + fs.writeFileSync(bin, '#!/bin/sh\n' + body + '\n'); + fs.chmodSync(bin, 0o755); + return bin; + }; + const PARTIAL = "printf '%s\\n' 0123456789abcdef0123456789abcdef01234567 'diff --git a/x b/x' '+++ b/x' '@@ -0,0 +1 @@' '+SEALED ANSWER: 1'"; + const run = (o: { bin?: string; timeoutMs?: number }) => { + const lines: string[] = []; + let error = ''; + try { gitLines(os.tmpdir(), 'diff-tree -p', ['diff-tree'], { text: 'x\n' }, 'utf8', l => lines.push(l), o); } catch (e: any) { error = e.message; } + return { lines, error }; + }; + + test('real git outside a repository: exit 128 with git\'s own stderr', () => { + expect(() => textFindings(tmp('sealed-norepo-'), ['0'.repeat(40)], POLICY)).toThrow(/^git diff-tree -p failed \(exit 128\): fatal: not a git repository/); + }); + + test.skipIf(process.platform === 'win32')('a non-zero exit after partial output: nothing parsed, exit code named even with empty stderr', () => { + expect(run({ bin: fake(PARTIAL + '\nexit 3') })).toEqual({ lines: [], error: 'git diff-tree -p failed (exit 3)' }); + expect(run({ bin: fake("echo 'fatal: boom' >&2; exit 128") })).toEqual({ lines: [], error: 'git diff-tree -p failed (exit 128): fatal: boom' }); + }); + + test.skipIf(process.platform === 'win32')('a process killed mid-stream (truncated output): nothing parsed, signal named', () => { + expect(run({ bin: fake(PARTIAL + '\nkill -9 $$') })).toEqual({ lines: [], error: 'git diff-tree -p failed (killed by SIGKILL)' }); + }); + + test.skipIf(process.platform === 'win32')('a timeout: nothing parsed, timeout and signal named', () => { + expect(run({ bin: fake(PARTIAL + '\nexec sleep 5'), timeoutMs: 300 })).toEqual({ lines: [], error: 'git diff-tree -p failed (timed out after 0.3 s, SIGTERM)' }); + }); + + test('a missing git binary: the spawn error is named', () => { + expect(run({ bin: path.join(tmp('sealed-nobin-'), 'no-such-git') }).error).toMatch(/^git diff-tree -p failed \(could not run git: .+\)$/); + }); + + test('temp files are removed on success and on failure', () => { + const scratch = tmp('sealed-tmpdir-'); + const before = process.env.TMPDIR; + process.env.TMPDIR = scratch; + try { + const f = textFixture(); + expect(textFindings(f.dir, f.commits, POLICY).length).toBeGreaterThan(0); + expect(run({ bin: path.join(scratch, 'no-such-git') }).error).not.toBe(''); + expect(fs.readdirSync(scratch).filter(n => n.startsWith('gstack-sealed-'))).toEqual([]); + } finally { + if (before === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = before; + } + }); + + test('an unreadable object in a published commit refuses the push, and the skip lookup scans everything', () => { + const r = repo(); + r.write({ '.gstack/pregate.json': JSON.stringify({ sealed: { answer_markers: ['SEALED ANSWER:'] } }) + '\n', 'README.md': '# x\n' }, 'base'); + const mb = r.git('rev-parse', 'HEAD'); + r.write({ 'base.txt': 'base moves on\n' }, 'base moves'); + r.git('checkout', '-q', '-b', 'feature', mb); + const pushed = r.write({ 'payload.txt': 'harmless payload\n' }, 'payload'); + const blob = r.git('rev-parse', 'HEAD:payload.txt'); + fs.rmSync(path.join(r.dir, '.git', 'objects', blob.slice(0, 2), blob.slice(2))); + fs.rmSync(path.join(r.dir, 'payload.txt')); + const report = evaluateSealed({ repoRoot: r.dir, targets: [{ commits: [pushed], pushedSha: pushed }], baseRef: 'main', remoteUrl: null, target: 'origin' }); + expect(report.status).toBe('error'); + expect(report.error).toMatch(/^could not read the published commits: git diff-tree -p failed \(exit 128\): (fatal|error): /); + expect(report.notes.some(n => /^skipping failed \(git diff-tree -p failed \(exit 128\)/.test(n))).toBe(true); + expect(report.skipped).toEqual([]); + expect(renderSealed(report, 'gstack-pregate sealed')).toContain('SEALED_OUTPUT_REFUSED'); + }); +}); diff --git a/test/setup-production-deps.test.ts b/test/setup-production-deps.test.ts index 5289b4e1399..38b3e4d1033 100644 --- a/test/setup-production-deps.test.ts +++ b/test/setup-production-deps.test.ts @@ -572,7 +572,8 @@ describe('setup and runtime need only production dependencies', () => { queue.push(target); } } - expect(Object.keys(reached)).toContain('scripts/discover-skills.ts'); + expect(Object.keys(reached)).toContain('scripts/gen-agents-digest.ts'); + expect(Object.keys({ ...files, ...reached })).toContain('scripts/discover-skills.ts'); expect(Object.keys(reached)).toContain('test/helpers/providers/claude.ts'); expect(nonProductionImports(PKG, reached)).toEqual([]); }); diff --git a/test/shared-libs-rendering.test.ts b/test/shared-libs-rendering.test.ts index 0a246d7b6a0..07bde9b55f7 100644 --- a/test/shared-libs-rendering.test.ts +++ b/test/shared-libs-rendering.test.ts @@ -4,7 +4,7 @@ import { mkdtempSync, readFileSync, readdirSync, existsSync, rmSync } from 'node import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { ALL_HOST_CONFIGS } from '../hosts'; -import { discoverTemplates, RETIRED_SKILLS } from '../scripts/discover-skills'; +import { discoverTemplates } from '../scripts/discover-skills'; import { sharedLibsPlanExcerpt } from './helpers/shared-libs-plan-excerpt'; import { readSkillEffective } from './helpers/skill-startup'; @@ -12,7 +12,6 @@ const ROOT = resolve(import.meta.dir, '..'); let output: string; function rendered(host: (typeof ALL_HOST_CONFIGS)[number], skill: string): string { - if (host.name !== 'claude' && RETIRED_SKILLS.includes(skill)) return readFileSync(join(output, host.hostSubdir, 'skills', 'gstack-autoplan', `${skill}.md`), 'utf8'); const dir = host.name === 'claude' ? join(output, skill) : join(output, host.hostSubdir, 'skills', `gstack-${skill}`); const sections = join(dir, 'sections'); diff --git a/test/ship-gate-dispositions.test.ts b/test/ship-gate-dispositions.test.ts new file mode 100644 index 00000000000..3e55c090f27 --- /dev/null +++ b/test/ship-gate-dispositions.test.ts @@ -0,0 +1,289 @@ +/** + * Owner gate dispositions (GST-2491, founderstar#906 at 3a273935b): an unattended /ship logs every gate finding `open` + * (gstack-review-log), and only the owner's `gstack-approvals gate` row, at that fingerprint and a head inside the review + * row's range, closes it. Rulings, the lane's own review-log claims and rows recorded inside the open /ship run close nothing, + * and every disposition is printed by finish and carried by the receipt, the PR body and READY. + */ +import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { extractReceipt, readyTailLines } from '../lib/ship-receipt'; +import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; +import { spawnSync } from 'node:child_process'; +import { buildRow, locate, type ApprovalRow, type StoreLocation } from '../lib/approval-record'; +import { GATE_SOURCE, gateDispositionDigest, gateDispositionRow } from '../lib/gate-dispositions'; + +setDefaultTimeout(90_000); +const BIN = path.dirname(RELEASE); +const LANE = 'tests=printf " 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [5.00ms]\\n"'; +const ships: ShipFx[] = []; +afterEach(() => { while (ships.length) ships.pop()!.cleanup(); }); + +const GATE = 'tests/balance.test.ts:3:gate-integrity'; +const OTHER = 'tests/balance.test.ts:9:gate-integrity'; +const GATE_ID = '69c7c3432501'; +const WORDS = 'Do it'; +const REASON = 'fed-careless gate allows 6 of 48 seeds'; +const BY = 'Founderstar Captain (FOUN-1)'; +const TEST_V1 = "import { expect, test } from 'bun:test';\ntest('a', () => { expect(4).toBeLessThanOrEqual(4); });\n"; +const TEST_V2 = "import { expect, test } from 'bun:test';\ntest('a', () => { expect(4).toBeLessThanOrEqual(6); });\n"; +/** The founderstar#906 review row: one RH-15 gate finding an unattended session logs open, and a below-floor note. */ +const gateRow = (extra: Record = {}) => ({ + completed: true, converged: true, status: 'issues_found', issues_found: 1, critical: 1, informational: 0, + findings: [ + { fingerprint: GATE, severity: 'CRITICAL', locus: 'diff', kind: 'defect', blocking: true, raised_by: 'core', gate: 'RH-15', gate_id: GATE_ID, action: 'kept', reason: 'owner approved', ...extra }, + { fingerprint: 'src/x.ts:1:naming', severity: 'INFORMATIONAL', action: 'noted', blocking: false, raised_by: 'red-team' }, + ], +}); +const NOT_CLEAN = 'FIX_CHECK: not counted (review has unresolved findings or did not finish clean)'; + +const run = (f: ShipFx, bin: string, args: string[]) => f.run(path.join(BIN, bin), args, { GSTACK_APPROVALS_MIRROR: '0' }); +const gate = (f: ShipFx, finding: string, head: string, o: { words?: string; by?: string; reason?: string; gateId?: string } = {}) => + run(f, 'gstack-approvals', ['gate', '--finding', finding, '--gate-id', o.gateId ?? GATE_ID, '--head', head, '--reason', o.reason ?? REASON, '--words', o.words ?? WORDS, '--by', o.by ?? BY]); +const log = (f: ShipFx, skill: string, row: Record) => { + const env = { GSTACK_APPROVALS_MIRROR: '0', GSTACK_SESSION_KIND: 'unattended' }; + const start = f.run(path.join(BIN, 'gstack-review-log'), ['--start', skill], env); + expect(start.status, start.stderr).toBe(0); + const logged = f.run(path.join(BIN, 'gstack-review-log'), [JSON.stringify({ skill, timestamp: '2026-11-11T20:30:13Z', via: 'ship', review_scope: 'frozen', ...row }), '--finish', start.stdout.trim()], env); + expect(logged.status, logged.stderr).toBe(0); +}; +/** A /ship run open on `dir` as preflight leaves it: the run marker plus an open lease held by this live test process. */ +const openRun = (f: ShipFx, dir = f.work) => { + const marker = path.resolve(dir, spawnSync('git', ['rev-parse', '--git-path', 'gstack-ship-run'], { cwd: dir, encoding: 'utf8', timeout: 60_000 }).stdout.trim()); + fs.writeFileSync(marker, 'ship-906-3a27393\n'); + const lease = spawnSync(path.join(BIN, 'gstack-lease'), ['touch', '--root', dir, '--pid', String(process.pid), '--run', 'ship-906-3a27393'], { encoding: 'utf8', timeout: 60_000 }); + expect(lease.status, lease.stderr).toBe(0); + return marker; +}; +/** The newest row of a skill as gstack-review-read prints it. */ +const read = (f: ShipFx, skill = 'review') => run(f, 'gstack-review-read', []).stdout.split('\n---CONFIG---')[0]!.split('\n') + .flatMap(l => { try { const v = JSON.parse(l); return v?.skill === skill ? [v] : []; } catch { return []; } }).at(-1); + +/** Pass 1 read the gate change at its commit and logged the gate finding open (unattended). */ +function firstPass(extra: Record = {}, rowExtra: Record = {}) { + const f = shipFixture({ 'tests/balance.test.ts': TEST_V1 }, { 'tests/balance.test.ts': TEST_V2 }); + ships.push(f); + log(f, 'review', { pass: 1, range_base: null, ...gateRow(extra), ...rowExtra }); + return { f, head: f.git('rev-parse', 'HEAD').stdout.trim(), mergeBase: f.git('merge-base', 'main', 'HEAD').stdout.trim() }; +} + +// Value: protects=founderstar#906: an owner-approved gate change finishes unattended once the owner's disposition is recorded, +// and only then; fails_when=the row still reads UNVERIFIED with a matching gate_disposition row, or reads CURRENT without one; +// seam=gstack-approvals gate, gstack-review-read and lib/gate-dispositions.ts on the stored review row; no_claim=the review +// plan's flags, which /ship derives from this row +describe('a recorded owner disposition closes an unattended gate finding (GST-2491)', () => { + test('the logger keeps it open, and a matching gate row closes it on the review row', () => { + const { f, head } = firstPass(); + const before = read(f); + expect(before.findings[0]).toMatchObject({ action: 'open', actor: 'unattended' }); + expect([before.review_freshness.status, before.gate_dispositions]).toEqual(['UNVERIFIED', undefined]); + const rec = gate(f, GATE, head); + expect([rec.status, rec.stdout]).toEqual([0, expect.stringMatching(/^APPROVAL_RECORDED: a-[0-9a-f]{12} /)]); + const approval = rec.stdout.split(' ')[1]!; + const after = read(f); + expect([after.review_freshness.status, after.gate_dispositions]).toEqual(['CURRENT', [approval]]); + expect(after.findings[0]).toMatchObject({ action: 'kept', actor: 'unattended', disposition: approval, reason: `owner disposition ${approval}: ${REASON}` }); + expect(run(f, 'gstack-approvals', ['dispositions']).stdout).toMatch(new RegExp(`^Gate disposition: ${GATE} \\[gate ${GATE_ID}\\] at ${head.slice(0, 12)} by Founderstar Captain \\(FOUN-1\\) at \\d{4}-\\d\\d-\\d\\dT[^ ]+Z: ${REASON} — "Do it" \\(approval a-[0-9a-f]{12}\\)\\n$`)); + }); + + test('negative controls stay open: no row, another fingerprint or gate_id, a head outside the range, a ruling, a gstack row', () => { + const { f, head, mergeBase } = firstPass(); + const open = () => [read(f).review_freshness.status, read(f).gate_dispositions, read(f).findings[0].action]; + expect(open()).toEqual(['UNVERIFIED', undefined, 'open']); + expect(gate(f, OTHER, head).status).toBe(0); + expect(open()).toEqual(['UNVERIFIED', undefined, 'open']); + expect(gate(f, GATE, head, { gateId: '0123456789ab' }).status).toBe(0); + expect(open()).toEqual(['UNVERIFIED', undefined, 'open']); + expect(gate(f, GATE, mergeBase).status).toBe(0); + expect(open()).toEqual(['UNVERIFIED', undefined, 'open']); + const ruling = run(f, 'gstack-approvals', ['rule', '--finding', GATE, '--head', head, '--reason', REASON, '--words', WORDS, '--by', BY]); + expect(ruling.status).toBe(0); + expect(open()).toEqual(['UNVERIFIED', undefined, 'open']); + const self = gate(f, GATE, head, { by: 'gstack no-stop default (K1)' }); + expect([self.status, self.stderr]).toEqual([EXIT.usage, expect.stringContaining('--by names gstack')]); + expect(open()).toEqual(['UNVERIFIED', undefined, 'open']); + }); + + test('a later head is outside a first pass too: the owner answers at the commit the review read', () => { + const { f } = firstPass(); + f.write({ 'README.md': '# Fx later\n' }); f.commit('later'); + expect(gate(f, GATE, f.git('rev-parse', 'HEAD').stdout.trim()).status).toBe(0); + expect(read(f).review_freshness.status).not.toBe('CURRENT'); + expect(read(f).gate_dispositions).toBeUndefined(); + }); + + test('gate refuses a call inside the open /ship run, empty or multi-line words, and add with the scope', () => { + const { f, head } = firstPass(); + const marker = openRun(f); + const inRun = gate(f, GATE, head); + expect([inRun.status, inRun.stderr]).toEqual([EXIT.usage, expect.stringContaining('/ship run ship-906-3a27393 is open on this checkout')]); + fs.rmSync(marker); + for (const words of ['', ' ']) { + const empty = gate(f, GATE, head, { words }); + expect([empty.status, empty.stderr]).toEqual([EXIT.usage, expect.stringContaining('--words')]); + } + const noId = gate(f, GATE, head, { gateId: '' }); + expect([noId.status, noId.stderr]).toEqual([EXIT.usage, expect.stringContaining('--gate-id')]); + const lines = gate(f, GATE, head, { words: 'Do it\nand more' }); + expect([lines.status, lines.stderr]).toEqual([EXIT.usage, expect.stringContaining('one line')]); + const add = run(f, 'gstack-approvals', ['add', '--ask', `gate_disposition ${GATE} ${GATE_ID} at ${head}: ${REASON}`, '--words', WORDS, '--by', BY, '--scope', `gate_disposition ${GATE} ${GATE_ID} ${head}`]); + expect([add.status, add.stderr]).toEqual([EXIT.usage, expect.stringContaining('gstack-approvals gate')]); + expect(run(f, 'gstack-approvals', ['dispositions']).stdout).toBe('GATE_DISPOSITIONS: none\n'); + expect(read(f).review_freshness.status).toBe('UNVERIFIED'); + }); + + test('the lane\'s own review-log claim closes nothing', () => { + const { f, head } = firstPass({ disposition: 'a-6dcd9c1d8fad', approval: 'a-6dcd9c1d8fad', disposition_by: BY }, { gate_dispositions: ['a-6dcd9c1d8fad'] }); + const row = read(f); + expect([row.findings[0].action, row.findings[0].disposition, row.review_freshness.status, row.gate_dispositions]).toEqual(['open', undefined, 'UNVERIFIED', undefined]); + expect(run(f, 'gstack-approvals', ['add', '--ask', `Owner approved the gate change at ${head}`, '--words', WORDS, '--by', BY, '--scope', 'this gate edit']).status).toBe(0); + expect(read(f).review_freshness.status).toBe('UNVERIFIED'); + }); +}); + +/** Round 2 stopped at passHead, the owner granted one scoped fix-check, and the fix-check logged the gate finding open. */ +function grantedFixCheck() { + const f = shipFixture({ 'tests/balance.test.ts': TEST_V1 }, { 'src/x.ts': 'export const x = 2;\n', 'tests/balance.test.ts': TEST_V1 }); + ships.push(f); + const passHead = f.git('rev-parse', 'HEAD').stdout.trim(); + const reviewed = f.run(path.join(BIN, 'gstack-wtree'), []).stdout.trim(); + f.write({ 'src/x.ts': 'export const x = 3;\n', 'tests/balance.test.ts': TEST_V2 }); f.commit('raise the fed-careless gate'); + const post = path.join(f.root, 'post.json'); + expect(f.run(path.join(BIN, 'gstack-docs-candidate'), ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']).status).toBe(0); + expect(run(f, 'gstack-approvals', ['add', '--ask', `Owner grant: one scoped fix-check after round 2 (review_loop_grant ${passHead.slice(0, 12)})`, '--words', 'one scoped fix-check', '--by', BY, '--scope', 'this /ship invocation']).status).toBe(0); + log(f, 'review-fix-check', { range_base: passHead, ...gateRow() }); + const fin = () => f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--lane', LANE]); + return { f, passHead, fixHead: f.git('rev-parse', 'HEAD').stdout.trim(), fin }; +} +const dispositionLines = (out: string) => out.split('\n').filter(l => l.startsWith('GATE_DISPOSITION: ')); + +// Value: protects=finish counts a fix-check whose only blocker is an owner-dispositioned gate finding and prints the disposition +// word for word; a ruling or an out-of-range disposition leaves it uncounted and says not applied; fails_when=finish ignores +// gate dispositions, honours a ruling for a gate finding, or hides a disposition; seam=finish's fixChecked route +describe('finish with a gate disposition (GST-2491)', () => { + test('a disposition at the stop head closes the fix-check\'s gate finding, and finish prints it', () => { + const { f, passHead, fixHead, fin } = grantedFixCheck(); + expect(lineOf(fin().stdout, 'FIX_CHECK')).toBe(NOT_CLEAN); + expect(run(f, 'gstack-approvals', ['rule', '--finding', GATE, '--head', passHead, '--reason', REASON, '--words', WORDS, '--by', BY]).status).toBe(0); + expect(lineOf(fin().stdout, 'FIX_CHECK')).toBe(NOT_CLEAN); + expect(gate(f, GATE, f.git('merge-base', 'main', 'HEAD').stdout.trim()).status).toBe(0); + const early = fin(); + expect(lineOf(early.stdout, 'FIX_CHECK')).toBe(NOT_CLEAN); + expect(dispositionLines(early.stdout)).toEqual([expect.stringMatching(/; not applied\)$/)]); + expect(gate(f, GATE, passHead).status).toBe(0); + const r = fin(); + expect(lineOf(r.stdout, 'FIX_CHECK')).toStartWith(`FIX_CHECK: reviewed src/x.ts,tests/balance.test.ts (fix-check at ${fixHead.slice(0, 12)}, range from ${passHead.slice(0, 12)}`); + expect(dispositionLines(r.stdout)).toEqual([ + expect.stringMatching(/; not applied\)$/), + expect.stringMatching(new RegExp(`^GATE_DISPOSITION: ${GATE} \\[gate ${GATE_ID}\\] at ${passHead.slice(0, 12)} by Founderstar Captain \\(FOUN-1\\) at [^ ]+Z: ${REASON} — "Do it" \\(approval a-[0-9a-f]{12}\\)$`)), + ]); + }); + + // Value: protects=nothing dispositioned is hidden (R73): the receipt records every gate disposition, write refuses a PR body + // without each line word for word, and READY prints it; fails_when=write drops it or accepts a body without it; + // seam=gstack-ship-receipt write and readyTailLines + test('the receipt records every disposition, write refuses a body without its line, and READY prints it', () => { + const { f, head } = firstPass(); + expect(gate(f, GATE, head).status).toBe(0); + const line = run(f, 'gstack-approvals', ['dispositions']).stdout.trim(); + const body = path.join(f.root, 'body.md'); + const write = () => f.run(path.join(BIN, 'gstack-ship-receipt'), ['write', '--pr', '906', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body], { GSTACK_APPROVALS_MIRROR: '0' }); + fs.writeFileSync(body, '## Pre-Landing Review\n\nGate edits: 1 listed, 1 read, 1 findings — 1 kept, 0 restored, 0 open\n'); + const short = write(); + expect([short.status, short.stderr]).toEqual([EXIT.fail, expect.stringContaining(`does not list gate disposition ${JSON.stringify(line)}`)]); + fs.writeFileSync(body, `## Pre-Landing Review\n\n${line}\n`); + const ok = write(); + expect(ok.status, ok.stderr).toBe(EXIT.ok); + const receipt = extractReceipt(ok.stdout); + expect(receipt.errors).toEqual([]); + expect(receipt.receipt?.gate_dispositions).toEqual([{ finding: GATE, gate_id: GATE_ID, head, by: BY, reason: REASON, words: WORDS, at: expect.stringMatching(/Z$/), approval: expect.stringMatching(/^a-[0-9a-f]{12}$/) }]); + expect(readyTailLines(receipt.receipt).filter(l => l.startsWith('GATE_DISPOSITION: '))).toEqual([`GATE_DISPOSITION: ${line.slice('Gate disposition: '.length)}`]); + }); +}); + +// Value: protects=the GSTA-518 audit's lane-side paths (B1 sibling writer, N1 lock, N2 undefined gate id, N4 malformed rows, N5 +// skipped --body) are refused or ignored; fails_when=a sibling worktree records while the branch's /ship run is open, a row +// missing a writer field or edited after writing closes the finding, --gate-id undefined records, or write skips the body check; +// seam=gstack-approvals gate, gstack-review-read and gstack-ship-receipt write; no_claim=a well-formed row a same-user lane +// forges (the lander's --accept-gate-disposition is that boundary, test/ship-queue-land-direct.test.ts) +describe('a disposition the lane makes for itself is refused or ignored (GST-2491)', () => { + const store = (f: ShipFx) => locate({ cwd: f.work, env: { ...process.env, GSTACK_STATE_ROOT: f.state, GSTACK_HOME: f.state, GSTACK_APPROVALS_MIRROR: '0' }, branch: 'feat' }) as StoreLocation; + + test('a recorder name is trimmed and one line, and a parked run whose lease ended no longer refuses', () => { + const { f, head } = firstPass(); + const lines = gate(f, GATE, head, { by: 'Founderstar\nCaptain' }); + expect([lines.status, lines.stderr]).toEqual([EXIT.usage, expect.stringContaining('one line')]); + const marker = path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim()); + fs.writeFileSync(marker, 'ship-906-parked\n'); + const spaced = gate(f, GATE, head, { by: ` ${BY} ` }); + expect(spaced.status, spaced.stderr).toBe(0); + expect(run(f, 'gstack-approvals', ['dispositions']).stdout).toContain(`by ${BY} at`); + expect(read(f).review_freshness.status).toBe('CURRENT'); + }); + + test('a sibling worktree cannot record while the branch has an open /ship run, and records once it closes', () => { + const { f, head } = firstPass(); + const marker = openRun(f); + const sib = path.join(f.root, 'sib'); + expect(f.git('worktree', 'add', '-q', '-b', 'owner-side', sib, 'HEAD').status).toBe(0); + const fromSib = () => spawnSync(path.join(BIN, 'gstack-approvals'), ['gate', '--branch', 'feat', '--finding', GATE, '--gate-id', GATE_ID, '--head', head, '--reason', REASON, '--words', WORDS, '--by', BY], + { cwd: sib, encoding: 'utf8', timeout: 60_000, env: { ...process.env, GSTACK_STATE_ROOT: f.state, GSTACK_HOME: f.state, GSTACK_APPROVALS_MIRROR: '0', GIT_CONFIG_GLOBAL: path.join(f.root, 'gitconfig') } }); + const refused = fromSib(); + expect([refused.status, refused.stderr]).toEqual([EXIT.usage, expect.stringContaining(`/ship run ship-906-3a27393 is open in the worktree ${f.work} (branch feat)`)]); + expect(read(f).review_freshness.status).toBe('UNVERIFIED'); + fs.rmSync(marker); + const recorded = fromSib(); + expect(recorded.status, recorded.stderr).toBe(0); + expect(read(f).review_freshness.status).toBe('CURRENT'); + }); + + test('a raw row missing a writer field, edited after writing, or for another branch closes nothing; the written row does', () => { + const { f, head } = firstPass(); + expect(gate(f, GATE, head).status).toBe(0); + const file = store(f).file; + const good = JSON.parse(fs.readFileSync(file, 'utf8').trim().split('\n').at(-1)!); + expect([good.source, good.digest]).toEqual(['gate', expect.stringMatching(/^sha256:[0-9a-f]{64}$/)]); + const { digest: _d, ...noDigest } = good, { by: _b, ...noBy } = good, { recorded_at: _r, ...noTime } = good; + for (const bad of [noDigest, noBy, noTime, { ...good, source: 'manual' }, { ...good, words: 'Do it all' }, { ...good, branch: 'other' }, { ...good, id: 'gate-1' }, { ...good, ask: good.ask.replace(REASON, 'any gate change') }]) { + fs.writeFileSync(file, JSON.stringify(bad) + '\n'); + expect([read(f).review_freshness.status, run(f, 'gstack-approvals', ['dispositions']).stdout]).toEqual(['UNVERIFIED', 'GATE_DISPOSITIONS: none\n']); + } + fs.writeFileSync(file, JSON.stringify(good) + '\n'); + expect(read(f).review_freshness.status).toBe('CURRENT'); + }); + + test('a literal undefined gate id is refused, and an id-less gate finding stays open even under a digest-correct row', () => { + const { f, head } = firstPass({ gate_id: undefined }); + for (const gateId of ['undefined', 'null']) { + const lit = gate(f, GATE, head, { gateId }); + expect([lit.status, lit.stderr]).toEqual([EXIT.usage, expect.stringContaining('--gate-id')]); + } + const row = buildRow({ ...gateDispositionRow(GATE, 'undefined', head, REASON), words: WORDS, by: BY, source: GATE_SOURCE }, 'feat') as ApprovalRow; + fs.mkdirSync(path.dirname(store(f).file), { recursive: true }); + fs.appendFileSync(store(f).file, JSON.stringify({ ...row, digest: gateDispositionDigest(row as unknown as Record) }) + '\n'); + expect([read(f).review_freshness.status, read(f).findings[0].action]).toEqual(['UNVERIFIED', 'open']); + }); + + test('write refuses a receipt without --body while a disposition applies at HEAD', () => { + const { f, head } = firstPass(); + expect(gate(f, GATE, head).status).toBe(0); + const w = f.run(path.join(BIN, 'gstack-ship-receipt'), ['write', '--pr', '906', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended'], { GSTACK_APPROVALS_MIRROR: '0' }); + expect([w.status, w.stderr]).toEqual([EXIT.fail, expect.stringContaining('so write needs --body ')]); + }); + + // Value: protects=a branch whose disposition row names a commit a rewrite and gc removed still ships (the 0a9a0c4 review's + // blocker): in a full clone that row is not applied; fails_when=git's exit 128 on the missing head strands write for good + test('write records an explicit empty gate_dispositions, and a row whose head a rewrite and gc removed is not applied', () => { + const { f, head } = firstPass(); + expect(gate(f, GATE, head).status).toBe(0); + for (const args of [['commit', '-q', '--amend', '-m', 'feat rewritten'], ['push', '-q', '-f', 'origin', 'HEAD:refs/heads/feat'], ['reflog', 'expire', '--expire=now', '--all'], ['gc', '-q', '--prune=now']]) expect(f.git(...args).status).toBe(0); + for (const args of [['reflog', 'expire', '--expire=now', '--all'], ['gc', '-q', '--prune=now']]) expect(f.git('--git-dir', f.origin, ...args).status).toBe(0); + expect([f.git('cat-file', '-e', `${head}^{commit}`).status, f.git('--git-dir', f.origin, 'cat-file', '-e', `${head}^{commit}`).status]).not.toContain(0); + const body = path.join(f.root, 'body.md'); + fs.writeFileSync(body, '## Pre-Landing Review\n\nNo issues found.\n'); + const ok = f.run(path.join(BIN, 'gstack-ship-receipt'), ['write', '--pr', '906', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body], { GSTACK_APPROVALS_MIRROR: '0' }); + expect(ok.status, ok.stderr).toBe(EXIT.ok); + expect(extractReceipt(ok.stdout).receipt?.gate_dispositions).toEqual([]); + }); +}); diff --git a/test/ship-queue-land-direct.test.ts b/test/ship-queue-land-direct.test.ts index d25bf3ae71e..4b83b19ea22 100644 --- a/test/ship-queue-land-direct.test.ts +++ b/test/ship-queue-land-direct.test.ts @@ -28,6 +28,8 @@ import { gitIn } from '../crew/scripts/train-gate'; import type { GhRunner } from '../crew/scripts/recover-receipts'; import { TRAIN_BLOCK } from './helpers/ship-queue-train-fixture'; import { CHECK_IDS } from '../lib/pregate/index'; +import { appliedGateDispositions, gateAcceptance, GATE_SOURCE, gateDispositionDigest, gateDispositionRow, gateDispositionText, type GateDisposition } from '../lib/gate-dispositions'; +import { buildRow, locate, type ApprovalRow, type StoreLocation } from '../lib/approval-record'; const REQUIRED = ['free-tests', 'Check VERSION is not stale vs queue']; const POLICY = { ...BASE_POLICY, release_tool: null, release_outputs: [], changelog_fragments: { dir: 'changelog.d', required_checks: REQUIRED }, merge: 'direct', min_gstack_version: MERGE_KEY_VERSION }; @@ -1234,3 +1236,193 @@ describe('the backstop rewrites a freeze by compare-and-swap (GST-1354)', () => expect(freezeOf(fx).cleared_by).toBe(`repair #7; backstop 703 green on ${green.sha}`); }, 180_000); }); + +// Value: protects=the authority for an owner gate disposition is the lander's explicit acceptance, re-derived from the approval +// store at the pin (GSTA-518 audit B1, N5): a row the lane wrote itself, a receipt or PR body that hides or invents one, and an +// accepted id that names nothing all refuse, and verify --pin agrees with land line for line; fails_when=land trusts the +// receipt, merges an unaccepted disposition, or verify and land print different GATE_DISPOSITION lines; seam=pinAcceptance +// (lib/ship-queue-land-direct.ts) over gateAcceptance (lib/gate-dispositions.ts); no_claim=who wrote a well-formed row +describe('land --pin and verify --pin accept owner gate dispositions (GST-2491)', () => { + const F = 'tests/balance.test.ts:3:gate-integrity', G = '69c7c3432501', REASON = 'fed-careless gate allows 6 of 48 seeds'; + const prep = () => { const fx = setup(); fx.env.GSTACK_APPROVALS_MIRROR = '0'; return fx; }; + const storeEnv = (fx: Fx) => ({ ...process.env, ...fx.repo.env, ...fx.env }); + const record = (fx: Fx, pr: string, head: string) => runBin(fx.repo, 'gstack-approvals', ['gate', '--branch', 'pr-' + pr, '--finding', F, '--gate-id', G, '--head', head, '--reason', REASON, '--words', 'Do it', '--by', 'Founderstar Captain (FOUN-1)'], fx.env); + const applied = (fx: Fx, pr: string, head: string) => appliedGateDispositions(fx.repo.work, { branch: 'pr-' + pr, pin: head, env: storeEnv(fx) }).applied; + const bodyWith = (pr: string, head: string, ds: GateDisposition[], lines = ds) => shippedBody(pr, head, ds.length ? { gate_dispositions: ds } : {}) + lines.map(d => `\nGate disposition: ${gateDispositionText(d)}\n`).join(''); + const setBody = (fx: Fx, pr: string, body: string) => fx.write(d => { d.prs[pr].body = body; }); + const verify = (fx: Fx, pr: string, pin: string, extra: string[] = []) => runBin(fx.repo, 'gstack-ship-queue', ['verify', '--pr', pr, '--pin', pin, '--base', 'main', ...extra], fx.env); + const gateLines = (out: string) => out.split('\n').filter(l => l.startsWith('GATE_DISPOSITION')); + const why = (err: string) => err.replace(/^gstack-ship-queue (?:land|verify): /m, ''); + + test('end to end: the owner records, the unattended review reads CURRENT, ready prints it, land refuses until the lander accepts it, and verify agrees', () => { + const fx = prep(); + const head = openPr(fx, '41', { ready: false }); + fx.repo.git('checkout', '-q', 'pr-41'); + const lane = { ...fx.env, GSTACK_SESSION_KIND: 'unattended' }; + const start = runBin(fx.repo, 'gstack-review-log', ['--start', 'review'], lane); + expect(start.status, start.err).toBe(0); + const row = { skill: 'review', timestamp: '2026-11-11T20:30:13Z', via: 'ship', review_scope: 'frozen', pass: 1, range_base: null, completed: true, converged: true, status: 'issues_found', issues_found: 1, critical: 1, informational: 0, + findings: [{ fingerprint: F, severity: 'CRITICAL', locus: 'diff', kind: 'defect', blocking: true, raised_by: 'core', gate: 'RH-15', gate_id: G, action: 'kept', reason: 'owner approved' }] }; + const logged = runBin(fx.repo, 'gstack-review-log', [JSON.stringify(row), '--finish', start.out.trim()], lane); + expect(logged.status, logged.err).toBe(0); + const review = () => runBin(fx.repo, 'gstack-review-read', [], fx.env).out.split('\n---CONFIG---')[0]!.split('\n') + .flatMap(l => { try { const v = JSON.parse(l); return v?.skill === 'review' ? [v] : []; } catch { return []; } }).at(-1); + expect([review().review_freshness.status, review().findings[0].action]).toEqual(['UNVERIFIED', 'open']); + const rec = record(fx, '41', head); + expect(rec.status, rec.err).toBe(0); + const id = rec.out.split(' ')[1]!; + expect([review().review_freshness.status, review().findings[0].action, review().findings[0].disposition]).toEqual(['CURRENT', 'kept', id]); + const ds = applied(fx, '41', head); + expect(ds.map(d => d.approval)).toEqual([id]); + setBody(fx, '41', bodyWith('41', head, ds)); + const pregate = path.join(fx.repo.root, 'pregate.json'); + fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree: runBin(fx.repo, 'gstack-wtree', []).out.trim(), head, verdict: 'pass', checks: FULL_CHECKS })); + const ready = runBin(fx.repo, 'gstack-ship-queue', ['ready', '--pr', '41', '--pregate', pregate, '--base', 'main'], fx.env); + expect(ready.status, ready.out + ready.err).toBe(EXIT.ok); + expect(gateLines(ready.out)).toEqual([`GATE_DISPOSITION: ${gateDispositionText(ds[0]!)}`, expect.stringMatching(new RegExp(`^GATE_DISPOSITIONS: applied=${id} store=`))]); + fx.repo.git('checkout', '-q', '--detach', 'origin/main'); + const bare = land(fx, '41', head); + expect([bare.status, bare.err]).toEqual([EXIT.refused, expect.stringContaining(`disposition ${id} is not accepted`)]); + expect(bare.err).toContain('(QUEUE_GATE_DISPOSITION)'); + expect(fx.read().mergeArgs).toBeUndefined(); + const checked = verify(fx, '41', head); + expect([checked.status, why(checked.err)]).toEqual([EXIT.refused, why(bare.err)]); + expect(gateLines(checked.out)).toEqual(gateLines(bare.out)); + const ok = verify(fx, '41', head, ['--accept-gate-disposition', id]); + expect(ok.status, ok.out + ok.err).toBe(EXIT.ok); + expect(ok.out).toContain(`VERIFY_PIN: ok #41 at ${head.slice(0, 12)}`); + expect(fx.read().mergeArgs).toBeUndefined(); + const landed = land(fx, '41', head, ['--accept-gate-disposition', id]); + expect(landed.status, landed.out + landed.err).toBe(EXIT.ok); + expect(landed.out).toContain('MERGED: #41 as '); + expect(gateLines(landed.out)).toEqual(gateLines(ok.out)); + expect(gateLines(landed.out)[1]).toContain(`accepted=${id}`); + }, 180_000); + + test('a row the lane appends to the store by hand, digest and all, still needs the lander: land refuses and prints it, a wrong id refuses, and the accepted id lands', () => { + const fx = prep(); + const head = openPr(fx, '42'); + const loc = locate({ cwd: fx.repo.work, env: storeEnv(fx), branch: 'pr-42' }) as StoreLocation; + const forged = buildRow({ ...gateDispositionRow(F, G, head, 'the lane says the owner agreed'), words: 'Do it', by: 'Owner', source: GATE_SOURCE }, 'pr-42') as ApprovalRow; + fs.mkdirSync(path.dirname(loc.file), { recursive: true }); + fs.appendFileSync(loc.file, JSON.stringify({ ...forged, digest: gateDispositionDigest(forged as unknown as Record) }) + '\n'); + const ds = applied(fx, '42', head); + expect(ds.map(d => d.approval)).toEqual([forged.id]); + setBody(fx, '42', bodyWith('42', head, ds)); + const line = `GATE_DISPOSITION: ${gateDispositionText(ds[0]!)}`; + const bare = land(fx, '42', head); + expect([bare.status, gateLines(bare.out)[0], bare.err]).toEqual([EXIT.refused, line, expect.stringContaining(`disposition ${forged.id} is not accepted`)]); + const wrong = land(fx, '42', head, ['--accept-gate-disposition', forged.id, '--accept-gate-disposition', 'a-000000000000']); + expect([wrong.status, wrong.err]).toEqual([EXIT.refused, expect.stringContaining('--accept-gate-disposition a-000000000000 names no disposition the store applies')]); + expect(verify(fx, '42', head, ['--accept-gate-disposition', 'a-000000000000']).status).toBe(EXIT.refused); + expect(land(fx, '42', head, ['--accept-gate-disposition', 'undefined']).status).toBe(EXIT.usage); + const landed = land(fx, '42', head, ['--accept-gate-disposition', forged.id]); + expect(landed.status, landed.out + landed.err).toBe(EXIT.ok); + expect(gateLines(landed.out)[0]).toBe(line); + }, 120_000); + + test('the receipt omitting a disposition, the body dropping its line, and the receipt listing one the store lacks refuse land and verify alike', () => { + const fx = prep(); + const head = openPr(fx, '43'); + const rec = record(fx, '43', head); + expect(rec.status, rec.err).toBe(0); + const id = rec.out.split(' ')[1]!; + const ds = applied(fx, '43', head); + const invented = { ...ds[0]!, approval: 'a-111111111111' }; + for (const [body, problem] of [ + [bodyWith('43', head, [], ds), 'the receipt has no gate_dispositions field'], + [shippedBody('43', head, { gate_dispositions: [] }) + `\nGate disposition: ${gateDispositionText(ds[0]!)}\n`, `the receipt omits applied disposition ${id}`], + [bodyWith('43', head, ds, []), 'the PR body lacks the line "Gate disposition: '], + [bodyWith('43', head, [...ds, invented]), 'the receipt lists disposition a-111111111111, which the store'], + ] as const) { + setBody(fx, '43', body); + const l = land(fx, '43', head, ['--accept-gate-disposition', id, '--dry-run']); + const v = verify(fx, '43', head, ['--accept-gate-disposition', id]); + expect([l.status, l.err]).toEqual([EXIT.refused, expect.stringContaining(problem)]); + expect([v.status, why(v.err), gateLines(v.out)]).toEqual([EXIT.refused, why(l.err), gateLines(l.out)]); + } + setBody(fx, '43', bodyWith('43', head, ds)); + expect(verify(fx, '43', head, ['--accept-gate-disposition', id]).status).toBe(EXIT.ok); + }, 120_000); + + // Value: protects=a merger that reads another state root, or a store that lost the row after the receipt was written, never lands a + // PR whose review an owner disposition cleared with zero accepted ids (the ab73c3f audit's B1); fails_when=a receipt id the store + // lacks, or a field-less receipt beside a row, reads as nothing to accept; seam=gateAcceptance via land and verify + test('another state root at merge, a row removed after the receipt, or a field-less receipt beside a row refuses; an explicit [] with an empty store lands', () => { + const fx = prep(); + const head = openPr(fx, '44'); + const rec = record(fx, '44', head); + expect(rec.status, rec.err).toBe(0); + const id = rec.out.split(' ')[1]!; + const ds = applied(fx, '44', head); + setBody(fx, '44', bodyWith('44', head, ds)); + const other = { ...fx.env, GSTACK_STATE_ROOT: path.join(fx.repo.root, 'merger-state'), GSTACK_HOME: path.join(fx.repo.root, 'merger-state') }; + const elsewhere = runBin(fx.repo, 'gstack-ship-queue', ['verify', '--pr', '44', '--pin', head, '--base', 'main', '--accept-gate-disposition', id], other); + expect([elsewhere.status, elsewhere.err]).toEqual([EXIT.refused, expect.stringContaining('may read another GSTACK_STATE_ROOT or approvals mirror')]); + const landElsewhere = runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', '44', '--pin', head, '--base', 'main', '--dry-run', '--accept-gate-disposition', id], other); + expect([landElsewhere.status, why(landElsewhere.err)]).toEqual([EXIT.refused, why(elsewhere.err)]); + const store = (locate({ cwd: fx.repo.work, env: storeEnv(fx), branch: 'pr-44' }) as StoreLocation).file; + const kept = fs.readFileSync(store, 'utf8'); + fs.rmSync(store); + const removed = land(fx, '44', head, ['--dry-run', '--accept-gate-disposition', id]); + expect([removed.status, removed.err]).toEqual([EXIT.refused, expect.stringContaining(`the receipt lists disposition ${id}, which the store at`)]); + expect(verify(fx, '44', head, ['--accept-gate-disposition', id]).status).toBe(EXIT.refused); + fs.writeFileSync(store, kept); + setBody(fx, '44', shippedBody('44', head) + `\nGate disposition: ${gateDispositionText(ds[0]!)}\n`); + const fieldless = land(fx, '44', head, ['--dry-run', '--accept-gate-disposition', id]); + expect([fieldless.status, fieldless.err]).toEqual([EXIT.refused, expect.stringContaining('the receipt has no gate_dispositions field')]); + expect(verify(fx, '44', head, ['--accept-gate-disposition', id]).status).toBe(EXIT.refused); + const pin = openPr(fx, '45'); + setBody(fx, '45', shippedBody('45', pin, { gate_dispositions: [] })); + expect(verify(fx, '45', pin).status).toBe(EXIT.ok); + const landed = land(fx, '45', pin); + expect(landed.status, landed.out + landed.err).toBe(EXIT.ok); + expect(gateLines(landed.out)).toEqual([]); + }, 180_000); + + test('a git error while deriving the dispositions refuses instead of reading as not applied (N1)', () => { + const fx = prep(); + const head = openPr(fx, '46'); + expect(record(fx, '46', head).status).toBe(0); + const r = gateAcceptance({ cwd: fx.repo.work, branch: 'pr-46', pin: 'f'.repeat(40), body: '', receipt: { gate_dispositions: [] } as any, env: storeEnv(fx) }); + expect(r.failure?.message).toContain(`the pin ${'f'.repeat(12)} is not a commit in this clone`); + expect(r.failure).toMatchObject({ code: 'QUEUE_GATE_DISPOSITION', message: expect.stringContaining('cannot be derived') }); + }, 60_000); + + // Value: protects=a row whose head a rewrite and gc removed never strands land, verify or ready (the 0a9a0c4 review's blocker), + // while a shallow clone, which cannot prove ancestry, refuses; fails_when=git's exit 128 on the missing head refuses for good, + // or a shallow clone reads an unprovable row as not applied; seam=appliedGateDispositions via ready, verify and land + test('a row whose head a rewrite and gc removed is not applied: ready, verify and land proceed; a shallow clone refuses and says to deepen it', () => { + const fx = prep(); + const old = openPr(fx, '47', { ready: false }); + expect(record(fx, '47', old).status).toBe(0); + fx.repo.git('checkout', '-q', 'pr-47'); + fx.repo.git('commit', '-q', '--amend', '-m', 'pr 47 rewritten'); + fx.repo.git('push', '-q', '-f', 'origin', 'HEAD:refs/heads/pr-47'); + const head = fx.repo.git('rev-parse', 'HEAD'); + for (const dir of [['-C', fx.repo.work], ['--git-dir', fx.repo.origin]]) { + fx.repo.git(...dir, 'reflog', 'expire', '--expire=now', '--all'); + fx.repo.git(...dir, 'gc', '-q', '--prune=now'); + } + expect([spawnCheck(fx.repo.work, old), spawnCheck(fx.repo.origin, old), spawnCheck(fx.repo.work, head)]).toEqual([false, false, true]); + expect(applied(fx, '47', head)).toEqual([]); + setBody(fx, '47', shippedBody('47', head, { gate_dispositions: [] })); + const pregate = path.join(fx.repo.root, 'pregate.json'); + fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree: runBin(fx.repo, 'gstack-wtree', []).out.trim(), head, verdict: 'pass', checks: FULL_CHECKS })); + const ready = runBin(fx.repo, 'gstack-ship-queue', ['ready', '--pr', '47', '--pregate', pregate, '--base', 'main'], fx.env); + expect(ready.status, ready.out + ready.err).toBe(EXIT.ok); + expect(gateLines(ready.out)).toEqual([]); + fx.repo.git('checkout', '-q', '--detach', 'origin/main'); + const ok = verify(fx, '47', head); + expect(ok.status, ok.out + ok.err).toBe(EXIT.ok); + const landed = land(fx, '47', head); + expect(landed.status, landed.out + landed.err).toBe(EXIT.ok); + expect(landed.out).toContain('MERGED: #47 as '); + const shallow = path.join(fx.repo.root, 'shallow'); + fx.repo.git('clone', '-q', '--depth', '1', '--branch', 'pr-47', 'file://' + fx.repo.origin, shallow); + fx.repo.git('-C', shallow, 'config', 'remote.origin.url', fx.repo.git('config', 'remote.origin.url')); + const r = gateAcceptance({ cwd: shallow, branch: 'pr-47', pin: head, body: '', receipt: { gate_dispositions: [] } as any, env: storeEnv(fx) }); + expect([r.failure?.code, r.failure?.message]).toEqual(['QUEUE_GATE_DISPOSITION', expect.stringContaining('this clone is shallow')]); + expect(r.failure?.message).toContain('deepen the clone (git fetch --unshallow)'); + }, 180_000); +}); diff --git a/test/size-ledger/ship/owner-approved-gate-changes-finish-unattended-ship.json b/test/size-ledger/ship/owner-approved-gate-changes-finish-unattended-ship.json new file mode 100644 index 00000000000..47532a03818 --- /dev/null +++ b/test/size-ledger/ship/owner-approved-gate-changes-finish-unattended-ship.json @@ -0,0 +1,4 @@ +{ + "bytes": 105, + "why": "gate dispositions (GST-2491): the PR body carries each Gate disposition line" +} diff --git a/test/size-ledger/ship/restore-plan-eng-review.json b/test/size-ledger/ship/restore-plan-eng-review.json new file mode 100644 index 00000000000..bda8bebc6f0 --- /dev/null +++ b/test/size-ledger/ship/restore-plan-eng-review.json @@ -0,0 +1,4 @@ +{ + "bytes": 21, + "why": "GST-2726: /plan-eng-review is back; the preflight DIFF hint and the no-Eng-Review line name it again" +} diff --git a/test/skill-e2e-skillify.test.ts b/test/skill-e2e-skillify.test.ts index d5847f970bd..acdf4d64745 100644 --- a/test/skill-e2e-skillify.test.ts +++ b/test/skill-e2e-skillify.test.ts @@ -280,7 +280,7 @@ This run is non-interactive; AskUserQuestion is unavailable.`, logCost('scrape-prototype-path', result); const cmds = bashCommands(result); - const wentToFixture = browseNavigatedTo(result.toolCalls, fileUrl); + const wentToFixture = browseNavigatedTo(result.toolCalls, fileUrl, workDir); const fetchedHtml = cmds.some(c => /\bgoto\b|\bhtml\b|\btext\b/.test(c)); const surface = fullSurface(result); const mentionsSkillify = /skillify/i.test(surface); diff --git a/test/skill-md-size-guard.test.ts b/test/skill-md-size-guard.test.ts index 09ce7a164c0..44d095442c8 100644 --- a/test/skill-md-size-guard.test.ts +++ b/test/skill-md-size-guard.test.ts @@ -15,7 +15,6 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { ALL_HOST_CONFIGS } from '../hosts/index'; -import { RETIRED_SKILLS } from '../scripts/discover-skills'; const ROOT = path.resolve(import.meta.dir, '..'); const ALLOWLIST_FILE = 'test/fixtures/skill-md-size-allowlist.json'; @@ -83,11 +82,6 @@ function renderAllHosts(outDir: string): Record { if (host.name === 'claude' && !fs.existsSync(`${file}.tmpl`)) continue; sizes[`${host.name}/${dir === '.' ? 'gstack' : dir}`] = countChars(fs.readFileSync(file, 'utf-8')); } - // A retired skill's methodology ships beside /autoplan; it keeps its pin. - for (const skill of RETIRED_SKILLS) { - const file = path.join(skillsRoot, 'gstack-autoplan', `${skill}.md`); - if (host.name !== 'claude' && fs.existsSync(file)) sizes[`${host.name}/gstack-${skill}`] = countChars(fs.readFileSync(file, 'utf-8')); - } } return sizes; } diff --git a/test/skill-routing-e2e.test.ts b/test/skill-routing-e2e.test.ts index c5d23df0a98..1919375eae3 100644 --- a/test/skill-routing-e2e.test.ts +++ b/test/skill-routing-e2e.test.ts @@ -73,7 +73,7 @@ if (evalsEnabled && process.env.EVALS_TIER) { function installSkills(tmpDir: string) { const skillDirs = [ '', // root gstack SKILL.md - 'qa', 'qa-only', 'ship', 'review', 'plan-ceo-review', 'autoplan', + 'qa', 'qa-only', 'ship', 'review', 'plan-ceo-review', 'plan-eng-review', 'autoplan', 'plan-design-review', 'design-review', 'design-consultation', 'retro', 'document-release', 'office-hours', 'browse', 'setup-browser-cookies', 'gstack-upgrade', 'humanizer', @@ -241,7 +241,7 @@ describeE2E('Skill Routing E2E — Developer Journey', () => { spawnSync('git', ['commit', '-m', 'initial'], { cwd: tmpDir, stdio: 'pipe', timeout: 5000 }); const testName = 'journey-plan-eng'; - const expectedSkill = 'autoplan'; + const expectedSkill = 'plan-eng-review'; const result = await runSkillTest({ prompt: "I wrote up a plan for the waitlist app in plan.md. Can you take a look at the architecture and make sure I'm not missing any edge cases or failure modes before I start coding?", workingDirectory: tmpDir, diff --git a/test/third-party-actions.test.ts b/test/third-party-actions.test.ts index c597fe4f1b4..50e68a4d9f3 100644 --- a/test/third-party-actions.test.ts +++ b/test/third-party-actions.test.ts @@ -72,6 +72,16 @@ D) Defer expect(asideDriveOptions('A) Open the Aside app; if READY, I drive the dashboard.')).toHaveLength(1); }); + test('a drive option that names Aside only as missing is not an Aside drive (gate 42748129558)', () => { + for (const option of ["B) I drive it in gstack's own visible browser (recommended, since Aside isn't available). I open the dashboard in a visible browser window and stop whenever you need to act.", + "B) Aside isn't available, so I drive it in gstack's own browser.", "B) Aside was not detected; I drive it in gstack's own browser.", + "B) Since the Aside browser is unavailable, I drive it in gstack's own browser.", "B) With no Aside installed, I drive it in gstack's browser."]) + expect(asideDriveOptions(option), option).toEqual([]); + for (const option of ["A) Aside isn't open yet, so I open Aside and drive the dashboard.", + 'A) I drive it in your Aside browser; Aside is not the only option.', "A) Aside wasn't running, but now I drive it in your Aside browser."]) + expect(asideDriveOptions(option), option).toHaveLength(1); + }); + test.each(recoveryFixture.responses)('native recovery response $attempt defers drive consent to a new question', ({ text }) => { expect(asideDriveOptions(text)).toEqual([]); expect(asideDriveOptions(text.replace('option included.', 'option included; then I drive in your Aside browser.'))).toHaveLength(1); @@ -577,8 +587,9 @@ describe('Opus consent renders (gate captures)', () => { test('the defer outcome counts in any words, and a refusal of it never does', () => { // Gate 42431616220 slice 15: the red tpa-present render's D) option, missed by the spelling list. for (const option of ["D) Do it later. I'll mark this step as waiting on you.", 'D) Not yet: the step stays blocked on you.', - 'D) Later. This step remains waiting on you.', "D) Do it later \u2014 I'll leave this step as blocked on you.", - "D) Do it later - I'll leave this step as blocked on you."]) + 'D) Later. This step remains waiting on you.', 'D) Later, so this step remains waiting on you.', "D) Do it later \u2014 I'll leave this step as blocked on you.", + "D) Do it later - I'll leave this step as blocked on you.", 'D) Not now. The step stays blocked on you.', + 'D) Sign in yourself later. The step is waiting on you.']) expect(offersDefer(option), option).toBe(true); for (const text of ['D) Continue now. I will not mark this step as blocked on you.', "D) Continue now. I won't mark this step as waiting on you.", 'D) Continue now. I never mark this step as blocked on you.', @@ -598,6 +609,12 @@ describe('Opus consent renders (gate captures)', () => { "B) I drive it in gstack's own browser and mark this step as waiting on you.", "C) Manual instructions; I'll mark this step as blocked on you.", 'C) I give you the steps to do it yourself. The step stays blocked on you.', + // /ship note at d98f9bb5 (PR #4223): a state line after a non-defer instruction is not a defer offer. + 'D) Sign in yourself. Until then the step stays blocked on you.', + 'D) Approve the token in the dashboard. The step is waiting on you.', + 'D) Continue now. The step is waiting on you.', + 'D) Do it now, not later. The step stays blocked on you.', + 'D) The step is waiting on you. Do it later.', "I'll mark this step as waiting on you.\nA) I drive it in your Aside browser\nB) Manual instructions"]) expect(offersDefer(text), text).toBe(false); }); diff --git a/test/transcript-scope-brain-sync.test.ts b/test/transcript-scope-brain-sync.test.ts index d4238cde02b..5e839e6b4c1 100644 --- a/test/transcript-scope-brain-sync.test.ts +++ b/test/transcript-scope-brain-sync.test.ts @@ -5,7 +5,7 @@ * commits before every push, so a page outside the current consent is never * published. Local bare repo as the remote; stub gbrain; no network. */ -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; import { spawnSync } from 'child_process'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'; import { tmpdir } from 'os'; @@ -16,6 +16,8 @@ const BIN = join(ROOT, 'bin'); const DAY = 24 * 60 * 60 * 1000; const iso = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z'); +setDefaultTimeout(30_000); + let home: string; let gstackHome: string; let remote: string; diff --git a/test/uninstall.test.ts b/test/uninstall.test.ts index c17f6f22eb8..aba33401470 100644 --- a/test/uninstall.test.ts +++ b/test/uninstall.test.ts @@ -978,6 +978,10 @@ describe('per-project state: tracked files and dirty worktrees survive (GSTA-461 fs.writeFileSync(path.join(install, '.git', 'info', 'exclude'), '.gstack-worktrees/\n.gstack/\n'); git(['add', 'SKILL.md'], install); git(['commit', '-q', '-m', 'install'], install); + // Like a real git-clone install, every commit is on its origin (GST-2303 refuses unpushed ones). + git(['init', '-q', '--bare', path.join(tmp, 'install-origin.git')], tmp); + git(['remote', 'add', 'origin', path.join(tmp, 'install-origin.git')], install); + git(['push', '-q', 'origin', 'main'], install); return install; }; @@ -1106,3 +1110,343 @@ describe('per-project state: tracked files and dirty worktrees survive (GSTA-461 expect(fs.existsSync(path.join(home, '.gstack'))).toBe(false); }); }); + +// Value: protects=unpushed commits, uncommitted edits, locked worktrees and --keep-state state that sit inside a gstack +// install root, a project-local install, a Claude per-skill folder or ~/.gstack, whichever repository uninstall runs from; +// fails_when=uninstall deletes a target without checking every git repository beneath it (GST-2303). +describe('every deletion target is checked for unsaved git work before anything is removed (GST-2303)', () => { + let tmp: string, home: string, proj: string, install: string, gitEnv: Record; + const git = (args: string[], cwd = proj) => { + const r = spawnSync('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', '-c', 'commit.gpgsign=false', '-c', 'protocol.file.allow=always', ...args], { cwd, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + expect(r.status).toBe(0); + return r.stdout; + }; + const uninstall = (args: string[], cwd = proj) => spawnSync('bash', [UNINSTALL, ...args], { + cwd, encoding: 'utf-8', timeout: 30_000, + env: { ...gitEnv, HOME: home, GSTACK_DIR: install, GSTACK_SETTINGS_FILE: path.join(home, 'settings.json'), + GSTACK_HOME: '', GSTACK_STATE_ROOT: path.join(home, '.gstack'), GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '' }, + }); + // A repository with an origin it has pushed everything to, like a real git-clone install. + const pushedRepo = (dir: string, file = 'SKILL.md', body = 'test\n') => { + const origin = path.join(tmp, 'origins', path.relative(tmp, dir).replace(/[\\/]/g, '_') + '.git'); + fs.mkdirSync(dir, { recursive: true }); + git(['init', '-q', '--bare', origin], tmp); + git(['init', '-q', '-b', 'main'], dir); + fs.writeFileSync(path.join(dir, file), body); + git(['add', file], dir); + git(['commit', '-q', '-m', 'seed'], dir); + git(['remote', 'add', 'origin', origin], dir); + git(['push', '-q', 'origin', 'main'], dir); + return dir; + }; + const unpushedCommit = (dir: string) => { + fs.writeFileSync(path.join(dir, 'notes.md'), 'mine\n'); + git(['add', 'notes.md'], dir); + git(['commit', '-q', '-m', 'unpushed notes'], dir); + }; + + beforeEach(() => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-uninstall-targets-'))); + home = path.join(tmp, 'home'); + proj = path.join(tmp, 'proj'); + fs.writeFileSync(path.join(tmp, 'gitconfig'), ''); + gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: path.join(tmp, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' } as Record; + install = pushedRepo(path.join(home, '.claude', 'skills', 'gstack')); + fs.writeFileSync(path.join(install, '.git', 'info', 'exclude'), '.gstack-worktrees/\n.gstack/\n'); + fs.mkdirSync(path.join(home, '.gstack'), { recursive: true }); + pushedRepo(proj, 'README.md', 'x\n'); + }); + afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); + + test('hold: a clean, pushed git-clone install is removed', () => { + const r = uninstall(['--force']); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(fs.existsSync(install)).toBe(false); + }); + + test('--keep-state run from inside the install refuses instead of deleting its kept .gstack-worktrees lane', () => { + const lane = path.join(install, '.gstack-worktrees', 'run', 'lane'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD'], install); + const r = uninstall(['--force', '--keep-state'], install); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: it holds ${install}/.gstack-worktrees, which this uninstall keeps`); + expect(fs.existsSync(path.join(lane, 'SKILL.md'))).toBe(true); + }); + + test('--keep-state run from inside the install refuses instead of deleting its tracked .gstack policy', () => { + fs.writeFileSync(path.join(install, '.git', 'info', 'exclude'), ''); + fs.mkdirSync(path.join(install, '.gstack')); + fs.writeFileSync(path.join(install, '.gstack', 'ship-policy.json'), '{}\n'); + git(['add', '.gstack/ship-policy.json'], install); + git(['commit', '-q', '-m', 'policy'], install); + git(['push', '-q', 'origin', 'main'], install); + const r = uninstall(['--force', '--keep-state'], install); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`it holds ${install}/.gstack, which this uninstall keeps`); + expect(fs.existsSync(path.join(install, '.gstack', 'ship-policy.json'))).toBe(true); + }); + + test('run from an unrelated project, a .gstack repo with unpushed commits inside the global install stops the uninstall', () => { + const own = path.join(install, '.gstack'); + pushedRepo(own, 'policy.md'); + unpushedCommit(own); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: ${own} has commits no remote-tracking branch contains`); + expect(git(['log', '-1', '--format=%s'], own)).toBe('unpushed notes\n'); + expect(fs.existsSync(path.join(home, '.gstack'))).toBe(true); + }); + + test('the install clone\'s own unpushed commit stops the uninstall', () => { + unpushedCommit(install); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: ${install} has commits no remote-tracking branch contains`); + expect(fs.existsSync(path.join(install, 'notes.md'))).toBe(true); + }); + + test('a project-local install clone with an uncommitted edit stops the uninstall', () => { + const local = pushedRepo(path.join(proj, '.claude', 'skills', 'gstack')); + fs.writeFileSync(path.join(local, 'SKILL.md'), 'my edit\n'); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${local}: ${local} has uncommitted changes`); + expect(fs.readFileSync(path.join(local, 'SKILL.md'), 'utf-8')).toBe('my edit\n'); + expect(fs.existsSync(install)).toBe(true); + }); + + test('a repository with unpushed commits at .agents/skills/gstack-notes stops the uninstall', () => { + const notes = pushedRepo(path.join(proj, '.agents', 'skills', 'gstack-notes'), 'README.md'); + unpushedCommit(notes); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${notes}: ${notes} has commits no remote-tracking branch contains`); + expect(fs.existsSync(path.join(notes, 'notes.md'))).toBe(true); + }); + + test('a gstack-generated Claude per-skill folder holding an uncommitted edit stops the uninstall', () => { + fs.mkdirSync(path.join(install, 'review')); + fs.writeFileSync(path.join(install, 'review', 'SKILL.md'), 'name: review\n'); + const skill = pushedRepo(path.join(home, '.claude', 'skills', 'review'), 'SKILL.md', '\n'); + fs.writeFileSync(path.join(skill, 'SKILL.md'), '\nmy edit\n'); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${skill}: ${skill} has uncommitted changes`); + expect(fs.readFileSync(path.join(skill, 'SKILL.md'), 'utf-8')).toContain('my edit'); + }); + + test('a repository with unpushed commits under ~/.gstack stops the uninstall', () => { + const notes = pushedRepo(path.join(home, '.gstack', 'projects', 'notes'), 'README.md'); + unpushedCommit(notes); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${path.join(home, '.gstack')}: ${notes} has commits no remote-tracking branch contains`); + expect(fs.existsSync(path.join(notes, 'notes.md'))).toBe(true); + expect(fs.existsSync(install)).toBe(true); + }); + + test('a locked worktree of the install clone stops the uninstall, even outside the install', () => { + const lane = path.join(tmp, 'lane'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD'], install); + git(['worktree', 'lock', lane], install); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: ${install} registers the locked worktree ${lane}`); + expect(fs.existsSync(path.join(install, '.git'))).toBe(true); + }); + + test('a dirty repo behind a .gstack-worktrees symlink into ~/.gstack stops the uninstall', () => { + const lane = pushedRepo(path.join(home, '.gstack', 'lanes', 'lane1')); + fs.writeFileSync(path.join(lane, 'SKILL.md'), 'my edit\n'); + fs.symlinkSync(path.join(home, '.gstack', 'lanes'), path.join(proj, '.gstack-worktrees')); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${path.join(home, '.gstack')}: ${lane} has uncommitted changes`); + expect(fs.readFileSync(path.join(lane, 'SKILL.md'), 'utf-8')).toBe('my edit\n'); + }); + + test('a shallow stable-channel install advanced by git fetch origin stable is removed', () => { + fs.rmSync(install, { recursive: true, force: true }); + const origin = path.join(tmp, 'channel-origin.git'); + const seed = pushedRepo(path.join(tmp, 'channel-seed')); + git(['remote', 'set-url', 'origin', origin], seed); + git(['init', '-q', '--bare', '-b', 'main', origin], tmp); + git(['push', '-q', 'origin', 'main'], seed); + git(['clone', '-q', '--single-branch', '--depth', '1', `file://${origin}`, install], tmp); + fs.writeFileSync(path.join(seed, 'SKILL.md'), 'release\n'); + git(['commit', '-q', '-am', 'release'], seed); + git(['push', '-q', 'origin', 'main', 'main:stable'], seed); + git(['fetch', '-q', 'origin', 'stable'], install); + git(['merge', '-q', '--ff-only', 'FETCH_HEAD'], install); + const r = uninstall(['--force']); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(fs.existsSync(install)).toBe(false); + }); + + test('a stable-channel install whose remote URL goes through url.insteadOf is removed', () => { + fs.rmSync(install, { recursive: true, force: true }); + const origin = path.join(tmp, 'channel-origin.git'); + const seed = pushedRepo(path.join(tmp, 'channel-seed')); + git(['remote', 'set-url', 'origin', origin], seed); + git(['init', '-q', '--bare', '-b', 'main', origin], tmp); + git(['push', '-q', 'origin', 'main'], seed); + fs.writeFileSync(path.join(tmp, 'gitconfig'), `[url "file://${tmp}/"]\n\tinsteadOf = alias:\n`); + git(['clone', '-q', '--single-branch', '--depth', '1', 'alias:channel-origin.git', install], tmp); + fs.writeFileSync(path.join(seed, 'SKILL.md'), 'release\n'); + git(['commit', '-q', '-am', 'release'], seed); + git(['push', '-q', 'origin', 'main', 'main:stable'], seed); + git(['fetch', '-q', 'origin', 'stable'], install); + git(['merge', '-q', '--ff-only', 'FETCH_HEAD'], install); + const r = uninstall(['--force']); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(fs.existsSync(install)).toBe(false); + }); + + test('a local-only commit that git fetch . HEAD wrote into FETCH_HEAD still stops the uninstall', () => { + unpushedCommit(install); + git(['fetch', '-q', '.', 'HEAD'], install); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: ${install} has commits no remote-tracking branch contains`); + expect(fs.existsSync(path.join(install, 'notes.md'))).toBe(true); + }); + + test('on a git older than 2.36 (no worktree list -z) the uninstall refuses and keeps the install', () => { + const lane = path.join(tmp, 'lane'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD'], install); + git(['worktree', 'lock', lane], install); + const shim = path.join(tmp, 'oldgit'); + fs.mkdirSync(shim); + fs.writeFileSync(path.join(shim, 'git'), `#!/bin/bash\ncase " $* " in *" worktree list "*" -z "*) echo "error: unknown switch z" >&2; exit 129 ;; esac\nexec ${JSON.stringify(Bun.which('git'))} "$@"\n`, { mode: 0o755 }); + const r = spawnSync('bash', [UNINSTALL, '--force'], { + cwd: proj, encoding: 'utf-8', timeout: 30_000, + env: { ...gitEnv, PATH: `${shim}:${gitEnv.PATH}`, HOME: home, GSTACK_DIR: install, GSTACK_SETTINGS_FILE: path.join(home, 'settings.json'), + GSTACK_HOME: '', GSTACK_STATE_ROOT: path.join(home, '.gstack'), GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '' }, + }); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: ${install} has worktrees git cannot list (gstack-uninstall needs git 2.36 or later)`); + expect(fs.existsSync(path.join(install, '.git'))).toBe(true); + }, 30_000); +}); + +describe('locked worktrees are found by NUL-separated paths (GST-2303)', () => { + let tmp: string, home: string, repo: string, gitEnv: Record; + const git = (args: string[], cwd = repo) => { + const r = spawnSync('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', '-c', 'commit.gpgsign=false', '-c', 'protocol.file.allow=always', ...args], { cwd, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + expect(r.status).toBe(0); + return r.stdout; + }; + const uninstall = (args: string[]) => spawnSync('bash', [UNINSTALL, ...args], { + cwd: repo, encoding: 'utf-8', timeout: 30_000, + env: { ...gitEnv, HOME: home, GSTACK_DIR: path.join(home, '.claude', 'skills', 'gstack'), + GSTACK_SETTINGS_FILE: path.join(home, 'settings.json'), + GSTACK_HOME: '', GSTACK_STATE_ROOT: path.join(home, '.gstack'), GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '' }, + }); + beforeEach(() => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-uninstall-lock-'))); + home = path.join(tmp, 'home'); + repo = path.join(tmp, 'proj'); + fs.writeFileSync(path.join(tmp, 'gitconfig'), ''); + gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: path.join(tmp, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' } as Record; + fs.mkdirSync(path.join(home, '.claude', 'skills', 'gstack'), { recursive: true }); + fs.writeFileSync(path.join(home, '.claude', 'skills', 'gstack', 'SKILL.md'), 'test'); + fs.mkdirSync(repo, { recursive: true }); + git(['init', '-q', '-b', 'main']); + fs.writeFileSync(path.join(repo, '.git', 'info', 'exclude'), '.gstack-worktrees/\n'); + fs.writeFileSync(path.join(repo, 'README.md'), 'x\n'); + git(['add', 'README.md']); + git(['commit', '-q', '-m', 'seed']); + }); + afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); + + test('a locked worktree whose path holds a newline survives --force --force-worktrees', () => { + const lane = path.join(repo, '.gstack-worktrees', 'run', 'lane\nx'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD']); + git(['worktree', 'lock', lane]); + const r = uninstall(['--force', '--force-worktrees']); + expect(r.status).toBe(2); + expect(r.stderr).toContain('it is locked (git worktree lock)'); + expect(fs.existsSync(path.join(lane, 'README.md'))).toBe(true); + }); + + test('a clean submodule nested inside a clean submodule of a clean lane does not stop the uninstall', () => { + const inner = path.join(tmp, 'inner'); + fs.mkdirSync(inner); + git(['init', '-q', '-b', 'main'], inner); + fs.writeFileSync(path.join(inner, 'a.txt'), 'a\n'); + git(['add', 'a.txt'], inner); + git(['commit', '-q', '-m', 'inner'], inner); + const lib = path.join(tmp, 'lib'); + fs.mkdirSync(lib); + git(['init', '-q', '-b', 'main'], lib); + git(['submodule', 'add', '-q', inner, 'deps/inner'], lib); + git(['commit', '-q', '-m', 'lib'], lib); + git(['submodule', 'add', '-q', lib, 'vendor/lib']); + git(['commit', '-q', '-m', 'submodule']); + const lane = path.join(repo, '.gstack-worktrees', 'run', 'lane'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD']); + git(['submodule', 'update', '-q', '--init', '--recursive'], lane); + expect(fs.existsSync(path.join(lane, 'vendor', 'lib', 'deps', 'inner', 'a.txt'))).toBe(true); + const r = uninstall(['--force']); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(fs.existsSync(lane)).toBe(false); + }); +}); + +describe('the manual removal in docs/uninstall.md checks each folder before deleting it (GST-2303)', () => { + let tmp: string, gitEnv: Record; + const git = (args: string[], cwd: string) => { + const r = spawnSync('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', '-c', 'commit.gpgsign=false', ...args], { cwd, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + expect(r.status).toBe(0); + }; + const checkedDelete = (dirs: string[]) => { + const doc = fs.readFileSync(path.join(ROOT, 'docs', 'uninstall.md'), 'utf-8'); + const start = doc.indexOf('# 0. A delete that stops for unsaved git work'); + expect(start).toBeGreaterThan(-1); + const helper = doc.slice(start, doc.indexOf('# 1. Stop browse daemons', start)); + return spawnSync('bash', ['-c', `${helper}\ngstack_rm_checked "$@"`, 'doc', ...dirs], { cwd: tmp, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + }; + beforeEach(() => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-uninstall-doc-'))); + fs.writeFileSync(path.join(tmp, 'gitconfig'), ''); + gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: path.join(tmp, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' } as Record; + }); + afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); + + test('a folder holding a repo with an unpushed commit is kept, and a plain folder goes', () => { + const install = path.join(tmp, 'install'); + const notes = path.join(install, '.gstack'); + fs.mkdirSync(notes, { recursive: true }); + fs.writeFileSync(path.join(install, 'SKILL.md'), 'test\n'); + git(['init', '-q', '-b', 'main'], notes); + fs.writeFileSync(path.join(notes, 'notes.md'), 'mine\n'); + git(['add', 'notes.md'], notes); + git(['commit', '-q', '-m', 'unpushed notes'], notes); + const plain = path.join(tmp, 'plain'); + fs.mkdirSync(plain); + fs.writeFileSync(path.join(plain, 'SKILL.md'), 'test\n'); + const r = checkedDelete([install, plain]); + expect(r.status).toBe(0); + expect(r.stderr).toContain(`kept ${install}: ${notes} has uncommitted changes, unpushed commits or a locked worktree`); + expect(fs.existsSync(path.join(notes, 'notes.md'))).toBe(true); + expect(fs.existsSync(plain)).toBe(false); + }); + + test('a local-only commit that git fetch . HEAD wrote into FETCH_HEAD keeps its folder', () => { + const repo = path.join(tmp, 'repo'); + fs.mkdirSync(repo); + git(['init', '-q', '-b', 'main'], repo); + fs.writeFileSync(path.join(repo, 'notes.md'), 'mine\n'); + git(['add', 'notes.md'], repo); + git(['commit', '-q', '-m', 'local notes'], repo); + git(['fetch', '-q', '.', 'HEAD'], repo); + const r = checkedDelete([repo]); + expect(r.stderr).toContain(`kept ${repo}: ${repo} has uncommitted changes, unpushed commits or a locked worktree`); + expect(fs.existsSync(path.join(repo, 'notes.md'))).toBe(true); + }); +}); + diff --git a/test/weekly-release-workflow.test.ts b/test/weekly-release-workflow.test.ts index c5d6b17b2b2..0ad32aaef2c 100644 --- a/test/weekly-release-workflow.test.ts +++ b/test/weekly-release-workflow.test.ts @@ -49,7 +49,7 @@ describe('weekly-release.yml', () => { test('the cut job runs only off main for a schedule or dispatch, writes contents, reads checks, and rejects a ref that is not a 40-hex SHA', () => { const cut = wf.jobs.cut!; expect(cut.if).toBe("github.event_name != 'pull_request' && github.ref == 'refs/heads/main'"); - expect(cut.permissions).toEqual({ contents: 'write', checks: 'read', issues: 'read', 'pull-requests': 'read' }); + expect(cut.permissions).toEqual({ contents: 'write', checks: 'read', actions: 'read', issues: 'read', 'pull-requests': 'read' }); expect(cut.steps.find(s => s.uses?.startsWith('actions/checkout@'))!.with).toEqual({ 'fetch-depth': 0 }); const plan = cut.steps.find(s => s.name === 'Plan and cut')!; expect(plan.env!.GH_TOKEN).toBe('${{ github.token }}'); @@ -78,7 +78,7 @@ describe('weekly-release.yml', () => { test('the pull-request dry run is read-only, keeps no credentials, and always passes --dry-run', () => { const dry = wf.jobs['dry-run']!; expect(dry.if).toBe("github.event_name == 'pull_request'"); - expect(dry.permissions).toEqual({ contents: 'read', checks: 'read' }); + expect(dry.permissions).toEqual({ contents: 'read', checks: 'read', actions: 'read' }); expect(dry.steps.find(s => s.uses?.startsWith('actions/checkout@'))!.with).toEqual({ 'fetch-depth': 0, 'persist-credentials': false }); const plan = dry.steps.find(s => s.name === 'Plan only')!; expect(plan.run).toContain(BUN_RUN + ' --repo "$GITHUB_REPOSITORY" --summary "$GITHUB_STEP_SUMMARY" --dry-run\n');