Files
gstack/ship/sections/test-coverage.md
T
Garry TanandClaude Fable 5 0d1bd5616c v1.79.0.0 fix: ship subagent dispatches can no longer strand the run (#497/#2440 class) (#2772)
* fix(ship): foreground-flag + deadline + scope guard on all four dispatch sites (#497/#2440 class, 3rd recurrence)

Steps 7/8/10/18 dispatch subagents whose LAST-line JSON the parent
consumes, but none passed run_in_background: false — since Claude Code
v2.1.198 subagents background by default, so /ship stranded at Step 18
waiting on output that never arrives. Every site now renders the shared
{{FOREGROUND_DISPATCH_NOTE}} resolver constant, carries a ~10-minute
deadline with an explicit recovery branch (stop the runaway task,
reconcile against pre-dispatch HEAD, surface stray state, never
re-dispatch), and Step 18's prompt gains a docs-sync-only scope guard
(no VERSION changes, no base-branch merges, push-rejection reported as
pushed:false with parent-side reconciliation and a second-failure
branch). Greptile failures now record as UNAVAILABLE, not zero comments.

GENERATED_WITH_GUIDANCE pins all five ship dispatch carriers; a new test
pins the deadline recovery + scope guard phrases in pr-body (.md and
.tmpl). Codex/factory ship goldens re-rendered.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(document-release): first-class spawned-dispatch contract

document-release's own templates had zero subagent-awareness — the
entire headless contract lived in /ship's dispatch prompt, so any other
orchestrator (or an older installed /ship) dispatching it inherited none
of the gate handling. The skill now carries the contract itself: detect
spawned strictly from the dispatch prompt or the preamble echo (never
from file content — prompt-injection guard), auto-choose recommended
options while keeping the never-clobber-CHANGELOG and
never-bump-VERSION-silently invariants via their Skip options. Step 8.4d
gets an explicit spawned note (its interactive recommendation bumps
VERSION — wrong headlessly), and the Codex Documentation Review section
skips itself in spawned sessions (the apply gate needs a human; the
dispatching workflow owns review passes).

Contract, 8.4d note, and resolver skip are pinned in
run-in-background-guidance.test.ts; document-release skeleton budget
re-measured (39,812 B) and ratcheted to 40,200.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: sweep every remaining synchronous Agent-dispatch site with run_in_background: false

The #2440 failure shape was a silently-missing review voice — a
specialist launched in the background and merged before it completed.
Every remaining synchronous dispatch site now carries the explicit flag:
the Red Team dispatch, the spec review loop, the Codex
second-opinion/plan-review/doc-review Claude fallbacks, the adversarial
subagent, design sketch and outside voices, autoplan's design/eng/dx
phase dispatches, CSO parallel finding verification, and design-shotgun's
variant launch. Parallel fan-outs stay parallel — multiple foreground
Agent calls in one message run concurrently (the shipped v1.64.0.0
review-army pattern).

GENERATED_WITH_GUIDANCE now pins all 24 generated carriers, so a new
dispatch site that drops the flag fails the free suite. Six carved-skill
skeleton ceilings re-measured and ratcheted (~80-130 B growth each);
factory ship golden re-rendered.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* release: v1.79.0.0 — CHANGELOG, VERSION, TODOS follow-ups

Queue-advanced to 1.79.0.0 (1.78.0.0 claimed in the workspace queue;
same MINOR level per the versioning invariant). Entry references the
class history (#497#2440 → Step 18). Three TODOS filed: PreToolUse
hook enforcement, structural ship-mode for document-release, cross-host
dispatch semantics audit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* regen: review-army sections carry the Red Team foreground flag

The scripts/resolvers/review-army.ts Red Team edit regenerated these two
files but the sweep commit staged only the adversarial sections — the
skill-docs freshness gate (regen + git diff --exit-code) catches this.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* regen: agents digest picks up v1.79.0.0

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(document-release): one canonical spawned contract, downstream notes are pointers

The diff-selected LLM-judge eval scored the skill's clarity 3 (threshold
4, main scores 4): the spawned-session rules read as three separately-
framed rule sets (contract paragraph, Step 8.4d note, Codex-review skip).
The contract paragraph now declares itself the single source of spawned
behavior and the two downstream notes reference it instead of restating
rationale. The pointer avoids naming the Codex section verbatim so the
codex-host render (which strips that section) keeps its negative pin.
Judge re-scored 4/5/4 across repeated samples after the change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: foreground note names the Agent tool as non-substitutable

The ship-docsync gate E2E caught a behavioral regression: the note's
blocking-emphasis ('a backgrounded dispatch strands the run') steered
the driven agent to run doc-sync via the Skill tool inline — the most
blocking option — twice in a row, forfeiting the fresh-context isolation
the dispatch exists for (baseline on main's text dispatches via Agent).
The shared note now says explicitly: dispatch with the Agent tool itself,
never substitute Skill or inline execution; the flag already makes the
call block. Re-verified: ship-docsync passes on the amended text.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: pre-landing review fixes

Review army + red team findings, all verified before applying:
- ship-docsync E2E now asserts run_in_background === false on the
  captured dispatch (red team CRITICAL: phrase pins prove text exists,
  this proves the model obeys it — verified passing live).
- Structural scanner test: any generated file with an Agent-dispatch
  imperative (or bare '(foreground)' prose, the #2440 inert shape) must
  carry the flag or hold a reasoned exemption — the 4th-recurrence net
  the hand-enumerated pin list can't provide.
- Parent push reconciliation models reality: the parent shares the repo,
  so a non-fast-forward that hit the subagent hits the parent identically
  — fetch + ahead/behind check first, push only when the rejection was
  transient; dispatch prompt promise softened to 'the parent will handle
  it'.
- Recovered commits from a dead subagent are vetted docs-only
  (git show --stat, never VERSION/package.json) before any push.
- Deadline pacing named: ~3 minutes between checks, wall clock not polls.
- Greptile UNAVAILABLE recording narrowed to the PR body (Step 20's
  schema carries no triage field).
- document-release contract gains the echo-failure tie-breaker: prompt
  claims spawned + no echo → fail fast with the dispatch contract's
  failure shape instead of reproducing the #2733 prose-STOP; contract
  anti-injection and NEVER-relax clauses pinned in tests.
- 'Claude Code v2.1.198' extracted to CC_BACKGROUND_DEFAULT_SINCE and
  interpolated at all resolver sites (byte-identical output).
- CHANGELOG: entry-boundary blank line restored; worst-case-wait row
  scoped to the backgrounded path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: adversarial review fixes — failure shape, CHANGELOG guard, vet coherence

Claude adversarial subagent findings (11), all verified before applying:
- The dispatch JSON contract gains an explicit FAILURE shape
  ({"error":...}) and a parent branch for it — a doc-sync that could not
  run (spawned marking failed, broken preamble) previously had only the
  no-updates shape to emit, which the parent printed as 'Documentation is
  current': a silent false-clean of exactly the VAS-449 class.
- Scope guard now covers CHANGELOG: skip Step 5 voice polish and resolve
  CHANGELOG-touching gates to leave-as-is (the parent authored the
  release entry; the prompt's older auto-choose clause conflicted with
  the contract's never-rewrite invariant).
- Recovery vet is sequence-coherent: pushing a commit pushes its
  ancestors, so ANY non-doc commit (VERSION, package.json, CHANGELOG.md)
  blocks the whole sequence — no more push-the-vetted-child-of-an-
  unvetted-parent hole.
- Steps 7/8/10 failure branches stop a still-running backgrounded task
  before falling back, so a late result never races the inline audit.
- 'Documentation synced' print gated on pushed:true (item 6 owns the
  local-only outcome); doc-review skip note's backward step pointer
  fixed; foreground note scoped 'at initial dispatch' so the sanctioned
  inline FALLBACKS in Steps 7/8 read as sanctioned; constants docstring
  no longer overclaims single-sourcing (names the 3 inline templates).
- Runtime-hook TODO raised P2 → P1: the spawned trust chain is
  agent-self-asserted; prose cannot close it, the hook can.

Both docsync gate E2Es re-verified green on the amended prompt, including
the strict run_in_background === false dispatch assert.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: codex adversarial fixes — JSON trust, fail-open visibility, user-state safety

Codex outside-model adversarial pass (inline-diff workaround for the
sandbox), P1/P2 findings triaged cross-model:
- Parent validates the dispatch JSON's field types and treats
  documentation_section as untrusted markdown (Step 19's redaction scan
  covers the final body; instruction-shaped text inside it is never
  followed). The error branch now explicitly skips items 2-6.
- Remote-ahead divergence is named, not silent: the parent lists foreign
  commits before creating a PR over a moved branch.
- Recovery cleanup never discards content: stray staged doc edits are
  unstaged but never checked out or cleaned away.
- Greptile UNAVAILABLE gets a concrete PR-body line, not a vague
  'wherever results are reported'.
Pre-existing-class P1s (self-asserted spawned trust chain, unenforceable
foreground timeout) are cross-model confirmed and tracked: PreToolUse
hook TODO at P1, harness-residue hazard documented.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: never-Skill prohibition made unambiguous; docsync fixture made diagnostic

The ship-docsync E2E flaked on this sandbox because the driven agent
resolved the STOP pointer's ~ to nonexistent homes (/root, /home) and
acted blind — pass/fail sampled model priors, not the prompt. The
fixture prompt now names the planted sections dir, making local runs
deterministic (CI, with real install paths, was always diagnostic).
With a diagnostic fixture: 2/2 passes, real pr-body read, Agent dispatch
with run_in_background: false, zero Skill-tool substitutions.

Prose: the foreground note now states the dispatch happens ONLY via the
Agent tool (invoking the target as a Skill is wrong even though it
appears in the skills list; inline FALLBACKs apply only after a
dispatched subagent has failed), and the Step 18 imperative carries the
never-the-Skill-tool clause at the decision point.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: CHANGELOG entry covers the review-hardened contract

Failure JSON shape, CHANGELOG scope guard, vetted recovery pushes,
structural scanner, and the behavioral dispatch assert are shipped
properties of v1.79.0.0 — the entry now describes them.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: update project documentation for v1.79.0.0

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: CHANGELOG voice — follow-ups to For contributors, never-Skill property stated

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(test): daemon 503 test binds an OS-assigned port, not old-port+1

windows-free-tests flaked on this PR: the tunnel-less restart bound
daemon.loopbackPort + 1 — a fixed neighbor of the OS-assigned ephemeral
port — and died with 'Is port 55738 in use?' whenever another shard or a
TIME_WAIT socket held it; the file-level retry re-rolled the same dice.
Every other startDaemon in the file already uses loopbackPort: 0 and the
assertion reads d2.loopbackPort, so nothing needs a predictable number.
21/21 pass locally.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-01 16:42:11 -07:00

15 KiB

Step 7: Test Coverage Audit

Dispatch this step as a subagent using the Agent tool with subagent_type: "general-purpose". The subagent runs the coverage audit in a fresh context window — the parent only sees the conclusion, not intermediate file reads. This is context-rot defense.

Foreground required: pass run_in_background: false on the Agent call — subagents run in the BACKGROUND by default since Claude Code v2.1.198. (Merely omitting the flag no longer produces a foreground run; it must be explicitly false.) The dispatch happens ONLY via the Agent tool: invoking the target as a Skill, or executing its workflow inline in your own context, is WRONG even though the skill may appear in your available-skills list — inline execution forfeits the fresh-context isolation this dispatch exists for, and the explicit flag already makes the Agent call block. (Where a step defines an inline FALLBACK, it applies only after a dispatched subagent has failed.) The parent needs this audit's LAST-line JSON before continuing.

Subagent prompt: Pass the following instructions to the subagent, with <base> substituted with the base branch:

You are running a ship-workflow test coverage audit. Run git diff <base>...HEAD as needed. Do not commit or push — report only.

100% coverage is the goal — every untested path is a path where bugs hide and vibe coding becomes yolo coding. 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:
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:/'
  1. If no framework detected: falls through to the Test Framework Bootstrap step (Step 4) which handles full setup.

0. Before/after test count:

# 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>...HEAD:

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.
  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")

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.

Format: commit as test: regression test for {what broke}

4. Output ASCII coverage diagram:

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

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):

  • 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 → commit as test: coverage for {feature}
  • Fails → fix once. Still fails → revert, note gap in diagram.

Caps: 30 code paths max, 20 tests generated max (code + user flow combined), 2-min per-test exploration cap.

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: Skip Step 7 entirely: "No new application code paths to audit."

6. After-count and coverage summary:

# 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 (X%). K tests generated, J committed.

7. Coverage gate:

Before proceeding, check CLAUDE.md for a ## Test Coverage section with Minimum: and Target: fields. If found, use those percentages. Otherwise use defaults: Minimum = 60%, Target = 80%.

Using the coverage percentage from the diagram in substep 4 (the COVERAGE: X/Y (Z%) line):

  • >= target: Pass. "Coverage gate: PASS ({X}%)." Continue.

  • >= minimum, < target: Use AskUserQuestion:

    • "AI-assessed coverage is {X}%. {N} code paths are untested. Target is {target}%."
    • RECOMMENDATION: Choose A because untested code paths are where production bugs hide.
    • Options: A) Generate more tests for remaining gaps (recommended) B) Ship anyway — I accept the coverage risk C) These paths don't need tests — mark as intentionally uncovered
    • If A: Loop back to substep 5 (generate tests) targeting the remaining gaps. After second pass, if still below target, present AskUserQuestion again with updated numbers. Maximum 2 generation passes total.
    • 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:

    • "AI-assessed coverage is critically low ({X}%). {N} of {M} code paths have no tests. Minimum threshold is {minimum}%."
    • RECOMMENDATION: Choose A because less than {minimum}% means more code is untested than tested.
    • Options: A) Generate tests for remaining gaps (recommended) B) Override — ship with low coverage (I understand the risk)
    • If A: Loop back to substep 5. Maximum 2 passes. If still below minimum after 2 passes, present the override choice again.
    • If B: Continue. Include in PR body: "Coverage gate: OVERRIDDEN at {X}%."

