---
type: skill
domain: development
links: [Corpus_Callosum/CONSTITUTION.md, PULSE_OS.md]
---

# TEST_DRIVEN.md
> **ROLE:** QA ENGINEER
> **TRIGGER:** "TDD MODE"

## Protocol: 5-Step Red-Green-Refactor

1. **Brain Check** -- Run `brain_query.py --query "test failures <module>"` to find past test issues. Apply lessons before writing new tests.
2. **RED -- Write Failing Test** -- Create the test FIRST. Name it `test_<behavior>_<expected_result>`. Assert the exact behavior you want. Run it -- it MUST fail. If it passes, your test is wrong.
3. **GREEN -- Minimal Implementation** -- Write the bare minimum code to make the test pass. No extra features, no "while I'm here" additions. Run the test -- it MUST pass.
4. **REFACTOR -- Clean Without Breaking** -- Improve code structure (extract functions, rename variables, remove duplication). Run ALL tests after each change. If any test fails, undo the refactor.
5. **Coverage Gate** -- Run `pytest --cov=<module> --cov-fail-under=80`. Check the report for untested branches. Add tests for any uncovered critical paths.

## Test Pyramid

| Layer | Coverage Target | What to Test | Mock Strategy |
|-------|----------------|--------------|---------------|
| Unit (70%) | Pure functions, validators, parsers | Mock external deps, DB, APIs |
| Integration (20%) | Module interactions, file I/O, DB queries | Mock only network/external APIs |
| E2E (10%) | Full CLI flows, daemon boot/shutdown | No mocks -- real system |

## Good Example

```python
# RED: test_brain_query_returns_lessons.py
def test_brain_query_finds_matching_lesson(tmp_path):
    lessons_file = tmp_path / "auto_lessons.md"
    lessons_file.write_text("- Use filelock for atomic task claiming\n")
    results = brain_search(str(tmp_path), "filelock")
    assert len(results) >= 1
    assert "filelock" in results[0].lower()

# GREEN: implement brain_search() with minimal grep logic
# REFACTOR: extract file reading into _load_region()
```

## Anti-Patterns

- **Test-after development** -- Writing tests after implementation confirms bugs, not behavior. Test FIRST.
- **Assertion-free tests** -- A test that calls code but asserts nothing proves nothing. Every test needs >= 1 meaningful assertion.
- **Mocking everything** -- Over-mocking makes tests pass when real code fails. Mock boundaries (network, DB), not internal logic.

## Tools to Use

- `brain_query.py --query "test failures <module>"` -- Find past test issues
- `pulse_save.py --agent <you> --learnings "test pattern: <what worked>"` -- Record test insights
- `pulse_relay.py --tasks "Add tests for <module>:development:fast"` -- Delegate test writing

## Verification Checklist

- [ ] Brain queried for past test failures in this module
- [ ] Test written BEFORE implementation (RED confirmed)
- [ ] Implementation is minimal (GREEN, no extras)
- [ ] All tests pass after refactor
- [ ] Coverage >= 80%, pyramid ratio approximately 70/20/10
