Tdd workflow

From woditschka/agentic-coding-reference · View interactive version

Tdd workflow is an AI agent skill from the GitHub repository woditschka/agentic-coding-reference. TDD cycle process and design-check decision tree for feature implementation. Load when implementing features using test-driven development.

How to use this skill

Skill file

For principles and rationale behind this cycle — including the nine-clause bar a passing cycle must meet — see CODE0 (§ Scope Discipline, § Code That Reads Cold, § Operationally Honest, § Secure by Design, § The Conjunctive Bar).

Pipeline Position

This skill drives the inner loop of the four-nested-loop pipeline (inner / middle / outer / architectural). The design-check decision tree in step 2 is the consultation interface to the middle loop (system-design-expert) and the outer loop (product-requirements-expert). See CODE0 for the loop model.

Design is Discovered, Not Planned

The design-block record from the middle-loop triage is a starting hypothesis, not a contract. The inner loop is free — and expected — to discover better shape as red → green → refactor cycles run. Tests force interface decisions; refactoring at each green forces structural improvement. When the loop discovers something worth recording in durable memory, route it back through a consultation-request (see step 2 below) so the system-design-expert can crystallize it for the next slice to inherit.

What the inner loop must not do is silently absorb a discovery that contradicts durable memory. That's how drift takes hold. Surface it via consultation.

TDD Cycle

  1. Start from the contract — the active prd-entry's test_names and acceptance_criteria are the tests the slice owes. The first failing test comes from that list; each later test emerges from the cycle before it. Keep no plan file: the working tree is the record of progress, and the ledger is the record of decisions. The target file set is the union of design-block.primary_paths, supporting_paths, and patterns[*].ref — treat that union as exhaustive. Widening it is a Requirement or Design gap (step 2), not an exploration task: append a consultation-request rather than grepping for additional files. Every file in that set is opened once in this dispatch before its first edit, whatever tool performs the edit, a scripted shell edit included. An edit to a file not opened in this dispatch rests on no basis, whatever the model recalls of the codebase. A call site the caller check finds outside the set means the public name stays as it was; the set widens only by consultation. Slice-size sanity check: fix the cycle count the owed tests imply at the Pre-Check (§ Partial-Artifact Contract defines N). More than twelve owed test_names entries, or a second behavior the Scope check finds, means the slice was mis-sized at intake. A few cycles the criteria add on top of the names do not. Stop and append the wrong-shape-slice abort record (§ Wrong-Shape Slice Abort) before starting Red; its route reaches the re-split. If the slice needs only 1–2 cycles and is not a coherent standalone behavior, consider batching with a sibling slice instead.
  2. Design check — before each cycle, verify the current design supports the behavior:

Each branch routes by who owns the gap: a code gap is yours to refactor, a design gap the system-design-expert's, a requirement gap the product-requirements-expert's. A gap only the human can close targets human (handoff-routing § Mid-Implementation Consultation). On an owner-absent dispatch the question stays recorded: proceed at the narrowest reading consistent with the intake's decisions and append the open question to .scratch/escalations.md. An architecture misfit is a design gap large enough to re-triage the slice. The inner loop surfaces a decision that isn't its to make; it never absorbs one silently, because silent absorption is how drift takes hold.

  1. Red — write a failing test.
  2. Green — write minimum code to pass.
  3. Refactor — clean up, keep tests green. State in one transcript line what was cleaned up, or why nothing needed it: the refactor step is where an agent under-delivers, and the line keeps it deliberate.
  4. Next cycle — return to step 2.

Fast inner-loop verification (optional)

When your toolchain provides an IDE semantic oracle, use it between cycles for a fast inspection pre-check instead of a full build every iteration, and to ground a Refactor's "matches the existing pattern" decision by resolving the neighbor rather than recalling it. The oracle reads and inspects; it does not compile — the toolchain gate does that. The inspection pre-check is optional, but the pattern decision is not: when an oracle is connected, a "reuses pattern X" / "matches the existing pattern" justification must cite the symbol-resolution call that resolves the neighbor — without an oracle, cite the grep and label it the weaker basis. Accelerator only otherwise: tests and the canonical quality gate (code-quality-gate) are unchanged. Where a stack provides oracle mechanics, they live in that stack's IDE-oracle skill.

