claude-code-workflow 7.2.13 → 7.2.15

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 (76) hide show
  1. package/.claude/commands/workflow/analyze-with-file.md +61 -40
  2. package/.claude/skills/workflow-lite-plan/SKILL.md +3 -7
  3. package/.codex/skills/analyze-with-file/SKILL.md +1181 -1182
  4. package/.codex/skills/brainstorm/SKILL.md +723 -725
  5. package/.codex/skills/brainstorm-with-file/SKILL.md +10 -5
  6. package/.codex/skills/clean/SKILL.md +33 -26
  7. package/.codex/skills/collaborative-plan-with-file/SKILL.md +830 -831
  8. package/.codex/skills/csv-wave-pipeline/SKILL.md +906 -906
  9. package/.codex/skills/issue-discover/SKILL.md +57 -50
  10. package/.codex/skills/issue-discover/phases/01-issue-new.md +18 -11
  11. package/.codex/skills/issue-discover/phases/02-discover.md +31 -26
  12. package/.codex/skills/issue-discover/phases/03-discover-by-prompt.md +13 -11
  13. package/.codex/skills/issue-discover/phases/04-quick-execute.md +32 -27
  14. package/.codex/skills/parallel-dev-cycle/SKILL.md +402 -402
  15. package/.codex/skills/project-documentation-workflow/SKILL.md +13 -3
  16. package/.codex/skills/roadmap-with-file/SKILL.md +901 -897
  17. package/.codex/skills/session-sync/SKILL.md +222 -212
  18. package/.codex/skills/spec-add/SKILL.md +620 -613
  19. package/.codex/skills/spec-generator/SKILL.md +2 -2
  20. package/.codex/skills/spec-generator/phases/01-5-requirement-clarification.md +10 -10
  21. package/.codex/skills/spec-generator/phases/01-discovery.md +11 -18
  22. package/.codex/skills/spec-generator/phases/02-product-brief.md +5 -5
  23. package/.codex/skills/spec-generator/phases/03-requirements.md +7 -7
  24. package/.codex/skills/spec-generator/phases/04-architecture.md +4 -4
  25. package/.codex/skills/spec-generator/phases/05-epics-stories.md +5 -6
  26. package/.codex/skills/spec-generator/phases/06-readiness-check.md +10 -17
  27. package/.codex/skills/spec-generator/phases/07-issue-export.md +326 -329
  28. package/.codex/skills/spec-setup/SKILL.md +669 -657
  29. package/.codex/skills/team-arch-opt/SKILL.md +50 -50
  30. package/.codex/skills/team-arch-opt/agents/completion-handler.md +3 -3
  31. package/.codex/skills/team-brainstorm/SKILL.md +724 -725
  32. package/.codex/skills/team-coordinate/SKILL.md +51 -51
  33. package/.codex/skills/team-coordinate/agents/completion-handler.md +3 -3
  34. package/.codex/skills/team-coordinate/agents/plan-reviewer.md +4 -4
  35. package/.codex/skills/team-designer/SKILL.md +691 -691
  36. package/.codex/skills/team-designer/agents/requirement-clarifier.md +11 -12
  37. package/.codex/skills/team-executor/SKILL.md +45 -45
  38. package/.codex/skills/team-frontend/SKILL.md +45 -45
  39. package/.codex/skills/team-frontend/agents/completion-handler.md +3 -3
  40. package/.codex/skills/team-frontend/agents/qa-gate-reviewer.md +4 -4
  41. package/.codex/skills/team-frontend-debug/SKILL.md +50 -50
  42. package/.codex/skills/team-frontend-debug/agents/completion-handler.md +3 -3
  43. package/.codex/skills/team-frontend-debug/agents/conditional-skip-gate.md +4 -4
  44. package/.codex/skills/team-issue/SKILL.md +751 -740
  45. package/.codex/skills/team-iterdev/SKILL.md +825 -826
  46. package/.codex/skills/team-lifecycle-v4/SKILL.md +775 -775
  47. package/.codex/skills/team-lifecycle-v4/agents/quality-gate.md +165 -165
  48. package/.codex/skills/team-lifecycle-v4/agents/requirement-clarifier.md +163 -163
  49. package/.codex/skills/team-perf-opt/SKILL.md +50 -50
  50. package/.codex/skills/team-perf-opt/agents/completion-handler.md +3 -3
  51. package/.codex/skills/team-planex-v2/SKILL.md +652 -637
  52. package/.codex/skills/team-quality-assurance/SKILL.md +51 -52
  53. package/.codex/skills/team-review/SKILL.md +40 -40
  54. package/.codex/skills/team-roadmap-dev/SKILL.md +51 -51
  55. package/.codex/skills/team-roadmap-dev/agents/roadmap-discusser.md +8 -8
  56. package/.codex/skills/team-tech-debt/SKILL.md +50 -50
  57. package/.codex/skills/team-tech-debt/agents/plan-approver.md +5 -5
  58. package/.codex/skills/team-testing/SKILL.md +51 -52
  59. package/.codex/skills/team-uidesign/SKILL.md +40 -40
  60. package/.codex/skills/team-uidesign/agents/completion-handler.md +177 -177
  61. package/.codex/skills/team-ultra-analyze/SKILL.md +786 -787
  62. package/.codex/skills/team-ultra-analyze/agents/discussion-feedback.md +8 -8
  63. package/.codex/skills/team-ux-improve/SKILL.md +51 -52
  64. package/.codex/skills/team-ux-improve/agents/ux-designer.md +2 -2
  65. package/.codex/skills/team-ux-improve/agents/ux-explorer.md +1 -1
  66. package/.codex/skills/unified-execute-with-file/SKILL.md +797 -796
  67. package/.codex/skills/workflow-execute/SKILL.md +1117 -1118
  68. package/.codex/skills/workflow-lite-planex/SKILL.md +1144 -1141
  69. package/.codex/skills/workflow-plan/SKILL.md +631 -636
  70. package/.codex/skills/workflow-tdd-plan/SKILL.md +753 -759
  71. package/.codex/skills/workflow-test-fix-cycle/SKILL.md +402 -392
  72. package/README.md +25 -0
  73. package/ccw/dist/commands/install.d.ts.map +1 -1
  74. package/ccw/dist/commands/install.js +12 -0
  75. package/ccw/dist/commands/install.js.map +1 -1
  76. package/package.json +1 -1
