@frankzhang2026/opencode-android-orchestrator 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +28 -1
  2. package/README.md +81 -22
  3. package/THIRD_PARTY_NOTICES.md +15 -11
  4. package/dist/cli.js +2 -0
  5. package/dist/cli.js.map +1 -1
  6. package/dist/config/verification-policy.d.ts +20 -0
  7. package/dist/config/verification-policy.d.ts.map +1 -0
  8. package/dist/config/verification-policy.js +59 -0
  9. package/dist/config/verification-policy.js.map +1 -0
  10. package/dist/doctor/installation.d.ts.map +1 -1
  11. package/dist/doctor/installation.js +46 -3
  12. package/dist/doctor/installation.js.map +1 -1
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -2
  16. package/dist/index.js.map +1 -1
  17. package/dist/installer/adaptive-templates.d.ts +9 -6
  18. package/dist/installer/adaptive-templates.d.ts.map +1 -1
  19. package/dist/installer/adaptive-templates.js +13 -0
  20. package/dist/installer/adaptive-templates.js.map +1 -1
  21. package/dist/installer/index.d.ts +1 -1
  22. package/dist/installer/index.d.ts.map +1 -1
  23. package/dist/installer/index.js +1 -1
  24. package/dist/installer/index.js.map +1 -1
  25. package/dist/installer/init.d.ts +1 -1
  26. package/dist/installer/init.d.ts.map +1 -1
  27. package/dist/installer/init.js.map +1 -1
  28. package/dist/installer/install-manifest.d.ts.map +1 -1
  29. package/dist/installer/install-manifest.js +13 -1
  30. package/dist/installer/install-manifest.js.map +1 -1
  31. package/dist/installer/opencode-config.d.ts +3 -4
  32. package/dist/installer/opencode-config.d.ts.map +1 -1
  33. package/dist/installer/opencode-config.js +1 -3
  34. package/dist/installer/opencode-config.js.map +1 -1
  35. package/dist/installer/upgrade.d.ts.map +1 -1
  36. package/dist/installer/upgrade.js +34 -2
  37. package/dist/installer/upgrade.js.map +1 -1
  38. package/dist/plugin/index.d.ts +2 -0
  39. package/dist/plugin/index.d.ts.map +1 -1
  40. package/dist/plugin/index.js +32 -0
  41. package/dist/plugin/index.js.map +1 -1
  42. package/docs/MIGRATION.md +27 -10
  43. package/docs/SECURITY.md +24 -7
  44. package/docs/TROUBLESHOOTING.md +13 -6
  45. package/package.json +3 -1
  46. package/resources/third-party/superpowers-v6.2.0/LICENSE +21 -0
  47. package/resources/third-party/superpowers-v6.2.0/PROVENANCE.md +21 -0
  48. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-brainstorming/SKILL.md +43 -0
  49. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-systematic-debugging/SKILL.md +288 -0
  50. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-systematic-debugging/references/condition-based-waiting-example.ts +158 -0
  51. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-systematic-debugging/references/condition-based-waiting.md +115 -0
  52. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-systematic-debugging/references/defense-in-depth.md +122 -0
  53. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-systematic-debugging/references/root-cause-tracing.md +169 -0
  54. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-systematic-debugging/scripts/find-polluter.sh +72 -0
  55. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-test-driven-development/SKILL.md +327 -0
  56. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-test-driven-development/references/writing-good-tests.md +197 -0
  57. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-verification-before-completion/SKILL.md +125 -0
  58. package/resources/third-party/superpowers-v6.2.0/skills/android-orchestrator-writing-plans/SKILL.md +50 -0
  59. package/templates/.opencode/agents/scheduled-coder.md +3 -4
  60. package/templates/.opencode/agents/scheduled-planner.md +5 -5
  61. package/templates/.opencode/agents/scheduled-reviewer.md +1 -2
  62. package/templates/.opencode/skills/scheduled-quality-coder/SKILL.md +11 -9
  63. package/templates/.opencode/skills/scheduled-quality-orchestrator/SKILL.md +2 -1
  64. package/templates/.opencode/skills/scheduled-quality-reviewer/SKILL.md +4 -3
  65. package/templates/README.md +10 -3
  66. package/templates/automation/config.json +8 -9
  67. package/templates/automation/config.schema.json +6 -11
  68. package/templates/automation/task-contract.schema.json +7 -7
  69. package/templates/automation/tasks/TASK-TEMPLATE.json.example +6 -6
  70. package/templates/scripts/automation/claim-task.sh +23 -8
  71. package/templates/scripts/automation/lib.sh +37 -3
  72. package/templates/scripts/automation/orchestrate-task.sh +1 -1
  73. package/templates/scripts/automation/preflight.sh +0 -3
  74. package/templates/scripts/automation/tests/run-tests.sh +36 -15
  75. package/templates/scripts/automation/validate-contract.sh +7 -2
  76. package/templates/scripts/automation/verify-integration.sh +2 -9
  77. package/templates/scripts/automation/verify-task.sh +2 -9
