---
name: testing
description: "The test-lifecycle skill — three modes. Plan-gate mode: after `boundary` passes, derives the tests a plan owes and writes the Test Obligations ledger into the plan (a row per behavior: layer, target file, oracle, fixtures); writes no test files. Placement mode: layered test strategy — which ownership strata the application has, where a test lives and what it may assert (on a rendered surface every user-observable promise lives in the surface's journey; component tests are residual); use for any testing-strategy, test-architecture, test-pyramid, or 'unit/integration/e2e?' question, even if 'layer' is never said. Gate mode: executes the verification gate — derives the behavioral checklist, drives the real surface (browser automation, the real CLI, HTTP; the `/test` runner where wired), pins durable behaviors, discharges every ledger row. Triggers on 'test plan', 'testing strategy', 'test architecture', 'test layers', 'where should this test live', 'run the verification gate'."
---

# Testing — Ledger, Layers, Gate

One skill owns the test lifecycle's three procedural moments; the standing constraints (regimes, deferral, gate preconditions) are `.claude/rules/testing.md` and are never restated here. Pick the mode from the moment:

| Moment | Mode |
| --- | --- |
| The plan pass, after `boundary`'s amendments are folded | **Plan-gate** — derive what the plan owes |
| A strategy / placement / altitude question, or laying out a suite | **Placement** — derive the strata, place the tests |
| The build pass reaches its tail — the unit's code is written | **Gate** — drive, fix, pin, discharge |

---

## Plan-gate mode — the Test Obligations ledger

You derive the tests an implementation plan owes and pin them into the plan as an explicit, reviewable manifest — in the same pass that writes the plan, after `boundary`'s amendments are folded, ordered second; a plan shown to the user already carries this ledger. You never write a test file; you write the **ledger gate mode discharges**, so the gate proves a checklist instead of a vibe.

**The litmus is "which promise, at which altitude, proven by what?"** A plan promises behavior; each promise earns exactly one test at the cheapest layer that can actually prove it. Spend your reading deciding the *layer* and the *oracle*, not on prose. Writing tests *before* the code exists fabricates implementation coupling or leaves the suite red for the plan's duration; writing them *during* the build loop taxes every iteration — so the plan gate emits obligations, the loop stays free of test files, and gate mode discharges the manifest in one pass.

### Contract sources

- **The plan's Proposed Changes** — each file/entity/API change is a behavior that may owe a test.
- **The owning LLD** (`docs/features/{feature}.md`, via the ownership index) — every obligation names the LLD promise it proves; the LLD is referenced, never restated. This one-directional chain (LLD → manifest → tests + Completion checklist) is what stops the artifacts drifting.
- **`.claude/rules/testing.md`** — frameworks and canonical placement per stack; target paths come from there, never invented. The repo's existing runner always wins.
- **`boundary`'s output** — a HIGH/CRITICAL finding is itself a behavior owed a regression test. Fold boundary's amendments first, then read the amended plan.

### Layer assignment

Assign each behavior the **cheapest layer that can prove it**, then name the oracle. The ledger altitudes are `unit` / `component` / `integration` / `e2e` (strata mapping: § Bridge below). **Integration is the default for server behavior** — a route/handler against a real in-memory datastore via the app instance; server-side error paths, races, and idempotency belong there with injected faults (network mock, fake timers, forced constraint). **A journey is the default for a rendered surface** — any promise a user could observe in a real browser (what a screen shows over real rows, what a click changes, where navigation lands and what the URL carries, what a refused or failed request shows) is owed at layer 8 as `extend journey <surface>`, never as a component test; the surface's own fault paths (a 500 on load, a 400 on submit) stay in the journey too, injected at the app's own endpoint from the browser. What a rendered surface still owes below the browser is enumerated in § Placement discipline: a pure derivation with real branches (layer 6), a regression pin for a state the journey world cannot reach (layer 7), the wire's error taxonomy (layer 5), and geometry that shipped wrong (7b).