@@ -1,759 +1,753 @@
1
- ---
2
- name: workflow-tdd-plan
3
- description: |
4
- TDD planning pipeline with multi-mode routing (plan/verify). Session discovery →
5
- context gathering (spawn_agent) → test coverage analysis (spawn_agent) → conditional
6
- conflict resolution → TDD task generation (spawn_agent) → structure validation →
7
- interactive verification. Produces IMPL_PLAN.md with Red-Green-Refactor cycles,
8
- task JSONs, TODO_LIST.md.
9
- argument-hint: "[-y|--yes] [--session ID] \"task description\" | verify [--session ID]"
10
- allowed-tools: spawn_agent, wait, send_input, close_agent, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep
11
- ---
12
-
13
- ## Auto Mode
14
-
15
- When `--yes` or `-y`: Skip all confirmations, use defaults, auto-verify, auto-continue to execute if PROCEED.
16
-
17
- # Workflow TDD Plan
18
-
19
- ## Usage
20
-
21
- ```bash
22
- # Plan mode (default)
23
- $workflow-tdd-plan "Build authentication system with JWT and OAuth"
24
- $workflow-tdd-plan -y "Add rate limiting to API endpoints"
25
- $workflow-tdd-plan --session WFS-auth "Extend with 2FA support"
26
-
27
- # Verify mode
28
- $workflow-tdd-plan verify --session WFS-auth
29
- $workflow-tdd-plan verify
30
- ```
31
-
32
- **Flags**:
33
- - `-y, --yes`: Skip all confirmations (auto mode)
34
- - `--session ID`: Use specific session
35
-
36
- ---
37
-
38
- ## Overview
39
-
40
- Multi-mode TDD planning pipeline using subagent coordination. Plan mode runs 6 sequential phases with conditional branching; verify mode operates on existing plans with TDD compliance validation.
41
-
42
- **Core Principle**: NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
43
-
44
- ```
45
- ┌──────────────────────────────────────────────────────────────────┐
46
- │ WORKFLOW TDD PLAN PIPELINE │
47
- ├──────────────────────────────────────────────────────────────────┤
48
- │ │
49
- │ Mode Detection: plan | verify │
50
- │ │
51
- │ ═══ Plan Mode (default) ═══ │
52
- │ │
53
- │ Phase 1: Session Discovery │
54
- │ ├─ Create or find workflow session │
55
- │ └─ Initialize planning-notes.md with TDD context │
56
- │ │
57
- │ Phase 2: Context Gathering (spawn_agent: context-search-agent) │
58
- │ ├─ Codebase analysis → context-package.json │
59
- │ └─ Conflict risk assessment │
60
- │ │
61
- │ Phase 3: Test Coverage Analysis (spawn_agent: cli-explore-agent)│
62
- │ ├─ Detect test framework and conventions │
63
- │ ├─ Analyze existing test coverage │
64
- │ └─ Output: test-context-package.json │
65
- │ │
66
- │ Phase 4: Conflict Resolution (conditional: risk ≥ medium) │
67
- │ ├─ CLI-driven conflict analysis │
68
- │ └─ User-selected resolution strategies │
69
- │ │
70
- │ Phase 5: TDD Task Generation (spawn_agent: action-planning-agent)│
71
- │ ├─ Generate tasks with Red-Green-Refactor cycles │
72
- │ └─ Output: IMPL_PLAN.md + task JSONs + TODO_LIST.md │
73
- │ │
74
- │ Phase 6: TDD Structure Validation │
75
- │ ├─ Validate Red-Green-Refactor structure │
76
- │ └─ Present Plan Confirmation Gate │
77
- │ │
78
- │ Plan Confirmation Gate
79
- │ ├─ "Verify TDD Compliance" → Phase 7 │
80
- │ ├─ "Start Execution" → workflow-execute
81
- │ └─ "Review Status" → Display inline │
82
- │ │
83
- │ ═══ Verify Mode ═══ │
84
- │ Phase 7: TDD Verification (spawn_agent: cli-explore-agent) │
85
- │ └─ 4-dimension TDD compliance → TDD_COMPLIANCE_REPORT.md │
86
- │ │
87
- └──────────────────────────────────────────────────────────────────┘
88
- ```
89
-
90
- ---
91
-
92
- ## Data Flow
93
-
94
- ```
95
- User Input (task description)
96
-
97
- ↓ [Convert to TDD Structured Format]
98
- │ TDD: [Feature Name]
99
- │ GOAL: [objective]
100
- │ SCOPE: [boundaries]
101
- │ CONTEXT: [background]
102
- │ TEST_FOCUS: [test scenarios]
103
-
104
- Phase 1 ──→ sessionId, planning-notes.md
105
-
106
- Phase 2 ──→ context-package.json, conflictRisk
107
-
108
- Phase 3 ──→ test-context-package.json
109
-
110
- ├── conflictRisk ≥ medium ──→ Phase 4 ──→ conflict-resolution.json
111
- └── conflictRisk < medium ──→ skip Phase 4
112
-
113
- Phase 5 ──→ IMPL_PLAN.md (with Red-Green-Refactor), task JSONs, TODO_LIST.md
114
-
115
- Phase 6 ──→ TDD structure validation
116
-
117
- ├── Verify → Phase 7 → TDD_COMPLIANCE_REPORT.md
118
- ├── Execute → workflow-execute skill
119
- └── Review → inline display
120
- ```
121
-
122
- ---
123
-
124
- ## Session Structure
125
-
126
- ```
127
- .workflow/active/WFS-{session}/
128
- ├── workflow-session.json # Session metadata
129
- ├── planning-notes.md # Accumulated context across phases
130
- ├── IMPL_PLAN.md # Implementation plan with TDD cycles
131
- ├── plan.json # Structured plan overview
132
- ├── TODO_LIST.md # Task checklist
133
- ├── .task/ # Task definitions with TDD phases
134
- │ ├── IMPL-1.json # Each task has Red-Green-Refactor steps
135
- │ └── IMPL-N.json
136
- └── .process/
137
- ├── context-package.json # Phase 2 output
138
- ├── test-context-package.json # Phase 3 output
139
- ├── conflict-resolution.json # Phase 4 output (conditional)
140
- └── TDD_COMPLIANCE_REPORT.md # Phase 7 output
141
- ```
142
-
143
- ---
144
-
145
- ## Implementation
146
-
147
- ### Session Initialization
148
-
149
- ```javascript
150
- const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
151
-
152
- // Parse flags
153
- const AUTO_YES = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
154
- const sessionMatch = $ARGUMENTS.match(/--session\s+(\S+)/)
155
- const existingSessionId = sessionMatch ? sessionMatch[1] : null
156
-
157
- // Mode detection
158
- const cleanArgs = $ARGUMENTS
159
- .replace(/--yes|-y|--session\s+\S+/g, '').trim()
160
-
161
- let mode = 'plan'
162
- if (cleanArgs.startsWith('verify')) mode = 'verify'
163
-
164
- const taskDescription = cleanArgs
165
- .replace(/^verify\s*/, '')
166
- .replace(/^["']|["']$/g, '')
167
- .trim()
168
-
169
- // Convert to TDD structured format
170
- function toTddStructured(desc) {
171
- const featureName = desc.split(/\s+/).slice(0, 3).join(' ')
172
- return `TDD: ${featureName}
173
- GOAL: ${desc}
174
- SCOPE: Core implementation
175
- CONTEXT: New development
176
- TEST_FOCUS: Unit tests, integration tests, edge cases`
177
- }
178
-
179
- const structuredDesc = toTddStructured(taskDescription)
180
- ```
181
-
182
- ---
183
-
184
- ### Phase 1: Session Discovery (Plan Mode)
185
-
186
- **Objective**: Create or find workflow session, initialize planning notes with TDD context.
187
-
188
- ```javascript
189
- if (mode !== 'plan') {
190
- // verify: locate existing session
191
- // → Jump to Phase 7
192
- }
193
-
194
- let sessionId, sessionFolder
195
-
196
- if (existingSessionId) {
197
- sessionId = existingSessionId
198
- sessionFolder = `.workflow/active/${sessionId}`
199
- if (!Bash(`test -d "${sessionFolder}" && echo yes`).trim()) {
200
- console.log(`ERROR: Session ${sessionId} not found`)
201
- return
202
- }
203
- } else {
204
- // Auto-detect from .workflow/active/ or create new
205
- const sessions = Bash(`ls -d .workflow/active/WFS-* 2>/dev/null`).trim().split('\n').filter(Boolean)
206
-
207
- if (sessions.length === 0 || taskDescription) {
208
- // Create new session
209
- const slug = taskDescription.toLowerCase()
210
- .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').substring(0, 40)
211
- sessionId = `WFS-${slug}`
212
- sessionFolder = `.workflow/active/${sessionId}`
213
- Bash(`mkdir -p "${sessionFolder}/.task" "${sessionFolder}/.process"`)
214
-
215
- Write(`${sessionFolder}/workflow-session.json`, JSON.stringify({
216
- session_id: sessionId,
217
- status: 'planning',
218
- workflow_type: 'tdd',
219
- created_at: getUtc8ISOString(),
220
- task_description: taskDescription
221
- }, null, 2))
222
- } else if (sessions.length === 1) {
223
- sessionId = sessions[0].split('/').pop()
224
- sessionFolder = sessions[0]
225
- } else {
226
- // Multiple sessions — ask user
227
- if (AUTO_YES) {
228
- sessionFolder = sessions[0]
229
- sessionId = sessions[0].split('/').pop()
230
- } else {
231
- const answer = AskUserQuestion({
232
- questions: [{
233
- question: "Multiple sessions found. Select one:",
234
- header: "Session",
235
- multiSelect: false,
236
- options: sessions.slice(0, 4).map(s => ({
237
- label: s.split('/').pop(),
238
- description: s
239
- }))
240
- }]
241
- })
242
- sessionId = answer.Session
243
- sessionFolder = `.workflow/active/${sessionId}`
244
- }
245
- }
246
- }
247
-
248
- // Initialize planning-notes.md with TDD context
249
- Write(`${sessionFolder}/planning-notes.md`, `# TDD Planning Notes
250
-
251
- ## User Intent
252
- ${structuredDesc}
253
-
254
- ## TDD Principles
255
- - NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
256
- - Red-Green-Refactor cycle for all tasks
257
- - Test-first forces edge case discovery before implementation
258
- `)
259
-
260
- console.log(`Session: ${sessionId}`)
261
- ```
262
-
263
- ---
264
-
265
- ### Phase 2: Context Gathering (spawn_agent)
266
-
267
- **Objective**: Gather project context, assess conflict risk.
268
-
269
- ```javascript
270
- console.log(`\n## Phase 2: Context Gathering\n`)
271
-
272
- const ctxAgent = spawn_agent({
273
- agent: `~/.codex/agents/context-search-agent.md`,
274
- instruction: `
275
- Gather implementation context for TDD planning.
276
-
277
- **Session**: ${sessionFolder}
278
- **Task**: ${taskDescription}
279
- **Mode**: TDD_PLAN
280
-
281
- ### Steps
282
- 1. Analyze project structure (package.json, tsconfig, etc.)
283
- 2. Search for existing similar implementations
284
- 3. Identify integration points and dependencies
285
- 4. Assess conflict risk with existing code
286
- 5. Generate context package
287
-
288
- ### Output
289
- Write context package to: ${sessionFolder}/.process/context-package.json
290
- Format: {
291
- "critical_files": [...],
292
- "patterns": [...],
293
- "dependencies": [...],
294
- "integration_points": [...],
295
- "conflict_risk": "none" | "low" | "medium" | "high",
296
- "conflict_areas": [...],
297
- "constraints": [...]
298
- }
299
- `
300
- })
301
-
302
- wait({ id: ctxAgent })
303
- close_agent({ id: ctxAgent })
304
-
305
- // Parse outputs
306
- const contextPkg = JSON.parse(Read(`${sessionFolder}/.process/context-package.json`) || '{}')
307
- const conflictRisk = contextPkg.conflict_risk || 'none'
308
-
309
- // Update planning-notes.md
310
- Edit(`${sessionFolder}/planning-notes.md`, {
311
- oldText: '## User Intent',
312
- newText: `## Context Findings
313
- - Critical files: ${(contextPkg.critical_files || []).join(', ')}
314
- - Conflict risk: ${conflictRisk}
315
- - Constraints: ${(contextPkg.constraints || []).join('; ')}
316
-
317
- ## User Intent`
318
- })
319
-
320
- console.log(` Context gathered. Conflict risk: ${conflictRisk}`)
321
- ```
322
-
323
- ---
324
-
325
- ### Phase 3: Test Coverage Analysis (spawn_agent)
326
-
327
- **Objective**: Analyze existing test patterns and coverage.
328
-
329
- ```javascript
330
- console.log(`\n## Phase 3: Test Coverage Analysis\n`)
331
-
332
- const testAgent = spawn_agent({
333
- agent: `~/.codex/agents/cli-explore-agent.md`,
334
- instruction: `
335
- Analyze test coverage and framework for TDD planning.
336
-
337
- **Session**: ${sessionFolder}
338
- **Context**: ${sessionFolder}/.process/context-package.json
339
-
340
- ### Steps
341
- 1. Detect test framework (Jest, Vitest, Mocha, etc.)
342
- 2. Identify test file patterns and conventions
343
- 3. Analyze existing test coverage
344
- 4. Identify coverage gaps
345
- 5. Extract test utilities and helpers
346
-
347
- ### Output
348
- Write test context to: ${sessionFolder}/.process/test-context-package.json
349
- Format: {
350
- "test_framework": "jest" | "vitest" | "mocha" | "other",
351
- "test_patterns": {
352
- "unit": "**/*.test.ts",
353
- "integration": "**/*.integration.test.ts"
354
- },
355
- "coverage_summary": {
356
- "lines": 75.5,
357
- "branches": 68.2,
358
- "functions": 80.1
359
- },
360
- "coverage_gaps": [...],
361
- "test_utilities": [...],
362
- "conventions": {
363
- "naming": "describe/it",
364
- "mocking": "jest.mock",
365
- "assertions": "expect"
366
- }
367
- }
368
- `
369
- })
370
-
371
- wait({ id: testAgent })
372
- close_agent({ id: testAgent })
373
-
374
- const testContext = JSON.parse(Read(`${sessionFolder}/.process/test-context-package.json`) || '{}')
375
-
376
- // Update planning-notes
377
- Edit(`${sessionFolder}/planning-notes.md`, {
378
- oldText: '## TDD Principles',
379
- newText: `## Test Context
380
- - Framework: ${testContext.test_framework || 'unknown'}
381
- - Coverage: ${testContext.coverage_summary?.lines || 'N/A'}% lines
382
- - Gaps: ${(testContext.coverage_gaps || []).join(', ')}
383
-
384
- ## TDD Principles`
385
- })
386
-
387
- console.log(` Test framework: ${testContext.test_framework}`)
388
- ```
389
-
390
- ---
391
-
392
- ### Phase 4: Conflict Resolution (Conditional)
393
-
394
- **Objective**: Detect and resolve conflicts when risk ≥ medium.
395
-
396
- ```javascript
397
- if (['medium', 'high'].includes(conflictRisk)) {
398
- console.log(`\n## Phase 4: Conflict Resolution (risk: ${conflictRisk})\n`)
399
-
400
- Bash({
401
- command: `ccw cli -p "PURPOSE: Analyze and resolve conflicts between planned changes and existing codebase.
402
- TASK:
403
- Read context package for conflict areas
404
- Analyze each conflict area in detail
405
- Propose resolution strategies (refactor, adapt, isolate, defer)
406
- • For each conflict: assess impact and recommend approach
407
- MODE: analysis
408
- CONTEXT: @**/*
409
- EXPECTED: JSON: {conflicts: [{area, severity, description, strategy, impact}], summary: string}
410
- CONSTRAINTS: Focus on ${(contextPkg.conflict_areas || []).join(', ')}
411
-
412
- TASK DESCRIPTION: ${taskDescription}" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause`,
413
- run_in_background: true
414
- })
415
- // Wait for CLI → conflicts[]
416
-
417
- if (!AUTO_YES && conflicts.length > 0) {
418
- // Present conflicts and let user select strategies
419
- console.log(`\n### Conflicts Found: ${conflicts.length}\n`)
420
- conflicts.forEach((c, i) => {
421
- console.log(`${i + 1}. [${c.severity}] ${c.area}: ${c.description}`)
422
- console.log(` Strategy: ${c.strategy} | Impact: ${c.impact}`)
423
- })
424
-
425
- const answer = AskUserQuestion({
426
- questions: [{
427
- question: "Accept conflict resolution strategies?",
428
- header: "Conflicts",
429
- multiSelect: false,
430
- options: [
431
- { label: "Accept All", description: "Apply all recommended strategies" },
432
- { label: "Review Each", description: "Approve strategies individually" },
433
- { label: "Skip", description: "Proceed without resolving" }
434
- ]
435
- }]
436
- })
437
- }
438
-
439
- // Write resolution
440
- Write(`${sessionFolder}/.process/conflict-resolution.json`,
441
- JSON.stringify({ conflicts, resolved_at: getUtc8ISOString() }, null, 2))
442
- } else {
443
- console.log(` Conflict risk: ${conflictRisk} — skipping Phase 4`)
444
- }
445
- ```
446
-
447
- ---
448
-
449
- ### Phase 5: TDD Task Generation (spawn_agent)
450
-
451
- **Objective**: Generate IMPL_PLAN.md with Red-Green-Refactor cycles, task JSONs, TODO_LIST.md.
452
-
453
- ```javascript
454
- console.log(`\n## Phase 5: TDD Task Generation\n`)
455
-
456
- const planAgent = spawn_agent({
457
- agent: `~/.codex/agents/action-planning-agent.md`,
458
- instruction: `
459
- Generate TDD implementation plan with Red-Green-Refactor cycles.
460
-
461
- **Session**: ${sessionFolder}
462
- **Task**: ${taskDescription}
463
- **Context**: ${sessionFolder}/.process/context-package.json
464
- **Test Context**: ${sessionFolder}/.process/test-context-package.json
465
- **Planning Notes**: ${sessionFolder}/planning-notes.md
466
- ${conflictRisk === 'medium' || conflictRisk === 'high'
467
- ? `**Conflict Resolution**: ${sessionFolder}/.process/conflict-resolution.json` : ''}
468
-
469
- ### TDD Requirements
470
- Each task MUST include Red-Green-Refactor cycle:
471
- 1. **Red Phase**: Write failing test first
472
- - Define test cases
473
- - Verify test fails (proves test is valid)
474
- - Document expected failure
475
- 2. **Green Phase**: Implement minimal code to pass
476
- - Write simplest implementation
477
- - Run tests until passing
478
- - Max 3 test-fix iterations (auto-revert if exceeded)
479
- 3. **Refactor Phase**: Improve code quality
480
- - Refactor with tests as safety net
481
- - Maintain passing tests
482
- - Document improvements
483
-
484
- ### Output Requirements
485
- 1. **IMPL_PLAN.md** at ${sessionFolder}/IMPL_PLAN.md
486
- - Section 1: Requirements Summary
487
- - Section 2: Test Strategy (framework, patterns, coverage goals)
488
- - Section 3: Task Breakdown with TDD cycles
489
- - Section 4: Implementation Strategy
490
- - Section 5: Risk Assessment
491
- 2. **plan.json** at ${sessionFolder}/plan.json
492
- - {task_ids[], recommended_execution, complexity, tdd_compliance: true}
493
- 3. **Task JSONs** at ${sessionFolder}/.task/IMPL-{N}.json
494
- - Each task has "implementation" array with 3 steps:
495
- [
496
- {step: 1, tdd_phase: "red", description: "Write failing test", ...},
497
- {step: 2, tdd_phase: "green", description: "Implement code", test_fix_cycle: {max_iterations: 3, auto_revert: true}},
498
- {step: 3, tdd_phase: "refactor", description: "Refactor code", ...}
499
- ]
500
- 4. **TODO_LIST.md** at ${sessionFolder}/TODO_LIST.md
501
- - Checkbox format: - [ ] IMPL-{N}: {title} (TDD)
502
- `
503
- })
504
-
505
- wait({ id: planAgent })
506
- close_agent({ id: planAgent })
507
-
508
- console.log(` TDD tasks generated`)
509
- ```
510
-
511
- ---
512
-
513
- ### Phase 6: TDD Structure Validation
514
-
515
- **Objective**: Validate Red-Green-Refactor structure in all tasks.
516
-
517
- ```javascript
518
- console.log(`\n## Phase 6: TDD Structure Validation\n`)
519
-
520
- // Read all task JSONs
521
- const taskFiles = Bash(`ls ${sessionFolder}/.task/IMPL-*.json 2>/dev/null`).trim().split('\n').filter(Boolean)
522
- const tasks = taskFiles.map(f => JSON.parse(Read(f)))
523
-
524
- // Validate TDD structure
525
- const validationErrors = []
526
- for (const task of tasks) {
527
- const impl = task.implementation || []
528
-
529
- // Check 3-step structure
530
- if (impl.length !== 3) {
531
- validationErrors.push(`${task.id}: Expected 3 steps, found ${impl.length}`)
532
- continue
533
- }
534
-
535
- // Check Red phase
536
- if (impl[0].tdd_phase !== 'red') {
537
- validationErrors.push(`${task.id}: Step 1 must be Red phase`)
538
- }
539
-
540
- // Check Green phase with test-fix-cycle
541
- if (impl[1].tdd_phase !== 'green') {
542
- validationErrors.push(`${task.id}: Step 2 must be Green phase`)
543
- }
544
- if (!impl[1].test_fix_cycle || !impl[1].test_fix_cycle.max_iterations) {
545
- validationErrors.push(`${task.id}: Green phase missing test-fix-cycle config`)
546
- }
547
-
548
- // Check Refactor phase
549
- if (impl[2].tdd_phase !== 'refactor') {
550
- validationErrors.push(`${task.id}: Step 3 must be Refactor phase`)
551
- }
552
- }
553
-
554
- if (validationErrors.length > 0) {
555
- console.log(`\n### TDD Structure Validation Errors:\n`)
556
- validationErrors.forEach(e => console.log(` - ${e}`))
557
-
558
- if (!AUTO_YES) {
559
- const answer = AskUserQuestion({
560
- questions: [{
561
- question: "TDD structure validation failed. Continue anyway?",
562
- header: "Validation",
563
- multiSelect: false,
564
- options: [
565
- { label: "Fix and Retry", description: "Regenerate tasks with correct structure" },
566
- { label: "Continue", description: "Proceed despite errors" },
567
- { label: "Abort", description: "Stop planning" }
568
- ]
569
- }]
570
- })
571
-
572
- if (answer.Validation === "Fix and Retry") {
573
- // Re-run Phase 5
574
- // → goto Phase 5
575
- } else if (answer.Validation === "Abort") {
576
- return
577
- }
578
- }
579
- } else {
580
- console.log(` ✓ All tasks have valid Red-Green-Refactor structure`)
581
- }
582
-
583
- // Plan Confirmation Gate
584
- const taskCount = tasks.length
585
- console.log(`\n## Plan Generated\n`)
586
- console.log(` Tasks: ${taskCount}`)
587
- console.log(` Plan: ${sessionFolder}/IMPL_PLAN.md`)
588
-
589
- if (AUTO_YES) {
590
- console.log(` [--yes] Auto-verifying TDD compliance...`)
591
- // → Fall through to Phase 7
592
- } else {
593
- const nextStep = AskUserQuestion({
594
- questions: [{
595
- question: "TDD plan generated. What's next?",
596
- header: "Next Step",
597
- multiSelect: false,
598
- options: [
599
- { label: "Verify TDD Compliance (Recommended)", description: "Run full TDD compliance verification" },
600
- { label: "Start Execution", description: "Proceed to workflow-execute" },
601
- { label: "Review Status", description: "Display plan summary inline" }
602
- ]
603
- }]
604
- })
605
-
606
- if (nextStep['Next Step'] === 'Start Execution') {
607
- console.log(`\nReady to execute. Run: $workflow-execute --session ${sessionId}`)
608
- return
609
- }
610
- if (nextStep['Next Step'] === 'Review Status') {
611
- const plan = Read(`${sessionFolder}/IMPL_PLAN.md`)
612
- console.log(plan)
613
- return
614
- }
615
- // Verify → continue to Phase 7
616
- }
617
- ```
618
-
619
- ---
620
-
621
- ### Phase 7: TDD Verification (Verify Mode)
622
-
623
- **Objective**: Full TDD compliance verification with quality gate.
624
-
625
- ```javascript
626
- if (mode === 'verify' || /* auto-verify from Phase 6 */) {
627
- console.log(`\n## Phase 7: TDD Verification\n`)
628
-
629
- // Find session if in verify mode entry
630
- if (mode === 'verify' && !sessionFolder) {
631
- // Session discovery (same logic as Phase 1)
632
- }
633
-
634
- const verifyAgent = spawn_agent({
635
- agent: `~/.codex/agents/cli-explore-agent.md`,
636
- instruction: `
637
- Verify TDD compliance across 4 dimensions.
638
-
639
- **Session**: ${sessionFolder}
640
-
641
- ### Verification Dimensions
642
-
643
- **A. Test-First Structure**
644
- - Every task has Red-Green-Refactor cycle
645
- - Red phase defines failing tests
646
- - Green phase implements code
647
- - Refactor phase improves quality
648
-
649
- **B. Test Coverage**
650
- - All critical paths have tests
651
- - Edge cases covered
652
- - Integration points tested
653
- - Coverage meets project standards
654
-
655
- **C. Cycle Integrity**
656
- - Red phase: test fails before implementation
657
- - Green phase: minimal code to pass
658
- - Refactor phase: maintains passing tests
659
- - No production code without failing test first
660
-
661
- **D. Quality Gates**
662
- - Test-fix-cycle configured (max 3 iterations)
663
- - Auto-revert on iteration limit
664
- - Clear acceptance criteria
665
- - Testable convergence conditions
666
-
667
- ### Output
668
- Write report to: ${sessionFolder}/.process/TDD_COMPLIANCE_REPORT.md
669
-
670
- Format:
671
- # TDD Compliance Report
672
-
673
- ## Summary
674
- - Quality Gate: APPROVED | CONDITIONAL | BLOCKED
675
- - Tasks Analyzed: N
676
- - Compliance Score: X%
677
-
678
- ## Dimension Scores
679
- - A. Test-First Structure: PASS/WARN/FAIL
680
- - B. Test Coverage: PASS/WARN/FAIL
681
- - C. Cycle Integrity: PASS/WARN/FAIL
682
- - D. Quality Gates: PASS/WARN/FAIL
683
-
684
- ## Issues Found
685
- [List specific issues with task IDs]
686
-
687
- ## Recommendations
688
- [Actionable recommendations]
689
-
690
- ## Quality Gate Decision
691
- APPROVED: All dimensions PASS, ready for execution
692
- CONDITIONAL: Minor warnings, can proceed with caution
693
- BLOCKED: Critical failures, must fix before execution
694
- `
695
- })
696
-
697
- wait({ id: verifyAgent })
698
- close_agent({ id: verifyAgent })
699
-
700
- const report = Read(`${sessionFolder}/.process/TDD_COMPLIANCE_REPORT.md`)
701
- const qualityGate = report.match(/Quality Gate: (\w+)/)?.[1] || 'UNKNOWN'
702
-
703
- console.log(` Quality gate: ${qualityGate}`)
704
- console.log(` Report: ${sessionFolder}/.process/TDD_COMPLIANCE_REPORT.md`)
705
-
706
- if (AUTO_YES && qualityGate === 'APPROVED') {
707
- console.log(` [--yes] TDD compliance verified. Ready for execution.`)
708
- console.log(` Run: $workflow-execute --session ${sessionId}`)
709
- }
710
- }
711
- ```
712
-
713
- ---
714
-
715
- ## Error Handling
716
-
717
- | Error | Recovery |
718
- |-------|----------|
719
- | No active session | Guide: run `$workflow-tdd-plan "description"` first |
720
- | Context gathering timeout | Retry with reduced scope |
721
- | Test framework detection failed | Manual specification in test-context-package.json |
722
- | TDD structure validation failed | Regenerate tasks or fix manually |
723
- | Conflict analysis failure | Skip Phase 4, proceed with warning |
724
- | Task generation failure | Retry agent with simplified context |
725
- | Verification failure | Display partial results |
726
- | Session not found (verify) | List available sessions |
727
-
728
- ---
729
-
730
- ## TDD Compliance Requirements
731
-
732
- ### The Iron Law
733
-
734
- ```
735
- NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
736
- ```
737
-
738
- ### Red-Green-Refactor Cycle
739
-
740
- Every task must have:
741
- 1. **Red**: Write failing test (proves test is valid)
742
- 2. **Green**: Implement minimal code to pass (with test-fix-cycle)
743
- 3. **Refactor**: Improve code quality (maintain passing tests)
744
-
745
- ### Quality Gates
746
-
747
- - Test-fix-cycle: max 3 iterations
748
- - Auto-revert: triggered when max iterations reached
749
- - Coverage goals: defined per project
750
- - Acceptance criteria: testable and measurable
751
-
752
- ---
753
-
754
- ## Compact Protection
755
-
756
- > **COMPACT DIRECTIVE**: If context compression occurs:
757
- > - Re-read `planning-notes.md` for accumulated context
758
- > - Re-read `workflow-session.json` for session state
759
- > - Phase 5 is the most token-intensive — if compressed, re-read task JSONs on demand
1
+ ---
2
+ name: workflow-tdd-plan
3
+ description: |
4
+ TDD planning pipeline with multi-mode routing (plan/verify). Session discovery →
5
+ context gathering (spawn_agent) → test coverage analysis (spawn_agent) → conditional
6
+ conflict resolution → TDD task generation (spawn_agent) → structure validation →
7
+ interactive verification. Produces IMPL_PLAN.md with Red-Green-Refactor cycles,
8
+ task JSONs, TODO_LIST.md.
9
+ argument-hint: "[-y|--yes] [--session ID] \"task description\" | verify [--session ID]"
10
+ allowed-tools: spawn_agent, wait, send_input, close_agent, request_user_input, Read, Write, Edit, Bash, Glob, Grep
11
+ ---
12
+
13
+ ## Auto Mode
14
+
15
+ When `--yes` or `-y`: Skip all confirmations, use defaults, auto-verify. **This skill is planning-only it NEVER executes implementation. Output is the plan for user review.**
16
+
17
+ # Workflow TDD Plan
18
+
19
+ ## Usage
20
+
21
+ ```bash
22
+ # Plan mode (default)
23
+ $workflow-tdd-plan "Build authentication system with JWT and OAuth"
24
+ $workflow-tdd-plan -y "Add rate limiting to API endpoints"
25
+ $workflow-tdd-plan --session WFS-auth "Extend with 2FA support"
26
+
27
+ # Verify mode
28
+ $workflow-tdd-plan verify --session WFS-auth
29
+ $workflow-tdd-plan verify
30
+ ```
31
+
32
+ **Flags**:
33
+ - `-y, --yes`: Skip all confirmations (auto mode)
34
+ - `--session ID`: Use specific session
35
+
36
+ ---
37
+
38
+ ## Overview
39
+
40
+ Multi-mode TDD planning pipeline using subagent coordination. Plan mode runs 6 sequential phases with conditional branching; verify mode operates on existing plans with TDD compliance validation.
41
+
42
+ **Core Principle**: NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
43
+
44
+ ```
45
+ ┌──────────────────────────────────────────────────────────────────┐
46
+ │ WORKFLOW TDD PLAN PIPELINE │
47
+ ├──────────────────────────────────────────────────────────────────┤
48
+ │ │
49
+ │ Mode Detection: plan | verify │
50
+ │ │
51
+ │ ═══ Plan Mode (default) ═══ │
52
+ │ │
53
+ │ Phase 1: Session Discovery │
54
+ │ ├─ Create or find workflow session │
55
+ │ └─ Initialize planning-notes.md with TDD context │
56
+ │ │
57
+ │ Phase 2: Context Gathering (spawn_agent: context-search-agent) │
58
+ │ ├─ Codebase analysis → context-package.json │
59
+ │ └─ Conflict risk assessment │
60
+ │ │
61
+ │ Phase 3: Test Coverage Analysis (spawn_agent: cli-explore-agent)│
62
+ │ ├─ Detect test framework and conventions │
63
+ │ ├─ Analyze existing test coverage │
64
+ │ └─ Output: test-context-package.json │
65
+ │ │
66
+ │ Phase 4: Conflict Resolution (conditional: risk ≥ medium) │
67
+ │ ├─ CLI-driven conflict analysis │
68
+ │ └─ User-selected resolution strategies │
69
+ │ │
70
+ │ Phase 5: TDD Task Generation (spawn_agent: action-planning-agent)│
71
+ │ ├─ Generate tasks with Red-Green-Refactor cycles │
72
+ │ └─ Output: IMPL_PLAN.md + task JSONs + TODO_LIST.md │
73
+ │ │
74
+ │ Phase 6: TDD Structure Validation │
75
+ │ ├─ Validate Red-Green-Refactor structure │
76
+ │ └─ Present Plan Confirmation Gate │
77
+ │ │
78
+ │ Plan Confirmation Gate (PLANNING ENDS HERE)
79
+ │ ├─ "Verify TDD Compliance" → Phase 7 │
80
+ │ ├─ "Done" → Display next-step command for user
81
+ │ └─ "Review Status" → Display inline │
82
+ │ │
83
+ │ ═══ Verify Mode ═══ │
84
+ │ Phase 7: TDD Verification (spawn_agent: cli-explore-agent) │
85
+ │ └─ 4-dimension TDD compliance → TDD_COMPLIANCE_REPORT.md │
86
+ │ │
87
+ └──────────────────────────────────────────────────────────────────┘
88
+ ```
89
+
90
+ ---
91
+
92
+ ## Data Flow
93
+
94
+ ```
95
+ User Input (task description)
96
+
97
+ ↓ [Convert to TDD Structured Format]
98
+ │ TDD: [Feature Name]
99
+ │ GOAL: [objective]
100
+ │ SCOPE: [boundaries]
101
+ │ CONTEXT: [background]
102
+ │ TEST_FOCUS: [test scenarios]
103
+
104
+ Phase 1 ──→ sessionId, planning-notes.md
105
+
106
+ Phase 2 ──→ context-package.json, conflictRisk
107
+
108
+ Phase 3 ──→ test-context-package.json
109
+
110
+ ├── conflictRisk ≥ medium ──→ Phase 4 ──→ conflict-resolution.json
111
+ └── conflictRisk < medium ──→ skip Phase 4
112
+
113
+ Phase 5 ──→ IMPL_PLAN.md (with Red-Green-Refactor), task JSONs, TODO_LIST.md
114
+
115
+ Phase 6 ──→ TDD structure validation
116
+
117
+ ├── Verify → Phase 7 → TDD_COMPLIANCE_REPORT.md
118
+ ├── Execute → workflow-execute skill
119
+ └── Review → inline display
120
+ ```
121
+
122
+ ---
123
+
124
+ ## Session Structure
125
+
126
+ ```
127
+ .workflow/active/WFS-{session}/
128
+ ├── workflow-session.json # Session metadata
129
+ ├── planning-notes.md # Accumulated context across phases
130
+ ├── IMPL_PLAN.md # Implementation plan with TDD cycles
131
+ ├── plan.json # Structured plan overview
132
+ ├── TODO_LIST.md # Task checklist
133
+ ├── .task/ # Task definitions with TDD phases
134
+ │ ├── IMPL-1.json # Each task has Red-Green-Refactor steps
135
+ │ └── IMPL-N.json
136
+ └── .process/
137
+ ├── context-package.json # Phase 2 output
138
+ ├── test-context-package.json # Phase 3 output
139
+ ├── conflict-resolution.json # Phase 4 output (conditional)
140
+ └── TDD_COMPLIANCE_REPORT.md # Phase 7 output
141
+ ```
142
+
143
+ ---
144
+
145
+ ## Implementation
146
+
147
+ ### Session Initialization
148
+
149
+ ```javascript
150
+ const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
151
+
152
+ // Parse flags
153
+ const AUTO_YES = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
154
+ const sessionMatch = $ARGUMENTS.match(/--session\s+(\S+)/)
155
+ const existingSessionId = sessionMatch ? sessionMatch[1] : null
156
+
157
+ // Mode detection
158
+ const cleanArgs = $ARGUMENTS
159
+ .replace(/--yes|-y|--session\s+\S+/g, '').trim()
160
+
161
+ let mode = 'plan'
162
+ if (cleanArgs.startsWith('verify')) mode = 'verify'
163
+
164
+ const taskDescription = cleanArgs
165
+ .replace(/^verify\s*/, '')
166
+ .replace(/^["']|["']$/g, '')
167
+ .trim()
168
+
169
+ // Convert to TDD structured format
170
+ function toTddStructured(desc) {
171
+ const featureName = desc.split(/\s+/).slice(0, 3).join(' ')
172
+ return `TDD: ${featureName}
173
+ GOAL: ${desc}
174
+ SCOPE: Core implementation
175
+ CONTEXT: New development
176
+ TEST_FOCUS: Unit tests, integration tests, edge cases`
177
+ }
178
+
179
+ const structuredDesc = toTddStructured(taskDescription)
180
+ ```
181
+
182
+ ---
183
+
184
+ ### Phase 1: Session Discovery (Plan Mode)
185
+
186
+ **Objective**: Create or find workflow session, initialize planning notes with TDD context.
187
+
188
+ ```javascript
189
+ if (mode !== 'plan') {
190
+ // verify: locate existing session
191
+ // → Jump to Phase 7
192
+ }
193
+
194
+ let sessionId, sessionFolder
195
+
196
+ if (existingSessionId) {
197
+ sessionId = existingSessionId
198
+ sessionFolder = `.workflow/active/${sessionId}`
199
+ if (!Bash(`test -d "${sessionFolder}" && echo yes`).trim()) {
200
+ console.log(`ERROR: Session ${sessionId} not found`)
201
+ return
202
+ }
203
+ } else {
204
+ // Auto-detect from .workflow/active/ or create new
205
+ const sessions = Bash(`ls -d .workflow/active/WFS-* 2>/dev/null`).trim().split('\n').filter(Boolean)
206
+
207
+ if (sessions.length === 0 || taskDescription) {
208
+ // Create new session
209
+ const slug = taskDescription.toLowerCase()
210
+ .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').substring(0, 40)
211
+ sessionId = `WFS-${slug}`
212
+ sessionFolder = `.workflow/active/${sessionId}`
213
+ Bash(`mkdir -p "${sessionFolder}/.task" "${sessionFolder}/.process"`)
214
+
215
+ Write(`${sessionFolder}/workflow-session.json`, JSON.stringify({
216
+ session_id: sessionId,
217
+ status: 'planning',
218
+ workflow_type: 'tdd',
219
+ created_at: getUtc8ISOString(),
220
+ task_description: taskDescription
221
+ }, null, 2))
222
+ } else if (sessions.length === 1) {
223
+ sessionId = sessions[0].split('/').pop()
224
+ sessionFolder = sessions[0]
225
+ } else {
226
+ // Multiple sessions — ask user
227
+ if (AUTO_YES) {
228
+ sessionFolder = sessions[0]
229
+ sessionId = sessions[0].split('/').pop()
230
+ } else {
231
+ const answer = request_user_input({
232
+ questions: [{
233
+ question: "Multiple sessions found. Select one:",
234
+ header: "Session",
235
+ options: sessions.slice(0, 4).map(s => ({
236
+ label: s.split('/').pop(),
237
+ description: s
238
+ }))
239
+ }]
240
+ })
241
+ sessionId = answer.Session
242
+ sessionFolder = `.workflow/active/${sessionId}`
243
+ }
244
+ }
245
+ }
246
+
247
+ // Initialize planning-notes.md with TDD context
248
+ Write(`${sessionFolder}/planning-notes.md`, `# TDD Planning Notes
249
+
250
+ ## User Intent
251
+ ${structuredDesc}
252
+
253
+ ## TDD Principles
254
+ - NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
255
+ - Red-Green-Refactor cycle for all tasks
256
+ - Test-first forces edge case discovery before implementation
257
+ `)
258
+
259
+ console.log(`Session: ${sessionId}`)
260
+ ```
261
+
262
+ ---
263
+
264
+ ### Phase 2: Context Gathering (spawn_agent)
265
+
266
+ **Objective**: Gather project context, assess conflict risk.
267
+
268
+ ```javascript
269
+ console.log(`\n## Phase 2: Context Gathering\n`)
270
+
271
+ const ctxAgent = spawn_agent({
272
+ agent: `~/.codex/agents/context-search-agent.md`,
273
+ instruction: `
274
+ Gather implementation context for TDD planning.
275
+
276
+ **Session**: ${sessionFolder}
277
+ **Task**: ${taskDescription}
278
+ **Mode**: TDD_PLAN
279
+
280
+ ### Steps
281
+ 1. Analyze project structure (package.json, tsconfig, etc.)
282
+ 2. Search for existing similar implementations
283
+ 3. Identify integration points and dependencies
284
+ 4. Assess conflict risk with existing code
285
+ 5. Generate context package
286
+
287
+ ### Output
288
+ Write context package to: ${sessionFolder}/.process/context-package.json
289
+ Format: {
290
+ "critical_files": [...],
291
+ "patterns": [...],
292
+ "dependencies": [...],
293
+ "integration_points": [...],
294
+ "conflict_risk": "none" | "low" | "medium" | "high",
295
+ "conflict_areas": [...],
296
+ "constraints": [...]
297
+ }
298
+ `
299
+ })
300
+
301
+ wait({ id: ctxAgent })
302
+ close_agent({ id: ctxAgent })
303
+
304
+ // Parse outputs
305
+ const contextPkg = JSON.parse(Read(`${sessionFolder}/.process/context-package.json`) || '{}')
306
+ const conflictRisk = contextPkg.conflict_risk || 'none'
307
+
308
+ // Update planning-notes.md
309
+ Edit(`${sessionFolder}/planning-notes.md`, {
310
+ oldText: '## User Intent',
311
+ newText: `## Context Findings
312
+ - Critical files: ${(contextPkg.critical_files || []).join(', ')}
313
+ - Conflict risk: ${conflictRisk}
314
+ - Constraints: ${(contextPkg.constraints || []).join('; ')}
315
+
316
+ ## User Intent`
317
+ })
318
+
319
+ console.log(` Context gathered. Conflict risk: ${conflictRisk}`)
320
+ ```
321
+
322
+ ---
323
+
324
+ ### Phase 3: Test Coverage Analysis (spawn_agent)
325
+
326
+ **Objective**: Analyze existing test patterns and coverage.
327
+
328
+ ```javascript
329
+ console.log(`\n## Phase 3: Test Coverage Analysis\n`)
330
+
331
+ const testAgent = spawn_agent({
332
+ agent: `~/.codex/agents/cli-explore-agent.md`,
333
+ instruction: `
334
+ Analyze test coverage and framework for TDD planning.
335
+
336
+ **Session**: ${sessionFolder}
337
+ **Context**: ${sessionFolder}/.process/context-package.json
338
+
339
+ ### Steps
340
+ 1. Detect test framework (Jest, Vitest, Mocha, etc.)
341
+ 2. Identify test file patterns and conventions
342
+ 3. Analyze existing test coverage
343
+ 4. Identify coverage gaps
344
+ 5. Extract test utilities and helpers
345
+
346
+ ### Output
347
+ Write test context to: ${sessionFolder}/.process/test-context-package.json
348
+ Format: {
349
+ "test_framework": "jest" | "vitest" | "mocha" | "other",
350
+ "test_patterns": {
351
+ "unit": "**/*.test.ts",
352
+ "integration": "**/*.integration.test.ts"
353
+ },
354
+ "coverage_summary": {
355
+ "lines": 75.5,
356
+ "branches": 68.2,
357
+ "functions": 80.1
358
+ },
359
+ "coverage_gaps": [...],
360
+ "test_utilities": [...],
361
+ "conventions": {
362
+ "naming": "describe/it",
363
+ "mocking": "jest.mock",
364
+ "assertions": "expect"
365
+ }
366
+ }
367
+ `
368
+ })
369
+
370
+ wait({ id: testAgent })
371
+ close_agent({ id: testAgent })
372
+
373
+ const testContext = JSON.parse(Read(`${sessionFolder}/.process/test-context-package.json`) || '{}')
374
+
375
+ // Update planning-notes
376
+ Edit(`${sessionFolder}/planning-notes.md`, {
377
+ oldText: '## TDD Principles',
378
+ newText: `## Test Context
379
+ - Framework: ${testContext.test_framework || 'unknown'}
380
+ - Coverage: ${testContext.coverage_summary?.lines || 'N/A'}% lines
381
+ - Gaps: ${(testContext.coverage_gaps || []).join(', ')}
382
+
383
+ ## TDD Principles`
384
+ })
385
+
386
+ console.log(` Test framework: ${testContext.test_framework}`)
387
+ ```
388
+
389
+ ---
390
+
391
+ ### Phase 4: Conflict Resolution (Conditional)
392
+
393
+ **Objective**: Detect and resolve conflicts when risk ≥ medium.
394
+
395
+ ```javascript
396
+ if (['medium', 'high'].includes(conflictRisk)) {
397
+ console.log(`\n## Phase 4: Conflict Resolution (risk: ${conflictRisk})\n`)
398
+
399
+ Bash({
400
+ command: `ccw cli -p "PURPOSE: Analyze and resolve conflicts between planned changes and existing codebase.
401
+ TASK:
402
+ • Read context package for conflict areas
403
+ Analyze each conflict area in detail
404
+ Propose resolution strategies (refactor, adapt, isolate, defer)
405
+ For each conflict: assess impact and recommend approach
406
+ MODE: analysis
407
+ CONTEXT: @**/*
408
+ EXPECTED: JSON: {conflicts: [{area, severity, description, strategy, impact}], summary: string}
409
+ CONSTRAINTS: Focus on ${(contextPkg.conflict_areas || []).join(', ')}
410
+
411
+ TASK DESCRIPTION: ${taskDescription}" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause`,
412
+ run_in_background: true
413
+ })
414
+ // Wait for CLI → conflicts[]
415
+
416
+ if (!AUTO_YES && conflicts.length > 0) {
417
+ // Present conflicts and let user select strategies
418
+ console.log(`\n### Conflicts Found: ${conflicts.length}\n`)
419
+ conflicts.forEach((c, i) => {
420
+ console.log(`${i + 1}. [${c.severity}] ${c.area}: ${c.description}`)
421
+ console.log(` Strategy: ${c.strategy} | Impact: ${c.impact}`)
422
+ })
423
+
424
+ const answer = request_user_input({
425
+ questions: [{
426
+ question: "Accept conflict resolution strategies?",
427
+ header: "Conflicts",
428
+ options: [
429
+ { label: "Accept All", description: "Apply all recommended strategies" },
430
+ { label: "Review Each", description: "Approve strategies individually" },
431
+ { label: "Skip", description: "Proceed without resolving" }
432
+ ]
433
+ }]
434
+ })
435
+ }
436
+
437
+ // Write resolution
438
+ Write(`${sessionFolder}/.process/conflict-resolution.json`,
439
+ JSON.stringify({ conflicts, resolved_at: getUtc8ISOString() }, null, 2))
440
+ } else {
441
+ console.log(` Conflict risk: ${conflictRisk} skipping Phase 4`)
442
+ }
443
+ ```
444
+
445
+ ---
446
+
447
+ ### Phase 5: TDD Task Generation (spawn_agent)
448
+
449
+ **Objective**: Generate IMPL_PLAN.md with Red-Green-Refactor cycles, task JSONs, TODO_LIST.md.
450
+
451
+ ```javascript
452
+ console.log(`\n## Phase 5: TDD Task Generation\n`)
453
+
454
+ const planAgent = spawn_agent({
455
+ agent: `~/.codex/agents/action-planning-agent.md`,
456
+ instruction: `
457
+ Generate TDD implementation plan with Red-Green-Refactor cycles.
458
+
459
+ **Session**: ${sessionFolder}
460
+ **Task**: ${taskDescription}
461
+ **Context**: ${sessionFolder}/.process/context-package.json
462
+ **Test Context**: ${sessionFolder}/.process/test-context-package.json
463
+ **Planning Notes**: ${sessionFolder}/planning-notes.md
464
+ ${conflictRisk === 'medium' || conflictRisk === 'high'
465
+ ? `**Conflict Resolution**: ${sessionFolder}/.process/conflict-resolution.json` : ''}
466
+
467
+ ### TDD Requirements
468
+ Each task MUST include Red-Green-Refactor cycle:
469
+ 1. **Red Phase**: Write failing test first
470
+ - Define test cases
471
+ - Verify test fails (proves test is valid)
472
+ - Document expected failure
473
+ 2. **Green Phase**: Implement minimal code to pass
474
+ - Write simplest implementation
475
+ - Run tests until passing
476
+ - Max 3 test-fix iterations (auto-revert if exceeded)
477
+ 3. **Refactor Phase**: Improve code quality
478
+ - Refactor with tests as safety net
479
+ - Maintain passing tests
480
+ - Document improvements
481
+
482
+ ### Output Requirements
483
+ 1. **IMPL_PLAN.md** at ${sessionFolder}/IMPL_PLAN.md
484
+ - Section 1: Requirements Summary
485
+ - Section 2: Test Strategy (framework, patterns, coverage goals)
486
+ - Section 3: Task Breakdown with TDD cycles
487
+ - Section 4: Implementation Strategy
488
+ - Section 5: Risk Assessment
489
+ 2. **plan.json** at ${sessionFolder}/plan.json
490
+ - {task_ids[], recommended_execution, complexity, tdd_compliance: true}
491
+ 3. **Task JSONs** at ${sessionFolder}/.task/IMPL-{N}.json
492
+ - Each task has "implementation" array with 3 steps:
493
+ [
494
+ {step: 1, tdd_phase: "red", description: "Write failing test", ...},
495
+ {step: 2, tdd_phase: "green", description: "Implement code", test_fix_cycle: {max_iterations: 3, auto_revert: true}},
496
+ {step: 3, tdd_phase: "refactor", description: "Refactor code", ...}
497
+ ]
498
+ 4. **TODO_LIST.md** at ${sessionFolder}/TODO_LIST.md
499
+ - Checkbox format: - [ ] IMPL-{N}: {title} (TDD)
500
+ `
501
+ })
502
+
503
+ wait({ id: planAgent })
504
+ close_agent({ id: planAgent })
505
+
506
+ console.log(` TDD tasks generated`)
507
+ ```
508
+
509
+ ---
510
+
511
+ ### Phase 6: TDD Structure Validation
512
+
513
+ **Objective**: Validate Red-Green-Refactor structure in all tasks.
514
+
515
+ ```javascript
516
+ console.log(`\n## Phase 6: TDD Structure Validation\n`)
517
+
518
+ // Read all task JSONs
519
+ const taskFiles = Bash(`ls ${sessionFolder}/.task/IMPL-*.json 2>/dev/null`).trim().split('\n').filter(Boolean)
520
+ const tasks = taskFiles.map(f => JSON.parse(Read(f)))
521
+
522
+ // Validate TDD structure
523
+ const validationErrors = []
524
+ for (const task of tasks) {
525
+ const impl = task.implementation || []
526
+
527
+ // Check 3-step structure
528
+ if (impl.length !== 3) {
529
+ validationErrors.push(`${task.id}: Expected 3 steps, found ${impl.length}`)
530
+ continue
531
+ }
532
+
533
+ // Check Red phase
534
+ if (impl[0].tdd_phase !== 'red') {
535
+ validationErrors.push(`${task.id}: Step 1 must be Red phase`)
536
+ }
537
+
538
+ // Check Green phase with test-fix-cycle
539
+ if (impl[1].tdd_phase !== 'green') {
540
+ validationErrors.push(`${task.id}: Step 2 must be Green phase`)
541
+ }
542
+ if (!impl[1].test_fix_cycle || !impl[1].test_fix_cycle.max_iterations) {
543
+ validationErrors.push(`${task.id}: Green phase missing test-fix-cycle config`)
544
+ }
545
+
546
+ // Check Refactor phase
547
+ if (impl[2].tdd_phase !== 'refactor') {
548
+ validationErrors.push(`${task.id}: Step 3 must be Refactor phase`)
549
+ }
550
+ }
551
+
552
+ if (validationErrors.length > 0) {
553
+ console.log(`\n### TDD Structure Validation Errors:\n`)
554
+ validationErrors.forEach(e => console.log(` - ${e}`))
555
+
556
+ if (!AUTO_YES) {
557
+ const answer = request_user_input({
558
+ questions: [{
559
+ question: "TDD structure validation failed. Continue anyway?",
560
+ header: "Validation",
561
+ options: [
562
+ { label: "Fix and Retry", description: "Regenerate tasks with correct structure" },
563
+ { label: "Continue", description: "Proceed despite errors" },
564
+ { label: "Abort", description: "Stop planning" }
565
+ ]
566
+ }]
567
+ })
568
+
569
+ if (answer.Validation === "Fix and Retry") {
570
+ // Re-run Phase 5
571
+ // → goto Phase 5
572
+ } else if (answer.Validation === "Abort") {
573
+ return
574
+ }
575
+ }
576
+ } else {
577
+ console.log(` ✓ All tasks have valid Red-Green-Refactor structure`)
578
+ }
579
+
580
+ // Plan Confirmation Gate
581
+ const taskCount = tasks.length
582
+ console.log(`\n## Plan Generated\n`)
583
+ console.log(` Tasks: ${taskCount}`)
584
+ console.log(` Plan: ${sessionFolder}/IMPL_PLAN.md`)
585
+
586
+ if (AUTO_YES) {
587
+ console.log(` [--yes] Auto-verifying TDD compliance...`)
588
+ // → Fall through to Phase 7
589
+ } else {
590
+ const nextStep = request_user_input({
591
+ questions: [{
592
+ question: "TDD plan generated. What's next?",
593
+ header: "Next Step",
594
+ options: [
595
+ { label: "Verify TDD Compliance (Recommended)", description: "Run full TDD compliance verification" },
596
+ { label: "Done", description: "Planning complete — show next-step command" },
597
+ { label: "Review Status", description: "Display plan summary inline" }
598
+ ]
599
+ }]
600
+ })
601
+
602
+ if (nextStep['Next Step'] === 'Done') {
603
+ console.log(`\nPlanning complete. To execute, run: $workflow-execute --session ${sessionId}`)
604
+ return // STOP — this skill is planning-only
605
+ }
606
+ if (nextStep['Next Step'] === 'Review Status') {
607
+ const plan = Read(`${sessionFolder}/IMPL_PLAN.md`)
608
+ console.log(plan)
609
+ return // STOP — this skill is planning-only
610
+ }
611
+ // Verify continue to Phase 7
612
+ }
613
+ ```
614
+
615
+ ---
616
+
617
+ ### Phase 7: TDD Verification (Verify Mode)
618
+
619
+ **Objective**: Full TDD compliance verification with quality gate.
620
+
621
+ ```javascript
622
+ if (mode === 'verify' || /* auto-verify from Phase 6 */) {
623
+ console.log(`\n## Phase 7: TDD Verification\n`)
624
+
625
+ // Find session if in verify mode entry
626
+ if (mode === 'verify' && !sessionFolder) {
627
+ // Session discovery (same logic as Phase 1)
628
+ }
629
+
630
+ const verifyAgent = spawn_agent({
631
+ agent: `~/.codex/agents/cli-explore-agent.md`,
632
+ instruction: `
633
+ Verify TDD compliance across 4 dimensions.
634
+
635
+ **Session**: ${sessionFolder}
636
+
637
+ ### Verification Dimensions
638
+
639
+ **A. Test-First Structure**
640
+ - Every task has Red-Green-Refactor cycle
641
+ - Red phase defines failing tests
642
+ - Green phase implements code
643
+ - Refactor phase improves quality
644
+
645
+ **B. Test Coverage**
646
+ - All critical paths have tests
647
+ - Edge cases covered
648
+ - Integration points tested
649
+ - Coverage meets project standards
650
+
651
+ **C. Cycle Integrity**
652
+ - Red phase: test fails before implementation
653
+ - Green phase: minimal code to pass
654
+ - Refactor phase: maintains passing tests
655
+ - No production code without failing test first
656
+
657
+ **D. Quality Gates**
658
+ - Test-fix-cycle configured (max 3 iterations)
659
+ - Auto-revert on iteration limit
660
+ - Clear acceptance criteria
661
+ - Testable convergence conditions
662
+
663
+ ### Output
664
+ Write report to: ${sessionFolder}/.process/TDD_COMPLIANCE_REPORT.md
665
+
666
+ Format:
667
+ # TDD Compliance Report
668
+
669
+ ## Summary
670
+ - Quality Gate: APPROVED | CONDITIONAL | BLOCKED
671
+ - Tasks Analyzed: N
672
+ - Compliance Score: X%
673
+
674
+ ## Dimension Scores
675
+ - A. Test-First Structure: PASS/WARN/FAIL
676
+ - B. Test Coverage: PASS/WARN/FAIL
677
+ - C. Cycle Integrity: PASS/WARN/FAIL
678
+ - D. Quality Gates: PASS/WARN/FAIL
679
+
680
+ ## Issues Found
681
+ [List specific issues with task IDs]
682
+
683
+ ## Recommendations
684
+ [Actionable recommendations]
685
+
686
+ ## Quality Gate Decision
687
+ APPROVED: All dimensions PASS, ready for execution
688
+ CONDITIONAL: Minor warnings, can proceed with caution
689
+ BLOCKED: Critical failures, must fix before execution
690
+ `
691
+ })
692
+
693
+ wait({ id: verifyAgent })
694
+ close_agent({ id: verifyAgent })
695
+
696
+ const report = Read(`${sessionFolder}/.process/TDD_COMPLIANCE_REPORT.md`)
697
+ const qualityGate = report.match(/Quality Gate: (\w+)/)?.[1] || 'UNKNOWN'
698
+
699
+ console.log(` Quality gate: ${qualityGate}`)
700
+ console.log(` Report: ${sessionFolder}/.process/TDD_COMPLIANCE_REPORT.md`)
701
+
702
+ console.log(`\nPlanning complete. To execute, run: $workflow-execute --session ${sessionId}`)
703
+ // STOP — this skill is planning-only, NEVER proceed to execution
704
+ }
705
+ ```
706
+
707
+ ---
708
+
709
+ ## Error Handling
710
+
711
+ | Error | Recovery |
712
+ |-------|----------|
713
+ | No active session | Guide: run `$workflow-tdd-plan "description"` first |
714
+ | Context gathering timeout | Retry with reduced scope |
715
+ | Test framework detection failed | Manual specification in test-context-package.json |
716
+ | TDD structure validation failed | Regenerate tasks or fix manually |
717
+ | Conflict analysis failure | Skip Phase 4, proceed with warning |
718
+ | Task generation failure | Retry agent with simplified context |
719
+ | Verification failure | Display partial results |
720
+ | Session not found (verify) | List available sessions |
721
+
722
+ ---
723
+
724
+ ## TDD Compliance Requirements
725
+
726
+ ### The Iron Law
727
+
728
+ ```
729
+ NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
730
+ ```
731
+
732
+ ### Red-Green-Refactor Cycle
733
+
734
+ Every task must have:
735
+ 1. **Red**: Write failing test (proves test is valid)
736
+ 2. **Green**: Implement minimal code to pass (with test-fix-cycle)
737
+ 3. **Refactor**: Improve code quality (maintain passing tests)
738
+
739
+ ### Quality Gates
740
+
741
+ - Test-fix-cycle: max 3 iterations
742
+ - Auto-revert: triggered when max iterations reached
743
+ - Coverage goals: defined per project
744
+ - Acceptance criteria: testable and measurable
745
+
746
+ ---
747
+
748
+ ## Compact Protection
749
+
750
+ > **COMPACT DIRECTIVE**: If context compression occurs:
751
+ > - Re-read `planning-notes.md` for accumulated context
752
+ > - Re-read `workflow-session.json` for session state
753
+ > - Phase 5 is the most token-intensive — if compressed, re-read task JSONs on demand