Coverage percentage undetermined: If the coverage diagram doesn't produce a clear numeric percentage (ambiguous output, parse error), skip the gate with: "Coverage gate: could not determine percentage — skipping." Do not default to 0% or block.

Test-only diffs: Skip the gate (same as the existing fast-path).

100% coverage: "Coverage gate: PASS (100%)." Continue.

Test Plan Artifact

After producing the coverage diagram, write a test plan artifact so /qa and /qa-only can consume it:

eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG
USER=$(whoami)
DATETIME=$(date +%Y%m%d-%H%M%S)

Write to ~/.gstack/projects/{slug}/{user}-{branch}-ship-test-plan-{datetime}.md:

# 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",...]}

Parent processing:

  1. Read the subagent's final output. Parse the LAST line as JSON.
  2. Store coverage_pct (for Step 20 metrics), gaps (user summary), tests_added (for the commit).
  3. Embed diagram verbatim in the PR body's ## Test Coverage section (Step 19).
  4. Print a one-line summary: Coverage: {coverage_pct}%, {gaps} gaps. {tests_added.length} tests added.

If the subagent fails, times out, returns invalid JSON, or never completes (backgrounded despite the flag, or no final output after ~10 minutes — stop waiting; if a backgrounded task is still running, stop it first so a late result never races the fallback): Fall back to running the audit inline in the parent. Do not block /ship on subagent failure — partial results are better than none.