**The journey world is a precondition, not an excuse.** A rendered surface owes its journeys whether or not the repo's e2e config boots today. If it does not — no config, a world pointed at a deleted package, a job parked in CI — the plan's **first** obligation row is wiring it (`e2e · <config> · the world builds, seeds, boots and one journey passes from a cold shell`), and every journey row names it as a dependency. Emitting `blocked` rows in place of journeys and routing the promises down to component tests is the failure this rule exists to stop: a broken world that nothing obliges anyone to fix stays broken, and every UI promise for months lands in a simulated DOM. Density is one spec file per surface and one `test()` per user journey, carrying as many assertions as the journey has observable steps — prefer **"extend journey `<surface>`"** over a new file.

### Run (plan-gate)

**Input:** a plan path (given, or the newest in `docs/history/plans/`), boundary-checked with amendments folded; skipped on a boundary BLOCK. For a non-plan diff, the hunks stand in for Proposed Changes but the obligations are paid **immediately** — only a plan has a ledger to defer into.

1. **Build the behavior list** from Proposed Changes + the LLD's promises + HIGH/CRITICAL boundary findings. Note compiler-guarded behaviors — they owe **no** test.
2. **Assign layer + oracle** per behavior; cheapest proving layer wins.
3. **Map to a target file** per `testing.md`; name fixtures/factories and fault injection; use the repo-standard fake-data source.
4. **Route by surface**: a user-observable promise on a rendered surface → `e2e` (its surface's journey, with the world-wiring row first if the world does not boot); server behavior → `integration`; only what § Placement discipline keeps below the browser → `component` / `unit`.
5. **Emit the Test Obligations section into the plan** (an executor dispatched with only the plan sees nothing else), plus a one-line chat summary:

   ```
   ## Test Obligations

   | # | Behavior (LLD promise) | Layer | Target file | Oracle | Fixtures / faults | Outcome |
   | - | ---------------------- | ----- | ----------- | ------ | ----------------- | ------- |

   Coverage: {N} behaviors · {N} integration · {N} component · {N} unit · {N} e2e ({N} extend, {N} new)
   Completion checklist: docs/tests/{feature}.md  (derived at the gate, not now)
   ```

   A behavior with no obligation is stated too, with the reason — "none — compiler-guarded" reads as *checked*; an empty cell reads as *not analyzed*. A short manifest is valid — do not pad. **`Outcome` is written empty here — it is gate mode's cell**, and the completion walls read it: a plan cannot reach `Status: Complete` while any row's Outcome is empty.

---

## Placement mode — layered test strategy

You decide **where a test lives and what it may assert**. **The litmus is "where can this defect originate?"** A test lives with the only layer that can produce the defect it catches. "The 409 response carries the current body" can only break in a route handler — service-contract layer. "The buffer the user typed survives the 409" can only break in component state — component layer. Same feature, two owners, two tests, zero overlap. Placement is decided by this question alone — testing a feature wherever you first *see* it is what makes suites flat, duplicative, and multiplicative in cost.

### The stack

The maximum form, for a full-stack application. Each layer names what only it can break, the oracle that proves it, and the technology **class** — the concrete framework comes from `testing.md`'s stack table, never from here.

**7b is lettered, not numbered, because it is layer 7's other half rather than a rung above it** — same subject, same tests-shaped artifacts, a different oracle. It exists because a simulated DOM computes no layout: `getBoundingClientRect()` returns zeros, so an assertion about what a person can actually see has nowhere legal to live and comes out as a class-name proxy (`classList.contains("w-24")`) that fails on a benign restyle and passes on `w-[10000px]`. A stack without a rendered surface has no 7b.

| # | Layer | Owns (defects only it can originate) | Oracle | Technology class |
| --- | --- | --- | --- | --- |
| 1 | **Persistence schema** | Invariants the storage engine enforces against any code: uniqueness, checks, cascades, append-only triggers | The engine's refusal of a forbidden write | The real engine, in-memory — never a mock of storage you own |
| 2 | **Domain** | Business rules and state transitions, via direct calls | Resulting state in real storage | Real datastore + modeled fakes for external ports |
| 3 | **Service contract** | The published wire: authn/authz at the door, envelope shape, status mapping, field projection, stream/event grammar. For a CLI this is argv/stdout/exit codes; for a library, its exported API | Requests against the real app instance, in-process | `supertest` / `SELF.fetch` class — never a spawned server, never naked handler functions |
| 4 | **Contract artifact** | Nothing behavioral. Typed fixtures / interception handlers **compiled from the provider's own types**, exported for every consumer-side test | The typechecker — drift from the provider is a compile error | No runner; a module the provider owns |
| 5 | **Client data** | The consumer's half of the wire: error taxonomy, parsing, byte fidelity, stream reassembly, retry/abort | Intercepted network serving layer-4 artifacts; no DOM | `msw`-class interception |
| 6 | **View logic** | Pure presentation derivations: grouping, ordering, status vocabularies, formatting | Table-driven equality | Plain runner |
| 7 | **Component / surface** | **Residual on any stack that has layer 8.** Regression pins for what the journey world cannot reach: a state only a fixture the world lacks can produce, a flow behind an external system (a GitHub installation, an AI reply), an orchestration detail no user step exposes (a debounce, a buffer surviving an abort) | Rendered output a user can observe; network answered by layer 4 | DOM testing-library class + interception — never the default home of a UI promise |
| 7b | **Rendered composition** | Defects only a real rendering engine produces: geometry (overlap, clipping, a container that grows when a panel opens), the theme cascade where your tokens meet a component library's, focus order and accessible names through a third-party primitive | Measurement in a real browser engine — `getBoundingClientRect`, computed style, the accessibility tree | Real-renderer component runner (the unit runner's browser mode), **never** a simulated DOM |
| 8 | **Journeys** | Everything a user can observe on a rendered surface: what a screen shows over real rows, what an action changes, where navigation lands and what the URL carries, what a refused or failed request shows, a create-then-delete round trip — and composition: the build serves, auth flows end to end | A real browser (or the real binary/wire, for a stack that renders nothing) against the really-running app over a seeded world; faults injected at the app's own endpoints | Browser/process driver class; **one spec file per surface**, one test per user journey, variants wherever a user can see them |