Self-Review Pass

After the last TDD cycle, run the final gate's checks (code-quality-gate skill). Then walk the nine clauses of the conjunctive bar against the diff, with the gate's conventions-map listing in context. A fix the walk makes re-runs the gate; build-pass follows a green run on the walked tree. The canonical slug list and the clauses themselves live in CODE3 (§§ Scope Discipline, Code That Reads Cold, Operationally Honest, Secure by Design). For each clause, ask the question and fix any honest "no":

| Clause | Question |

|---|---|

| fit-for-purpose | Anything here that the spec did not ask for? |

| spec-grounded | Is every change traceable to a requirement, or am I drifting? |

| legible-cold | Would a stranger reading this in two years understand intent without me? Does every function read at one level of abstraction and call only one level down or sideways? |

| correct | Does the code handle every spec case and every listed failure mode? Did a rename or signature change keep every call site, a framework-bound name such as a request parameter included? |

| tested-as-spec | Do test names read as the spec? Any tests of implementation detail? Any mocks inside the boundary? Is each rule tested once, at the unit that owns it, never again through a client's suite? Then run the Test-Conventions Walk below. |

| consistent-with-codebase | Does the change match neighboring patterns? Any unjustified deviations? Does a matched neighbor break a security law? Then the match is the defect, not the deviation. Does each new decision, mapping, and parse sit where docs/architecture-principles.md places it, or did a neighbor's placement win? |

| operationally-honest | Do errors carry 3am-debuggable context? Does each path that scales with data fit the § Scale and Load row the design record cites, or did I raise the gap? Is anything hand-written that the standard library or an approved source provides? Does a performance claim name its measurement? |

| human-maintainable | Would this still be comfortable to own with the agents turned off? |

| secure-by-design | Does any input, boundary, secret, or privilege appear in this diff? If so: does it validate at the boundary, keep secrets out of logs and errors, grant least privilege, and fail closed? Does a request bind into a persisted type whole? Then it binds a request-scoped object or an allow-list instead. |

Test-Conventions Walk

Every class below is a write-time decision — the right form costs the same keystrokes as the wrong one, and a coverage trace costs one read of the records already in context. Walk the new tests once against these classes as part of the tested-as-spec check:

The walk narrows what reviewers find, never what they check. Every class stays on the reviewer checklists, the roster floor is untouched, and reviewers keep reading the change set with fresh eyes. Single-shot on conventions is the goal; the independent review cycle stays load-bearing for everything that needs judgment.

The pass is one walk through the diff — minutes, not a record. It is mandatory because it is where most quality comes from and is far cheaper than a reviewer-driven retry. No .scratch/ file is required; if reviewers later flag something a clause walk would have caught, the gap is yours to close in the next round.

Scoping Pre-Check

Every creator and verifier dispatch — including this one — runs a three-step Scoping Pre-Check before its first edit, finding, or record draft. The dispatch-start append is the first tool call, the step-1 reads follow it, and the step-3 decision closes the check:

  1. Read the inbound and the durable memory. Read the active prd-entry, design-block, and any review-feedback records for the current req_id. Read the durable memory the role normally reads (for the feature-implementer that is docs/system-design.md, docs/architecture-principles.md, docs/testing-principles.md, and the files named in design-block.primary_paths + supporting_paths + patterns[*].ref). The two principle briefs are read in full before the first edit of the slice's first dispatch. On a fix round, the sections the findings and the design record cite are read. The fewer-reads bias never applies to them. The ADR directory is outside the read set. The design doc's current-state lines are what the implementer executes from; an ADR is the decision log behind one of them, for humans. The conventions the reviewers hold the change to live in the briefs, not in this skill's summary of them.
  2. Estimate by category. Break the dispatch down by tool category — reads, edits, bash invocations (the checkpoint gate run included), writes — and sum. Single-digit precision is sufficient; the goal is to catch 3× overruns, not to forecast accurately.
  3. Decide. Run two independent checks:

toolCallBudget governs only the length check; the scope check never references it.

