mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 09:56:57 +02:00
* refactor(resolvers): split review.ts into MECE resolver modules (pure move) Move every function from scripts/resolvers/review.ts, unchanged, into: - review-dashboard.ts: review dashboard, plan-file review report - plan-gates.ts: approval check, exit-plan-mode gate, plan-file discovery, plan-completion audit/gate (ship + review), plan verification exec - spec-review.ts: both spec review loops, benefits-from, anti-shortcut clause - outside-voice-steps.ts: Codex second opinion, adversarial step, Codex plan review, Codex doc review, disabled-outside record - review-scope.ts: scope drift, cross-review dedup, shared-code reuse review.ts is deleted; index.ts imports the new modules. gen-skill-docs output is byte-identical for every host (--host all). Test imports and source-path references are re-pointed; the two source-text report/gate tests in gen-skill-docs.test.ts become behavioral renders across every consuming skill and host. All 46 touchfile entries that named review.ts now name all five modules, guarded by a recorded selection golden. * test(browse): black-box auth matrix for every server route and both surfaces Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token, root token, scoped token and the SSE cookie for all 33 routes, plus unmatched paths and wrong methods. Denials assert today's exact status, body and content type; allowed credentials assert the handler was reached. Written against the unchanged if-chain server so the W3 route-table refactor must keep it green. * refactor(shard-engine): move scripts/test-strict-output.ts to scripts/lib/shard-engine.ts The shared shard engine grows from the existing strict-output module (runShardChild, killProcessGroup, signal forwarding, strict classifier). scripts/test-strict-output.ts stays as a re-export so existing importers, mock.module paths and the strict-output/run-shard-child tests are unchanged. The engine inherits the global touchfile entry; the free runner's CLI-routing fixture copies the new module. * refactor(resolvers): decompose the three >150-line review resolvers (output-neutral) Split generateAdversarialStep, generateCodexPlanReview and generatePlanCompletionAuditInner into per-section helpers whose template literals are copied verbatim, so every function in the new modules is at or under 150 lines. gen-skill-docs output is byte-identical for every host (--host all, compared against96764e80with a fixed --link-root). * refactor(resolvers): one outside-voice failure policy (deliberate prose unification) outsideVoiceFailurePolicy(ctx, opts) in outside-voice.ts now renders the auth / timeout / empty-response bullets for all four call sites that hand-typed them (Codex second opinion, adversarial step, Codex plan review, design outside voices). Options are explicit per site (timeoutMinutes, onTimeout, stderrOnEmpty, fallback, escape) with no defaults. Deliberate generated-prose changes (every host): - office-hours: 'Fall back to <native> subagent.' becomes 'Fall back to the <native> subagent below.' - plan-devex-review: the plain 'Auth failure (stderr contains ...)' bullets become the canonical bold bullets; auth also triggers on 'API key'; 'auth failed' becomes 'authentication failed'. - review/ship adversarial: 'exceeded 9 minutes and was terminated' becomes 'timed out after 9 minutes and was terminated'; the timeout is still MISSING COVERAGE. - design outside voices: unchanged. Adds ratchet (d) (test/outside-voice-failure-policy.test.ts) with a reasoned allowlist for /codex's own CLI errors, the MISSING COVERAGE retention test, refreshed codex/factory ship goldens, and outside-voice.ts in every touchfile entry of review.ts and design.ts (selection golden extended). * test(pty): fake PTY session driver with an injectable clock through the runner launch seam The three plan-skill runners take an optional PtyDriver (launch, now, monotonic, sleep); omitted, they use the real launcher and clocks exactly as before. test/helpers/pty/fake-session.ts feeds scripted frames through that seam, and claude-pty-runner.runners.unit.test.ts runs observation, counting and floor for success, deadline timeout, permission prompt and plan-ready outcomes with no CLI or real timers. These cases must stay green unchanged through the W4 split and the runPtySession extraction. Touchfiles: every entry that lists claude-pty-runner.ts or pty-screen.ts now also lists test/helpers/pty/**. * refactor(shard-engine): run both lanes on the shared engine; lane policy injected Engine (scripts/lib/shard-engine.ts) gains the W2 primitives: per-shard tmp/Chromium sandbox + async cleanup backstop, log-path allocation and full-stream log capture, one duration-seed reader/writer with a lane predicate, LanePolicy (seed predicate + zero-execution verdict), strictShardStatus, and the shared CLI flag loop. runShardChild takes an optional companion (signal/settle) and waits a bounded 250ms to reap a wall-killed child. Free lane stops spawning shards itself: runFreeShard uses runShardChild with trackShardBrowser as the companion (win32 path unchanged: no process group, no negative-pid kill). Its sync state-dir removal stays lane policy. Paid lane uses the sandbox, log, seed, verdict and flag primitives; the hollow-shard guard applies PAID_LANE_POLICY. Lane outcomes are unchanged (free keeps >= 0 seeds and file-count zero-exec rule; paid keeps > 0 seeds, warning under selection and passed-empty under EVALS_ALL). paid-free-boundary's closure assertion now names the engine module, where the strict classifier lives. * test(shard-engine): engine unit tests, fixture-corpus equivalence, per-lane CLI parity - test/shard-engine.test.ts: failing/unhandled/module-load output fails both lanes, per-lane zero-execution and seed rules, whole-group kill on a wall timeout (both lanes), mocked-win32 path with no negative-pid kill, companion settle order, log capture, sandbox isolation, flag loop. - test/shard-engine-equivalence.test.ts + test/fixtures/shard-equivalence: seven outcome fixtures plus one real shard, run through both lanes and compared with classifications recorded from the base runners (96764e80). - test/shard-cli-parity.test.ts + test/fixtures/shard-cli-parity: flag set, defaults, validation errors and the Unknown argument error per lane match the base runners. * refactor(shard-engine): decompose runFreeShard and runPaidShard to <= 150 lines Output-neutral extraction under the fixture-corpus equivalence and runner tests: captureFreeStream, explainFreeVerdict and logFreeRecovery (free); paidShardCommand, settleShardSpool, settleBootstrapRetention and printLogTail (paid). The bootstrap scope-creation block that bootstrap-retention.test.ts evaluates stays verbatim. * refactor(pty): split claude-pty-runner.ts into test/helpers/pty/* behind a barrel Pure move: every line of the former 5,047-line runner lands verbatim in one module (four private helpers gain `export` for cross-module use): binary, screen (absorbs test/helpers/pty-screen.ts, which now re-exports it), launch, session (PtyDriver), judge, classify, auq, plan-native, boundaries, runners/{observation,counting,floor}. claude-pty-runner.ts re-exports the original public surface by name; pty/ modules import siblings directly. Tests that read the runner's source text: - rewritten as behavioral: the unit test's model-pin tripwire (fake CLI argv: fallback chain, --model before extraArgs, hermetic --strict-mcp-config), pty-skill-seeding-wiring (runners through the fake driver; launcher through a fake CLI reporting CLAUDE_CONFIG_DIR). The "three wrappers forward model" grep is replaced by the runners' fake-driver launch assertions. - pty-screen-session / pty-screen-supervision: stop copying runner source; they mock.module the real pty/screen.ts (and the fixture cleanup) instead. - re-pointed to the owning module (they execute a sliced runner body with injected boundaries; no seam exists for those boundaries yet): eng-seeded-completion-ai, plan-floor-permission, plan-create-prepublication, plan-count-completion; hermetic-wiring's source guard now reads pty/launch.ts and scans every pty/ module for raw process.env spreads. - plan-count-timeout and pty-output-wake mock the viewport at pty/screen.ts. * test(ratchet-c): enforcing module/function size ratchet and moved-code touchfile coverage Ratchet (c) ships enforcing: test/helpers/module-size.ts counts file and top-level function lengths by brace matching over masked source (strings, comments, regex literals and template text masked; ${} expressions kept), covering function declarations, arrow functions assigned to consts and route-table handler properties, with no parser dependency. Its self-test uses template literals and code-fence braces copied from scripts/resolvers/review.ts and design.ts. test/fixtures/module-size-ratchet.json binds scripts/lib/shard-engine.ts (<= 800 lines, <= 150 per function) and records the residual runner sizes (free 2352, paid 1921) as non-growth caps; allowlist entries are keyed on file plus matched text and need a reason. Failure output lists file:line, the rule, Fix: and the allowlist path. touchfiles.test.ts gains the moved-code superset check over test/fixtures/touchfile-move-goldens/ (W2 golden recorded at96764e80: test-strict-output.ts and test-paid-shards.ts global, test-free-shards.ts none). * refactor(browse): declared route table replaces the buildFetchHandler if-chain The ~1,300-line if-chain in buildFetchHandler becomes a route table: each entry declares method, path, auth kind and surfaces, and one auth gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer, scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token required; extension-origin: 403 Forbidden). Unmatched requests take the declared fallthrough (root-bearer check, then plain-text 404). Handlers move to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files, inspector}.ts and receive a RouteContext with auth checks as functions instead of closing over factory locals. Dispatch order is unchanged: tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a literal in server.ts. Behavior-preserving: the black-box auth matrix from the previous commit passes unchanged. /memory and /inspector/events are declared root-bearer because the blanket check always ran before their SSE-cookie branch. Source-text route tests are rewritten as behavioral tests through buildFetchHandler or a route's real handler with a stub RouteContext (browse/test/route-test-harness.ts). Checks with no runtime seam are re-pointed to the route modules: Surface type, /inspector/events SSE helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import, and the ngrok config lookup and startTunnel wiring that stay in server.ts. * test(browse): stubbed-handler auth matrix and route inventory for the route table Every ROUTES entry runs through the real dispatcher and gate with stub handlers on each declared surface and six credentials; denials assert the exact status and body each auth kind returned at96764e8, admitted credentials assert the handler ran (with the gate's TokenInfo for scoped routes). Also pins the reviewed route inventory (method, path, auth kind, surfaces), that every entry declares auth and surfaces, that the table's tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the unmatched fallthrough, and that the root token is rejected on every tunnel route through buildFetchHandler. * test(browse): ratchet (b) keeps route dispatch inside the route table Scans browse/src/server.ts and browse/src/routes/*.ts for pathname comparisons; only the table matcher and the tunnel-surface filter are allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file plus line text). Also checks every entry declares auth and surfaces and that gstack registers no beforeRoute overlay itself. Self-tests plant a violation and assert the file:line, Fix: and allowlist path in the message, that a shifted line stays allowlisted, and that a reasonless entry is rejected. * test: touchfile superset check for modules moved out of browse/src/server.ts Records the paid evals selected by touching browse/src/server.ts at96764e80(17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects a superset. The test reads every golden in test/fixtures/moved-module-selection/ so other moved-code goldens can sit beside it. * test(shard-engine): give non-timeout corpus fixtures CI headroom; keep the POSIX golden off the Windows lane Only the wall-timeout fixture keeps a 3s wall; the rest get 60s so a loaded host cannot turn a pass into a timeout. Base and branch runners still agree on every classification under the new walls. The Windows exclusion entry moves the free runner's ratchet (c) residual cap to 2356 lines. * refactor(pty): one runPtySession loop drives observation, counting and floor test/helpers/pty/session.ts owns launch -> start -> (poll -> tick)* -> timeout and the failure contract the three runners each hand-rolled: the run's own error wins over capture and close errors, close always runs, owned fixture cleanup runs last (also when launch fails). Each runner now supplies a PtySessionPlan: its boot/command step, poll cadence (2s observation/floor sleep; counting's output wake + 250ms coalesce), tick policy (permission handling, native identity, terminal rules stay per runner because they differ) and capture hooks. The runner bodies are decomposed into top-level steps so no function exceeds 150 lines; behavior is unchanged and the fake-driver cases from the first W4 commit pass unmodified. The counting capture step and the native completion-summary predicate are now named functions (countingCapture, isNativeCompletionSummary), so plan-create-prepublication and plan-count-completion call them directly instead of executing sliced source. The two harnesses that still execute a sliced runner body with injected boundaries (eng-seeded-completion-ai, plan-floor-permission) pass the PtyDriver seam instead of overriding Date/Bun.sleep. * test(ratchet-c): register route modules, review resolver modules and server.ts residual cap * refactor(pty): decompose launchClaudePty and engNumberedFindingAUQ under 150 lines launchClaudePty (349 lines) becomes launch preparation (args, hermetic child env, owned state roots), recorder creation, spawn, the trust-dialog watcher, close, and the session handle over one PtyProcess state object. The failure order is unchanged: abort the viewport, dispose any recorders created so far, dispose the viewport, rethrow. The --model / --strict-mcp-config ordering and seedSkills wiring stay pinned by the behavioral fake-CLI tests. engNumberedFindingAUQ (345 lines) keeps its guards and dispatch; each self-contained issue family (declared cache, library retry hooks, cache owner, injected singleton, shared writers, injected export) moves verbatim into its own function. Every pty/ module is now <= 800 lines and every top-level function <= 150 lines. * test(pty): split claude-pty-runner.unit.test.ts along the pty/ module seams The 188 unit tests move verbatim into claude-pty-runner.{screen,classify, auq,launch,plan-native,boundaries}.unit.test.ts (test names unchanged; each file imports only what it uses from the barrel). The five files that no longer read a SKILL.md template join the test-of-test ratchet baseline with a reason. * test(touchfiles): moved PTY modules keep their paid-eval selection test/fixtures/touchfile-selection/w4-pty.json records, at96764e8, the paid evals selected by touching test/helpers/claude-pty-runner.ts (20) and test/helpers/pty-screen.ts (20). touchfiles.test.ts now asserts every .ts file under test/helpers/pty/ (and pty/screen.ts for both sources) selects a superset, reading every golden in that directory so later moves can add one; a planted-violation case pins the report and its Fix line. * fix(browse): unexchanged pair setup keys no longer authenticate bearer requests validateToken accepted a gsk_setup_ key as a bearer on /command, /batch and /file (found while building the W3 auth matrix). A setup key now only authenticates the /connect exchange. * W1: one state-root owner (lib/state-root.ts + bin/gstack-state-root.sh), gstack-paths --explain and fail-stop, parity tests * W1: guarded migration of every executable state-root site; uninstall deletes only ~/.gstack Bins, careful/freeze hooks, setup, upgrade migrations, browse/src, design, ios-qa daemon, lib and scripts resolve the state root through bin/gstack-state-root.sh (bash) or lib/state-root.ts (TS). Bins source the twin and stop with a reinstall message when it is missing; hooks source it and never spawn gstack-paths. browse/src/config.ts and lib/cso/state.ts delegate to resolveStateRoot. Analytics writers and readers move together so the usage log stays one file. gstack-uninstall deletes state only at ~/.gstack, refuses (exit 2) when it resolves to /, $HOME or an ancestor, the checkout or the git root, and leaves any other resolved root in place with the removal command. Fixtures that copy single bins now copy the twin. * W1: privacy keys and trust-policy deny tiers merge across state roots; gstack-config reporting; test hermeticity readConfigKey / gstack_read_config_key return the most restrictive telemetry, memorable_recall, codex_reviews and update_check across the resolved root and ~/.gstack; other keys read the resolved root only. gstack-config set reports an overriding root with the exact override command, list shows the winning root and a root-variable disagreement line. gstack-gbrain-repo-policy get merges deny/read-only tiers. gstack-egress reads through readConfigKey. test-setup.ts strips inherited GSTACK_STATE_ROOT/GSTACK_STATE_DIR and redirects the legacy root. * W1: shared hook logging helper (hosts/claude/hooks/hook-log.ts) One hook-errors.log writer: root from resolveStateRoot, 0600 on every append, opt-in rate limit used only by memorable-user-prompt. The five hooks route through it. * W1: docs/state-root.md and README troubleshooting pointer Precedence table, a real --explain example, the move-your-state recipe, merged privacy keys, the uninstall rule, the resolver-failure fix, and the plugin-mode note (evidence gate: no official plugin distribution). * W1b: template and resolver prose resolve state through guarded gstack-paths; ratchet (a) Every gstack-paths eval in templates and resolvers carries the fail-stop guard; executable ~/.gstack paths in bash blocks (context recovery preamble, eureka log, analytics, project artifacts, upgrade snooze, setup-gbrain lock, retro snapshots, ship consent marker) use $GSTACK_STATE_ROOT, and the writer prose that pairs with them points at the printed PROJECT_DIR / RETRO_FILE. ship drops export GSTACK_STATE_ROOT. SKILL.md regenerated (claude + codex), ship goldens re-pinned, parity and context-budget caps raised to the measured sizes with notes. test/state-root-ratchet.test.ts enforces the rule with a reasoned allowlist; W1 touchfile entries plus a superset golden. * refactor: apply W1 state-root edits in W2/W3/W5-owned files; one moved-code touchfile golden for all workstreams * test: fold the moved-code touchfile golden into touchfiles.test.ts; fix integration fixture closure and caps * v1.91.11.0: CHANGELOG, TODOS, docs and conventions for the refactor wave * test: re-measure plan-ceo/design-consultation caps and ship goldens after the guarded plan-discovery and spec-review blocks; add the state-root twin to the workflow-boundaries fixture * fix(windows): migrations resolve their directory with either path separator; state-root parity compares under the HOME Git Bash actually sees * fix(review,ship): state plan-check timing after smoke expiry and test_stub Skip semantics (review workflow judge clarity) * test(qa-eval): webhook fix eval asks for the fix loop's post-repair probes; eight-scenario coverage stays in the report-only case and the harness recheck * test(qa-eval): re-pin the webhook prompt contract to the fix-loop stage; R29 coverage omissions stay bound by the report-only case * fix(review,ship): plan checks publish a checkpoint before each probe; only the smoke expiry stop is skipped * fix(qa): carry #2999's checkpoint receipt link, report-template line and full-revision placeholder (identical hunks) * test(qa-callers): disable git auto maintenance in the caller fixture Git 2.47+ runs auto maintenance detached after commit; on the CI runner's git 2.55 it rewrote .git/objects fan-out directories while the write observer was running, which surfaced as unauthorized mutations. Same gc.auto=0 / maintenance.auto=false guard the shared-libs fixture already uses. * test(plan-mode-no-op): require prose evidence for the prose-fallback members so a spinner-frame judge verdict cannot end the run as asked * test(ship-docsync): carry #2999's seeded-attempt docsync harness (identical files) The doc-sync fault cases replayed attempt 1 before reaching their gate and ran out of their 285s budget. The fixture now seeds attempt 1 and the parent starts at the gate under test. Taken byte-identical from origin/capy/audit-fix-wave (fb526898,e6ac813d,6ce10ff7,d0c53577,77cce3be). Local: stale-before, recovery and late-result 6/6 PASS (97-164s); the whole file 12/12 PASS.
418 lines
30 KiB
Markdown
418 lines
30 KiB
Markdown
<!-- AUTO-GENERATED from test-coverage.md.tmpl — do not edit directly -->
|
||
<!-- Regenerate: bun run gen:skill-docs -->
|
||
## Step 7: Test Coverage Audit
|
||
|
||
### Shared subagent dispatch
|
||
|
||
For Steps 7, 8 and 10, use the Agent tool with `run_in_background: false`.
|
||
Omitting the flag runs the subagent in the background. The explicit flag waits
|
||
for a result while keeping a fresh context. Do not invoke the target as a Skill
|
||
or run it inline instead. Inline work is allowed only under that section's
|
||
documented fallback, after a failed subagent has stopped.
|
||
|
||
Dispatch the audit through Agent with `subagent_type: "general-purpose"` and
|
||
`run_in_background: false`, using the shared foreground-dispatch rule above.
|
||
Wait for its LAST-line JSON before applying the coverage gate.
|
||
|
||
**Generation allowance:** Maximum 2 generation passes total per invocation.
|
||
Count each generation-authorized attempt before dispatch/inline execution, including
|
||
the initial audit, failures and zero-test results. Re-entry never resets it.
|
||
Two passes already used means no further generation; read-only reassessment uses no pass.
|
||
|
||
**Subagent prompt:** Supply `<base>`, Step 4's framework/bootstrap decision,
|
||
permitted paths/commands, remaining gaps, passes used and generation allowance,
|
||
plus the CLAUDE.md `## Test Coverage` values the gate below reads (`Generation cap:`,
|
||
`Base control:`, `Base control budget:`). No allowance means audit only; missing
|
||
permission is not approval. Preserve the 30-path/5-tests-per-pass/2-minute per-test caps.
|
||
|
||
**Before the first dispatch,** sweep base-control worktrees a previous interrupted run left behind:
|
||
|
||
```bash
|
||
git worktree prune
|
||
find "${TMPDIR:-/tmp}" -maxdepth 1 -name 'gstack-base-control.*' -mmin +10 2>/dev/null | while IFS= read -r d; do git worktree remove --force "$d/wt" >/dev/null 2>&1; rm -rf "$d"; done
|
||
```
|
||
|
||
````text
|
||
You are running a ship-workflow test coverage audit. Run `git diff origin/<base>` to include uncommitted tracked changes; also read relevant non-ignored untracked source/tests. Do not commit or push. Perform only this audit; return unresolved user decisions to the parent instead of asking or advancing to another workflow step.
|
||
|
||
Generation: <allowed|audit-only>; passes used: <N> of 2. Audit-only overrides every generation instruction below.
|
||
|
||
Coverage goal: every changed behavior is protected by a test that would catch a real regression. Test count is not a goal. Evaluate what was ACTUALLY coded (from the diff), not what was planned.
|
||
|
||
### Test Framework Detection
|
||
|
||
Before analyzing coverage, detect the project's test framework:
|
||
|
||
1. **Read CLAUDE.md** — look for a `## Testing` section with test command and framework name. If found, use that as the authoritative source.
|
||
2. **If CLAUDE.md has no testing section, auto-detect:**
|
||
|
||
```bash
|
||
setopt +o nomatch 2>/dev/null || true # zsh compat
|
||
# Detect project runtime (markers are evidence, not commands to run blind)
|
||
[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django"
|
||
{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"
|
||
{ [ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ]; } && echo "RUNTIME:ruby"
|
||
[ -f package.json ] && echo "RUNTIME:node"
|
||
[ -f go.mod ] && echo "RUNTIME:go"
|
||
[ -f Cargo.toml ] && echo "RUNTIME:rust"
|
||
[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"
|
||
{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"
|
||
# Check for existing test infrastructure — config files, scripts, AND test files
|
||
ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini tox.ini phpunit.xml 2>/dev/null
|
||
[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"
|
||
[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"
|
||
git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'
|
||
```
|
||
|
||
3. **If no framework detected:** use the bootstrap decision already made in Step 4; report diagram-only coverage if setup was declined. Do not restart bootstrap from this audit.
|
||
|
||
**0. Before/after test count:**
|
||
|
||
```bash
|
||
# Count test files before any generation
|
||
git ls-files 2>/dev/null | grep -E '(\.test\.|\.spec\.|_test\.|_spec\.)' | wc -l
|
||
```
|
||
|
||
Store this number for the PR body.
|
||
|
||
**1. Trace every codepath changed** using `git diff origin/<base>`:
|
||
|
||
Read every changed file. For each one, trace how data flows through the code — don't just list functions, actually follow the execution:
|
||
|
||
1. **Read the diff.** For each changed file, read the full file (not just the diff hunk) to understand context.
|
||
Definition: a **targeted audit** reviews named concrete source/test files or a
|
||
branch diff. A **prototype** is existing runnable code referenced by the plan,
|
||
not a proposed future component.
|
||
|
||
When grounded in concrete source and test files, read them in a dedicated tool
|
||
call before drawing the diagram. Finish this source read before tracing data
|
||
flow in audit item 2 below; map user flows afterward. Do not mix diff, grep,
|
||
package/config, git, or commentary into that read; use separate calls for
|
||
context. Base the diagram on that read.
|
||
2. **Trace data flow.** Starting from each entry point (route handler, exported function, event listener, component render), follow the data through every branch:
|
||
- Where does input come from? (request params, props, database, API call)
|
||
- What transforms it? (validation, mapping, computation)
|
||
- Where does it go? (database write, API response, rendered output, side effect)
|
||
- What can go wrong at each step? (null/undefined, invalid input, network failure, empty collection)
|
||
3. **Diagram the execution.** For each changed file, draw an ASCII diagram showing:
|
||
- Every function/method that was added or modified
|
||
- Every conditional branch (if/else, switch, ternary, guard clause, early return)
|
||
- Every error path (try/catch, rescue, error boundary, fallback)
|
||
- Every call to another function (trace into it — does IT have untested branches?)
|
||
- Every edge: what happens with null input? Empty array? Invalid type?
|
||
|
||
This is the critical step — you're building a map of every line of code that can execute differently based on input. Every branch in this diagram needs a test.
|
||
|
||
**2. Map user flows, interactions, and error states:**
|
||
|
||
Code coverage isn't enough — you need to cover how real users interact with the changed code. For each changed feature, think through:
|
||
|
||
- **User flows:** What sequence of actions does a user take that touches this code? Map the full journey (e.g., "user clicks 'Pay' → form validates → API call → success/failure screen"). Each step in the journey needs a test.
|
||
- **Interaction edge cases:** What happens when the user does something unexpected?
|
||
- Double-click/rapid resubmit
|
||
- Navigate away mid-operation (back button, close tab, click another link)
|
||
- Submit with stale data (page sat open for 30 minutes, session expired)
|
||
- Slow connection (API takes 10 seconds — what does the user see?)
|
||
- Concurrent actions (two tabs, same form)
|
||
- **Error states the user can see:** For every error the code handles, what does the user actually experience?
|
||
- Is there a clear error message or a silent failure?
|
||
- Can the user recover (retry, go back, fix input) or are they stuck?
|
||
- What happens with no network? With a 500 from the API? With invalid data from the server?
|
||
- **Empty/zero/boundary states:** What does the UI show with zero results? With 10,000 results? With a single character input? With maximum-length input?
|
||
|
||
Add these to your diagram alongside the code branches. A user flow with no test is just as much a gap as an untested if/else.
|
||
|
||
**3. Check each branch against existing tests:**
|
||
|
||
Go through your diagram branch by branch — both code paths AND user flows. For each one, search for a test that exercises it:
|
||
- Function `processPayment()` → look for `billing.test.ts`, `billing.spec.ts`, `test/billing_test.rb`
|
||
- An if/else → look for tests covering BOTH the true AND false path
|
||
- An error handler → look for a test that triggers that specific error condition
|
||
- A call to `helperFn()` that has its own branches → those branches need tests too
|
||
- A user flow → look for an integration or E2E test that walks through the journey
|
||
- An interaction edge case → look for a test that simulates the unexpected action
|
||
|
||
Quality scoring rubric:
|
||
- ★★★ Tests behavior with edge cases AND error paths
|
||
- ★★ Tests correct behavior, happy path only
|
||
- ★ Smoke test / existence check / trivial assertion (e.g., "it renders", "it doesn't throw"); weak, never counts as coverage
|
||
|
||
**Test value bar.** Propose or write a test only with all four answers; otherwise extend an existing test or drop it:
|
||
|
||
1. What observable behavior, invariant or independent contract does it protect?
|
||
2. What credible regression makes it fail?
|
||
3. Why does existing coverage not already catch that? Prefer adding a row to an existing table-driven test or shared fixture over a near-duplicate.
|
||
4. Does it need a production seam (export, flag, wrapper, injection hook) that no production caller needs? If yes, test at the real boundary instead.
|
||
|
||
A test that breaks under a behavior-preserving refactor asserts implementation: rewrite it at the owning boundary, unless exact output is the declared contract (goldens, prompt bytes, wire formats).
|
||
|
||
Value card: `Value: protects=<...>; fails_when=<...>; why_new=<...>; seam=none` (seam: `none` or its name); each field at most 160 UTF-8 bytes here (clamp to 157 plus `...`; JSON keeps full values). Write it as a header comment in each generated test, next to the attribution (wrap, do not truncate); with no known comment syntax, put it in the PR body's Test value details. A missing upstream card never blocks: derive it; ignore unknown fields.
|
||
|
||
Example: Value: protects=refundPayment rejects an empty reason; fails_when=the reason guard is removed or inverted; why_new=billing.test.ts covers processPayment only; seam=none
|
||
Rejected (covered_elsewhere): "checkout renders"; checkout.e2e.ts:15 covers it, so extend that test.
|
||
|
||
Weak tests (★ smoke/existence/trivial, gate-failing or unrated) never count as coverage. X = paths with a ★★/★★★ test / total paths (value-weighted; the gate uses X); Y = paths with any test / total paths. Total paths = the diff's codepath trace, max 30; zero skips the gate. A path with only weak tests is uncovered in X, covered in Y, and goes to `weak_gaps` (reason `star_one|gate_failed|unrated`), not `gaps`. Rate stars only for tests reachable from changed paths.
|
||
|
||
Retention bar: keep a test that independently enforces a public API, protocol, config, migration, storage, security, platform, default, prompt-byte, generated-output (golden), package, release or architecture contract; static or slow is no reason to delete.
|
||
|
||
Regression proof: a regression test must fail at HEAD before any repair, in its own assertion (a pass at HEAD drops the regression label; an import, fixture or env failure is a test defect: correct once or drop). It must pass at base as the control (an assertion failure there marks it invalid; any other failure is "base control unavailable: collection error") and pass after the repair. Record: `Regression proof — fails at HEAD: yes · passes at base: yes | unavailable (<reason>) | manual · passes after fix: yes | pending`.
|
||
|
||
### E2E Test Decision Matrix
|
||
|
||
When checking each branch, also determine whether a unit test or E2E/integration test is the right tool:
|
||
|
||
**RECOMMEND E2E (mark as [→E2E] in the diagram):**
|
||
- Common user flow spanning 3+ components/services (e.g., signup → verify email → first login)
|
||
- Integration point where mocking hides real failures (e.g., API → queue → worker → DB)
|
||
- Auth/payment/data-destruction flows — too important to trust unit tests alone
|
||
|
||
**RECOMMEND EVAL (mark as [→EVAL] in the diagram):**
|
||
- Critical LLM call that needs a quality eval (e.g., prompt change → test output still meets quality bar)
|
||
- Changes to prompt templates, system instructions, or tool definitions
|
||
|
||
**STICK WITH UNIT TESTS:**
|
||
- Pure function with clear inputs/outputs
|
||
- Internal helper with no side effects
|
||
- Edge case of a single function (null input, empty array)
|
||
- Obscure/rare flow that isn't customer-facing
|
||
|
||
### REGRESSION RULE (mandatory)
|
||
|
||
**IRON RULE:** When the coverage audit identifies a REGRESSION — code that previously worked but the diff broke — a regression test is written immediately. No AskUserQuestion. No skipping. Regressions are the highest-priority test because they prove something broke.
|
||
|
||
A regression is when:
|
||
- The diff modifies existing behavior (not new code)
|
||
- The existing test suite (if any) doesn't cover the changed path
|
||
- The change introduces a new failure mode for existing callers
|
||
|
||
When uncertain whether a change is a regression, err on the side of writing the test.
|
||
|
||
**Red-first proof.** Apply the value bar's Regression proof to every regression test: the diff at HEAD is the pre-fix code, so run the new test at HEAD before any repair. Then, unless the parent says `Base control: off`, run this base control once per regression test in diff order, within a 3-minute total per /ship run (`Base control budget:` seconds per test, default 90). Past the total, record "base control unavailable: budget" and report "N of M regression tests got base control". The block is one shell invocation; it installs nothing and runs no build or postinstall.
|
||
|
||
```bash
|
||
# Set: BASE = the base branch this /ship run resolved; TEST = the test file; FIXTURES = new
|
||
# test-only fixtures it imports (repo-relative, may be empty); RUN = the detected
|
||
# runner for one file (e.g. "bun test $TEST"); BUDGET = seconds for this run (default 90).
|
||
ROOT=$(git rev-parse --show-toplevel)
|
||
CTL_TMP=$(mktemp -d "${TMPDIR:-/tmp}/gstack-base-control.XXXXXX")
|
||
cleanup() { git -C "$ROOT" worktree remove --force "$CTL_TMP/wt" >/dev/null 2>&1; rm -rf "$CTL_TMP"; [ -e "$CTL_TMP" ] && echo "BASE_CONTROL_LEFTOVER: $CTL_TMP (run: git worktree prune)"; }
|
||
trap cleanup EXIT INT TERM
|
||
(
|
||
[ -f "$ROOT/package.json" ] || { echo "BASE_CONTROL: unavailable (ecosystem)"; exit 0; }
|
||
git -C "$ROOT" remote get-url origin >/dev/null 2>&1 || { echo "BASE_CONTROL: unavailable (no base remote)"; exit 0; }
|
||
timeout 30 git -C "$ROOT" fetch --quiet origin "$BASE" || { echo "BASE_CONTROL: unavailable (base not fetched)"; exit 0; }
|
||
git -C "$ROOT" worktree add --quiet --detach "$CTL_TMP/wt" "origin/$BASE" >/dev/null 2>&1 || { echo "BASE_CONTROL: unavailable (worktree add failed)"; exit 0; }
|
||
for f in $TEST $FIXTURES; do mkdir -p "$CTL_TMP/wt/$(dirname "$f")" && cp "$ROOT/$f" "$CTL_TMP/wt/$f"; done
|
||
[ -d "$ROOT/node_modules" ] && ln -s "$ROOT/node_modules" "$CTL_TMP/wt/node_modules"
|
||
cd "$CTL_TMP/wt" && timeout "${BUDGET:-90}" sh -c "$RUN" > "$CTL_TMP/out" 2>&1; rc=$?
|
||
tail -n 40 "$CTL_TMP/out"
|
||
if [ "$rc" -eq 0 ]; then echo "BASE_CONTROL: passes at base"
|
||
elif [ "$rc" -eq 124 ]; then echo "BASE_CONTROL: unavailable (budget)"
|
||
else echo "BASE_CONTROL: fails at base (exit $rc)"; fi
|
||
)
|
||
```
|
||
|
||
Classify "fails at base" from the output: a failure in the test's own assertion marks it invalid (correct once or drop it); an import, collection, missing generated artifact or dependency failure is "base control unavailable: collection error" and the test stays. Print each unavailable result as: base control unavailable: <reason>. The fails-at-HEAD result still stands. To check by hand: `git worktree add --detach <tmp> <base>`; copy the test and its new fixtures to the same paths; run the detected test command in <tmp>; `git worktree remove --force <tmp>`. Then report `passes at base: manual`. (see ~/.claude/skills/gstack/docs/test-value-bar.md#base-control-unavailable)
|
||
|
||
Return `"regression_proof":{"red_at_head":N,"base_green":N,"base_unavailable":N}` counts in the JSON and each test's record line in the diagram.
|
||
|
||
**4. Output ASCII coverage diagram:**
|
||
|
||
For targeted audits, start Test review output with the coverage diagram. In full
|
||
plan reviews, put it inside the normal Test review section. Required outputs
|
||
keep the final terminal report order.
|
||
|
||
Include BOTH code paths and user flows in the same diagram. Mark E2E-worthy and eval-worthy paths:
|
||
|
||
```
|
||
CODE PATHS USER FLOWS
|
||
[+] src/services/billing.ts [+] Payment checkout
|
||
├── processPayment() ├── [★★★ TESTED] Complete purchase — checkout.e2e.ts:15
|
||
│ ├── [★★★ TESTED] happy + declined + timeout ├── [GAP] [→E2E] Double-click submit
|
||
│ ├── [GAP] Network timeout └── [GAP] Navigate away mid-payment
|
||
│ └── [GAP] Invalid currency
|
||
└── refundPayment() [+] Error states
|
||
├── [★★ TESTED] Full refund — :89 ├── [★★ TESTED] Card declined message
|
||
└── [★ TESTED] Partial (non-throw only) — :101 └── [GAP] Network timeout UX
|
||
|
||
LLM integration: [GAP] [→EVAL] Prompt template change — needs eval test
|
||
|
||
COVERAGE: 5/13 paths tested (38%) | Code paths: 3/5 (60%) | User flows: 2/8 (25%)
|
||
QUALITY: ★★★:2 ★★:2 ★:1 | GAPS: 8 (2 E2E, 1 eval)
|
||
```
|
||
|
||
Legend: ★★★ behavior + edge + error | ★★ happy path | ★ smoke check
|
||
[→E2E] = needs integration test | [→EVAL] = needs LLM eval
|
||
|
||
Avoid bare `[ ]` or `[x]` in diagrams unless the block includes
|
||
`Legend: [x] tested | [ ] no test`. Prefer `[GAP]`, `[★★ TESTED]`,
|
||
`[→E2E]`, `[→EVAL]`; keep user-flow markers off code-path rows.
|
||
|
||
**Fast path:** All paths covered → "Step 7: All new code paths have test coverage ✓" Continue.
|
||
|
||
**5. Generate tests for uncovered paths:**
|
||
|
||
If test framework detected (or bootstrapped in Step 4):
|
||
- Apply the test value bar before writing each test. Extend an existing test (a new table row, fixture case or assertion) before creating a file. Record every proposal you decline in `tests_rejected` with a `reason_code` from `duplicate_protects, needs_seam, incomplete_card, no_credible_regression, covered_elsewhere, implementation_coupled`.
|
||
- Never add a production seam for a test; a seam that is not `none` names its non-test callers: `seam=<name> (non-test callers: N, via <search command>)`.
|
||
- Write the value card as a header comment in each generated or extended test.
|
||
- Prioritize error handlers and edge cases first (happy paths are more likely already tested)
|
||
- Read 2-3 existing test files to match conventions exactly
|
||
- Generate unit tests. Mock all external dependencies (DB, API, Redis).
|
||
- For paths marked [→E2E]: generate integration/E2E tests using the project's E2E framework (Playwright, Cypress, Capybara, etc.)
|
||
- For paths marked [→EVAL]: generate eval tests using the project's eval framework, or flag for manual eval if none exists
|
||
- Write tests that exercise the specific uncovered path with real assertions
|
||
- Run each test. Passes → keep the change and report its path; the parent commits in Step 15.
|
||
- Fails → diagnose whether the test/fixture is invalid or a declared product contract is broken. Correct a demonstrated test defect once; preserve a valid red regression and route the reproduced product failure through the parent's fix/approval flow. Never delete or weaken it to manufacture green; retain unresolved coverage in the diagram.
|
||
|
||
Caps: 30 code paths max; 5 tests per generation pass (code + user flow combined; the parent's `Generation cap:` overrides 5); an extension uses one slot and a rejection uses none; 2-min per-test exploration cap. List each remaining gap below the diagram (inside `diagram`) as a proposed test with its value card.
|
||
|
||
Do not rate stars for tests you wrote in this pass: count them as unrated (weak, reason `unrated`). The parent's read-only rating dispatch rates them. Counts are disjoint, precedence extended > added > rejected: one gap lands in at most one of `tests_extended`, `tests_added`, `tests_rejected`.
|
||
|
||
If no test framework AND user declined bootstrap → diagram only, no generation. Note: "Test generation skipped — no test framework configured."
|
||
|
||
**Diff is test-only changes:** Return a skipped audit with null coverage, zero gaps, and "No new application code paths to audit."
|
||
|
||
**6. After-count and coverage summary:**
|
||
|
||
```bash
|
||
# Count test files after generation
|
||
git ls-files 2>/dev/null | grep -E '(\.test\.|\.spec\.|_test\.|_spec\.)' | wc -l
|
||
```
|
||
|
||
For PR body: `Tests: {before} → {after} (+{delta} new)`
|
||
Coverage line: `Test Coverage Audit: N new code paths. M covered (Y% any test, X% value-weighted). K tests generated, awaiting parent commit.`
|
||
|
||
### Test Plan Artifact
|
||
|
||
After producing the coverage diagram, write a test plan artifact so `/qa` and `/qa-only` can consume it:
|
||
|
||
```bash
|
||
eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"
|
||
eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG"
|
||
USER=$(whoami)
|
||
DATETIME=$(date +%Y%m%d-%H%M%S)
|
||
```
|
||
|
||
Write to `<PROJECT_DIR>/{user}-{branch}-ship-test-plan-{datetime}.md` (`PROJECT_DIR` printed above):
|
||
|
||
```markdown
|
||
# Test Plan
|
||
Generated by /ship on {date}
|
||
Branch: {branch}
|
||
Repo: {owner/repo}
|
||
|
||
## Affected Pages/Routes
|
||
- {URL path} — {what to test and why}
|
||
|
||
## Key Interactions to Verify
|
||
- {interaction description} on {page}
|
||
|
||
## Edge Cases
|
||
- {edge case} on {page}
|
||
|
||
## Critical Paths
|
||
- {end-to-end flow that must work}
|
||
```
|
||
|
||
After your analysis, output a single JSON object on the LAST LINE of your response (no other text after it):
|
||
{"coverage_pct":N,"gaps":N,"diagram":"<full markdown coverage diagram for PR body>","tests_added":["path",...],"coverage_pct_value":N,"weak_gaps":[{"path":"...","existing_test":"...","reason":"star_one|gate_failed|unrated"}],"tests_extended":["path",...],"tests_rejected":[{"path_or_gap":"...","reason_code":"...","reason":"..."}],"regression_proof":{"red_at_head":N,"base_green":N,"base_unavailable":N}}
|
||
`coverage_pct` is Y (paths with any test), `coverage_pct_value` is X (paths with a ★★/★★★ test), `gaps` counts only paths with no test. Use null for an undetermined or skipped coverage percentage, not zero. Include every remaining gap in the diagram so the parent can target a second pass.
|
||
````
|
||
|
||
**Parent processing:**
|
||
|
||
1. Read the subagent's final output. Parse the LAST line as JSON.
|
||
2. Store `coverage_pct`, `coverage_pct_value`, `gaps`, `weak_gaps`, `tests_added`,
|
||
`tests_extended`, `tests_rejected` and `regression_proof`. A missing new key counts
|
||
as empty; say so in the summary (an older installed prompt must not fail the gate).
|
||
A key with the wrong type (for example `weak_gaps` not an array) is ignored the same
|
||
way and printed as: malformed <key> ignored: the audit returned the wrong type, so it counts as empty. The likely cause is an outdated installed skill; run /gstack-upgrade. (see ~/.claude/skills/gstack/docs/test-value-bar.md#malformed-key-ignored)
|
||
3. **Machine checks** on every test written in this run (`tests_added` and
|
||
`tests_extended`): a value-card header with four non-empty fields (else
|
||
`incomplete_card`); `protects` unique across the run after casefolding and stripping
|
||
punctuation and repeated whitespace (a later duplicate is `duplicate_protects`); seam
|
||
`none`, or a named seam with at least one non-test caller (N = 0 or an unavailable
|
||
caller check is `needs_seam`). Move each failure to `tests_rejected` with its
|
||
`reason_code`, then remove it before anything else reads the diff: an untracked new
|
||
file is deleted; for a tracked file, revert only this run's hunk with Edit, never
|
||
the whole file.
|
||
|
||
```bash
|
||
while IFS= read -r f; do
|
||
[ -n "$f" ] || continue
|
||
if git ls-files --error-unmatch -- "$f" >/dev/null 2>&1; then echo "REVERT_HUNK: $f"; else rm -f -- "$f" && echo "REMOVED: $f"; fi
|
||
done <<'REJECTED'
|
||
<one rejected test path per line>
|
||
REJECTED
|
||
```
|
||
|
||
No `tests_rejected` path may remain on disk as a new file. If every test written in
|
||
a pass is rejected, print all <N> generated tests rejected by machine checks; see tests_rejected. The gate proceeds with the unchanged value-weighted coverage. (see ~/.claude/skills/gstack/docs/test-value-bar.md#all-generated-tests-rejected)
|
||
4. **Rating dispatch.** When this run wrote tests that survived the machine checks,
|
||
dispatch one read-only Agent (`subagent_type: "general-purpose"`,
|
||
`run_in_background: false`) with no generation permission; it uses no generation
|
||
pass. Give it the diagram and the surviving test paths. It rates each against the
|
||
★ rubric and the test value bar and returns a LAST-line JSON
|
||
`{"coverage_pct_value":N,"weak_gaps":[...]}` recomputed with its ratings; use those
|
||
two values. Until rated, this run's tests count as weak (`unrated`). If it fails,
|
||
times out or returns invalid JSON, the gate is skipped for this run ("rating
|
||
unavailable").
|
||
5. Embed `diagram` verbatim in the PR body's `## Test Coverage` section (Step 19).
|
||
6. Print a one-line summary: `Coverage: {X}% value-weighted ({Y}% including {W} weakly covered paths), {gaps} gaps. {tests_added.length} tests added.`
|
||
Bindings for the PR body's Test value line: K = `tests_added.length`,
|
||
R = `tests_rejected.length`, E = `tests_extended.length`, W = `weak_gaps.length`.
|
||
|
||
**Audit failure:** On failure, invalid JSON or no completion after ~10 minutes,
|
||
stop the child and confirm it stopped before running the same audit inline.
|
||
Fallback recovers the audit; it does not pass or bypass the coverage gate.
|
||
Apply that gate to the recovered results, including its undetermined-percentage
|
||
and test-only rules. Preserve partial results as incomplete, not passing coverage.
|
||
|
||
|
||
**7. Coverage gate:**
|
||
|
||
The parent owns this gate, including after inline fallback. Generated tests stay uncommitted until Step 15. The gate only asks; it never hard-fails. Use Step 7's remaining generation allowance; supply it and the remaining gaps to the same audit prompt. At the cap, omit A's generation pass and recommend stopping; A then only lists proposals and the listed risk choices remain available.
|
||
|
||
Read CLAUDE.md's `## Test Coverage` section for `Minimum:` and `Target:`; otherwise use defaults: Minimum = 60%, Target = 80%. Also read the optional `Generation cap:` (tests per pass, default 5), `Base control:` (`auto` default, or `off`), `Base control budget:` (seconds per run, default 90) and `Star rating:` (`auto` default, or `off`). Missing keys use the defaults.
|
||
|
||
**Gate number X.** Take the first matching row; never substitute 0:
|
||
|
||
| Step 7 result | Gate number | Print |
|
||
|---|---|---|
|
||
| Rating dispatch failed or timed out | skip the gate | rating unavailable: the read-only rating dispatch failed or timed out, so the coverage gate is skipped for this run. Re-run Step 7 to re-rate the tests. (see ~/.claude/skills/gstack/docs/test-value-bar.md#rating-unavailable) |
|
||
| Zero paths, test-only diff, or `coverage_pct` null or unparseable | skip the gate | "Coverage gate: could not determine percentage — skipping." |
|
||
| `Star rating: off` | `coverage_pct` | "Star rating off: gate uses coverage_pct; weak paths still listed." |
|
||
| `coverage_pct_value` missing, not a number, or outside 0..100 | `coverage_pct` | value-weighted coverage unavailable (outdated installed skill); run /gstack-upgrade. The gate used coverage_pct (any test) this run. (see ~/.claude/skills/gstack/docs/test-value-bar.md#value-weighted-coverage-unavailable) |
|
||
| `coverage_pct_value` > `coverage_pct` | `coverage_pct` (clamped) | inconsistent coverage inputs: coverage_pct_value was above coverage_pct, so it was clamped to coverage_pct. Re-run Step 7 if the numbers look wrong. (see ~/.claude/skills/gstack/docs/test-value-bar.md#inconsistent-coverage-inputs) |
|
||
| Otherwise | `coverage_pct_value` | — |
|
||
|
||
Y is `coverage_pct`; W is `weak_gaps.length`; N is `gaps`. Remaining slots = 2 × generation cap − tests added or extended so far, and 0 once both passes are used. Option A reads "A) Strengthen the existing ★ test for each weak path and generate tests for true gaps ({slots} of {2 × cap} generation slots remaining)"; at 0 slots it reads "A) List the remaining gaps as proposed tests in the PR body" and dispatches nothing.
|
||
|
||
- **>= target:** Pass. "Coverage gate: PASS ({X}% value-weighted)." Continue; list weak paths in the PR body as proposed strengthening.
|
||
- **>= minimum, < target:** Use AskUserQuestion:
|
||
- "Value-weighted coverage is {X}% ({Y}% including {W} weakly covered paths). {W} paths have only weak tests and {N} have none. Target is {target}%."
|
||
- RECOMMENDATION: Choose A because weakly covered and untested paths are where regressions slip through.
|
||
- Options:
|
||
A) (as above, recommended)
|
||
B) Ship anyway — I accept the coverage risk
|
||
C) These paths don't need tests — mark as intentionally uncovered. Repo-wide sweep: run /test-audit.
|
||
- If A and allowance remains: dispatch one generation pass with the weak paths and gaps, then re-evaluate here. At the cap, offer only B/C or stop, plus A as the proposals list; never another generation pass.
|
||
- If B: Continue. Include in PR body: "Coverage gate: {X}% — user accepted risk."
|
||
- If C: Continue. Include in PR body: "Coverage gate: {X}% — {N} paths intentionally uncovered."
|
||
|
||
- **< minimum:** Use AskUserQuestion:
|
||
- "Value-weighted coverage is critically low ({X}%; {Y}% including {W} weakly covered paths). {N} of {M} code paths have no tests. Minimum threshold is {minimum}%."
|
||
- RECOMMENDATION: Choose A because less than {minimum}% means more behavior is unprotected than protected.
|
||
- Options:
|
||
A) (as above, recommended)
|
||
B) Override — ship with low coverage (I understand the risk)
|
||
- If A and allowance remains: dispatch one generation pass, then re-evaluate here. At the cap, offer only B or stop, plus A as the proposals list; never another generation pass.
|
||
- If B: Continue. Include in PR body: "Coverage gate: OVERRIDDEN at {X}%."
|
||
|
||
**Spawned or non-interactive session** (the preamble echoed `SESSION_KIND: spawned` or `headless`): ask nothing. Take A restricted to true `gaps` within the remaining slots; never edit tests for weak paths there. List weak paths in the PR body as proposed strengthening.
|
||
|
||
**100% coverage:** "Coverage gate: PASS (100%)." Continue.
|
||
|
||
---
|