Layer 4 is the hinge. Every layer ≥5 runs on the assumption that layers 1–3 are green — and the artifact makes that assumption *enforceable*: when the provider's response type changes, the fixture stops compiling, and every consumer test fails at typecheck before it runs. A consumer-side test that hand-writes a wire response has smuggled unverified layer-3 knowledge upward; route it through the artifact.

### How many layers — derived, never chosen

**A layer exists iff the application has the boundary that can originate that layer's defects; an absent boundary makes the layer vanish** — it never merges into a neighbor. Merging is the failure mode: "simplifying" layers 3 and 7 together reinvents the flat feature test, where every UI assertion silently re-verifies the API beneath it and cost goes multiplicative again.

| Application shape | Strata present |
| --- | --- |
| Full-stack web app | all eight — 8 is the home of every UI promise, 7 is residual |
| Backend-only service | 1, 2, 3, 8 |
| CLI | 2, 3 (the CLI's argv/stdout contract), 8 |
| Frontend on a third-party API | 4 (derived from the API's published spec), 5, 6, 7, 8 |
| Library | 2 only — its exported API is the contract, its tests are its consumers |

Derive the stack first, then place tests: a placement argument that starts "this feels like an integration test" has skipped the derivation.

### Placement discipline

- **Three conditions put a UI test below a real browser; all must hold.** *(a)* Its assertion names a **product promise**, not a construction detail — litmus: would it survive a total visual redesign that changes no behavior? `not.toHaveProperty("taskMode")` survives; `classList.contains("w-24")` does not. *(b)* The defect it catches can **originate below the layout engine** — a wrong wire path, a dropped field, a state-machine bug, a wrong string. *(c)* **The surface's journey cannot reach it** — the state needs a fixture the seeded world lacks, an external system, or an orchestration detail no user step exposes. Fail (a) or (b) and the honest home is 7b; fail (c) and the home is the journey, as one more assertion.
- **Geometry may never be asserted in a runner without a layout engine.** There is no valid proxy: a class token is not a width, and a test that pretends otherwise is simultaneously brittle and blind. When the only available runner simulates the DOM, the behavior is driven and pinned at 7b — never approximated.
- **An assertion provable at two layers is misplaced — it belongs at the lower one.** The duplication check is mechanical, not judgment.
- **Behavior variants sink to the cheapest layer that owns them** — a derivation's variants to 6, a rule's to 2. A variant a user can *see* (a second sort order, a filtered roster, a refused form) belongs in the journey that shows it, as one more assertion, not as a component case. A variant at layer 3 pays wire tax on a domain test.
- **One representative path upward for the server; the whole surface for the browser.** Layer 3 keeps one happy path per route plus exhaustive coverage of *contract edges only*. Layer 8 keeps one spec per surface covering everything a user can reach in the seeded world — the count is set by the surface, never by a cap. A cap on journeys is what pushes UI promises into a simulated DOM, and a simulated DOM talks to a hand-written fake of the wire, so a route rename or an envelope change passes it green.
- **7b stays small by construction.** It holds geometry regressions that actually shipped and the handful of composition assertions a component library's contract cannot make alone (the theme cascade, the accessible name through its primitive). It is not a second component suite — a behavior that a simulated DOM can prove has no business paying a browser's price.
- **External systems enter as modeled fakes, not spies.** A fake implements the port's semantics so tests assert resulting state; a spy only proves methods were called, which passes just as happily with the bytes swapped.
- **Failure localization is the payoff to protect.** One defect turns exactly one layer red, at its owner. When a single change reddens several layers, at most one of those tests was correctly placed — treat the rest as findings.

Layering makes cost **additive** — a new API behavior costs one layer-2 test and maybe a layer-3 edge, zero frontend tests; a new UI state costs one more assertion in its surface's journey, zero backend tests. A flat suite pays N×M, because every top-layer path implicitly re-verifies every behavior beneath it.

### The tree

```
tests/
  schema/      L1 — infrastructure-bound runner (real engine)
  domain/      L2 — infrastructure-bound runner (real storage, modeled ports)
  routes/      L3 — infrastructure-bound runner (in-process app)
  contract/    L4 — no runner; typed fixtures + interception handlers
  client/      L5 — plain unit runner
  view/        L6 — plain unit runner
  component/   L7 — unit runner + DOM environment (per-file opt-in); residual where e2e/ exists
  rendered/    L7b — the same runner in browser mode; a real engine, kept small
  helpers/     shared seeds, fakes, and builders — owned by no stratum
e2e/           L8 — one spec per surface over a seeded world; its own config, never mixed into the unit runner's glob
```

- **A stratum the app lacks gets no directory** — an empty `component/` in a backend service is a lie about the app's shape.
- **One shared glob list, imported by both runner configs** — two hand-maintained lists drift; one imported constant cannot.
- **Concrete runner, framework, and DOM environment come from `testing.md`'s per-stack table** — this skill names the slot, never the brand.
- **Contract modules the provider binds** (the layer-4 source types) live in the app's shared source zone — importable by both sides; `tests/contract/` holds only the compiled fixtures and fakes.

### Bridge to the obligation ledger

The ledger's altitudes are coarse names for where a test *runs*; the strata say what it may *assert*:

| Ledger altitude | Strata it covers |
| --- | --- |
| unit | 2 (pure domain), 5, 6 |
| integration | 1, 2 (stateful), 3 |
| component | 7, 7b |
| e2e | 8 |

When writing or discharging a ledger row, name the stratum, not just the altitude — "integration" alone leaves open whether the row asserts a schema invariant, a business rule, or an envelope: three owners, three oracles.

### Run (placement)

1. **Derive the stack** from the application's real boundaries (storage? published wire? separate client? DOM?).
2. **Place each behavior** by the litmus; name stratum, oracle, technology class; take the concrete framework and file placement from `testing.md`.
3. **Flag violations, don't just place** — assertions provable lower, derivation variants above 6, hand-written wire fixtures above layer 4, spies where fakes should model state, and UI promises pinned at 7 that the surface's journey can reach.
4. **Report as a stratum map** — one line per stratum: exists/absent (why), what lives there, what is misplaced and where it moves. For a plan, feed the strata into the ledger's rows.

---

## Gate mode — discharge the ledger

Runs as the tail of every build pass — the session opens it the moment the unit's code is written, without asking (constraints — preconditions, verdict-inline, tier, honesty — are `.claude/rules/testing.md` § The gate). **Drive the real thing first, then pin what must not regress**: driving finds the defects that matter to a user, and shows which behaviors are worth the permanent cost of a test.

1. **Write the checklist** — derive or update `docs/tests/{feature}.md` from the ledger and the LLD's promises (the `documentation` skill's `templates/behavioral-checklist.md`; one `**Assert**` per observable). Derived before the driving it is the script; derived after, it is merely a report with nothing to trace tests back to. `docs/tests/{feature}.md` pairs with `docs/features/{feature}.md` — writing a checklist whose feature doc does not exist is the tell that one is owed; check here, when the checklist is named.

   **The gate owns these files, not just their first draft.** Whoever drives a checklist maintains it in the same pass — nothing else in the repo is watching, because a checklist owns no code and no `owns:` glob implicates it, so a surface can be rewritten under a checklist and every hook stays silent. Before driving, reconcile the file against the surface you are about to drive: **retire** sections whose behavior no longer exists (delete them — a checklist is a truth document, and the history lives in git), **add** sections for behavior shipped since the last run, and **repair every `Pinned:` trace**, because a trace naming a test that no longer exists is worse than no trace — it reports coverage that cannot fail. A section you cannot pin says `none yet` and names the test it owes. **Never soften an assertion to make the run green**: the checklist states what the feature promises, the run records what happened, and the backlog carries the difference.
2. **Drive the real surface, and on a rendered surface drive it visually FIRST.** The old order ran every cheap oracle before earning the right to look at the product; it inverted here because the defects that reach users on a rendered surface are the ones no simulated DOM can see. A slider thumb sitting on its own labels, a settings panel that grows the box someone types into: a suite of two hundred component tests is blind to both by construction, and the only oracle that caught them was judgement applied to real pixels.

   **The browser is reached Chrome-CDP-first, Playwright second.** CDP drives the user's own browser interactively — it is the cheapest way to *look*, it needs no script written in advance, and looking is what discovery requires. Playwright is the fallback where CDP is unavailable (headless, CI, a runtime without it) and the tool of record for anything that must run unattended afterwards. Where the runtime offers neither, emit the browser-verification checklist for the user to run; their report is the rung's verdict and `Status: Complete` waits for it.

   **Judged and scripted are two different rungs and the difference is the point.** A *judged* drive — an agent or a person reading the actual rendering against the design's intent — is what **finds** geometry and taste defects; a *scripted* assertion only **guards** a contract someone already discovered. A generated script asserting "the slider sets the value" passes happily over a thumb covering its labels. So judgement leads and scripts follow it, never the reverse.

   Cheap oracles have not stopped mattering — they stopped being a gate you pass before looking. Suites, the CLI binary, and HTTP against the running worker run in the same pass and are what the drive's findings get **pinned into** (rung 3). On a surface with no rendering — a CLI, a service, a library — this rung is its own real binary or real wire, and the visual clause simply does not apply.

   **A failing checklist assertion is never softened to make a run green** — record the defect, send it to the backlog.
3. **Pin the durable behaviors — once, against the driven code** — as suite tests per `testing.md`, naming each test's stratum (§ Bridge). **On a rendered surface the pin is the surface's journey first**: the drive just performed *is* the journey, so write it down as the test against the seeded world, and reach for a component test only where § Placement discipline's third condition holds. Pins are written after the drive and the fixes, never beside the first attempt: a pin written earlier is rewritten on every iteration and proves only that its author and the code agree. **Pinning is written inline, by the agent that drove** — it alone knows what the drive found and what each pin must therefore assert; a sub-agent briefed from the ledger row reproduces the row, not the finding. **A pinned test must pass from a cold shell** — `pnpm test` with no dev server hand-started, no seeded state assumed beyond what the suite builds for itself. A test whose oracle is "fetch the server I happen to have running" is a driven check wearing a test's name: it goes red the moment the session ends (on Workers, `@cloudflare/vitest-pool-workers` is the self-contained harness; an Express app is driven via `supertest`, never a port). Before discharging, run the suite once from a clean shell — a suite that needs the session's environment discharges nothing. A test is a permanent maintenance cost, bought deliberately:

   | Earns a suite test | Verified by driving alone |
   | --- | --- |
   | A promise an LLD makes about the feature's contract | Copy and spacing that no defect has ever turned on — restated by a test, not protected by one |
   | A bug that occurred once — its regression test | A one-off migration or backfill's output |
| **A layout defect that shipped** — its geometry pin, at 7b, measured in a real engine | Layout a judged drive has looked at and found correct — looking is the proof, and a pin buys nothing until something breaks |
   | An error path, race, or idempotency guarantee | Behavior a type or the compiler already makes unshippable |
   | A user-observable step of a surface — as an assertion in its journey | A same-branch table row: an `it.each` earns one row per branch or boundary, never one per literal |

   A driven check is evidence, not an artifact — it proves the change works today and leaves nothing behind; that is why this rung exists. Two hygiene rules hold at every pin: **a suite whose subject is no longer reachable from the product's entry points is deleted with the code path**, never repointed to keep it green; and **a case that asserts nothing beyond "it did not throw" is not a pin** — give it an assertion on resulting state or delete it.
4. **Run the affected suite and the affected surface's journeys from a cold shell** — the e2e config builds, seeds and boots its own world, so "needs the world running" is never a reason a journey did not run.
5. **Discharge every ledger row into exactly one outcome**: **satisfied** (test green, or driven check passed), **owes nothing** (with the reason — compiler-guarded, covered elsewhere), or **blocked** (missing infrastructure named, row converted to a backlog item). **Open by re-reading the ledger from the plan file on disk, never from conversation memory** — a context-held copy is how rows get missed. **Write each row's outcome into its `Outcome` cell in the plan file** — exactly `satisfied`, `owes nothing — {reason}`, or `blocked → backlog` — because the Stop wall and CI read that cell, and a row left unexamined blocks completion.
6. **Report results honestly, including failures**; record which test now guards each checklist section (`Pinned:` traces) and each section's `AC:` line where the repo carries a keyed acceptance-criteria source, closing with the coverage count — `AC coverage: {n}/{m}; uncovered: {keys} → backlog`.

   **Record every section you drove — in the changelog entry, not in the checklist.** One line per section: what was driven, PASS or FAIL, the environment, and the evidence the assertion turned on (the literal observed, the row version, the request body). It goes in the entry because it is a dated event, and the checklist is a truth document that carries no dates (the `documentation` skill § Present tense, always). **A `FAIL` is recorded as a `FAIL` and stays** — with the backlog item it raised — because a corpus of driven records that has never recorded a failure is either describing a flawless product or being written by someone who already knew the answer, and a reader cannot tell which. In the checklist itself, the section's `Pinned:` trace is what distinguishes a verified promise from a typed one; a section the drive could not reach says `not reachable — {what blocks it}` there, so an unexamined section and a guarded one never look alike.

   Completion steps — freezing the plan, the changelog entry — are the root policy file's, not yours.