The pre-check is prompt-side discipline. There is no runtime enforcement, no transcript line, and no separate record type. The audit trail is the checkpoint gate run in the transcript, cycles on the build record, or the consultation-request of a scope stop.

Partial-Artifact Contract

The model cannot count its own tool calls precisely. The contract is therefore planned-checkpoint, not running-count. At Scoping Pre-Check time, name one explicit milestone in the cycle sequence where the dispatch checkpoints, regardless of whether the work feels close to done. The checkpoint is the trigger; the model's own tool-call count is not.

Choosing the checkpoint. N is the cycle count the owed test names imply: one per name, plus any an acceptance criterion adds. On a re-dispatch N counts the work left, not the slice. It is the owed names the coverage map still marks absent, any present test the last gate run left red, and the criteria still open. On a fix round it is the findings that change behavior. Fix it at the Pre-Check beside the tool estimate. For an N-cycle estimate, set the checkpoint at the end of cycle ⌈N/2⌉. A one-cycle slice names no checkpoint: its final gate is the checkpoint. The checkpoint is fixed before the first edit; its gate run is the trace.

At the checkpoint, the action is unconditional: run the full quality gate (code-quality-gate skill). Run the stack's formatter first where the gate names one. Green: proceed — no record. The build-pass waits for the final gate. The green run establishes that the tree built at the midpoint. The edits after it stay in the tree unrecorded, so a later cap hit is a no-record truncation. The continuation reads the working tree and the coverage map. Red: append the partial-artifact build-failure record below with the gate output, then stop. A red check whose gate procedure prescribes its own record (autofix-audit, contracts-sync, handoff-log) appends that record, never a partial. Do not assess "am I close to done" — that assessment is exactly the introspection the contract rejects. A partial handed off over green tests buys nothing but a re-dispatch; one gate run costs less.

Record shape. Copy this, fill in the fields, append it via python3 scripts/handoff.py append build-failure (handoff-append skill):

{"type":"build-failure","req_id":"<active req>","author":"feature-implementer","retry":<count>,"partial":true,"failed_check":"<gate step that failed, e.g. test or build>","attempted":"<one-sentence summary of what the dispatch was working on>","cycles":<cycles this dispatch ran>,"error_output":"<gate output, then progress: which tests pass, which files have been edited, which acceptance criteria remain>"}

The contract complement to a clean build-pass is this partial build-failure. Both are first-class outputs of a dispatch; neither is a verdict on the slice.

Wrong-Shape Slice Abort

The implementer may discover mid-loop that the slice cannot be implemented as triaged — not because the quality gate failed, but because the slice's shape is wrong, the design-block's design does not fit the code, or an external prerequisite is missing. Burning the full 3-retry cycle to surface this is wasteful. The implementer instead appends a build-failure record with the abort_reason field set, then exits. Build-Failure Recovery (route) short-circuits past the retry counter on these records.

Trigger: stop and write the abort record when, before completing TDD cycle 2, you have concluded that one of the three abort reasons applies. After cycle 2 the cost of one more retry is comparable to the abort overhead — finish the cycle and let the normal recovery path run.

The three abort_reason values:

Where each value routes is owned by handoff-routing § Build-Failure Recovery. A fourth value, prd-mismatch, belongs to the quality gate's autofix audit (code-quality-gate § Autofix Audit Procedure), never to a mid-loop diagnosis — do not use it here.

Record shape. Copy this, fill in the fields, append it via python3 scripts/handoff.py append build-failure (handoff-append skill):

{"type":"build-failure","req_id":"<active req>","author":"feature-implementer","retry":<count>,"failed_check":"<gate step not reached, e.g. build>","attempted":"<one-sentence summary of what the dispatch discovered>","error_output":"<diagnosis: why the slice cannot proceed as-is, what specifically blocks it, what re-scoping/re-triaging/escalation should address>","abort_reason":"<wrong-shape-slice | design-mismatch | prerequisite-missing>"}

Document Ownership

Never modify docs/prd.md, docs/system-design.md, docs/ubiquitous-language.md, or docs/adr/ directly. Route through the owning agent by appending a consultation-request targeting them; the owning agent updates durable memory through its consultation-response if the discovery warrants crystallizing. The ledger's consultation-request records are the log; keep no second one.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.