
Tdd
- 182 installs
- 1 repo stars
- Updated July 5, 2026
- jwilger/agent-skills
Run disciplined red-green-refactor cycles from your agent with orchestrated subagents, task dependencies, and Claude Code–specific harness rules.
About
TDD is an agent skill that forces test-driven development inside Claude Code and compatible agents by choosing an execution strategy up front—subagent orchestration when the Agent tool exists, otherwise chained steps in SKILL.md. The harness supplement spells out permissions subagents need, why delegate mode breaks file edits, and how to resume stopped agents with intact context rather than re-supplying delegation payloads. It also describes creating blocking RED-phase tasks so workflow state stays visible across a cycle. Solo builders install it when they want their coding agent to honor red-green-refactor instead of jumping straight to implementation, especially on backend services, CLIs, or APIs where regressions are costly. The skill is intermediate to advanced because it assumes comfort with tests, repo edits, and multi-step agent coordination. It pairs naturally with build-phase feature work and ship-phase quality gates without replacing a human judgment on what to test first.
- Strategy detection first: Agent tool → subagents via `references/orchestrator.md`, else chaining per SKILL.md
- Claude Code harness documents RED-task workflow with explicit task dependency protocol
- Subagents need Read, Write, Edit, Bash, Glob, Grep, Skill; avoid `mode: "delegate"` which strips edits
- Resume protocol for stopped agents instead of relaunching with duplicate context
- Fresh Context Protocol applies only to new invocations, not resumed agents
Tdd by the numbers
- 182 all-time installs (skills.sh)
- Ranked #829 of 2,153 Testing & QA skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/jwilger/agent-skills --skill tddAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 182 |
|---|---|
| repo stars | ★ 1 |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 5, 2026 |
| Repository | jwilger/agent-skills ↗ |
What it does
Run disciplined red-green-refactor cycles from your agent with orchestrated subagents, task dependencies, and Claude Code–specific harness rules.
Files
TDD
Value: Feedback -- short cycles with verifiable evidence keep AI-generated code honest and the human in control. Tests express intent; evidence confirms progress.
Purpose
Teaches a five-step TDD cycle (RED, DOMAIN, GREEN, DOMAIN, COMMIT) that adapts to whatever harness runs it. Detects available delegation primitives and routes to guided mode (human drives each phase) or automated mode (system orchestrates phases). Prevents primitive obsession, skipped reviews, and untested complexity regardless of mode.
Practices
The Five-Step Cycle
Every feature is built by repeating: RED -> DOMAIN -> GREEN -> DOMAIN -> COMMIT.
1. RED -- Write one failing test with one assertion. Only edit test files. Write the code you wish you had -- reference types and functions that do not exist yet. Run the test. Paste the failure output. Stop. Done when: tests run and FAIL (compilation error OR assertion failure).
2. DOMAIN (after RED) -- Review the test for primitive obsession and invalid-state risks. Create type definitions with stub bodies (todo!(), raise NotImplementedError, etc.). Do not implement logic. Stop. Done when: tests COMPILE but still FAIL (assertion/panic, not compilation error).
3. GREEN -- Address the immediate error — NEVER "make the test pass" in one go. Scope check before every change: can this be fixed with ~function-scope work (~20 lines, one file)? YES → make the change, run tests, check the next error. NO → drill down by writing a failing unit test for the smallest piece needed, then route it through a standard TDD cycle with swapped roles. Only edit production files (except when drilling down). Paste output after each change. Done when: tests PASS with minimal implementation.
4. DOMAIN (after GREEN) -- Review the implementation for domain violations: anemic models, leaked validation, primitive obsession that slipped through. If violations found, raise a concern and propose a revision. Done when: types are clean and tests still pass.
5. COMMIT -- Run the full test suite. Stage all changes and create a git commit referencing the GWT scenario. Run git status after committing to verify no uncommitted files remain. This is a hard gate: no new RED phase may begin until this commit exists and the working tree is clean. Done when: git commit created, all tests passing, working tree clean.
After step 5, either start the next RED phase or tidy the code (structural changes only, separate commit).
A compilation failure IS a test failure. Do not pre-create types to avoid compilation errors. Types flow FROM tests, never precede them.
Domain review has veto power over primitive obsession and invalid-state representability. Debate continues until resolved or escalated to the human — there is no round limit.
User-Facing Modes
Guided mode (/tdd red, /tdd domain, /tdd green, /tdd commit): Each phase loads references/{phase}.md with detailed instructions for that step. For experienced engineers who want explicit phase control. Works on any harness -- no delegation primitives required. The human decides when to advance phases.
Automated mode (/tdd or /tdd auto): The system detects harness capabilities, selects an execution strategy, and orchestrates the full cycle. The user sees working code, not sausage-making. For verbose output showing phase transitions and evidence, use /tdd auto --verbose.
Capability Detection (Automated Mode)
When automated mode activates, detect available primitives in this order:
1. Subagents available? Check for Agent tool. If present, use the subagents strategy with focused per-phase agents. 2. Fallback. Use the chaining strategy -- role-switch internally between phases within a single context.
Select the most capable strategy available. Do not attempt a higher strategy when its primitives are missing.
You are the orchestrator. The agent reading this file performs capability detection and dispatches directly. Do NOT spawn a single "orchestrator" subagent to do it for you -- that hides work, bypasses strategy detection, and pre-selects the wrong strategy. Whether you were invoked by /tdd, by the pipeline, or by any other caller: you detect capabilities, you choose the strategy, you spawn the phase agents yourself.
After determining your strategy, read ONLY the entry-point file for that strategy:
| Strategy | Entry-point file |
|---|---|
| Subagents | references/orchestrator.md |
| Chaining | (no entry file -- follow the chaining section below) |
Do NOT read orchestrator.md when using chaining.
orchestrator.md references references/shared-rules.md for rules that apply to all strategies (domain veto, outside-in progression, pipeline integration, pre-implementation context checklist). Read shared-rules.md when directed by your strategy's entry-point file.
Execution Strategy: Chaining (Fallback)
Used when no delegation primitives are available. The agent plays each role sequentially:
1. Load references/red.md. Execute the RED phase. 2. Load references/domain.md. Execute DOMAIN review of the test. 3. Load references/green.md. Execute the GREEN phase. 4. Load references/domain.md. Execute DOMAIN review of the implementation. 5. Load references/commit.md. Execute the COMMIT phase. 6. Repeat.
Role boundaries are advisory in this mode. The agent must self-enforce phase boundaries: only edit file types permitted by the current phase (see references/phase-boundaries.md).
Execution Strategy: Subagents
Used when the Agent tool is available for spawning focused subagents. Each phase runs in an isolated subagent with constrained scope.
- Spawn each phase agent using
Agent(subagent_type="<agent-name>", prompt="...")
with the prompt template in references/{phase}-prompt.md.
- The orchestrator follows
references/orchestrator.mdfor coordination rules. - Structural handoff schema (
references/handoff-schema.md): every phase
agent must return evidence fields (test output, file paths changed, domain concerns). Missing evidence fields = handoff blocked. The orchestrator does not proceed to the next phase until the schema is satisfied.
- Context isolation provides structural enforcement: each subagent receives
only the files relevant to its phase.
Named Team Member Personas (Subagent Strategy)
When .claude/agents/ definitions exist (from the ensemble-team skill), the subagent strategy uses named personas for ping and pong roles. The orchestrator selects team members based on slice context, spawns them as subagents using Agent(subagent_type="<agent-name>", prompt="..."), and collects results to pass as context to the next subagent.
See references/orchestrator.md for coordination rules and references/ping-pong-pairing.md for persona selection, rotation, and pairing history.
Phase Boundary Rules
Each phase edits only its own file types. This prevents drift. See references/phase-boundaries.md for the complete file-type matrix.
| Phase | Can Edit | Cannot Edit |
|---|---|---|
| RED | Test files | Production code, type definitions |
| DOMAIN | Type definitions (stubs) | Test logic, implementation bodies |
| GREEN | Implementation bodies | Test files, type signatures |
| COMMIT | Nothing -- git operations only | All source files |
If blocked by a boundary, stop and return to the orchestrator (automated) or report to the user (guided). Never circumvent boundaries.
Walking Skeleton First
The first vertical slice must be a walking skeleton: the thinnest end-to-end path proving all architectural layers connect. It may use hardcoded values or stubs. Build it before any other slice. It de-risks the architecture and gives subsequent slices a proven wiring path to extend.
Outside-In TDD
Start from an acceptance test at the application boundary -- the point where external input enters the system. Drill inward through unit tests. The outer acceptance test stays RED while inner unit tests go through their own red-green-domain-commit cycles. The slice is complete only when the outer acceptance test passes.
A test that calls internal functions directly is a unit test, not an acceptance test -- even if it asserts on user-visible behavior.
Boundary enforcement by mode:
- Pipeline mode: The CYCLE_COMPLETE evidence must include
boundary_type
and boundary_evidence on the acceptance test. The pipeline's TDD gate rejects evidence where the acceptance test calls internal functions directly.
- Automated mode (non-pipeline): The orchestrator checks boundary scope
and re-delegates if the first test is not a boundary test. Advisory -- no gate blocks progression.
- Guided mode: The human is responsible for ensuring boundary-level tests.
The skill text instructs correct behavior but cannot enforce it.
Cycle-Complete Evidence
At the end of each complete RED-DOMAIN-GREEN-DOMAIN-COMMIT cycle, produce a CYCLE_COMPLETE evidence packet containing: slice_id, acceptance_test {file, name, output, boundary_type, boundary_evidence}, unit_tests {count, all_passing, output}, domain_reviews [{phase, verdict, concerns}], commits [{hash, message}], rework_cycles, team {ping, pong, domain_reviewer}.
When pipeline-state is provided in context metadata, the TDD skill operates in pipeline mode: it receives a slice_id and stores evidence to .factory/audit-trail/slices/<slice-id>/tdd-cycles/cycle-NNN.json. When running standalone, the evidence is informational only (not stored).
See references/cycle-evidence.md for full schema.
Harness-Specific Guidance
If running on Claude Code, also read references/claude-code.md for harness-specific rules including hook-based enforcement. For maximum mechanical enforcement, ask the bootstrap skill to install optional hooks from references/hooks/claude-code-hooks.json.
Enforcement Note
- Guided mode: Advisory. The human enforces by controlling phase transitions.
- Chaining mode: Advisory. The agent self-enforces phase boundaries.
- Subagent mode: Structural. Context isolation and handoff schemas enforce
phase boundaries. Missing evidence blocks handoffs.
- Pipeline mode: Gating. Evidence gates reject incomplete phase transitions.
- Optional hooks (Claude Code): Mechanical. Pre-tool-use hooks block
unauthorized file edits per phase. See references/claude-code.md.
Hard constraints:
- Phase boundary violation (wrong file type in wrong phase):
[H] - Domain veto escalation (contested design decision):
[RP] - Commit gate (no new RED before prior cycle committed):
[H]
See references/constraint-resolution.md in the template directory for pipeline rework budget conflicts and domain veto resolution in pipeline mode.
Constraints
- Chaining mode self-enforcement: Self-enforcement means you produce the
same file-type restrictions as if separate agents were enforcing them. Writing production code during RED phase violates this constraint even though no mechanism prevents it. If you catch yourself reasoning about why a phase boundary doesn't apply in chaining mode, you are violating it.
- "~20 lines, one file" scope check: This is a judgment heuristic, not a
precise threshold. The spirit is: if the change touches multiple concerns, multiple files, or requires understanding distant code, it is too large for a single cycle. Do not game this by making a 40-line change across 2 functions in one file and claiming it's "one file."
Verification
After completing a cycle, verify:
- [ ] Every failing test was written BEFORE its implementation
- [ ] Domain review occurred after EVERY RED and GREEN phase
- [ ] Phase boundary rules were respected (file-type restrictions)
- [ ] Evidence (test output) was provided at each handoff
- [ ] Commit exists for every completed RED-GREEN cycle
- [ ] GREEN phase iterated one failure at a time (not full implementation in one pass)
- [ ] Working tree clean after every COMMIT (
git statusverified) - [ ] Walking skeleton completed first (first vertical slice)
HARD GATE -- COMMIT (must pass before any new RED phase):
- [ ] All tests pass
- [ ] Git commit created with message referencing the current GWT scenario
- [ ] No new RED phase started before this commit was made
Dependencies
This skill works standalone. For enhanced workflows, it integrates with:
- domain-modeling: Strengthens the domain review phases with parse-don't-validate,
semantic types, and invalid-state prevention principles.
- code-review: Three-stage review (spec compliance, code quality, domain
integrity) after TDD cycles complete.
- mutation-testing: Validates test quality by checking that tests detect
injected mutations in production code.
- ensemble-team: Provides real-world expert personas for pair selection
and mob review.
Missing a dependency? Install with:
npx skills add jwilger/agent-skills --skill domain-modelingClaude Code Harness Supplement
This file is loaded ONLY when the TDD skill runs on Claude Code. It documents Claude Code-specific patterns for orchestration, enforcement, and subagent workflows.
Strategy Detection (do this FIRST)
Before reading any other section of this file or any other reference file, determine your execution strategy:
1. Is Agent tool available? -> Subagents. Read references/orchestrator.md. 2. Neither? -> Chaining. Follow the chaining section in SKILL.md.
Agent Permissions
Subagents spawned via the Agent tool need these tools to do their work: Read, Write, Edit, Bash, Glob, Grep, Skill.
Do NOT use mode: "delegate" for phase agents -- delegate mode strips tool access and prevents file edits. Use mode: "default" or omit the mode parameter entirely.
Resume Protocol
Claude Code supports resuming stopped agents with their prior context intact. Use resume instead of re-launching when:
1. An agent stops because it needs information it cannot obtain (user input, output from another agent). 2. The orchestrator gathers the needed information. 3. The orchestrator resumes the stopped agent with the answer.
The resumed agent retains its full context -- do NOT re-supply the delegation context. The Fresh Context Protocol applies only to NEW agent invocations, not resumed ones.
Task Dependency Protocol
When starting a TDD cycle, create tasks with blocking relationships to make workflow state visible:
1. RED task 2. DOMAIN-after-RED task (addBlockedBy: [RED]) 3. GREEN task (addBlockedBy: [DOMAIN-after-RED]) 4. DOMAIN-after-GREEN task (addBlockedBy: [GREEN]) 5. COMMIT task (addBlockedBy: [DOMAIN-after-GREEN])
Pending tasks with non-empty blockedBy cannot be claimed. This makes the cycle state visible at a glance via TaskList.
Task dependencies provide supplementary visibility. They do not replace hook-based or structural enforcement -- they complement it.
Subagent Patterns
Agent tool: Spawn focused subagents. Each phase agent runs in its own Agent invocation with a phase-specific prompt from references/{phase}-prompt.md.
Agent Debate Protocol
The domain agent has veto power over primitive obsession, invalid-state representability, and parse-don't-validate violations.
1. Domain raises concern. 2. Affected agent responds substantively. 3. Orchestrator facilitates — debate continues until resolved. 4. No consensus: escalate to user via the ask-user skill or AskUserQuestion tool. There is no round limit.
Code Review Gate
Before creating PRs, run the three-stage code review:
1. Spec Compliance -- acceptance criteria met? 2. Code Quality -- clean, maintainable, well-tested? 3. Domain Integrity -- types used correctly, compile-time enforcement?
Use the code-review skill or code-reviewer agent for details.
Parallel Review
When the project's .claude/sdlc.yaml includes parallel_review: true, spawn three reviewer subagents using the Agent tool:
spec-reviewer-- checks acceptance criteria coveragequality-reviewer-- checks cleanliness, maintainability, testsdomain-reviewer-- checks type usage, parse-don't-validate
Collect results from all three and synthesize.
When parallel_review is not set or is false, use a single code-reviewer agent running all three stages sequentially.
Optional Hook Enforcement
For maximum mechanical enforcement, install the hook templates from references/hooks/claude-code-hooks.json. These add:
- PreToolUse hooks: Block unauthorized file edits per phase (RED
can only edit test files, GREEN only production files, DOMAIN only type definitions).
- PostToolUse hooks: Require running tests and pasting output
after every file edit.
- SubagentStop hooks: Enforce mandatory domain review after RED
and GREEN, prevent orchestrator from writing files directly.
Hooks are optional hardening, not a requirement. The TDD skill works without them via structural enforcement (handoff schemas, context isolation, role specialization).
COMMIT Phase Agent
You are the COMMIT phase agent. Your job is to verify all tests pass and create an atomic commit for the current TDD cycle.
Process
1. Run the full test suite. If any test fails, STOP and report the failure instead of committing. 2. Stage all files changed during this cycle (test files, type definitions, implementation files). 3. Create an atomic git commit. The commit message MUST reference the GWT scenario or acceptance criterion under test. 4. Return the commit details.
You MUST NOT
- Edit any source files.
- Commit files unrelated to the current TDD cycle.
- Create a commit if tests are failing.
Return Format (required)
You MUST return all three fields. Handoff is blocked if any field is missing.
{
"commit_hash": "<short SHA of the commit>",
"commit_message": "<the commit message used>",
"full_test_output": "<exact test runner output showing all tests pass>"
}COMMIT Phase -- Atomic Commit for the Completed Cycle
Goal
Create an atomic git commit that captures the completed RED-GREEN cycle.
Prerequisites
Before committing, verify:
- [ ] All tests pass. Run the full test suite (not just the single
test). Paste the output.
- [ ] Domain review approved. The post-GREEN domain review found no
violations, or all raised concerns have been resolved.
If either prerequisite is not met, go back and resolve it before committing.
Rules
1. One commit per RED-GREEN cycle. Each cycle produces exactly one commit. Do not batch multiple cycles into a single commit.
2. Commit message describes the behavior added. Reference the Given/When/Then scenario being implemented. Example:
Given a valid email, When creating a user, Then the user is created3. Include test output as evidence. The test suite output confirms the commit captures a working state.
4. Stage all changes from this cycle. Include the test file, any type definitions created, and the implementation code. Verify nothing unrelated is staged.
Hard Gate
No new `/tdd red` may begin until this commit exists.
This is non-negotiable. The commit is the checkpoint that proves the cycle is complete. Starting a new test without committing the previous cycle violates the TDD discipline and risks losing work.
Refactoring
If refactoring is warranted after this commit, do it in a SEPARATE commit. Never mix behavioral changes (the RED-GREEN cycle) with structural changes (refactoring) in the same commit.
Next Step
Cycle complete. Start the next cycle with /tdd red, or finish the task if all scenarios are implemented.
Cycle Evidence -- CYCLE_COMPLETE Packet
This reference documents the structured evidence packet that the TDD cycle produces at the end of each complete cycle. The pipeline's TDD gate consumes this packet to verify that a cycle completed successfully.
Purpose
The CYCLE_COMPLETE packet provides machine-readable proof that a TDD cycle followed the full RED-DOMAIN-GREEN-DOMAIN-COMMIT discipline. Without this evidence, the pipeline cannot distinguish a properly completed cycle from one that skipped phases. The packet captures what was tested, what was reviewed, and what was committed.
CYCLE_COMPLETE Schema
{
"slice_id": "string -- vertical slice identifier",
"cycle_number": "number -- sequential cycle within the slice (1-indexed)",
"acceptance_test": {
"file": "string -- absolute path to the acceptance test file",
"name": "string -- test function or case name",
"output": "string -- test runner stdout (pass/fail + output)",
"boundary_type": "string -- external boundary exercised (HTTP, CLI, message_queue, websocket, playwright_ui, manual_verification)",
"boundary_evidence": "string -- how the test interacts with the boundary (e.g., 'sends HTTP POST to /api/commands and asserts 201 response')"
},
"unit_tests": {
"count": "number -- total unit tests run",
"all_passing": "boolean -- true if every unit test passed",
"output": "string -- test runner stdout for full suite"
},
"domain_reviews": [
{
"phase": "string -- RED_DOMAIN or GREEN_DOMAIN",
"verdict": "string -- approved or flagged",
"concerns": ["string -- concern descriptions, empty if approved"]
}
],
"commits": [
{
"hash": "string -- git commit SHA",
"message": "string -- commit message"
}
],
"rework_cycles": "number -- times this cycle was sent back for rework (0 if clean)",
"team": {
"ping": "string -- engineer name (wrote failing test for this cycle)",
"pong": "string -- engineer name (wrote GREEN implementation for this cycle)",
"domain_reviewer": "string -- engineer name (reviewed test and implementation)"
}
}Field Details
acceptance_test
The boundary-level test for the vertical slice. This is the outside-in test written in the first RED phase of the slice. Its output must show a passing result for the cycle to be considered complete.
boundary_type identifies which external boundary the acceptance test exercises. Valid values: HTTP, CLI, message_queue, websocket, playwright_ui, manual_verification. A test that calls internal functions directly (e.g., CommandLogic.handle(), service.process()) is a unit test, not an acceptance test -- it disqualifies as the boundary-level test even if it asserts on user-visible behavior.
boundary_evidence describes how the test interacts with the external boundary in concrete terms (e.g., "sends HTTP POST to /api/commands and asserts 201 response", "spawns CLI process with --create flag and asserts exit code 0", "connects to WebSocket at /ws/events and asserts message received").
In standalone (non-pipeline) mode, these fields are informational. The TDD skill text instructs the agent to fill them, but only the pipeline gate structurally rejects missing values.
unit_tests
The full unit test suite output. all_passing must be true. The count field provides a sanity check -- a cycle that results in zero unit tests is suspicious and should be flagged.
domain_reviews
There are exactly two domain reviews per cycle: one after RED (reviewing the test and any new types) and one after GREEN (reviewing the implementation for domain violations). A flagged verdict with unresolved concerns means the cycle required rework -- this is captured in rework_cycles.
commits
One or more commits produced by the COMMIT phase. Typically one commit per cycle, but a rework cycle may produce additional commits. Each commit hash is a verifiable reference in git history.
rework_cycles
Number of times the cycle was sent back from a domain review or quality gate. Zero means the cycle completed cleanly on the first pass. This metric feeds into the pipeline's rework rate calculation.
team
The three members who worked the cycle. Ping writes the failing test (RED). Pong writes the GREEN implementation. Domain reviewer reviews both the test and the implementation. Roles swap between cycles within a slice (ping becomes pong, pong becomes ping; domain reviewer may stay or rotate).
When Produced
The CYCLE_COMPLETE packet is produced at the end of each complete RED-DOMAIN-GREEN-DOMAIN-COMMIT cycle. It is NOT produced for incomplete cycles (e.g., a RED phase that was abandoned) or for cycles that are still in progress.
Where Stored
.factory/audit-trail/slices/<slice-id>/tdd-cycles/cycle-NNN.jsonNNN is zero-padded to three digits (e.g., cycle-001.json, cycle-002.json). The slice directory is created when the first cycle for that slice completes.
In non-factory mode (standalone TDD), the packet is not written to disk. It exists only as structured output passed between the TDD orchestrator and the calling agent.
Pipeline Consumption
The pipeline's TDD gate reads CYCLE_COMPLETE packets to evaluate whether a slice is ready to proceed:
1. Acceptance test passes: acceptance_test.output shows a passing result 2. All unit tests pass: unit_tests.all_passing is true 3. Domain reviews approved: Every entry in domain_reviews has verdict: "approved" (no unresolved flagged verdicts) 4. Boundary scope verified: acceptance_test.boundary_type is present and matches the slice's GWT boundary annotation. acceptance_test.boundary_evidence describes an external interaction (not a direct call to an internal function).
If any condition is not met, the TDD gate fails and the slice enters a rework cycle. The pipeline records the gate failure in the audit trail and routes the slice back to the TDD pair.
DOMAIN Phase Agent
You are the DOMAIN phase agent. You guard domain integrity and create type definitions. You run in two modes depending on when you are invoked.
Rules
- Edit type definition files ONLY (structs, enums, traits, interfaces).
- Use stub bodies (
unimplemented!(),todo!(),raise NotImplementedError)
for function signatures. NEVER write implementation logic.
- You have VETO POWER over designs that violate domain modeling principles.
You MUST NOT
- Edit test files (red agent's job).
- Edit production implementation files (green agent's job).
- Write real implementation logic in function bodies.
Mode 1: After RED
1. Review the failing test for primitive obsession, invalid-state risks, and domain boundary violations. 2. Check that any event types contain domain facts only -- no runtime context (file paths, hostnames, PIDs). 3. If the test design is flawed, raise a concrete concern with a specific alternative (e.g., "use EmailAddress instead of String"). One round of pushback maximum. 4. Create minimal type definitions to satisfy compilation. Use stub bodies. 5. Run the type checker and capture output. 6. Done when the test COMPILES but still FAILS on an assertion or unimplemented!() panic -- not a compilation error.
Mode 2: After GREEN
1. Review the implementation for domain violations: structural vs semantic types, domain boundary crossings, type system shortcuts, validation in wrong places. 2. Run the full test suite and capture output. 3. Done when types are clean, no domain violations found, and tests pass.
Veto Protocol
When you identify a violation: 1. State the violation clearly. 2. Propose the alternative. 3. Explain the impact. 4. Return with a DOMAIN CONCERN RAISED status. The debate continues until resolved or escalated to the user — there is no round limit.
Return Format (required)
After RED:
{
"domain_review": "APPROVED" | "REVISED",
"type_files_created": ["<path1>", "<path2>"]
}After GREEN:
{
"review": "APPROVED" | "CONCERN_RAISED",
"full_test_output": "<exact test runner output>"
}DOMAIN Phase -- Domain Review and Type Definitions
The domain phase runs TWICE per cycle: once after RED and once after GREEN. Its focus depends on which mode is active.
File Restrictions
You may ONLY edit type definition files.
Type definition files contain structs, enums, traits, interfaces, type aliases, and function signatures with stub bodies (unimplemented!(), todo!(), raise NotImplementedError).
You must NOT edit: test files, implementation bodies with real logic, or any file that is not a type definition.
---
After RED -- Review Test and Create Types
Review the Test
Check the test for:
- Given-clause enforcement: Does the test setup actually enforce each
element of the scenario's Given clause? A test that would pass against any arbitrary server returning the right output does not verify its preconditions. VETO if the Given clause is not enforced by test setup. See shared-rules.md § Given-Clause Enforcement.
- Primitive obsession: Does the test use raw
String,i32, or
similar where a domain-specific newtype should exist?
- Naming: Do type and variable names reflect domain language?
- Boundary placement: Is behavior being tested at the right layer?
- Event types with runtime state: If the test references event
types, verify their fields contain domain facts only -- no file paths, hostnames, PIDs, or working directories.
Pushback Protocol
You CAN push back to RED if the test violates domain principles. Pushback rules:
- Pushback MUST include a concrete suggestion (e.g., "use
EmailAddress
instead of String")
- Debate continues until the concern is resolved or escalated to the
user — there is no round limit.
- The domain veto can only be overridden by the user, not by the
orchestrator.
Create Minimal Type Definitions
After review (or if no concerns):
1. Create type definitions for ALL types referenced by the test: core domain types, repository traits, infrastructure types, error types. 2. Use unimplemented!(), todo!(), or equivalent for function bodies. NEVER implement logic. 3. Run the type checker or compiler and paste the output.
Done When
Tests COMPILE but still FAIL -- the failure is now an assertion failure or todo!()/unimplemented!() panic, NOT a compilation error. The failure mode has shifted from "missing types" to "missing implementation."
Evidence Required
- Files created and types defined
- Compilation status (pasted output)
- Confirmation that tests compile but still fail at runtime
Next Step
Now invoke /tdd green to implement the minimal code.
---
After GREEN -- Review Implementation
Review for Domain Violations
Check the implementation for:
- Structural vs semantic types: Using
NonEmptyStringwhere
OrderId should exist.
- Domain boundary violations: Logic in the wrong layer.
- Type system shortcuts: Bypassing type safety for convenience.
- Validation in wrong places: Validation that belongs at the
boundary leaking into the domain or vice versa.
VETO POWER
You have VETO POWER over designs that violate domain modeling principles. When you identify a violation:
1. State the violation clearly. 2. Propose the specific alternative. 3. Explain the impact of leaving it as-is.
Do NOT back down from valid domain concerns to avoid conflict. The debate continues until resolved or escalated to the user — there is no round limit.
Mandatory Domain Review Checklist
The review fails if ANY item is not explicitly verified:
1. Semantic types: Domain concepts use the project's semantic type library (e.g. nutype in Rust, value objects in OOP), not raw primitives. Flag String, int, UUID etc. where a domain type should be.
2. Event definition conventions: Events are defined using the project's configured event sourcing library macros/conventions — not hand-rolled structs or plain data classes.
3. Property-based validation tests: Domain type constraint tests use property-based testing (e.g. proptest, hypothesis, fast-check), not hand-written examples. A test verifying valid_email("foo@bar.com") is not a domain type test — it is a single example.
4. No test infrastructure in production: No test-only routes, hardcoded test fixtures, or in-memory stubs masquerading as production infrastructure.
5. Persistence via configured event store: Persistence uses the project's documented event store, not in-memory structures or an undocumented abstraction.
A domain review that does not explicitly verify all five items is incomplete — issue a VETO listing the unchecked items.
Tautological Test Check
A test verifying a constant equals its own defined value tests nothing. Reject it. Tests must verify behavior, not implementation details.
Done When
Types are clean, no domain violations found, and all tests still pass.
Evidence Required
One of:
- No violations: "Reviewed -- no domain violations. Proceed to commit."
- Violation found: "DOMAIN CONCERN RAISED: [violation], [location],
[proposed alternative], [rationale]"
Next Step
Now invoke /tdd commit to commit the completed cycle.
GREEN Phase Agent
You are the GREEN phase agent. Your job is addressing the immediate error from the failing test — NOT "making the test pass" in one go.
Start of turn: Read references/green.md for the full GREEN phase protocol, including the scope check and drill-down rules. Do this at the start of EVERY turn, not just when first spawned.
Rules
- Edit production implementation files ONLY (
src/,lib/,app/). - Address ONLY the exact test failure message -- nothing more.
- Scope check before every change: Can this be fixed with ~function-scope
work (~20 lines, one file)? If NO, drill down instead of implementing.
- Stop immediately when the test passes.
- Delete unused or dead code.
You MUST NOT
- Edit test files (red agent's job) -- except when drilling down.
- Edit type definition files (domain agent's job).
- Add methods, validation, or behavior not required by the failing test.
- Keep dead code.
- Try to "make the acceptance test pass" in one session.
Architecture Check
Before implementing, read docs/ARCHITECTURE.md if it exists. If your implementation would violate documented patterns, STOP and return an ARCHITECTURE CONFLICT report.
Process
1. Read the exact failure output provided in the handoff. 2. Scope check: Can I fix this with ~function-scope work?
- YES: Make the change. Run tests. If new error, go to step 1.
- NO: Write a failing unit test for the smallest piece needed.
Return DRILL_DOWN format. 3. Stop when the test passes.
Layer Awareness
You implement method bodies for types the domain agent created. If compilation fails because a type is undefined (not just unimplemented!()), return to the orchestrator -- the domain agent should have created it.
Return Format (required)
Standard return (test passes):
You MUST return both fields. Handoff is blocked if any field is missing.
{
"implementation_files": ["<path1>", "<path2>"],
"test_output": "<exact test runner output showing the test passes>"
}Drill-down return (scope check fails):
Return this when the change needed is larger than function-scope.
{
"drill_down": true,
"outer_test": "<path to the test that is still failing>",
"outer_error": "<error message that triggered scope check>",
"inner_test_file": "<path to new failing unit test>",
"inner_test_name": "<name of the new test>",
"inner_failure_output": "<test runner output for the new failing test>",
"rationale": "<why drill-down was needed>"
}GREEN Phase -- Address the Immediate Error
Goal
Address the IMMEDIATE error from the test output. Before every change, check scope: can this be fixed with roughly function-scope work (~20 lines in one file)? If yes, implement it. If no, drill down by writing a failing unit test for the smallest piece needed.
The GREEN agent's goal is NEVER "make the acceptance test pass." It is always "address the immediate error" — one error at a time, with a scope check before each change.
File Restrictions
You may ONLY edit production/implementation files.
Production files live in src/, lib/, app/ directories or are otherwise clearly implementation code.
You must NOT edit: test files, type-only definition files (those with only stubs created by the domain phase), or any file in tests/, __tests__/, spec/, or test/ directories.
Exception: When drilling down, you write a NEW failing unit test. This is the one case where the GREEN agent creates a test file — because the drill-down makes you the RED/ping agent at the inner level. See Drill-Down below.
Rules
1. Address ONLY the exact failure message. Read the specific error from the test output. Ask: "What is the SMALLEST change that addresses THIS SPECIFIC message?" Make only that change.
2. Scope check before every change. Before implementing, ask: "Can I fix this with roughly function-scope work (~20 lines, one file)?"
- YES: Make the change. Run tests. Check the next error.
- NO: STOP implementing. Drill down (see below).
3. One small change at a time. Make a single change. Run tests. Check the result. Repeat the scope check for any new error.
4. Run tests after EACH change. Paste the output every time. Never claim tests pass without pasted evidence.
5. Stop IMMEDIATELY when the test passes. Do not add error handling, flexibility, or features not demanded by the test. Do not refactor. Do not anticipate future tests. Stop.
6. Delete unused/dead code. If your change makes any existing code unreachable or unnecessary, remove it.
7. Fill stubs, do not redefine types. You implement method bodies for types that the domain phase created. When you encounter unimplemented!() or todo!(), replace it with the simplest code that passes the test. If compilation fails because a type is undefined (not just unimplemented), stop -- the domain phase should have created it.
Scope Check
The scope check is the core discipline of outside-in TDD. It prevents the common failure mode where a single GREEN session tries to build an entire application to make an acceptance test pass.
Before EVERY change, ask:
"Can I fix this error with roughly function-scope work (~20 lines in
one file)?"
YES path: 1. Make the change. 2. Run tests. Paste output. 3. If a new error appears, do the scope check again for the new error. 4. When the test passes, stop.
NO path (drill down): 1. The change requires new modules, multiple files, or significant architecture work. 2. STOP the current GREEN phase. 3. Write a NEW failing unit test for the smallest piece needed to make progress on the current error. 4. Return the DRILL_DOWN format (see Evidence Required below). 5. The orchestrator routes the drill-down through a standard TDD cycle with swapped roles — you wrote the test, so someone else implements it.
Examples of function-scope work (YES):
- Changing a string literal ("Hello World" → "Component Showcase")
- Adding a return statement
- Implementing a method body with a few lines of logic
- Adding a match arm or case branch
Examples requiring drill-down (NO):
- Setting up a new module with its own dependencies
- Creating a server entry point with routing
- Wiring multiple layers (handler → service → repository)
- Adding build system configuration (Cargo.toml features, etc.)
What NOT to Do
- Do not touch test files (that is the RED phase's job — except during
drill-down)
- Do not add methods not called by tests
- Do not implement validation not required by the failing test
- Do not keep dead code
- Do not add imports or helpers before addressing the actual failure
- Do not try to "make the acceptance test pass" in one session
Evidence Required
Standard return (test passes):
Provide all of the following before moving on:
- Files modified and the specific change made
- Test output showing the test passes (pasted, not described)
Drill-down return (scope check fails):
When a scope check determines the change is too large:
- Outer test: Path to the test that is still failing
- Outer error: The error message that triggered the scope check
- Inner test file: Path to the new failing unit test you wrote
- Inner test name: Name of the new test
- Inner failure output: Test runner output for the new failing test
- Rationale: Why drill-down was needed (one sentence)
Next Step
If the test passes: invoke /tdd domain for post-implementation domain review.
If drill-down: return to the orchestrator with the DRILL_DOWN evidence. The orchestrator routes the inner test through a standard TDD cycle with swapped roles (you wrote the test, so someone else implements it).
Handoff Schema -- Structural Evidence Requirements
Every phase transition requires specific evidence fields. Missing fields block the handoff. This is structural enforcement -- the absence of evidence is itself a signal that the phase was not completed correctly.
RED -> DOMAIN Handoff
Required fields:
| Field | Description |
|---|---|
test_file | Absolute path to the test file created or modified |
test_name | Name of the specific test function or case |
failure_output | Actual test runner output, pasted verbatim |
failure_output must be real output from the test runner. "I expect it to fail" or "the test should fail" is not evidence. Compilation errors are valid failure output.
DOMAIN (post-RED) -> GREEN Handoff
Required fields:
| Field | Description |
|---|---|
domain_review | APPROVED or REVISED (with explanation of revision) |
type_files_created | List of type definition files created or modified (may be empty if no new types needed) |
If domain_review is REVISED, the revision explanation must include what was changed and why. The RED agent must re-run the test and provide updated failure output before the handoff proceeds.
GREEN -> DOMAIN (post-GREEN) Handoff
Required fields:
| Field | Description |
|---|---|
implementation_files | List of production files created or modified |
test_output | Actual test runner output showing the test now passes |
test_output must show the specific test passing. "Tests should pass now" is not evidence.
DOMAIN (post-GREEN) -> COMMIT Handoff
Required fields:
| Field | Description |
|---|---|
review | APPROVED or CONCERN_RAISED (with specific concern and proposed alternative) |
full_test_output | Full test suite output, not just the single test |
If review is CONCERN_RAISED, the concern must be resolved before proceeding to COMMIT. The implementation is revised via the GREEN phase, then domain reviews again.
GREEN -> DRILL_DOWN Handoff
Alternative to GREEN -> DOMAIN when the scope check determines the needed change is larger than function-scope. Instead of implementing, the GREEN agent writes a failing unit test and returns this evidence.
Required fields:
| Field | Description |
|---|---|
drill_down | Must be true |
outer_test | Path to the test that is still failing |
outer_error | The error message that triggered the scope check |
inner_test_file | Path to the new failing unit test written by the GREEN agent |
inner_test_name | Name of the new test function |
inner_failure_output | Actual test runner output showing the inner test fails |
rationale | Why drill-down was needed (one sentence) |
The orchestrator routes the inner test through a standard TDD cycle with swapped roles: the agent who wrote the inner test (GREEN/pong at outer level) becomes the RED/ping at inner level. The other engineer (RED/ping at outer level) implements the inner test as GREEN/pong at inner level. Domain review applies at the inner level too.
When the inner cycle commits, the orchestrator pops back to the outer level and re-runs the outer test. The next error (if any) goes through the same scope check.
Enforcement by Mode
Automated mode (subagents): The orchestrator checks returned evidence against this schema before spawning the next phase agent. A missing field means the orchestrator re-prompts the current agent for the missing evidence. When using named personas, the orchestrator passes these evidence fields as context in the next subagent's prompt.
Guided mode: The skill text prompts the user to provide this evidence at each phase transition. The user is responsible for verifying completeness before advancing.
Chaining mode: The agent self-checks against this schema before switching roles to the next phase.
{
"_comment": "Optional hook templates for Claude Code. These provide mechanical enforcement of TDD phase boundaries. Install via the bootstrap skill or copy into your project's .claude/hooks.json. These are static recipes -- not a maintained plugin.",
"hooks": {
"PreToolUse": [
{
"_category": "RED phase file-type verification",
"_description": "Blocks red agent from editing non-test files",
"matcher": "Edit",
"hooks": [
{
"type": "agent",
"prompt": "RED AGENT FILE-TYPE VERIFICATION\n\nVerify this is a test file. The hook input is: $ARGUMENTS\n\n1. Extract file_path from tool_input\n2. Check path indicators FIRST:\n - Path contains: tests/, __tests__/, spec/, test/\n - File name matches: *_test.rs, *.test.ts, test_*.py, *_spec.rb, *_test.go\n3. If ambiguous, read file and check for test content (annotations, imports)\n\nALLOW if test file. BLOCK if not.\n\n{\"ok\": true} - test file\n{\"ok\": false, \"reason\": \"red agent can only edit test files.\"} - not a test file",
"timeout": 60
}
]
},
{
"_category": "GREEN phase file-type verification",
"_description": "Blocks green agent from editing test files or type-only files",
"matcher": "Edit",
"hooks": [
{
"type": "agent",
"prompt": "GREEN AGENT FILE-TYPE VERIFICATION\n\nVerify this is production implementation code (NOT test, NOT type-only). The hook input is: $ARGUMENTS\n\n1. Extract file_path from tool_input\n2. BLOCK if path contains: tests/, __tests__/, spec/, test/\n3. BLOCK if file name matches test patterns\n4. ALLOW if path is in: src/, lib/, app/\n5. If ambiguous, check content: BLOCK if only type definitions with stubs\n\n{\"ok\": true} - production code\n{\"ok\": false, \"reason\": \"green agent can only edit production implementation code.\"} - otherwise",
"timeout": 60
}
]
},
{
"_category": "DOMAIN phase file-type verification",
"_description": "Blocks domain agent from editing test files or implementation bodies",
"matcher": "Edit",
"hooks": [
{
"type": "agent",
"prompt": "DOMAIN AGENT FILE-TYPE VERIFICATION\n\nVerify this edit is for type definitions ONLY (not tests, not implementations). The hook input is: $ARGUMENTS\n\n1. BLOCK if path contains: tests/, __tests__/, spec/, test/\n2. BLOCK if file name matches test patterns\n3. ALLOW if content contains type definitions (struct, enum, trait, interface)\n4. ALLOW if function signatures with stub bodies (unimplemented!(), todo!())\n5. BLOCK if function bodies contain real implementation logic\n\n{\"ok\": true} - type definition work\n{\"ok\": false, \"reason\": \"domain agent can only edit type definitions.\"} - otherwise",
"timeout": 60
}
]
},
{
"_category": "RED phase Write verification",
"_description": "Blocks red agent from creating non-test files",
"matcher": "Write",
"hooks": [
{
"type": "agent",
"prompt": "RED AGENT FILE-TYPE VERIFICATION\n\nVerify this is a test file being created. The hook input is: $ARGUMENTS\n\nCheck path indicators first, then content if ambiguous.\n\n{\"ok\": true} - test file\n{\"ok\": false, \"reason\": \"red agent can only create test files.\"} - not a test file",
"timeout": 60
}
]
},
{
"_category": "GREEN phase Write verification",
"_description": "Blocks green agent from creating test files or type-only files",
"matcher": "Write",
"hooks": [
{
"type": "agent",
"prompt": "GREEN AGENT FILE-TYPE VERIFICATION\n\nVerify this is a production implementation file being created. The hook input is: $ARGUMENTS\n\nCheck path indicators first, then content if ambiguous.\n\n{\"ok\": true} - production file\n{\"ok\": false, \"reason\": \"green agent can only create production implementation files.\"} - otherwise",
"timeout": 60
}
]
},
{
"_category": "DOMAIN phase Write verification",
"_description": "Blocks domain agent from creating test or implementation files",
"matcher": "Write",
"hooks": [
{
"type": "agent",
"prompt": "DOMAIN AGENT FILE-TYPE VERIFICATION\n\nVerify this file contains type definitions ONLY. The hook input is: $ARGUMENTS\nBLOCK test files and files with real implementation logic.\nALLOW type definitions with stub bodies.\n\n{\"ok\": true} - type definition file\n{\"ok\": false, \"reason\": \"domain agent can only create type definition files.\"} - otherwise",
"timeout": 60
}
]
}
],
"PostToolUse": [
{
"_category": "Evidence gate after Edit (all phases)",
"_description": "Requires running tests and pasting output after every file edit",
"matcher": "Edit",
"hooks": [
{
"type": "prompt",
"prompt": "POST-EDIT: Run tests and paste output. Show the actual result.\n\"I expect it to fail\" is not evidence. \"Tests should pass now\" is not evidence.\nRun the test. Paste the output.\nOutput ONLY: {\"ok\": true}"
}
]
},
{
"_category": "Evidence gate after Write (all phases)",
"_description": "Requires running tests and pasting output after every file creation",
"matcher": "Write",
"hooks": [
{
"type": "prompt",
"prompt": "POST-WRITE: Run tests or type checker and paste output. Show the exact result.\nNever claim success or failure without pasted evidence.\nOutput ONLY: {\"ok\": true}"
}
]
}
],
"SubagentStop": [
{
"_category": "Domain review checkpoint",
"_description": "Enforces mandatory domain review after RED and GREEN phases. Prevents skipping domain review.",
"hooks": [
{
"type": "prompt",
"prompt": "DOMAIN REVIEW CHECKPOINT (MANDATORY)\n\nDetect which agent just completed and enforce domain review requirements.\n\nExamine the conversation to determine which agent just finished. Look for agent invocation patterns, self-identification, and file modification patterns (test files = red, production = green).\n\n**If red just completed:**\nA failing test was just written. Domain review is MANDATORY before proceeding.\nNext action MUST be: Launch domain agent with DOMAIN_CONTEXT: AFTER_RED\nBlock if orchestrator tries to skip directly to GREEN.\n\n**If green just completed:**\nProduction code was just implemented. Domain review is MANDATORY before proceeding.\nNext action MUST be: Launch domain agent with DOMAIN_CONTEXT: AFTER_GREEN\nBlock if orchestrator tries to write another test without review.\n\n**If domain just completed:**\nDomain review passed, workflow may continue. Allow orchestrator to proceed.\n\n**If any other agent completed:**\nAllow (domain review not required).\n\nAfter RED or GREEN (domain review required):\n{\"ok\": false, \"reason\": \"Domain review is MANDATORY after {agent} phase. You must launch the domain agent with appropriate DOMAIN_CONTEXT before proceeding. This is NOT optional.\"}\n\nAfter DOMAIN or other agents:\n{\"ok\": true}"
}
]
},
{
"_category": "Orchestration reminder",
"_description": "Prevents the orchestrator from writing files directly. Reminds it to delegate to phase agents.",
"hooks": [
{
"type": "prompt",
"prompt": "SUBAGENT COMPLETED - ORCHESTRATION REMINDER\n\nAn agent just finished. Before proceeding:\n\nYOU ARE AN ORCHESTRATOR, NOT AN IMPLEMENTER.\n\nYou MUST NEVER use Edit or Write tools directly on project files.\n\nRole selection for file edits:\n- Test code -> Launch red agent\n- Production code -> Launch green agent\n- Type definitions -> Launch domain agent\n\nTDD CYCLE CHECKPOINT:\n- After RED -> Launch domain (review test)\n- After DOMAIN (post-red) -> Launch green (implement)\n- After GREEN -> Launch domain (review implementation)\n- After DOMAIN (post-green) -> Commit, then next test or refactor\n\nNO EXCEPTIONS. NO \"QUICK FIXES\". NO \"JUST ONE LINE\".\n\nAgents have ZERO memory of this conversation - provide complete context every time:\n- File paths\n- Test names and error messages\n- Current TDD phase\n- Requirements and constraints\n\nRespond with JSON only: {\"ok\": true}"
}
]
}
]
}
}
TDD Orchestrator Instructions
Scope: This file applies to the subagents execution strategy only.
If you are using chaining (no Agent tool), follow the chaining section in
SKILL.md.
You coordinate the TDD cycle by delegating to phase agents. You NEVER write, edit, or create project files yourself.
Shared Rules
Read references/shared-rules.md for rules that apply to all execution strategies: domain veto power, outside-in progression, type-first TDD anti-pattern, pre-implementation context checklist, pipeline integration, and recovery protocol.
Architecture Context Extraction is Non-Delegable
The orchestrator (not the RED or GREEN agent) reads the project's ARCHITECTURE.md and extracts sections relevant to the current slice. Include the extracted content verbatim in every agent spawn prompt for this slice. Agents are stateless — without explicit architectural context they will invent non-architectural solutions.
Required sections for every slice:
- Persistence layer (event store, database, connection patterns)
- Domain type conventions (semantic type library)
- Test strategy (acceptance test location, test pyramid shape)
- UI conventions (if UI slice: component framework, design token enforcement)
- The slice's bounded context location in the codebase
If a required architectural section is missing for a technology the slice uses, STOP. An ADR must be created and approved before the TDD cycle starts. Do not allow agents to invent architecture.
PR Branch Gate
Before spawning the RED agent for a slice's first scenario: verify a PR branch exists. Create it if not. No code lands on the main branch directly.
Core Rule
All file modifications flow through phase agents. Not "quick fixes," not "just one line," not "cleanup." Every file change is delegated.
Agent Selection
| File type | Agent | Scope |
|---|---|---|
| Test files | RED agent | *_test.*, *.test.*, tests/, spec/ |
| Type definitions | DOMAIN agent | Structs, enums, traits, interfaces |
| Production code | GREEN agent | src/, lib/, app/ |
| Commit | COMMIT agent | All changed files from this cycle |
Mandatory Cycle: RED -> DOMAIN -> GREEN -> DOMAIN -> COMMIT
Every phase is mandatory, every time. No exceptions for "trivial" changes.
Workflow Gates
Each gate must be satisfied before the next phase begins:
1. RED complete -> Test exists and fails (compilation failure counts). Required evidence: {test_file, test_name, failure_output}. 2. DOMAIN (after RED) complete -> Types compile, test is domain-correct. Required evidence: {domain_review, type_files_created}. 3. GREEN complete -> All tests pass. Required evidence: {implementation_files, test_output}. 4. DOMAIN (after GREEN) complete -> No domain violations. Required evidence: {review, full_test_output}. 5. COMMIT complete -> Atomic commit exists. Required evidence: {commit_hash, commit_message, full_test_output}.
No new RED without a completed COMMIT. This is a hard gate.
Handoff Schema Enforcement
Check every returned evidence object for the required fields listed above. If ANY field is missing, block progression and re-request from the same agent with a clear description of what is missing.
Fresh Context Protocol
Every new agent delegation MUST include complete context:
WORKING_DIRECTORY: <absolute path to project root>
TASK: What to accomplish
FILES: Specific file paths to read or modify
CURRENT STATE: What exists, what is passing/failing
REQUIREMENTS: What "done" looks like
CONSTRAINTS: Domain types to use, patterns to follow
ERROR: Exact error message (if applicable)NEVER say "as discussed earlier" or "continue from where we left off."
Passing Context to Phase Agents
All gathered context (see Pre-Implementation Context Checklist in references/shared-rules.md) goes into the CONSTRAINTS field of every Fresh Context Protocol delegation. This ensures each phase agent has full domain awareness without relying on conversational memory. Include file paths and relevant excerpts -- not just references to document names.
Subagent Delegation Cycle
The cycle above (RED -> DOMAIN -> GREEN -> DOMAIN -> COMMIT) is executed by spawning a fresh subagent for each phase using the Agent tool. Use the agent selection table and handoff schema enforcement in this file for coordination. For rules that apply to all strategies (domain veto, outside-in progression, type-first anti-pattern, pipeline integration, recovery), see references/shared-rules.md.
Phase Boundary Rules -- File-Type Restrictions
Each TDD phase may edit only specific file types. Violations indicate drift from the cycle discipline. These rules apply in every mode (guided, chaining, subagents).
RED Phase -- Test Files Only
Allowed files:
- Files in directories:
tests/,test/,__tests__/,spec/ - Files matching:
*_test.*,*.test.*,*_spec.*,*.spec.*,test_*.*
Forbidden: Production source files, type definition files, configuration files, documentation.
Verification checklist: 1. Every file edited has a path or name matching a test pattern above. 2. No src/, lib/, or app/ files were modified. 3. No type definition files (.d.ts, trait files, interface modules) were created or changed. 4. The test was run and failure output was pasted.
GREEN Phase -- Production Implementation Only
Allowed files:
- Implementation source files (typically in
src/,lib/,app/) - Filling in stub bodies created by the domain phase
Forbidden: Test files (all patterns listed under RED above), type-definition-only files (adding new type signatures or traits).
Verification checklist: 1. No file matching a test pattern was modified. 2. No new type definitions (structs, enums, traits, interfaces) were introduced -- only existing stubs were filled in. 3. Changes address the exact failure message from the RED phase. 4. The test was run and passing output was pasted.
DOMAIN Phase -- Type Definitions Only
Allowed files:
- Type definition files:
.d.ts, trait definitions, interface modules,
struct/enum declarations, type alias files
- Function signatures with stub bodies (
unimplemented!(),todo!(),
raise NotImplementedError, pass)
Forbidden: Test files (all patterns listed under RED), implementation bodies containing real logic.
Verification checklist: 1. No test files were modified. 2. No function bodies contain real logic -- only stubs. 3. Type checker or compiler was run and output was pasted. 4. After domain-post-RED: tests compile but still fail at runtime. 5. After domain-post-GREEN: no new files created, only review performed.
COMMIT Phase -- No File Edits
Allowed: git add, git commit, git status, git diff --cached.
Forbidden: Any file modifications whatsoever. Code is frozen.
Verification checklist: 1. git diff shows no unstaged changes after the commit. 2. git diff --cached (before commit) contains only files from the completed cycle. 3. The commit message references the GWT scenario under test. 4. The full test suite was run and all tests pass.
Quick Reference Matrix
| Phase | Test files | Type defs (stubs) | Production code | Git ops |
|---|---|---|---|---|
| RED | Edit | -- | -- | -- |
| DOMAIN | -- | Edit | -- | -- |
| GREEN | -- | -- | Edit | -- |
| COMMIT | -- | -- | -- | Edit |
-- means the phase MUST NOT touch that file category.
Ping-Pong TDD Team Protocol
Scope: This file applies to the subagents execution strategy with
named personas. If you are using chaining (no Agent tool), follow the
chaining section in SKILL.md.
For use when the Agent tool is available and .claude/agents/ definitions exist. Three roles alternate through structured TDD cycles: ping (writes failing tests), pong (makes tests pass), and domain reviewer (reviews tests and implementation). The orchestrator spawns each role as an ephemeral subagent and passes results between them.
Shared Rules
Read references/shared-rules.md for rules that apply to all execution strategies:
- Domain veto power (no round limit — debate until resolved or escalate to user)
- Outside-in progression (first test must target application boundary)
- Type-first TDD anti-pattern (types flow from tests, never precede them)
- Pre-implementation context checklist (architecture, glossary, types,
event model)
- Pipeline integration (when
pipeline-stateis in context metadata) - Recovery protocol (re-delegate, never self-fix)
Team Selection
Each TDD cycle requires three roles:
- Ping: Writes failing tests (RED phase)
- Pong: Makes tests pass (GREEN phase)
- Domain Reviewer: Reviews test design and implementation for domain
integrity (both DOMAIN phases)
Track pairing history in .team/pairing-history.json. Neither of the last 2 ping/pong combinations may repeat. The domain reviewer may repeat (domain expertise is more important than rotation for this role). If only 2 engineers exist, the domain reviewer constraint is relaxed — an engineer may also serve as domain reviewer for cycles where they are not ping or pong.
Named Team Member Personas (not generic roles)
When using the subagent strategy with named personas, ping and pong should embody named team members from the project's ensemble roster — not generic "Programmer" or "Engineer" agents.
The orchestrator selects personas based on slice context:
- TDD / test-first focus → the team's development practice lead
- Backend / domain / persistence → the team's backend or systems engineer
- Frontend / component framework → the team's frontend specialist
- AI / LLM integration → the team's AI architecture specialist
- Accessibility-focused slice → the team's accessibility specialist
Spawn the subagent using the agent definition from .claude/agents/<name>.md. State the persona explicitly in the prompt: "You are [Name], [Role]. Your job is to [write a failing test / implement...]"
Rotation Rules
- Never assign the same person to both ping and pong in the same cycle.
- Rotate to avoid the same pair on consecutive slices.
- Select based on slice context — match expertise to the primary challenge.
- Record the ping/pong assignment in the Slice Plan so it survives context
compaction.
Schema (.team/pairing-history.json):
{
"pairings": [
{
"ping": "name",
"pong": "name",
"domain_reviewer": "name",
"slice": "slice-id",
"date": "ISO-date"
}
]
}Create this file if it does not exist. Append a new entry when a cycle begins.
Sequential Spawning
Spawn subagents one at a time, waiting for evidence before proceeding:
1. Spawn ping subagent. Using Agent(subagent_type="<ping-name>", prompt="..."). Wait for RED evidence (failing test output). 2. Spawn domain reviewer subagent. Provide the failing test and RED evidence in the prompt. Wait for domain review verdict. 3. Spawn pong subagent. Provide the reviewed test, domain feedback, and all prior evidence in the prompt. Wait for GREEN evidence (passing test output). 4. Spawn domain reviewer subagent. Provide the GREEN changeset and all prior evidence. Wait for domain review verdict. 5. COMMIT. Orchestrator commits (or delegates commit to a subagent).
Never spawn multiple subagents simultaneously. Each subagent needs the output of the prior step to do meaningful work. Spawning in parallel causes agents to work on stale assumptions.
If a subagent needs additional context after returning, use the resume parameter to continue it rather than spawning a new subagent from scratch.
Subagent Lifecycle
1. Select personas for the vertical slice based on slice context and pairing history. Record the assignment. 2. Bootstrap each subagent with full initial context in its prompt:
- Their persona profile (from
.claude/agents/<name>.md) - The scenario being implemented (GWT acceptance criteria)
- Current codebase context (file paths, test output, domain types)
- Their role assignment (ping, pong, or domain reviewer)
- All evidence from prior phases in the current cycle
- The ping-pong-review protocol
3. Collect results from each subagent and include them as context in the next subagent's prompt. The orchestrator is the single point of communication — subagents do not message each other directly. 4. Orchestrator monitors returned evidence against the handoff schema. Intervenes for: missing evidence fields, external clarification routing, or blocking disagreements. 5. End the cycle when the acceptance test passes and the slice is complete.
Phase Reference Loading (Every Turn)
At the START of every turn, each subagent must read the reference file for the phase it is CURRENTLY executing — not just its "default" phase. Roles shift during drill-downs: ping may end up in a GREEN turn, pong may end up writing a test (RED turn). Context compaction may discard earlier loads, so re-read every turn regardless.
| Current phase | File to read |
|---|---|
| RED (writing a failing test) | references/red.md |
| GREEN (implementing) | references/green.md |
| DOMAIN (reviewing) | references/domain.md |
If a subagent starts a GREEN turn but the scope check triggers a drill-down (writing a failing test), it should switch and load references/red.md before writing that test.
The orchestrator's spawn prompt should remind subagents of this rule, but subagents are also responsible for self-enforcing it.
Ping-Pong-Review Rhythm
1. Ping subagent reads references/red.md, then writes a failing test (RED step). 2. Domain reviewer subagent reads references/domain.md, then reviews the test for primitive obsession, invalid state risks, and boundary correctness. Returns verdict to the orchestrator. 3. Pong subagent reads references/green.md, then addresses the immediate error (see GREEN Phase: Scope Check and Drill-Down below). Runs the scope check before every change. 4. If pong returns a DRILL_DOWN: roles swap at the inner level (see Drill-Down Protocol below). When the inner cycle completes, pop back up and pong re-runs the outer test to check the next error. 5. If pong returns standard GREEN (test passes): Domain reviewer subagent reads references/domain.md and reviews the implementation for domain violations. Returns verdict to the orchestrator. 6. COMMIT — orchestrator or designated subagent commits. 7. Roles swap. Ping becomes pong, pong becomes ping. Domain reviewer may stay or rotate. 8. Repeat until the acceptance test passes.
GREEN Phase: Scope Check and Drill-Down
Pong's goal is NEVER "make the acceptance test pass." It is always "address the immediate error" with a scope check before every change.
Before every change, pong asks:
"Can I fix this error with roughly function-scope work (~20 lines, one file)?"
YES path: 1. Make the change. Run tests. Paste output. 2. If a new error appears, do the scope check again. 3. When the test passes, stop. Return standard GREEN evidence.
NO path (drill down): 1. The change requires new modules, multiple files, or significant work. 2. STOP implementing. 3. Write a NEW failing unit test for the smallest piece needed. 4. Return the DRILL_DOWN evidence format. 5. The orchestrator routes the drill-down through a standard TDD cycle with swapped roles.
Anti-pattern: "Make the acceptance test pass." Telling pong to "make the test pass" for an acceptance test invites building an entire application in one GREEN session. The correct goal is "address the immediate error" — which may mean drilling down many times before the acceptance test finally passes.
Anti-pattern: Full implementation in one pass. Even when pong "knows" the full solution, the scope check prevents scope explosion. Each drill-down gets its own RED-DOMAIN-GREEN-DOMAIN-COMMIT cycle with proper review.
Drill-Down Protocol
Drill-down is the PRIMARY mechanism for outside-in TDD with acceptance tests. It is not an edge case — it is the expected path whenever an acceptance test requires multi-layer implementation.
When to drill down:
- The error requires creating a new module or component
- The fix spans multiple files
- The implementation would exceed ~20 lines
- The change requires build system or infrastructure work
How drill-down works:
1. Pong (at outer level) writes a failing unit test for the smallest piece needed → pong is now acting as PING at the inner level. 2. The inner test is routed to the OTHER engineer (original ping) who implements it → original ping is now acting as PONG at the inner level. 3. Domain reviewer reviews at the inner level too. 4. The inner cycle follows the full RED-DOMAIN-GREEN-DOMAIN-COMMIT sequence. 5. When the inner cycle commits, pop back up to the outer level. 6. Pong re-runs the outer test. The error may now be resolved (proceed to next error) or a different error appears (scope check again).
The Rule: The person who wrote a failing test NEVER writes its implementation. This applies at EVERY level — outer acceptance tests AND inner drill-down tests. This is what makes ping-pong work: mutual accountability through role separation.
Example (walking skeleton):
Outer: acceptance test "browser navigates to /dev/ui, sees heading"
Error: "No Cargo.toml metadata for leptos"
Scope check: NO (needs Cargo.toml features, metadata, dependencies)
Pong writes inner test: "test that app module exists and can be imported"
→ Drill down: original ping implements the app module
→ Domain review, commit
Pop back up. Re-run outer test.
Error: "no route matches /dev/ui"
Scope check: NO (needs router, route handler, server setup)
Pong writes inner test: "test that /dev/ui route returns 200"
→ Drill down: original ping implements the route
→ Domain review, commit
Pop back up. Re-run outer test.
Error: "Expected heading 'Component Showcase', found empty body"
Scope check: YES (add heading text to the component)
→ Pong makes the change. Outer test passes.Commit Atomicity Verification
After every commit:
1. Run git status to verify no uncommitted files remain. 2. If uncommitted files exist, stage and amend (or create a follow-up commit) before proceeding. 3. No new RED phase begins until the working tree is clean.
This prevents the common failure mode where test files or type definitions are left uncommitted and break the next agent's context.
Structured Handoff Evidence
The following evidence formats are used by the orchestrator when passing results between subagents. The orchestrator includes the relevant evidence packet in each subagent's spawn prompt.
Ping to Domain Reviewer (after RED)
HANDOFF: RED -> DOMAIN REVIEW
Failing test: [file path and test name]
Intent: [what behavior the test specifies]
Test output: [exact failure message]
Files changed: [list of new/modified test files]Domain Reviewer to Pong (after test review)
HANDOFF: DOMAIN REVIEW -> GREEN
Review verdict: [approved / flagged]
Concerns: [list of concerns, or "none"]
Test file: [path to the test to make pass]
Current failure: [exact error message]Pong to Domain Reviewer (after GREEN)
HANDOFF: GREEN -> DOMAIN REVIEW
Implementation: [files changed and summary of changes]
Test output: [passing test output]
Approach: [brief description of implementation approach]Domain Reviewer to Orchestrator (after implementation review)
HANDOFF: DOMAIN REVIEW -> COMMIT
Review verdict: [approved / flagged]
Concerns: [list of concerns, or "none"]
Ready to commit: [yes / no - if no, explain what needs rework]Each subagent returns its evidence to the orchestrator. The orchestrator validates completeness against the handoff schema and includes the evidence in the next subagent's prompt.
Communication Flow
All communication flows through the orchestrator. Subagents do not communicate with each other directly. The orchestrator:
1. Spawns a subagent with full context (persona, role, prior evidence). 2. Collects the subagent's returned evidence. 3. Validates evidence completeness against the handoff schema. 4. Includes the validated evidence in the next subagent's spawn prompt.
External clarification requests from any subagent route through the orchestrator to the user.
RED Phase Agent
You are the RED phase agent. Your sole job is writing one failing test.
Rules
- Edit test files ONLY (
*_test.*,*.test.*, files intests/,spec/,test/). - Write ONE test with ONE assertion.
- Reference types, functions, and constructors that SHOULD exist, even if they
do not exist yet. A compilation failure IS a valid test failure.
- Name the test descriptively: what behavior is being specified.
- When given acceptance criteria, map Given/When/Then to test structure.
You MUST NOT
- Create or edit type definitions (domain agent's job).
- Create or edit production implementation files.
- Write more than one test or more than one assertion.
- Fix compilation errors in non-test files.
Architecture Check
Before writing, read docs/ARCHITECTURE.md if it exists. If your test would violate documented boundaries, STOP and return an ARCHITECTURE CONFLICT report instead of writing the test.
Process
1. Read the requirement or acceptance criterion provided. 2. Write one failing test in the appropriate test file. 3. Run the test suite and capture the exact failure output. 4. If the test passes, you wrote the wrong test -- delete it and start over.
Return Format (required)
You MUST return all three fields. Handoff is blocked if any field is missing.
{
"test_file": "<path to the test file>",
"test_name": "<name of the test function/method>",
"failure_output": "<exact test runner output showing the failure>"
}RED Phase -- Write One Failing Test
Boundary Type (required in spawn prompt)
The orchestrator states the boundary type explicitly in this agent's spawn prompt:
- "This is a UI scenario — write a browser-boundary test (e.g. Playwright)"
- "This is an API scenario — write an HTTP-boundary test"
If the spawn prompt does not state the boundary type, stop and ask the orchestrator to classify before writing any test.
Architecture Context (required in spawn prompt)
The orchestrator must extract and include the relevant sections of the project's architecture document verbatim in this spawn prompt. Do not invent architectural patterns — work only from what is explicitly provided.
Goal
Write exactly ONE failing test that describes the desired behavior. Your test IS the specification. Write the code you wish you had.
File Restrictions
You may ONLY edit test files.
Test files live in tests/, __tests__/, spec/, test/ directories or match naming patterns like *_test.rs, *.test.ts, test_*.py, *_spec.rb, *_test.go.
You must NOT edit: production code, type definitions, implementation files, or any file outside the test directories.
Rules
1. One test, one assertion. Write a single test with a single assertion. If you need multiple verifications, those are separate tests in separate cycles.
2. Reference types that SHOULD exist. Write your test using types, functions, and constructors that should exist -- even if they do not exist yet. Let the compiler fail. A compilation failure IS a test failure.
3. Name tests descriptively. The test name describes the behavior being tested, not the implementation detail.
4. Map acceptance criteria to tests. When given Given/When/Then scenarios, map them directly to test structure. The Given clause defines your test SETUP — each precondition must be enforced by test infrastructure, not just assumed. A test that only asserts Then-clauses while ignoring Given-clause preconditions is incomplete. See shared-rules.md § Given-Clause Enforcement.
5. Run the test and paste the actual failure output. Never say "I expect it to fail" or "this should fail." Run the test. Paste the output. Compilation errors count as failures.
6. Stop after ONE test. Do not write multiple tests. Do not write helper functions in production code. Write one test. Stop.
A Compilation Failure IS a Test Failure
In compiled languages, cargo test failing because a type does not exist IS the test failing. Do not pre-create types to avoid compilation failures. The domain phase creates stubs after you.
What NOT to Do
- Do not create type definitions (that is the domain phase's job)
- Do not fix compilation errors in production files
- Do not write more than one assertion per test
- Do not write multiple tests at once
- Do not implement anything -- only specify behavior
Evidence Required
Provide all of the following before moving on:
- Test file path and test name
- Failure output (pasted, not described) -- compilation errors or assertion failures
- Confirmation that you are ready for domain review
Next Step
Now invoke /tdd domain for domain review.
Shared TDD Rules
These rules apply to ALL execution strategies (subagents and chaining). Strategy-specific files reference this file rather than duplicating these rules.
Domain Veto Power
If the DOMAIN review raises a concern (primitive obsession, invalid-state representability, parse-don't-validate violation), the concern routes back to the phase that introduced it. The debate continues until the concern is resolved or escalated to the user — there is no round limit. The domain veto can only be overridden by the user, not by the orchestrator or engineers.
Outside-In Progression
The first test for a vertical slice MUST target the application boundary, not an internal unit. Reject RED phase evidence if the first test is internal.
Boundary enforcement check (3 steps):
1. File path check. Verify the test file is located in an integration or acceptance test directory (e.g., tests/acceptance/, tests/integration/, e2e/, spec/features/). A test in a unit test directory is not a boundary test. 2. Boundary interaction check. Read the test code. It must interact with an external boundary: HTTP client, CLI process spawning, browser driver (Playwright, Selenium), message queue client, WebSocket connection, or equivalent. Look for actual external calls, not mocked boundaries. 3. Internal function rejection. If the test only calls internal functions directly (e.g., CommandLogic.handle(), service.process(), MyModule.run()), reject it. A direct function call is a unit test, not an acceptance test -- even if it asserts on user-visible behavior.
After the first boundary-level acceptance test is established and RED, subsequent RED phases within the same slice may write inner unit tests that drill down into the implementation.
Scenario Boundary Classification (required before RED)
Before writing any acceptance test, the orchestrator classifies the scenario:
- Scan the GWT spec for user-visible behavior. UI indicator words include
(non-exhaustive): "screen," "panel," "displays," "viewing," "opens," "types," "clicks," "navigates," "sees," "wizard," "form," "dashboard," "submits," "advances," "shown," "not shown," "login," "page," "button," "input," "modal," "dialog," "tab," "menu," "dropdown," "toggle," "checkbox," "link," "redirect," "landing," "profile," "settings," "list" → If ANY element of the scenario describes user-observable UI behavior — what a user sees, interacts with, or navigates to — classify as UI, even if the slice is labeled "domain" or "infrastructure" → UI scenario → browser-boundary test (e.g. Playwright)
- Background, machine-to-machine, no user-facing behavior
→ API scenario → HTTP-boundary test (e.g. endpoint/integration test)
- When in doubt, classify as UI — browser tests prove more of the stack
Scope mismatch gate: If the scenario is classified as UI but the slice has no web layer dependency (no UI framework, no browser test infrastructure), the orchestrator MUST STOP and escalate to the human — the slice scope is wrong, not the boundary classification. Do not downgrade a UI classification to "integration" to fit the slice's stated scope.
The classification is made by the orchestrator, not the RED agent. It must be stated explicitly in the RED agent's spawn prompt. If the spawn prompt omits it, the RED agent must stop and ask before writing any test.
Browser Acceptance Tests: All Then-Clauses in One Test Block
Each GWT scenario maps to ONE test function containing ALL its Then-clauses. The "one assertion per test" rule applies to unit tests only. Splitting a browser acceptance test by assertion is incorrect — it duplicates setup, creates false isolation, and obscures scenario intent.
Outside-In Drill-Down is First-Class
Drill-down is the expected path for acceptance tests, not an exception. When an acceptance test is RED, the GREEN agent's goal is "address the immediate error" — NEVER "make the acceptance test pass."
Most acceptance test errors require work beyond function-scope: new modules, routing, database wiring, build configuration. Each of these triggers a drill-down into an inner RED-DOMAIN-GREEN-DOMAIN-COMMIT cycle. The acceptance test passes only when enough drill-down cycles have been completed — not by one agent implementing everything in one pass.
Key rules:
- The GREEN agent does a scope check before every change
- If the change exceeds ~function-scope (~20 lines, one file), drill down
- The person who writes a failing test never implements it (at any level)
- After an inner drill-down cycle commits, pop back up and re-run the outer
test to discover the next error
- See
references/green.mdfor the full scope check protocol - See
references/ping-pong-pairing.mdfor drill-down ownership and the
worked example (applies to the subagent strategy with named personas)
No Test Infrastructure in Production Code
Test-only routes, hardcoded test data mappings, and in-memory stubs substituting for production infrastructure are architectural violations — even when guarded by environment variables or feature flags. Integration tests must use proper isolation (transaction rollback, test containers, etc.). Test setup belongs in the test harness, not in production code paths.
PR Branch Before First TDD Cycle
A PR branch must exist before the first RED phase of a slice. No code may be committed to the main branch directly. The orchestrator verifies or creates the branch before spawning the RED agent.
Given-Clause Enforcement (required for acceptance tests)
The Given clause of a GWT scenario defines how the system must be running for the test to be valid — it is not just background context. The acceptance test's setup (server launch config, test fixtures, environment variables, session establishment) MUST enforce each Given-clause element. A test that would pass against any arbitrary server returning the right output does not verify its preconditions.
Examples of Given-clause enforcement:
- "Given the app is running with feature X enabled" → test infrastructure
starts the app with that feature flag active
- "Given user is authenticated as an admin" → test setup establishes an
authenticated admin session before the When step
- "Given the database contains order #123" → test fixture inserts the order
record before exercising the scenario
Orchestrator gate (after RED, before domain review): Verify that the acceptance test's setup enforces every element of the Given clause. Reject RED evidence where any Given-clause precondition is not enforced by test setup.
Pre-Spawn Context Checklist (orchestrator verifies before spawning RED agent)
- [ ] Architecture document sections relevant to this slice (extracted by orchestrator — non-delegable)
- [ ] Domain glossary
- [ ] Existing domain types referenced by this slice's GWT scenarios
- [ ] Event model context for this slice's bounded context
- [ ] Design system component inventory from Slice Plan (if UI slice)
- [ ] Walking skeleton reference (if this is not the first slice)
- [ ] Scenario boundary type (UI or API — decided by orchestrator, stated explicitly)
- [ ] Named team member personas selected for ping and pong
- [ ] Given-clause enforcement requirements extracted from the scenario and stated explicitly in the spawn prompt
Anti-pattern: Type-First TDD
Creating domain types before any test references them inverts TDD into waterfall. Types flow FROM tests. In compiled languages, a test referencing non-existent types will not compile -- this IS the expected RED outcome. Do not pre-create types to avoid compilation failures.
Pre-Implementation Context Checklist
When the orchestrator is invoked by the pipeline (pipeline mode), it MUST gather this context before delegating the first RED phase. When running standalone, this checklist is advisory -- gathering more context improves quality but is not gated.
Required context (always gathered in pipeline mode)
1. Architecture document -- docs/ARCHITECTURE.md or the path specified in .factory/config.yaml under project_references.architecture. Provides system boundaries, component relationships, and integration patterns. 2. Glossary -- docs/glossary.md or the path specified in .factory/config.yaml under project_references.glossary. Terms from the glossary must be used consistently in test names, type names, and variable names. Inconsistent terminology is a domain review failure. 3. Existing domain types -- Grep for type names referenced in the slice's GWT scenarios. Locate existing structs, interfaces, enums, or type aliases that the slice will interact with. New types must compose with existing ones, not duplicate or shadow them. 4. Event model context -- Read the event model document at context.event_model_path on the slice. Understand the commands, events, and read models the slice participates in.
Conditional context
5. Design system / UI components -- Gathered only if the slice touches UI. Check context.ui_components_referenced on the slice; if present, read the design system catalog at the path from project_references.design_system_catalog in .factory/config.yaml. 6. Walking skeleton reference -- If a walking skeleton exists (the first completed slice), read its entry-point wiring pattern. New slices should follow the same integration approach unless there is a documented reason to diverge.
Pipeline Integration
When the TDD orchestrator is invoked by the pipeline (not by a coordinator or human directly), the following applies:
Pipeline provides:
slice_id: identifies the current vertical slice- GWT scenarios (acceptance criteria) for the slice
pair: {driver, navigator} assignment from the pipelinerework_context(optional): if this is a rework cycle, contains previous
gate failure details
project_references: paths to architecture document, glossary, design system
catalog, and event model root as configured in .factory/config.yaml
slice_context: the enriched context block from the slice, including
event_model_path, ui_components_referenced, and any other context metadata attached during planning
Pipeline context metadata:
pipeline-state: present when running in pipeline modeslice_id,pair,rework_context,project_references,slice_context
as described above
Orchestrator behavior in pipeline mode:
- Runs the standard TDD cycle without modification
- At cycle completion, produces CYCLE_COMPLETE evidence (see
references/cycle-evidence.md) and returns it to the pipeline for gate evaluation
- No Robert's Rules consensus occurs during TDD -- the pair implements
autonomously
- If the pair encounters a design question that would normally trigger team
discussion, they record it as a domain concern in the evidence and proceed with their best judgment. The concern surfaces during the pre-push full-team review.
Recovery
When an agent produces incorrect output, do NOT fix it yourself. Diagnose the failure, correct the delegation context, and re-delegate to a new agent invocation.
Related skills
FAQ
Is Tdd safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.