@@ -0,0 +1,169 @@
1
+ # Root Cause Tracing
2
+
3
+ ## Overview
4
+
5
+ Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom.
6
+
7
+ **Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source.
8
+
9
+ ## When to Use
10
+
11
+ ```dot
12
+ digraph when_to_use {
13
+ "Bug appears deep in stack?" [shape=diamond];
14
+ "Can trace backwards?" [shape=diamond];
15
+ "Fix at symptom point" [shape=box];
16
+ "Trace to original trigger" [shape=box];
17
+ "BETTER: Also add defense-in-depth" [shape=box];
18
+
19
+ "Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"];
20
+ "Can trace backwards?" -> "Trace to original trigger" [label="yes"];
21
+ "Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"];
22
+ "Trace to original trigger" -> "BETTER: Also add defense-in-depth";
23
+ }
24
+ ```
25
+
26
+ **Use when:**
27
+ - Error happens deep in execution (not at entry point)
28
+ - Stack trace shows long call chain
29
+ - Unclear where invalid data originated
30
+ - Need to find which test/code triggers the problem
31
+
32
+ ## The Tracing Process
33
+
34
+ ### 1. Observe the Symptom
35
+ ```
36
+ Error: git init failed in ~/project/packages/core
37
+ ```
38
+
39
+ ### 2. Find Immediate Cause
40
+ **What code directly causes this?**
41
+ ```typescript
42
+ await execFileAsync('git', ['init'], { cwd: projectDir });
43
+ ```
44
+
45
+ ### 3. Ask: What Called This?
46
+ ```typescript
47
+ WorktreeManager.createSessionWorktree(projectDir, sessionId)
48
+ → called by Session.initializeWorkspace()
49
+ → called by Session.create()
50
+ → called by test at Project.create()
51
+ ```
52
+
53
+ ### 4. Keep Tracing Up
54
+ **What value was passed?**
55
+ - `projectDir = ''` (empty string!)
56
+ - Empty string as `cwd` resolves to `process.cwd()`
57
+ - That's the source code directory!
58
+
59
+ ### 5. Find Original Trigger
60
+ **Where did empty string come from?**
61
+ ```typescript
62
+ const context = setupCoreTest(); // Returns { tempDir: '' }
63
+ Project.create('name', context.tempDir); // Accessed before beforeEach!
64
+ ```
65
+
66
+ ## Adding Stack Traces
67
+
68
+ When you can't trace manually, add instrumentation:
69
+
70
+ ```typescript
71
+ // Before the problematic operation
72
+ async function gitInit(directory: string) {
73
+ const stack = new Error().stack;
74
+ console.error('DEBUG git init:', {
75
+ directory,
76
+ cwd: process.cwd(),
77
+ nodeEnv: process.env.NODE_ENV,
78
+ stack,
79
+ });
80
+
81
+ await execFileAsync('git', ['init'], { cwd: directory });
82
+ }
83
+ ```
84
+
85
+ **Critical:** Use `console.error()` in tests (not logger - may not show)
86
+
87
+ **Run and capture:**
88
+ ```bash
89
+ npm test 2>&1 | grep 'DEBUG git init'
90
+ ```
91
+
92
+ **Analyze stack traces:**
93
+ - Look for test file names
94
+ - Find the line number triggering the call
95
+ - Identify the pattern (same test? same parameter?)
96
+
97
+ ## Finding Which Test Causes Pollution
98
+
99
+ If something appears during tests but you don't know which test:
100
+
101
+ Use the bisection script `../scripts/find-polluter.sh`:
102
+
103
+ ```bash
104
+ ../scripts/find-polluter.sh '.git' 'src/**/*.test.ts'
105
+ ```
106
+
107
+ Runs tests one-by-one, stops at first polluter. See script for usage.
108
+
109
+ ## Real Example: Empty projectDir
110
+
111
+ **Symptom:** `.git` created in `packages/core/` (source code)
112
+
113
+ **Trace chain:**
114
+ 1. `git init` runs in `process.cwd()` ← empty cwd parameter
115
+ 2. WorktreeManager called with empty projectDir
116
+ 3. Session.create() passed empty string
117
+ 4. Test accessed `context.tempDir` before beforeEach
118
+ 5. setupCoreTest() returns `{ tempDir: '' }` initially
119
+
120
+ **Root cause:** Top-level variable initialization accessing empty value
121
+
122
+ **Fix:** Made tempDir a getter that throws if accessed before beforeEach
123
+
124
+ **Also added defense-in-depth:**
125
+ - Layer 1: Project.create() validates directory
126
+ - Layer 2: WorkspaceManager validates not empty
127
+ - Layer 3: NODE_ENV guard refuses git init outside tmpdir
128
+ - Layer 4: Stack trace logging before git init
129
+
130
+ ## Key Principle
131
+
132
+ ```dot
133
+ digraph principle {
134
+ "Found immediate cause" [shape=ellipse];
135
+ "Can trace one level up?" [shape=diamond];
136
+ "Trace backwards" [shape=box];
137
+ "Is this the source?" [shape=diamond];
138
+ "Fix at source" [shape=box];
139
+ "Add validation at each layer" [shape=box];
140
+ "Bug impossible" [shape=doublecircle];
141
+ "NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
142
+
143
+ "Found immediate cause" -> "Can trace one level up?";
144
+ "Can trace one level up?" -> "Trace backwards" [label="yes"];
145
+ "Can trace one level up?" -> "NEVER fix just the symptom" [label="no"];
146
+ "Trace backwards" -> "Is this the source?";
147
+ "Is this the source?" -> "Trace backwards" [label="no - keeps going"];
148
+ "Is this the source?" -> "Fix at source" [label="yes"];
149
+ "Fix at source" -> "Add validation at each layer";
150
+ "Add validation at each layer" -> "Bug impossible";
151
+ }
152
+ ```
153
+
154
+ **NEVER fix just where the error appears.** Trace back to find the original trigger.
155
+
156
+ ## Stack Trace Tips
157
+
158
+ **In tests:** Use `console.error()` not logger - logger may be suppressed
159
+ **Before operation:** Log before the dangerous operation, not after it fails
160
+ **Include context:** Directory, cwd, environment variables, timestamps
161
+ **Capture stack:** `new Error().stack` shows complete call chain
162
+
163
+ ## Real-World Impact
164
+
165
+ From debugging session (2025-10-03):
166
+ - Found root cause through 5-level trace
167
+ - Fixed at source (getter validation)
168
+ - Added 4 layers of defense
169
+ - 1847 tests passed, zero pollution
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env bash
2
+ # Bisection script to find which test creates unwanted files/state
3
+ # Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>
4
+ # Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'
5
+
6
+ set -e
7
+
8
+ if [ $# -ne 2 ]; then
9
+ echo "Usage: $0 <file_to_check> <test_pattern>"
10
+ echo "Example: $0 '.git' 'src/**/*.test.ts'"
11
+ exit 1
12
+ fi
13
+
14
+ POLLUTION_CHECK="$1"
15
+ TEST_PATTERN="$2"
16
+
17
+ echo "🔍 Searching for test that creates: $POLLUTION_CHECK"
18
+ echo "Test pattern: $TEST_PATTERN"
19
+ echo ""
20
+
21
+ # Get list of test files (find . emits ./-prefixed paths, so accept the
22
+ # pattern written with or without a leading ./)
23
+ TEST_PATTERN="${TEST_PATTERN#./}"
24
+ # find -path can't match '**/' against zero directory levels, so a pattern
25
+ # like src/**/*.test.ts would skip src/top.test.ts; also try the pattern
26
+ # with '**/' collapsed to cover files directly under the base directory.
27
+ TEST_FILES=$(find . \( -path "./$TEST_PATTERN" -o -path "./${TEST_PATTERN//\*\*\//}" \) | sort -u)
28
+ if [ -z "$TEST_FILES" ]; then
29
+ TOTAL=0
30
+ else
31
+ TOTAL=$(printf '%s\n' "$TEST_FILES" | wc -l | tr -d ' ')
32
+ fi
33
+
34
+ echo "Found $TOTAL test files"
35
+ echo ""
36
+
37
+ COUNT=0
38
+ for TEST_FILE in $TEST_FILES; do
39
+ COUNT=$((COUNT + 1))
40
+
41
+ # Skip if pollution already exists
42
+ if [ -e "$POLLUTION_CHECK" ]; then
43
+ echo "⚠️ Pollution already exists before test $COUNT/$TOTAL"
44
+ echo " Skipping: $TEST_FILE"
45
+ continue
46
+ fi
47
+
48
+ echo "[$COUNT/$TOTAL] Testing: $TEST_FILE"
49
+
50
+ # Run the test
51
+ npm test "$TEST_FILE" > /dev/null 2>&1 || true
52
+
53
+ # Check if pollution appeared
54
+ if [ -e "$POLLUTION_CHECK" ]; then
55
+ echo ""
56
+ echo "🎯 FOUND POLLUTER!"
57
+ echo " Test: $TEST_FILE"
58
+ echo " Created: $POLLUTION_CHECK"
59
+ echo ""
60
+ echo "Pollution details:"
61
+ ls -la "$POLLUTION_CHECK"
62
+ echo ""
63
+ echo "To investigate:"
64
+ echo " npm test $TEST_FILE # Run just this test"
65
+ echo " cat $TEST_FILE # Review test code"
66
+ exit 1
67
+ fi
68
+ done
69
+
70
+ echo ""
71
+ echo "✅ No polluter found - all tests clean!"
72
+ exit 0
@@ -0,0 +1,327 @@
1
+ ---
2
+ name: android-orchestrator-test-driven-development
3
+ description: Apply strict RED-GREEN-REFACTOR while implementing an approved Android Orchestrator task
4
+ license: MIT
5
+ compatibility: opencode
6
+ metadata:
7
+ upstream: obra/superpowers@v6.2.0
8
+ workflow: scheduled-coding
9
+ ---
10
+
11
+ # Test-Driven Development (TDD)
12
+
13
+ ## Overview
14
+
15
+ Write the test first. Watch it fail. Write minimal code to pass.
16
+
17
+ **Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.
18
+
19
+ **Violating the letter of the rules is violating the spirit of the rules.**
20
+
21
+ ## When to Use
22
+
23
+ **Always:**
24
+ - New features
25
+ - Bug fixes
26
+ - Refactoring
27
+ - Behavior changes
28
+
29
+ **Exceptions (ask your human partner):**
30
+ - Throwaway prototypes
31
+ - Generated code
32
+ - Configuration files
33
+
34
+ Thinking "skip TDD just this once"? Stop. That's rationalization.
35
+
36
+ ## The Iron Law
37
+
38
+ ```
39
+ NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
40
+ ```
41
+
42
+ Write code before the test? Delete it. Start over.
43
+
44
+ **No exceptions:**
45
+ - Don't keep it as "reference"
46
+ - Don't "adapt" it while writing tests
47
+ - Don't look at it
48
+ - Delete means delete
49
+
50
+ Implement fresh from tests. Period.
51
+
52
+ ## Red-Green-Refactor
53
+
54
+ ```dot
55
+ digraph tdd_cycle {
56
+ rankdir=LR;
57
+ red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
58
+ verify_red [label="Verify fails\ncorrectly", shape=diamond];
59
+ green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
60
+ verify_green [label="Verify passes\nAll green", shape=diamond];
61
+ refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
62
+ next [label="Next", shape=ellipse];
63
+
64
+ red -> verify_red;
65
+ verify_red -> green [label="yes"];
66
+ verify_red -> red [label="wrong\nfailure"];
67
+ green -> verify_green;
68
+ verify_green -> refactor [label="yes"];
69
+ verify_green -> green [label="no"];
70
+ refactor -> verify_green [label="stay\ngreen"];
71
+ verify_green -> next;
72
+ next -> red;
73
+ }
74
+ ```
75
+
76
+ ### RED - Write Failing Test
77
+
78
+ Write one minimal test showing what should happen.
79
+
80
+ <Good>
81
+ ```typescript
82
+ test('retries failed operations 3 times', async () => {
83
+ let attempts = 0;
84
+ const operation = () => {
85
+ attempts++;
86
+ if (attempts < 3) throw new Error('fail');
87
+ return 'success';
88
+ };
89
+
90
+ const result = await retryOperation(operation);
91
+
92
+ expect(result).toBe('success');
93
+ expect(attempts).toBe(3);
94
+ });
95
+ ```
96
+ Clear name, tests real behavior, one thing
97
+ </Good>
98
+
99
+ <Bad>
100
+ ```typescript
101
+ test('retry works', async () => {
102
+ const mock = jest.fn()
103
+ .mockRejectedValueOnce(new Error())
104
+ .mockRejectedValueOnce(new Error())
105
+ .mockResolvedValueOnce('success');
106
+ await retryOperation(mock);
107
+ expect(mock).toHaveBeenCalledTimes(3);
108
+ });
109
+ ```
110
+ Vague name, tests mock not code
111
+ </Bad>
112
+
113
+ **Requirements:**
114
+ - One behavior
115
+ - Clear name
116
+ - Real code (no mocks unless unavoidable)
117
+
118
+ ### Verify RED - Watch It Fail
119
+
120
+ **MANDATORY. Never skip.**
121
+
122
+ ```bash
123
+ npm test path/to/test.test.ts
124
+ ```
125
+
126
+ Confirm:
127
+ - Test fails (not errors)
128
+ - Failure message is expected
129
+ - Fails because feature missing (not typos)
130
+
131
+ **Test passes?** You're testing existing behavior. Fix test.
132
+
133
+ **Test errors?** Fix error, re-run until it fails correctly.
134
+
135
+ ### GREEN - Minimal Code
136
+
137
+ Write simplest code to pass the test.
138
+
139
+ <Good>
140
+ ```typescript
141
+ async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
142
+ for (let i = 0; i < 3; i++) {
143
+ try {
144
+ return await fn();
145
+ } catch (e) {
146
+ if (i === 2) throw e;
147
+ }
148
+ }
149
+ throw new Error('unreachable');
150
+ }
151
+ ```
152
+ Just enough to pass
153
+ </Good>
154
+
155
+ <Bad>
156
+ ```typescript
157
+ async function retryOperation<T>(
158
+ fn: () => Promise<T>,
159
+ options?: {
160
+ maxRetries?: number;
161
+ backoff?: 'linear' | 'exponential';
162
+ onRetry?: (attempt: number) => void;
163
+ }
164
+ ): Promise<T> {
165
+ // YAGNI
166
+ }
167
+ ```
168
+ Over-engineered
169
+ </Bad>
170
+
171
+ Don't add features, refactor other code, or "improve" beyond the test.
172
+
173
+ ### Verify GREEN - Watch It Pass
174
+
175
+ **MANDATORY.**
176
+
177
+ ```bash
178
+ npm test path/to/test.test.ts
179
+ ```
180
+
181
+ Confirm:
182
+ - Test passes
183
+ - Other tests still pass
184
+ - Output pristine (no errors, warnings)
185
+
186
+ **Test fails?** Fix code, not test.
187
+
188
+ **Other tests fail?** Fix now.
189
+
190
+ ### REFACTOR - Clean Up
191
+
192
+ After green only:
193
+ - Remove duplication
194
+ - Improve names
195
+ - Extract helpers
196
+
197
+ Keep tests green. Don't add behavior.
198
+
199
+ ### Repeat
200
+
201
+ Next failing test for next feature.
202
+
203
+ ## Good Tests
204
+
205
+ | Quality | Good | Bad |
206
+ |---------|------|-----|
207
+ | **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
208
+ | **Clear** | Name describes behavior | `test('test1')` |
209
+ | **Shows intent** | Demonstrates desired API | Obscures what code should do |
210
+
211
+ When writing or changing any test, read
212
+ [references/writing-good-tests.md](references/writing-good-tests.md) for the
213
+ rules that keep tests honest:
214
+ - Name the production change that would make the test fail — before writing it
215
+ - Assert on real behavior, never on mock behavior
216
+ - Keep test-only code in test utilities, out of production classes
217
+ - Understand a dependency's side effects before mocking it
218
+
219
+ ## Common Rationalizations
220
+
221
+ | Excuse | Reality |
222
+ |--------|---------|
223
+ | "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
224
+ | "I'll test after" | Tests written after pass immediately — which proves nothing. They may test the wrong thing, test the implementation instead of the behavior, or miss the edge case you forgot. You never watched it fail, so you never proved it can catch the bug. Test-first forces that failure. |
225
+ | "Tests after achieve same goals (spirit not ritual)" | Tests-after answer "what does this do?"; tests-first answer "what should this do?" Tests written after are biased by the code you already wrote — you verify the cases you remembered, not the ones you'd have discovered. Coverage without proof the tests work. |
226
+ | "Already manually tested" | Manual testing is ad-hoc: no record of what you covered, no way to re-run it when the code changes, easy to forget cases under pressure. "Worked when I tried it" ≠ comprehensive. Automated tests run the same way every time. |
227
+ | "Deleting X hours is wasteful" | Sunk cost fallacy — that time is already spent either way. The real choice: rewrite with TDD (high confidence) vs. keep it and bolt tests on after (low confidence, likely bugs). Keeping code you can't trust is the waste. |
228
+ | "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
229
+ | "Need to explore first" | Fine. Throw away exploration, start with TDD. |
230
+ | "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
231
+ | "TDD will slow me down" | TDD IS the pragmatic path: catches bugs before commit, prevents regressions, lets you refactor without fear. "Pragmatic" shortcuts mean debugging in production — slower, not faster. |
232
+ | "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
233
+ | "Existing code has no tests" | You're improving it. Add tests for existing code. |
234
+
235
+ ## Red Flags - STOP and Start Over
236
+
237
+ - Code before test
238
+ - Test after implementation
239
+ - Test passes immediately
240
+ - Can't explain why test failed
241
+ - Tests added "later"
242
+ - Rationalizing "just this once"
243
+ - "I already manually tested it"
244
+ - "Tests after achieve the same purpose"
245
+ - "It's about spirit not ritual"
246
+ - "Keep as reference" or "adapt existing code"
247
+ - "Already spent X hours, deleting is wasteful"
248
+ - "TDD is dogmatic, I'm being pragmatic"
249
+ - "This is different because..."
250
+
251
+ **All of these mean: Delete code. Start over with TDD.**
252
+
253
+ ## Example: Bug Fix
254
+
255
+ **Bug:** Empty email accepted
256
+
257
+ **RED**
258
+ ```typescript
259
+ test('rejects empty email', async () => {
260
+ const result = await submitForm({ email: '' });
261
+ expect(result.error).toBe('Email required');
262
+ });
263
+ ```
264
+
265
+ **Verify RED**
266
+ ```bash
267
+ $ npm test
268
+ FAIL: expected 'Email required', got undefined
269
+ ```
270
+
271
+ **GREEN**
272
+ ```typescript
273
+ function submitForm(data: FormData) {
274
+ if (!data.email?.trim()) {
275
+ return { error: 'Email required' };
276
+ }
277
+ // ...
278
+ }
279
+ ```
280
+
281
+ **Verify GREEN**
282
+ ```bash
283
+ $ npm test
284
+ PASS
285
+ ```
286
+
287
+ **REFACTOR**
288
+ Extract validation for multiple fields if needed.
289
+
290
+ ## Verification Checklist
291
+
292
+ Before marking work complete:
293
+
294
+ - [ ] Every new function/method has a test
295
+ - [ ] Watched each test fail before implementing
296
+ - [ ] Each test failed for expected reason (feature missing, not typo)
297
+ - [ ] Wrote minimal code to pass each test
298
+ - [ ] All tests pass
299
+ - [ ] Output pristine (no errors, warnings)
300
+ - [ ] Tests use real code (mocks only if unavoidable)
301
+ - [ ] Edge cases and errors covered
302
+
303
+ Can't check all boxes? You skipped TDD. Start over.
304
+
305
+ ## When Stuck
306
+
307
+ | Problem | Solution |
308
+ |---------|----------|
309
+ | Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
310
+ | Test too complicated | Design too complicated. Simplify interface. |
311
+ | Must mock everything | Code too coupled. Use dependency injection. |
312
+ | Test setup huge | Extract helpers. Still complex? Simplify design. |
313
+
314
+ ## Debugging Integration
315
+
316
+ Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
317
+
318
+ Never fix bugs without a test.
319
+
320
+ ## Final Rule
321
+
322
+ ```
323
+ Production code → test exists and failed first
324
+ Otherwise → not TDD
325
+ ```
326
+
327
+ No exceptions without your human partner's permission.