relay-cc 2.0.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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +428 -0
  3. package/agents/relay-codebase-mapper.md +761 -0
  4. package/agents/relay-debugger.md +1203 -0
  5. package/agents/relay-estimator.md +257 -0
  6. package/agents/relay-executor.md +823 -0
  7. package/agents/relay-plan-checker.md +812 -0
  8. package/agents/relay-planner.md +1418 -0
  9. package/agents/relay-reviewer.md +279 -0
  10. package/agents/relay-ticket-researcher.md +287 -0
  11. package/agents/relay-verifier.md +778 -0
  12. package/bin/install.js +1667 -0
  13. package/commands/relay/add-todo.md +193 -0
  14. package/commands/relay/check-todos.md +200 -0
  15. package/commands/relay/debug.md +169 -0
  16. package/commands/relay/estimate.md +182 -0
  17. package/commands/relay/help.md +328 -0
  18. package/commands/relay/history.md +203 -0
  19. package/commands/relay/map-codebase.md +71 -0
  20. package/commands/relay/pause-work.md +128 -0
  21. package/commands/relay/pr.md +223 -0
  22. package/commands/relay/quick.md +307 -0
  23. package/commands/relay/resume-work.md +40 -0
  24. package/commands/relay/resume.md +181 -0
  25. package/commands/relay/review.md +322 -0
  26. package/commands/relay/rollback.md +248 -0
  27. package/commands/relay/set-profile.md +116 -0
  28. package/commands/relay/settings.md +165 -0
  29. package/commands/relay/setup.md +247 -0
  30. package/commands/relay/status.md +131 -0
  31. package/commands/relay/tickets.md +106 -0
  32. package/commands/relay/update.md +200 -0
  33. package/commands/relay/work.md +398 -0
  34. package/hooks/dist/relay-check-update.js +61 -0
  35. package/hooks/dist/relay-statusline.js +91 -0
  36. package/package.json +47 -0
  37. package/relay/references/checkpoints.md +1078 -0
  38. package/relay/references/continuation-format.md +249 -0
  39. package/relay/references/git-integration.md +209 -0
  40. package/relay/references/model-profiles.md +57 -0
  41. package/relay/references/planning-config.md +189 -0
  42. package/relay/references/questioning.md +141 -0
  43. package/relay/references/tdd.md +263 -0
  44. package/relay/references/ui-brand.md +162 -0
  45. package/relay/references/verification-patterns.md +612 -0
  46. package/relay/templates/DEBUG.md +159 -0
  47. package/relay/templates/UAT.md +247 -0
  48. package/relay/templates/analysis.md +101 -0
  49. package/relay/templates/codebase/architecture.md +255 -0
  50. package/relay/templates/codebase/concerns.md +310 -0
  51. package/relay/templates/codebase/conventions.md +307 -0
  52. package/relay/templates/codebase/integrations.md +280 -0
  53. package/relay/templates/codebase/stack.md +186 -0
  54. package/relay/templates/codebase/structure.md +285 -0
  55. package/relay/templates/codebase/testing.md +480 -0
  56. package/relay/templates/config.json +40 -0
  57. package/relay/templates/context.md +283 -0
  58. package/relay/templates/continue-here.md +78 -0
  59. package/relay/templates/debug-subagent-prompt.md +91 -0
  60. package/relay/templates/estimate.md +108 -0
  61. package/relay/templates/phase-prompt.md +567 -0
  62. package/relay/templates/planner-subagent-prompt.md +117 -0
  63. package/relay/templates/research.md +552 -0
  64. package/relay/templates/state.md +127 -0
  65. package/relay/templates/summary.md +246 -0
  66. package/relay/templates/verification-report.md +322 -0
  67. package/relay/workflows/analyze-ticket.md +42 -0
  68. package/relay/workflows/diagnose-issues.md +231 -0
  69. package/relay/workflows/execute-phase.md +700 -0
  70. package/relay/workflows/execute-plan.md +1851 -0
  71. package/relay/workflows/map-codebase.md +357 -0
  72. package/relay/workflows/resume-project.md +307 -0
  73. package/relay/workflows/sync-ticket.md +58 -0
  74. package/relay/workflows/verify-phase.md +628 -0
  75. package/relay/workflows/verify-ticket.md +596 -0
  76. package/scripts/build-hooks.js +42 -0
@@ -0,0 +1,1851 @@
1
+ <purpose>
2
+ Execute a phase prompt (PLAN.md) and create the outcome summary (SUMMARY.md).
3
+ </purpose>
4
+
5
+ <required_reading>
6
+ Read STATE.md before any operation to load project context.
7
+ Read config.json for planning behavior settings.
8
+
9
+ @~/.claude/relay/references/git-integration.md
10
+ </required_reading>
11
+
12
+ <process>
13
+
14
+ <step name="resolve_model_profile" priority="first">
15
+ Read model profile for agent spawning:
16
+
17
+ ```bash
18
+ MODEL_PROFILE=$(cat .relay/config.json 2>/dev/null | grep -o '"model_profile"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' || echo "balanced")
19
+ ```
20
+
21
+ Default to "balanced" if not set.
22
+
23
+ **Model lookup table:**
24
+
25
+ | Agent | quality | balanced | budget |
26
+ |-------|---------|----------|--------|
27
+ | relay-executor | opus | sonnet | sonnet |
28
+
29
+ Store resolved model for use in Task calls below.
30
+ </step>
31
+
32
+ <step name="load_project_state">
33
+ Before any operation, read project state:
34
+
35
+ ```bash
36
+ cat .relay/STATE.md 2>/dev/null
37
+ ```
38
+
39
+ **If file exists:** Parse and internalize:
40
+
41
+ - Current position (phase, plan, status)
42
+ - Accumulated decisions (constraints on this execution)
43
+ - Blockers/concerns (things to watch for)
44
+ - Brief alignment status
45
+
46
+ **If file missing but .relay/ exists:**
47
+
48
+ ```
49
+ STATE.md missing but planning artifacts exist.
50
+ Options:
51
+ 1. Reconstruct from existing artifacts
52
+ 2. Continue without project state (may lose accumulated context)
53
+ ```
54
+
55
+ **If .relay/ doesn't exist:** Error - project not initialized.
56
+
57
+ This ensures every execution has full project context.
58
+
59
+ **Load planning config:**
60
+
61
+ ```bash
62
+ # Check if planning docs should be committed (default: true)
63
+ COMMIT_PLANNING_DOCS=$(cat .relay/config.json 2>/dev/null | grep -o '"commit_docs"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")
64
+ # Auto-detect gitignored (overrides config)
65
+ git check-ignore -q .relay 2>/dev/null && COMMIT_PLANNING_DOCS=false
66
+ ```
67
+
68
+ Store `COMMIT_PLANNING_DOCS` for use in git operations.
69
+ </step>
70
+
71
+ <step name="identify_plan">
72
+ Find the next plan to execute:
73
+ - Check roadmap for "In progress" phase
74
+ - Find plans in that phase directory
75
+ - Identify first plan without corresponding SUMMARY
76
+
77
+ ```bash
78
+ cat .relay/ROADMAP.md
79
+ # Look for phase with "In progress" status
80
+ # Then find plans in that phase
81
+ ls .relay/tickets/XX-name/*-PLAN.md 2>/dev/null | sort
82
+ ls .relay/tickets/XX-name/*-SUMMARY.md 2>/dev/null | sort
83
+ ```
84
+
85
+ **Logic:**
86
+
87
+ - If `01-01-PLAN.md` exists but `01-01-SUMMARY.md` doesn't → execute 01-01
88
+ - If `01-01-SUMMARY.md` exists but `01-02-SUMMARY.md` doesn't → execute 01-02
89
+ - Pattern: Find first PLAN file without matching SUMMARY file
90
+
91
+ **Decimal phase handling:**
92
+
93
+ Phase directories can be integer or decimal format:
94
+
95
+ - Integer: `.relay/tickets/01-foundation/01-01-PLAN.md`
96
+ - Decimal: `.relay/tickets/01.1-hotfix/01.1-01-PLAN.md`
97
+
98
+ Parse phase number from path (handles both formats):
99
+
100
+ ```bash
101
+ # Extract phase number (handles XX or XX.Y format)
102
+ PHASE=$(echo "$PLAN_PATH" | grep -oE '[0-9]+(\.[0-9]+)?-[0-9]+')
103
+ ```
104
+
105
+ SUMMARY naming follows same pattern:
106
+
107
+ - Integer: `01-01-SUMMARY.md`
108
+ - Decimal: `01.1-01-SUMMARY.md`
109
+
110
+ Confirm with user if ambiguous.
111
+
112
+ <config-check>
113
+ ```bash
114
+ cat .relay/config.json 2>/dev/null
115
+ ```
116
+ </config-check>
117
+
118
+ <if mode="yolo">
119
+ ```
120
+ ⚡ Auto-approved: Execute {phase}-{plan}-PLAN.md
121
+ [Plan X of Y for Phase Z]
122
+
123
+ Starting execution...
124
+ ```
125
+
126
+ Proceed directly to parse_segments step.
127
+ </if>
128
+
129
+ <if mode="interactive" OR="custom with gates.execute_next_plan true">
130
+ Present:
131
+
132
+ ```
133
+ Found plan to execute: {phase}-{plan}-PLAN.md
134
+ [Plan X of Y for Phase Z]
135
+
136
+ Proceed with execution?
137
+ ```
138
+
139
+ Wait for confirmation before proceeding.
140
+ </if>
141
+ </step>
142
+
143
+ <step name="record_start_time">
144
+ Record execution start time for performance tracking:
145
+
146
+ ```bash
147
+ PLAN_START_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
148
+ PLAN_START_EPOCH=$(date +%s)
149
+ ```
150
+
151
+ Store in shell variables for duration calculation at completion.
152
+ </step>
153
+
154
+ <step name="parse_segments">
155
+ **Intelligent segmentation: Parse plan into execution segments.**
156
+
157
+ Plans are divided into segments by checkpoints. Each segment is routed to optimal execution context (subagent or main).
158
+
159
+ **1. Check for checkpoints:**
160
+
161
+ ```bash
162
+ # Find all checkpoints and their types
163
+ grep -n "type=\"checkpoint" .relay/tickets/XX-name/{phase}-{plan}-PLAN.md
164
+ ```
165
+
166
+ **2. Analyze execution strategy:**
167
+
168
+ **If NO checkpoints found:**
169
+
170
+ - **Fully autonomous plan** - spawn single subagent for entire plan
171
+ - Subagent gets fresh 200k context, executes all tasks, creates SUMMARY, commits
172
+ - Main context: Just orchestration (~5% usage)
173
+
174
+ **If checkpoints found, parse into segments:**
175
+
176
+ Segment = tasks between checkpoints (or start→first checkpoint, or last checkpoint→end)
177
+
178
+ **For each segment, determine routing:**
179
+
180
+ ```
181
+ Segment routing rules:
182
+
183
+ IF segment has no prior checkpoint:
184
+ → SUBAGENT (first segment, nothing to depend on)
185
+
186
+ IF segment follows checkpoint:human-verify:
187
+ → SUBAGENT (verification is just confirmation, doesn't affect next work)
188
+
189
+ IF segment follows checkpoint:decision OR checkpoint:human-action:
190
+ → MAIN CONTEXT (next tasks need the decision/result)
191
+ ```
192
+
193
+ **3. Execution pattern:**
194
+
195
+ **Pattern A: Fully autonomous (no checkpoints)**
196
+
197
+ ```
198
+ Spawn subagent → execute all tasks → SUMMARY → commit → report back
199
+ ```
200
+
201
+ **Pattern B: Segmented with verify-only checkpoints**
202
+
203
+ ```
204
+ Segment 1 (tasks 1-3): Spawn subagent → execute → report back
205
+ Checkpoint 4 (human-verify): Main context → you verify → continue
206
+ Segment 2 (tasks 5-6): Spawn NEW subagent → execute → report back
207
+ Checkpoint 7 (human-verify): Main context → you verify → continue
208
+ Aggregate results → SUMMARY → commit
209
+ ```
210
+
211
+ **Pattern C: Decision-dependent (must stay in main)**
212
+
213
+ ```
214
+ Checkpoint 1 (decision): Main context → you decide → continue in main
215
+ Tasks 2-5: Main context (need decision from checkpoint 1)
216
+ No segmentation benefit - execute entirely in main
217
+ ```
218
+
219
+ **4. Why segment:** Fresh context per subagent preserves peak quality. Main context stays lean (~15% usage).
220
+
221
+ **5. Implementation:**
222
+
223
+ **For fully autonomous plans:**
224
+
225
+ ```
226
+ 1. Run init_agent_tracking step first (see step below)
227
+
228
+ 2. Use Task tool with subagent_type="relay-executor" and model="{executor_model}":
229
+
230
+ Prompt: "Execute plan at .relay/tickets/{phase}-{plan}-PLAN.md
231
+
232
+ This is an autonomous plan (no checkpoints). Execute all tasks, create SUMMARY.md in phase directory, commit with message following plan's commit guidance.
233
+
234
+ Follow all deviation rules and authentication gate protocols from the plan.
235
+
236
+ When complete, report: plan name, tasks completed, SUMMARY path, commit hash."
237
+
238
+ 3. After Task tool returns with agent_id:
239
+
240
+ a. Write agent_id to current-agent-id.txt:
241
+ echo "[agent_id]" > .relay/current-agent-id.txt
242
+
243
+ b. Append spawn entry to agent-history.json:
244
+ {
245
+ "agent_id": "[agent_id from Task response]",
246
+ "task_description": "Execute full plan {phase}-{plan} (autonomous)",
247
+ "phase": "{phase}",
248
+ "plan": "{plan}",
249
+ "segment": null,
250
+ "timestamp": "[ISO timestamp]",
251
+ "status": "spawned",
252
+ "completion_timestamp": null
253
+ }
254
+
255
+ 4. Wait for subagent to complete
256
+
257
+ 5. After subagent completes successfully:
258
+
259
+ a. Update agent-history.json entry:
260
+ - Find entry with matching agent_id
261
+ - Set status: "completed"
262
+ - Set completion_timestamp: "[ISO timestamp]"
263
+
264
+ b. Clear current-agent-id.txt:
265
+ rm .relay/current-agent-id.txt
266
+
267
+ 6. Report completion to user
268
+ ```
269
+
270
+ **For segmented plans (has verify-only checkpoints):**
271
+
272
+ ```
273
+ Execute segment-by-segment:
274
+
275
+ For each autonomous segment:
276
+ Spawn subagent with prompt: "Execute tasks [X-Y] from plan at .relay/tickets/{phase}-{plan}-PLAN.md. Read the plan for full context and deviation rules. Do NOT create SUMMARY or commit - just execute these tasks and report results."
277
+
278
+ Wait for subagent completion
279
+
280
+ For each checkpoint:
281
+ Execute in main context
282
+ Wait for user interaction
283
+ Continue to next segment
284
+
285
+ After all segments complete:
286
+ Aggregate all results
287
+ Create SUMMARY.md
288
+ Commit with all changes
289
+ ```
290
+
291
+ **For decision-dependent plans:**
292
+
293
+ ```
294
+ Execute in main context (standard flow below)
295
+ No subagent routing
296
+ Quality maintained through small scope (2-3 tasks per plan)
297
+ ```
298
+
299
+ See step name="segment_execution" for detailed segment execution loop.
300
+ </step>
301
+
302
+ <step name="init_agent_tracking">
303
+ **Initialize agent tracking for subagent resume capability.**
304
+
305
+ Before spawning any subagents, set up tracking infrastructure:
306
+
307
+ **1. Create/verify tracking files:**
308
+
309
+ ```bash
310
+ # Create agent history file if doesn't exist
311
+ if [ ! -f .relay/agent-history.json ]; then
312
+ echo '{"version":"1.0","max_entries":50,"entries":[]}' > .relay/agent-history.json
313
+ fi
314
+
315
+ # Clear any stale current-agent-id (from interrupted sessions)
316
+ # Will be populated when subagent spawns
317
+ rm -f .relay/current-agent-id.txt
318
+ ```
319
+
320
+ **2. Check for interrupted agents (resume detection):**
321
+
322
+ ```bash
323
+ # Check if current-agent-id.txt exists from previous interrupted session
324
+ if [ -f .relay/current-agent-id.txt ]; then
325
+ INTERRUPTED_ID=$(cat .relay/current-agent-id.txt)
326
+ echo "Found interrupted agent: $INTERRUPTED_ID"
327
+ fi
328
+ ```
329
+
330
+ **If interrupted agent found:**
331
+ - The agent ID file exists from a previous session that didn't complete
332
+ - This agent can potentially be resumed using Task tool's `resume` parameter
333
+ - Present to user: "Previous session was interrupted. Resume agent [ID] or start fresh?"
334
+ - If resume: Use Task tool with `resume` parameter set to the interrupted ID
335
+ - If fresh: Clear the file and proceed normally
336
+
337
+ **3. Prune old entries (housekeeping):**
338
+
339
+ If agent-history.json has more than `max_entries`:
340
+ - Remove oldest entries with status "completed"
341
+ - Never remove entries with status "spawned" (may need resume)
342
+ - Keep file under size limit for fast reads
343
+
344
+ **When to run this step:**
345
+ - Pattern A (fully autonomous): Before spawning the single subagent
346
+ - Pattern B (segmented): Before the segment execution loop
347
+ - Pattern C (main context): Skip - no subagents spawned
348
+ </step>
349
+
350
+ <step name="segment_execution">
351
+ **Detailed segment execution loop for segmented plans.**
352
+
353
+ **This step applies ONLY to segmented plans (Pattern B: has checkpoints, but they're verify-only).**
354
+
355
+ For Pattern A (fully autonomous) and Pattern C (decision-dependent), skip this step.
356
+
357
+ **Execution flow:**
358
+
359
+ ````
360
+ 1. Parse plan to identify segments:
361
+ - Read plan file
362
+ - Find checkpoint locations: grep -n "type=\"checkpoint" PLAN.md
363
+ - Identify checkpoint types: grep "type=\"checkpoint" PLAN.md | grep -o 'checkpoint:[^"]*'
364
+ - Build segment map:
365
+ * Segment 1: Start → first checkpoint (tasks 1-X)
366
+ * Checkpoint 1: Type and location
367
+ * Segment 2: After checkpoint 1 → next checkpoint (tasks X+1 to Y)
368
+ * Checkpoint 2: Type and location
369
+ * ... continue for all segments
370
+
371
+ 2. For each segment in order:
372
+
373
+ A. Determine routing (apply rules from parse_segments):
374
+ - No prior checkpoint? → Subagent
375
+ - Prior checkpoint was human-verify? → Subagent
376
+ - Prior checkpoint was decision/human-action? → Main context
377
+
378
+ B. If routing = Subagent:
379
+ ```
380
+ Spawn Task tool with subagent_type="relay-executor" and model="{executor_model}":
381
+
382
+ Prompt: "Execute tasks [task numbers/names] from plan at [plan path].
383
+
384
+ **Context:**
385
+ - Read the full plan for objective, context files, and deviation rules
386
+ - You are executing a SEGMENT of this plan (not the full plan)
387
+ - Other segments will be executed separately
388
+
389
+ **Your responsibilities:**
390
+ - Execute only the tasks assigned to you
391
+ - Follow all deviation rules and authentication gate protocols
392
+ - Track deviations for later Summary
393
+ - DO NOT create SUMMARY.md (will be created after all segments complete)
394
+ - DO NOT commit (will be done after all segments complete)
395
+
396
+ **Report back:**
397
+ - Tasks completed
398
+ - Files created/modified
399
+ - Deviations encountered
400
+ - Any issues or blockers"
401
+
402
+ **After Task tool returns with agent_id:**
403
+
404
+ 1. Write agent_id to current-agent-id.txt:
405
+ echo "[agent_id]" > .relay/current-agent-id.txt
406
+
407
+ 2. Append spawn entry to agent-history.json:
408
+ {
409
+ "agent_id": "[agent_id from Task response]",
410
+ "task_description": "Execute tasks [X-Y] from plan {phase}-{plan}",
411
+ "phase": "{phase}",
412
+ "plan": "{plan}",
413
+ "segment": [segment_number],
414
+ "timestamp": "[ISO timestamp]",
415
+ "status": "spawned",
416
+ "completion_timestamp": null
417
+ }
418
+
419
+ Wait for subagent to complete
420
+ Capture results (files changed, deviations, etc.)
421
+
422
+ **After subagent completes successfully:**
423
+
424
+ 1. Update agent-history.json entry:
425
+ - Find entry with matching agent_id
426
+ - Set status: "completed"
427
+ - Set completion_timestamp: "[ISO timestamp]"
428
+
429
+ 2. Clear current-agent-id.txt:
430
+ rm .relay/current-agent-id.txt
431
+
432
+ ```
433
+
434
+ C. If routing = Main context:
435
+ Execute tasks in main using standard execution flow (step name="execute")
436
+ Track results locally
437
+
438
+ D. After segment completes (whether subagent or main):
439
+ Continue to next checkpoint/segment
440
+
441
+ 3. After ALL segments complete:
442
+
443
+ A. Aggregate results from all segments:
444
+ - Collect files created/modified from all segments
445
+ - Collect deviations from all segments
446
+ - Collect decisions from all checkpoints
447
+ - Merge into complete picture
448
+
449
+ B. Create SUMMARY.md:
450
+ - Use aggregated results
451
+ - Document all work from all segments
452
+ - Include deviations from all segments
453
+ - Note which segments were subagented
454
+
455
+ C. Commit:
456
+ - Stage all files from all segments
457
+ - Stage SUMMARY.md
458
+ - Commit with message following plan guidance
459
+ - Include note about segmented execution if relevant
460
+
461
+ D. Report completion
462
+
463
+ E. Self-check the aggregated SUMMARY:
464
+ - Parse `key-files.created` from the SUMMARY frontmatter
465
+ - Verify first 2 files exist on disk with `[ -f ]`
466
+ - Check `git log --oneline --all --grep="{phase}-{plan}"` returns at least 1 commit
467
+ - If any check fails: append `## Self-Check: FAILED` section to SUMMARY listing missing items
468
+ - If all pass: append `## Self-Check: PASSED`
469
+
470
+ **Example execution trace:**
471
+
472
+ ````
473
+
474
+ Plan: 01-02-PLAN.md (8 tasks, 2 verify checkpoints)
475
+
476
+ Parsing segments...
477
+
478
+ - Segment 1: Tasks 1-3 (autonomous)
479
+ - Checkpoint 4: human-verify
480
+ - Segment 2: Tasks 5-6 (autonomous)
481
+ - Checkpoint 7: human-verify
482
+ - Segment 3: Task 8 (autonomous)
483
+
484
+ Routing analysis:
485
+
486
+ - Segment 1: No prior checkpoint → SUBAGENT ✓
487
+ - Checkpoint 4: Verify only → MAIN (required)
488
+ - Segment 2: After verify → SUBAGENT ✓
489
+ - Checkpoint 7: Verify only → MAIN (required)
490
+ - Segment 3: After verify → SUBAGENT ✓
491
+
492
+ Execution:
493
+ [1] Spawning subagent for tasks 1-3...
494
+ → Subagent completes: 3 files modified, 0 deviations
495
+ [2] Executing checkpoint 4 (human-verify)...
496
+ ╔═══════════════════════════════════════════════════════╗
497
+ ║ CHECKPOINT: Verification Required ║
498
+ ╚═══════════════════════════════════════════════════════╝
499
+
500
+ Progress: 3/8 tasks complete
501
+ Task: Verify database schema
502
+
503
+ Built: User and Session tables with relations
504
+
505
+ How to verify:
506
+ 1. Check src/db/schema.ts for correct types
507
+
508
+ ────────────────────────────────────────────────────────
509
+ → YOUR ACTION: Type "approved" or describe issues
510
+ ────────────────────────────────────────────────────────
511
+ User: "approved"
512
+ [3] Spawning subagent for tasks 5-6...
513
+ → Subagent completes: 2 files modified, 1 deviation (added error handling)
514
+ [4] Executing checkpoint 7 (human-verify)...
515
+ User: "approved"
516
+ [5] Spawning subagent for task 8...
517
+ → Subagent completes: 1 file modified, 0 deviations
518
+
519
+ Aggregating results...
520
+
521
+ - Total files: 6 modified
522
+ - Total deviations: 1
523
+ - Segmented execution: 3 subagents, 2 checkpoints
524
+
525
+ Creating SUMMARY.md...
526
+ Committing...
527
+ ✓ Complete
528
+
529
+ ````
530
+
531
+ **Benefit:** Each subagent starts fresh (~20-30% context), enabling larger plans without quality degradation.
532
+ </step>
533
+
534
+ <step name="load_prompt">
535
+ Read the plan prompt:
536
+ ```bash
537
+ cat .relay/tickets/XX-name/{phase}-{plan}-PLAN.md
538
+ ````
539
+
540
+ This IS the execution instructions. Follow it exactly.
541
+
542
+ **If plan references CONTEXT.md:**
543
+ The CONTEXT.md file provides the user's vision for this phase — how they imagine it working, what's essential, and what's out of scope. Honor this context throughout execution.
544
+ </step>
545
+
546
+ <step name="previous_phase_check">
547
+ Before executing, check if previous phase had issues:
548
+
549
+ ```bash
550
+ # Find previous phase summary
551
+ ls .relay/tickets/*/SUMMARY.md 2>/dev/null | sort -r | head -2 | tail -1
552
+ ```
553
+
554
+ If previous phase SUMMARY.md has "Issues Encountered" != "None" or "Next Phase Readiness" mentions blockers:
555
+
556
+ Use AskUserQuestion:
557
+
558
+ - header: "Previous Issues"
559
+ - question: "Previous phase had unresolved items: [summary]. How to proceed?"
560
+ - options:
561
+ - "Proceed anyway" - Issues won't block this phase
562
+ - "Address first" - Let's resolve before continuing
563
+ - "Review previous" - Show me the full summary
564
+ </step>
565
+
566
+ <step name="execute">
567
+ Execute each task in the prompt. **Deviations are normal** - handle them automatically using embedded rules below.
568
+
569
+ 1. Read the @context files listed in the prompt
570
+
571
+ 2. For each task:
572
+
573
+ **If `type="auto"`:**
574
+
575
+ **Before executing:** Check if task has `tdd="true"` attribute:
576
+ - If yes: Follow TDD execution flow (see `<tdd_execution>`) - RED → GREEN → REFACTOR cycle with atomic commits per stage
577
+ - If no: Standard implementation
578
+
579
+ - Work toward task completion
580
+ - **If CLI/API returns authentication error:** Handle as authentication gate (see below)
581
+ - **When you discover additional work not in plan:** Apply deviation rules (see below) automatically
582
+ - Continue implementing, applying rules as needed
583
+ - Run the verification
584
+ - Confirm done criteria met
585
+ - **Commit the task** (see `<task_commit>` below)
586
+ - Track task completion and commit hash for Summary documentation
587
+ - Continue to next task
588
+
589
+ **If `type="checkpoint:*"`:**
590
+
591
+ - STOP immediately (do not continue to next task)
592
+ - Execute checkpoint_protocol (see below)
593
+ - Wait for user response
594
+ - Verify if possible (check files, env vars, etc.)
595
+ - Only after user confirmation: continue to next task
596
+
597
+ 3. Run overall verification checks from `<verification>` section
598
+ 4. Confirm all success criteria from `<success_criteria>` section met
599
+ 5. Document all deviations in Summary (automatic - see deviation_documentation below)
600
+ </step>
601
+
602
+ <authentication_gates>
603
+
604
+ ## Handling Authentication Errors During Execution
605
+
606
+ **When you encounter authentication errors during `type="auto"` task execution:**
607
+
608
+ This is NOT a failure. Authentication gates are expected and normal. Handle them dynamically:
609
+
610
+ **Authentication error indicators:**
611
+
612
+ - CLI returns: "Error: Not authenticated", "Not logged in", "Unauthorized", "401", "403"
613
+ - API returns: "Authentication required", "Invalid API key", "Missing credentials"
614
+ - Command fails with: "Please run {tool} login" or "Set {ENV_VAR} environment variable"
615
+
616
+ **Authentication gate protocol:**
617
+
618
+ 1. **Recognize it's an auth gate** - Not a bug, just needs credentials
619
+ 2. **STOP current task execution** - Don't retry repeatedly
620
+ 3. **Create dynamic checkpoint:human-action** - Present it to user immediately
621
+ 4. **Provide exact authentication steps** - CLI commands, where to get keys
622
+ 5. **Wait for user to authenticate** - Let them complete auth flow
623
+ 6. **Verify authentication works** - Test that credentials are valid
624
+ 7. **Retry the original task** - Resume automation where you left off
625
+ 8. **Continue normally** - Don't treat this as an error in Summary
626
+
627
+ **Example: Vercel deployment hits auth error**
628
+
629
+ ```
630
+ Task 3: Deploy to Vercel
631
+ Running: vercel --yes
632
+
633
+ Error: Not authenticated. Please run 'vercel login'
634
+
635
+ [Create checkpoint dynamically]
636
+
637
+ ╔═══════════════════════════════════════════════════════╗
638
+ ║ CHECKPOINT: Action Required ║
639
+ ╚═══════════════════════════════════════════════════════╝
640
+
641
+ Progress: 2/8 tasks complete
642
+ Task: Authenticate Vercel CLI
643
+
644
+ Attempted: vercel --yes
645
+ Error: Not authenticated
646
+
647
+ What you need to do:
648
+ 1. Run: vercel login
649
+ 2. Complete browser authentication
650
+
651
+ I'll verify: vercel whoami returns your account
652
+
653
+ ────────────────────────────────────────────────────────
654
+ → YOUR ACTION: Type "done" when authenticated
655
+ ────────────────────────────────────────────────────────
656
+
657
+ [Wait for user response]
658
+
659
+ [User types "done"]
660
+
661
+ Verifying authentication...
662
+ Running: vercel whoami
663
+ ✓ Authenticated as: user@example.com
664
+
665
+ Retrying deployment...
666
+ Running: vercel --yes
667
+ ✓ Deployed to: https://myapp-abc123.vercel.app
668
+
669
+ Task 3 complete. Continuing to task 4...
670
+ ```
671
+
672
+ **In Summary documentation:**
673
+
674
+ Document authentication gates as normal flow, not deviations:
675
+
676
+ ```markdown
677
+ ## Authentication Gates
678
+
679
+ During execution, I encountered authentication requirements:
680
+
681
+ 1. Task 3: Vercel CLI required authentication
682
+ - Paused for `vercel login`
683
+ - Resumed after authentication
684
+ - Deployed successfully
685
+
686
+ These are normal gates, not errors.
687
+ ```
688
+
689
+ **Key principles:**
690
+
691
+ - Authentication gates are NOT failures or bugs
692
+ - They're expected interaction points during first-time setup
693
+ - Handle them gracefully and continue automation after unblocked
694
+ - Don't mark tasks as "failed" or "incomplete" due to auth gates
695
+ - Document them as normal flow, separate from deviations
696
+ </authentication_gates>
697
+
698
+ <deviation_rules>
699
+
700
+ ## Automatic Deviation Handling
701
+
702
+ **While executing tasks, you WILL discover work not in the plan.** This is normal.
703
+
704
+ Apply these rules automatically. Track all deviations for Summary documentation.
705
+
706
+ ---
707
+
708
+ **RULE 1: Auto-fix bugs**
709
+
710
+ **Trigger:** Code doesn't work as intended (broken behavior, incorrect output, errors)
711
+
712
+ **Action:** Fix immediately, track for Summary
713
+
714
+ **Examples:**
715
+
716
+ - Wrong SQL query returning incorrect data
717
+ - Logic errors (inverted condition, off-by-one, infinite loop)
718
+ - Type errors, null pointer exceptions, undefined references
719
+ - Broken validation (accepts invalid input, rejects valid input)
720
+ - Security vulnerabilities (SQL injection, XSS, CSRF, insecure auth)
721
+ - Race conditions, deadlocks
722
+ - Memory leaks, resource leaks
723
+
724
+ **Process:**
725
+
726
+ 1. Fix the bug inline
727
+ 2. Add/update tests to prevent regression
728
+ 3. Verify fix works
729
+ 4. Continue task
730
+ 5. Track in deviations list: `[Rule 1 - Bug] [description]`
731
+
732
+ **No user permission needed.** Bugs must be fixed for correct operation.
733
+
734
+ ---
735
+
736
+ **RULE 2: Auto-add missing critical functionality**
737
+
738
+ **Trigger:** Code is missing essential features for correctness, security, or basic operation
739
+
740
+ **Action:** Add immediately, track for Summary
741
+
742
+ **Examples:**
743
+
744
+ - Missing error handling (no try/catch, unhandled promise rejections)
745
+ - No input validation (accepts malicious data, type coercion issues)
746
+ - Missing null/undefined checks (crashes on edge cases)
747
+ - No authentication on protected routes
748
+ - Missing authorization checks (users can access others' data)
749
+ - No CSRF protection, missing CORS configuration
750
+ - No rate limiting on public APIs
751
+ - Missing required database indexes (causes timeouts)
752
+ - No logging for errors (can't debug production)
753
+
754
+ **Process:**
755
+
756
+ 1. Add the missing functionality inline
757
+ 2. Add tests for the new functionality
758
+ 3. Verify it works
759
+ 4. Continue task
760
+ 5. Track in deviations list: `[Rule 2 - Missing Critical] [description]`
761
+
762
+ **Critical = required for correct/secure/performant operation**
763
+ **No user permission needed.** These are not "features" - they're requirements for basic correctness.
764
+
765
+ ---
766
+
767
+ **RULE 3: Auto-fix blocking issues**
768
+
769
+ **Trigger:** Something prevents you from completing current task
770
+
771
+ **Action:** Fix immediately to unblock, track for Summary
772
+
773
+ **Examples:**
774
+
775
+ - Missing dependency (package not installed, import fails)
776
+ - Wrong types blocking compilation
777
+ - Broken import paths (file moved, wrong relative path)
778
+ - Missing environment variable (app won't start)
779
+ - Database connection config error
780
+ - Build configuration error (webpack, tsconfig, etc.)
781
+ - Missing file referenced in code
782
+ - Circular dependency blocking module resolution
783
+
784
+ **Process:**
785
+
786
+ 1. Fix the blocking issue
787
+ 2. Verify task can now proceed
788
+ 3. Continue task
789
+ 4. Track in deviations list: `[Rule 3 - Blocking] [description]`
790
+
791
+ **No user permission needed.** Can't complete task without fixing blocker.
792
+
793
+ ---
794
+
795
+ **RULE 4: Ask about architectural changes**
796
+
797
+ **Trigger:** Fix/addition requires significant structural modification
798
+
799
+ **Action:** STOP, present to user, wait for decision
800
+
801
+ **Examples:**
802
+
803
+ - Adding new database table (not just column)
804
+ - Major schema changes (changing primary key, splitting tables)
805
+ - Introducing new service layer or architectural pattern
806
+ - Switching libraries/frameworks (React → Vue, REST → GraphQL)
807
+ - Changing authentication approach (sessions → JWT)
808
+ - Adding new infrastructure (message queue, cache layer, CDN)
809
+ - Changing API contracts (breaking changes to endpoints)
810
+ - Adding new deployment environment
811
+
812
+ **Process:**
813
+
814
+ 1. STOP current task
815
+ 2. Present clearly:
816
+
817
+ ```
818
+ ⚠️ Architectural Decision Needed
819
+
820
+ Current task: [task name]
821
+ Discovery: [what you found that prompted this]
822
+ Proposed change: [architectural modification]
823
+ Why needed: [rationale]
824
+ Impact: [what this affects - APIs, deployment, dependencies, etc.]
825
+ Alternatives: [other approaches, or "none apparent"]
826
+
827
+ Proceed with proposed change? (yes / different approach / defer)
828
+ ```
829
+
830
+ 3. WAIT for user response
831
+ 4. If approved: implement, track as `[Rule 4 - Architectural] [description]`
832
+ 5. If different approach: discuss and implement
833
+ 6. If deferred: note in Summary and continue without change
834
+
835
+ **User decision required.** These changes affect system design.
836
+
837
+ ---
838
+
839
+ **RULE PRIORITY (when multiple could apply):**
840
+
841
+ 1. **If Rule 4 applies** → STOP and ask (architectural decision)
842
+ 2. **If Rules 1-3 apply** → Fix automatically, track for Summary
843
+ 3. **If genuinely unsure which rule** → Apply Rule 4 (ask user)
844
+
845
+ **Edge case guidance:**
846
+
847
+ - "This validation is missing" → Rule 2 (critical for security)
848
+ - "This crashes on null" → Rule 1 (bug)
849
+ - "Need to add table" → Rule 4 (architectural)
850
+ - "Need to add column" → Rule 1 or 2 (depends: fixing bug or adding critical field)
851
+
852
+ **When in doubt:** Ask yourself "Does this affect correctness, security, or ability to complete task?"
853
+
854
+ - YES → Rules 1-3 (fix automatically)
855
+ - MAYBE → Rule 4 (ask user)
856
+
857
+ </deviation_rules>
858
+
859
+ <deviation_documentation>
860
+
861
+ ## Documenting Deviations in Summary
862
+
863
+ After all tasks complete, Summary MUST include deviations section.
864
+
865
+ **If no deviations:**
866
+
867
+ ```markdown
868
+ ## Deviations from Plan
869
+
870
+ None - plan executed exactly as written.
871
+ ```
872
+
873
+ **If deviations occurred:**
874
+
875
+ ```markdown
876
+ ## Deviations from Plan
877
+
878
+ ### Auto-fixed Issues
879
+
880
+ **1. [Rule 1 - Bug] Fixed case-sensitive email uniqueness constraint**
881
+
882
+ - **Found during:** Task 4 (Follow/unfollow API implementation)
883
+ - **Issue:** User.email unique constraint was case-sensitive - Test@example.com and test@example.com were both allowed, causing duplicate accounts
884
+ - **Fix:** Changed to `CREATE UNIQUE INDEX users_email_unique ON users (LOWER(email))`
885
+ - **Files modified:** src/models/User.ts, migrations/003_fix_email_unique.sql
886
+ - **Verification:** Unique constraint test passes - duplicate emails properly rejected
887
+ - **Commit:** abc123f
888
+
889
+ **2. [Rule 2 - Missing Critical] Added JWT expiry validation to auth middleware**
890
+
891
+ - **Found during:** Task 3 (Protected route implementation)
892
+ - **Issue:** Auth middleware wasn't checking token expiry - expired tokens were being accepted
893
+ - **Fix:** Added exp claim validation in middleware, reject with 401 if expired
894
+ - **Files modified:** src/middleware/auth.ts, src/middleware/auth.test.ts
895
+ - **Verification:** Expired token test passes - properly rejects with 401
896
+ - **Commit:** def456g
897
+
898
+ ---
899
+
900
+ **Total deviations:** 4 auto-fixed (1 bug, 1 missing critical, 1 blocking, 1 architectural with approval)
901
+ **Impact on plan:** All auto-fixes necessary for correctness/security/performance. No scope creep.
902
+ ```
903
+
904
+ **This provides complete transparency:**
905
+
906
+ - Every deviation documented
907
+ - Why it was needed
908
+ - What rule applied
909
+ - What was done
910
+ - User can see exactly what happened beyond the plan
911
+
912
+ </deviation_documentation>
913
+
914
+ <tdd_plan_execution>
915
+ ## TDD Plan Execution
916
+
917
+ When executing a plan with `type: tdd` in frontmatter, follow the RED-GREEN-REFACTOR cycle for the single feature defined in the plan.
918
+
919
+ **1. Check test infrastructure (if first TDD plan):**
920
+ If no test framework configured:
921
+ - Detect project type from package.json/requirements.txt/etc.
922
+ - Install minimal test framework (Jest, pytest, Go testing, etc.)
923
+ - Create test config file
924
+ - Verify: run empty test suite
925
+ - This is part of the RED phase, not a separate task
926
+
927
+ **2. RED - Write failing test:**
928
+ - Read `<behavior>` element for test specification
929
+ - Create test file if doesn't exist (follow project conventions)
930
+ - Write test(s) that describe expected behavior
931
+ - Run tests - MUST fail (if passes, test is wrong or feature exists)
932
+ - Commit: `test({phase}-{plan}): add failing test for [feature]`
933
+
934
+ **3. GREEN - Implement to pass:**
935
+ - Read `<implementation>` element for guidance
936
+ - Write minimal code to make test pass
937
+ - Run tests - MUST pass
938
+ - Commit: `feat({phase}-{plan}): implement [feature]`
939
+
940
+ **4. REFACTOR (if needed):**
941
+ - Clean up code if obvious improvements
942
+ - Run tests - MUST still pass
943
+ - Commit only if changes made: `refactor({phase}-{plan}): clean up [feature]`
944
+
945
+ **Commit pattern for TDD plans:**
946
+ Each TDD plan produces 2-3 atomic commits:
947
+ 1. `test({phase}-{plan}): add failing test for X`
948
+ 2. `feat({phase}-{plan}): implement X`
949
+ 3. `refactor({phase}-{plan}): clean up X` (optional)
950
+
951
+ **Error handling:**
952
+ - If test doesn't fail in RED phase: Test is wrong or feature already exists. Investigate before proceeding.
953
+ - If test doesn't pass in GREEN phase: Debug implementation, keep iterating until green.
954
+ - If tests fail in REFACTOR phase: Undo refactor, commit was premature.
955
+
956
+ **Verification:**
957
+ After TDD plan completion, ensure:
958
+ - All tests pass
959
+ - Test coverage for the new behavior exists
960
+ - No unrelated tests broken
961
+
962
+ **Why TDD uses dedicated plans:** TDD requires 2-3 execution cycles (RED → GREEN → REFACTOR), each with file reads, test runs, and potential debugging. This consumes 40-50% of context for a single feature. Dedicated plans ensure full quality throughout the cycle.
963
+
964
+ **Comparison:**
965
+ - Standard plans: Multiple tasks, 1 commit per task, 2-4 commits total
966
+ - TDD plans: Single feature, 2-3 commits for RED/GREEN/REFACTOR cycle
967
+
968
+ See `~/.claude/relay/references/tdd.md` for TDD plan structure.
969
+ </tdd_plan_execution>
970
+
971
+ <task_commit>
972
+ ## Task Commit Protocol
973
+
974
+ After each task completes (verification passed, done criteria met), commit immediately:
975
+
976
+ **1. Identify modified files:**
977
+
978
+ Track files changed during this specific task (not the entire plan):
979
+
980
+ ```bash
981
+ git status --short
982
+ ```
983
+
984
+ **2. Stage only task-related files:**
985
+
986
+ Stage each file individually (NEVER use `git add .` or `git add -A`):
987
+
988
+ ```bash
989
+ # Example - adjust to actual files modified by this task
990
+ git add src/api/auth.ts
991
+ git add src/types/user.ts
992
+ ```
993
+
994
+ **3. Determine commit type:**
995
+
996
+ | Type | When to Use | Example |
997
+ |------|-------------|---------|
998
+ | `feat` | New feature, endpoint, component, functionality | feat(08-02): create user registration endpoint |
999
+ | `fix` | Bug fix, error correction | fix(08-02): correct email validation regex |
1000
+ | `test` | Test-only changes (TDD RED phase) | test(08-02): add failing test for password hashing |
1001
+ | `refactor` | Code cleanup, no behavior change (TDD REFACTOR phase) | refactor(08-02): extract validation to helper |
1002
+ | `perf` | Performance improvement | perf(08-02): add database index for user lookups |
1003
+ | `docs` | Documentation changes | docs(08-02): add API endpoint documentation |
1004
+ | `style` | Formatting, linting fixes | style(08-02): format auth module |
1005
+ | `chore` | Config, tooling, dependencies | chore(08-02): add bcrypt dependency |
1006
+
1007
+ **4. Craft commit message:**
1008
+
1009
+ Format: `{type}({phase}-{plan}): {task-name-or-description}`
1010
+
1011
+ ```bash
1012
+ git commit -m "{type}({phase}-{plan}): {concise task description}
1013
+
1014
+ - {key change 1}
1015
+ - {key change 2}
1016
+ - {key change 3}
1017
+ "
1018
+ ```
1019
+
1020
+ **Examples:**
1021
+
1022
+ ```bash
1023
+ # Standard plan task
1024
+ git commit -m "feat(08-02): create user registration endpoint
1025
+
1026
+ - POST /auth/register validates email and password
1027
+ - Checks for duplicate users
1028
+ - Returns JWT token on success
1029
+ "
1030
+
1031
+ # Another standard task
1032
+ git commit -m "fix(08-02): correct email validation regex
1033
+
1034
+ - Fixed regex to accept plus-addressing
1035
+ - Added tests for edge cases
1036
+ "
1037
+ ```
1038
+
1039
+ **Note:** TDD plans have their own commit pattern (test/feat/refactor for RED/GREEN/REFACTOR phases). See `<tdd_plan_execution>` section above.
1040
+
1041
+ **5. Record commit hash:**
1042
+
1043
+ After committing, capture hash for SUMMARY.md:
1044
+
1045
+ ```bash
1046
+ TASK_COMMIT=$(git rev-parse --short HEAD)
1047
+ echo "Task ${TASK_NUM} committed: ${TASK_COMMIT}"
1048
+ ```
1049
+
1050
+ Store in array or list for SUMMARY generation:
1051
+ ```bash
1052
+ TASK_COMMITS+=("Task ${TASK_NUM}: ${TASK_COMMIT}")
1053
+ ```
1054
+
1055
+ </task_commit>
1056
+
1057
+ <step name="checkpoint_protocol">
1058
+ When encountering `type="checkpoint:*"`:
1059
+
1060
+ **Critical: Claude automates everything with CLI/API before checkpoints.** Checkpoints are for verification and decisions, not manual work.
1061
+
1062
+ **Display checkpoint clearly:**
1063
+
1064
+ ```
1065
+ ╔═══════════════════════════════════════════════════════╗
1066
+ ║ CHECKPOINT: [Type] ║
1067
+ ╚═══════════════════════════════════════════════════════╝
1068
+
1069
+ Progress: {X}/{Y} tasks complete
1070
+ Task: [task name]
1071
+
1072
+ [Display task-specific content based on type]
1073
+
1074
+ ────────────────────────────────────────────────────────
1075
+ → YOUR ACTION: [Resume signal instruction]
1076
+ ────────────────────────────────────────────────────────
1077
+ ```
1078
+
1079
+ **For checkpoint:human-verify (90% of checkpoints):**
1080
+
1081
+ ```
1082
+ Built: [what was automated - deployed, built, configured]
1083
+
1084
+ How to verify:
1085
+ 1. [Step 1 - exact command/URL]
1086
+ 2. [Step 2 - what to check]
1087
+ 3. [Step 3 - expected behavior]
1088
+
1089
+ ────────────────────────────────────────────────────────
1090
+ → YOUR ACTION: Type "approved" or describe issues
1091
+ ────────────────────────────────────────────────────────
1092
+ ```
1093
+
1094
+ **For checkpoint:decision (9% of checkpoints):**
1095
+
1096
+ ```
1097
+ Decision needed: [decision]
1098
+
1099
+ Context: [why this matters]
1100
+
1101
+ Options:
1102
+ 1. [option-id]: [name]
1103
+ Pros: [pros]
1104
+ Cons: [cons]
1105
+
1106
+ 2. [option-id]: [name]
1107
+ Pros: [pros]
1108
+ Cons: [cons]
1109
+
1110
+ [Resume signal - e.g., "Select: option-id"]
1111
+ ```
1112
+
1113
+ **For checkpoint:human-action (1% - rare, only for truly unavoidable manual steps):**
1114
+
1115
+ ```
1116
+ I automated: [what Claude already did via CLI/API]
1117
+
1118
+ Need your help with: [the ONE thing with no CLI/API - email link, 2FA code]
1119
+
1120
+ Instructions:
1121
+ [Single unavoidable step]
1122
+
1123
+ I'll verify after: [verification]
1124
+
1125
+ [Resume signal - e.g., "Type 'done' when complete"]
1126
+ ```
1127
+
1128
+ **After displaying:** WAIT for user response. Do NOT hallucinate completion. Do NOT continue to next task.
1129
+
1130
+ **After user responds:**
1131
+
1132
+ - Run verification if specified (file exists, env var set, tests pass, etc.)
1133
+ - If verification passes or N/A: continue to next task
1134
+ - If verification fails: inform user, wait for resolution
1135
+
1136
+ See ~/.claude/relay/references/checkpoints.md for complete checkpoint guidance.
1137
+ </step>
1138
+
1139
+ <step name="checkpoint_return_for_orchestrator">
1140
+ **When spawned by an orchestrator (execute-phase or execute-plan command):**
1141
+
1142
+ If you were spawned via Task tool and hit a checkpoint, you cannot directly interact with the user. Instead, RETURN to the orchestrator with structured checkpoint state so it can present to the user and spawn a fresh continuation agent.
1143
+
1144
+ **Return format for checkpoints:**
1145
+
1146
+ **Required in your return:**
1147
+
1148
+ 1. **Completed Tasks table** - Tasks done so far with commit hashes and files created
1149
+ 2. **Current Task** - Which task you're on and what's blocking it
1150
+ 3. **Checkpoint Details** - User-facing content (verification steps, decision options, or action instructions)
1151
+ 4. **Awaiting** - What you need from the user
1152
+
1153
+ **Example return:**
1154
+
1155
+ ```
1156
+ ## CHECKPOINT REACHED
1157
+
1158
+ **Type:** human-action
1159
+ **Plan:** 01-01
1160
+ **Progress:** 1/3 tasks complete
1161
+
1162
+ ### Completed Tasks
1163
+
1164
+ | Task | Name | Commit | Files |
1165
+ |------|------|--------|-------|
1166
+ | 1 | Initialize Next.js 15 project | d6fe73f | package.json, tsconfig.json, app/ |
1167
+
1168
+ ### Current Task
1169
+
1170
+ **Task 2:** Initialize Convex backend
1171
+ **Status:** blocked
1172
+ **Blocked by:** Convex CLI authentication required
1173
+
1174
+ ### Checkpoint Details
1175
+
1176
+ **Automation attempted:**
1177
+ Ran `npx convex dev` to initialize Convex backend
1178
+
1179
+ **Error encountered:**
1180
+ "Error: Not authenticated. Run `npx convex login` first."
1181
+
1182
+ **What you need to do:**
1183
+ 1. Run: `npx convex login`
1184
+ 2. Complete browser authentication
1185
+ 3. Run: `npx convex dev`
1186
+ 4. Create project when prompted
1187
+
1188
+ **I'll verify after:**
1189
+ `cat .env.local | grep CONVEX` returns the Convex URL
1190
+
1191
+ ### Awaiting
1192
+
1193
+ Type "done" when Convex is authenticated and project created.
1194
+ ```
1195
+
1196
+ **After you return:**
1197
+
1198
+ The orchestrator will:
1199
+ 1. Parse your structured return
1200
+ 2. Present checkpoint details to the user
1201
+ 3. Collect user's response
1202
+ 4. Spawn a FRESH continuation agent with your completed tasks state
1203
+
1204
+ You will NOT be resumed. A new agent continues from where you stopped, using your Completed Tasks table to know what's done.
1205
+
1206
+ **How to know if you were spawned:**
1207
+
1208
+ If you're reading this workflow because an orchestrator spawned you (vs running directly), the orchestrator's prompt will include checkpoint return instructions. Follow those instructions when you hit a checkpoint.
1209
+
1210
+ **If running in main context (not spawned):**
1211
+
1212
+ Use the standard checkpoint_protocol - display checkpoint and wait for direct user response.
1213
+ </step>
1214
+
1215
+ <step name="verification_failure_gate">
1216
+ If any task verification fails:
1217
+
1218
+ STOP. Do not continue to next task.
1219
+
1220
+ Present inline:
1221
+ "Verification failed for Task [X]: [task name]
1222
+
1223
+ Expected: [verification criteria]
1224
+ Actual: [what happened]
1225
+
1226
+ How to proceed?
1227
+
1228
+ 1. Retry - Try the task again
1229
+ 2. Skip - Mark as incomplete, continue
1230
+ 3. Stop - Pause execution, investigate"
1231
+
1232
+ Wait for user decision.
1233
+
1234
+ If user chose "Skip", note it in SUMMARY.md under "Issues Encountered".
1235
+ </step>
1236
+
1237
+ <step name="record_completion_time">
1238
+ Record execution end time and calculate duration:
1239
+
1240
+ ```bash
1241
+ PLAN_END_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
1242
+ PLAN_END_EPOCH=$(date +%s)
1243
+
1244
+ DURATION_SEC=$(( PLAN_END_EPOCH - PLAN_START_EPOCH ))
1245
+ DURATION_MIN=$(( DURATION_SEC / 60 ))
1246
+
1247
+ if [[ $DURATION_MIN -ge 60 ]]; then
1248
+ HRS=$(( DURATION_MIN / 60 ))
1249
+ MIN=$(( DURATION_MIN % 60 ))
1250
+ DURATION="${HRS}h ${MIN}m"
1251
+ else
1252
+ DURATION="${DURATION_MIN} min"
1253
+ fi
1254
+ ```
1255
+
1256
+ Pass timing data to SUMMARY.md creation.
1257
+ </step>
1258
+
1259
+ <step name="generate_user_setup">
1260
+ **Generate USER-SETUP.md if plan has user_setup in frontmatter.**
1261
+
1262
+ Check PLAN.md frontmatter for `user_setup` field:
1263
+
1264
+ ```bash
1265
+ grep -A 50 "^user_setup:" .relay/tickets/XX-name/{phase}-{plan}-PLAN.md | head -50
1266
+ ```
1267
+
1268
+ **If user_setup exists and is not empty:**
1269
+
1270
+ Create `.relay/tickets/XX-name/{phase}-USER-SETUP.md` using template from `~/.claude/relay/templates/user-setup.md`.
1271
+
1272
+ **Content generation:**
1273
+
1274
+ 1. Parse each service in `user_setup` array
1275
+ 2. For each service, generate sections:
1276
+ - Environment Variables table (from `env_vars`)
1277
+ - Account Setup checklist (from `account_setup`, if present)
1278
+ - Dashboard Configuration steps (from `dashboard_config`, if present)
1279
+ - Local Development notes (from `local_dev`, if present)
1280
+ 3. Add verification section with commands to confirm setup works
1281
+ 4. Set status to "Incomplete"
1282
+
1283
+ **Example output:**
1284
+
1285
+ ```markdown
1286
+ # Phase 10: User Setup Required
1287
+
1288
+ **Generated:** 2025-01-14
1289
+ **Phase:** 10-monetization
1290
+ **Status:** Incomplete
1291
+
1292
+ ## Environment Variables
1293
+
1294
+ | Status | Variable | Source | Add to |
1295
+ |--------|----------|--------|--------|
1296
+ | [ ] | `STRIPE_SECRET_KEY` | Stripe Dashboard → Developers → API keys → Secret key | `.env.local` |
1297
+ | [ ] | `STRIPE_WEBHOOK_SECRET` | Stripe Dashboard → Developers → Webhooks → Signing secret | `.env.local` |
1298
+
1299
+ ## Dashboard Configuration
1300
+
1301
+ - [ ] **Create webhook endpoint**
1302
+ - Location: Stripe Dashboard → Developers → Webhooks → Add endpoint
1303
+ - Details: URL: https://[your-domain]/api/webhooks/stripe, Events: checkout.session.completed
1304
+
1305
+ ## Local Development
1306
+
1307
+ For local testing:
1308
+ \`\`\`bash
1309
+ stripe listen --forward-to localhost:3000/api/webhooks/stripe
1310
+ \`\`\`
1311
+
1312
+ ## Verification
1313
+
1314
+ [Verification commands based on service]
1315
+
1316
+ ---
1317
+ **Once all items complete:** Mark status as "Complete"
1318
+ ```
1319
+
1320
+ **If user_setup is empty or missing:**
1321
+
1322
+ Skip this step - no USER-SETUP.md needed.
1323
+
1324
+ **Track for offer_next:**
1325
+
1326
+ Set `USER_SETUP_CREATED=true` if file was generated, for use in completion messaging.
1327
+ </step>
1328
+
1329
+ <step name="create_summary">
1330
+ Create `{phase}-{plan}-SUMMARY.md` as specified in the prompt's `<output>` section.
1331
+ Use ~/.claude/relay/templates/summary.md for structure.
1332
+
1333
+ **File location:** `.relay/tickets/XX-name/{phase}-{plan}-SUMMARY.md`
1334
+
1335
+ **Frontmatter population:**
1336
+
1337
+ Before writing summary content, populate frontmatter fields from execution context:
1338
+
1339
+ 1. **Basic identification:**
1340
+ - phase: From PLAN.md frontmatter
1341
+ - plan: From PLAN.md frontmatter
1342
+ - subsystem: Categorize based on phase focus (auth, payments, ui, api, database, infra, testing, etc.)
1343
+ - tags: Extract tech keywords (libraries, frameworks, tools used)
1344
+
1345
+ 2. **Dependency graph:**
1346
+ - requires: List prior phases this built upon (check PLAN.md context section for referenced prior summaries)
1347
+ - provides: Extract from accomplishments - what was delivered
1348
+ - affects: Infer from phase description/goal what future phases might need this
1349
+
1350
+ 3. **Tech tracking:**
1351
+ - tech-stack.added: New libraries from package.json changes or requirements
1352
+ - tech-stack.patterns: Architectural patterns established (from decisions/accomplishments)
1353
+
1354
+ 4. **File tracking:**
1355
+ - key-files.created: From "Files Created/Modified" section
1356
+ - key-files.modified: From "Files Created/Modified" section
1357
+
1358
+ 5. **Decisions:**
1359
+ - key-decisions: Extract from "Decisions Made" section
1360
+
1361
+ 6. **Metrics:**
1362
+ - duration: From $DURATION variable
1363
+ - completed: From $PLAN_END_TIME (date only, format YYYY-MM-DD)
1364
+
1365
+ Note: If subsystem/affects are unclear, use best judgment based on phase name and accomplishments. Can be refined later.
1366
+
1367
+ **Title format:** `# Phase [X] Plan [Y]: [Name] Summary`
1368
+
1369
+ The one-liner must be SUBSTANTIVE:
1370
+
1371
+ - Good: "JWT auth with refresh rotation using jose library"
1372
+ - Bad: "Authentication implemented"
1373
+
1374
+ **Include performance data:**
1375
+
1376
+ - Duration: `$DURATION`
1377
+ - Started: `$PLAN_START_TIME`
1378
+ - Completed: `$PLAN_END_TIME`
1379
+ - Tasks completed: (count from execution)
1380
+ - Files modified: (count from execution)
1381
+
1382
+ **Next Step section:**
1383
+
1384
+ - If more plans exist in this phase: "Ready for {phase}-{next-plan}-PLAN.md"
1385
+ - If this is the last plan: "Phase complete, ready for transition"
1386
+ </step>
1387
+
1388
+ <step name="update_current_position">
1389
+ Update Current Position section in STATE.md to reflect plan completion.
1390
+
1391
+ **Format:**
1392
+
1393
+ ```markdown
1394
+ Phase: [current] of [total] ([phase name])
1395
+ Plan: [just completed] of [total in phase]
1396
+ Status: [In progress / Phase complete]
1397
+ Last activity: [today] - Completed {phase}-{plan}-PLAN.md
1398
+
1399
+ Progress: [progress bar]
1400
+ ```
1401
+
1402
+ **Calculate progress bar:**
1403
+
1404
+ - Count total plans across all phases (from ROADMAP.md or ROADMAP.md)
1405
+ - Count completed plans (count SUMMARY.md files that exist)
1406
+ - Progress = (completed / total) × 100%
1407
+ - Render: ░ for incomplete, █ for complete
1408
+
1409
+ **Example - completing 02-01-PLAN.md (plan 5 of 10 total):**
1410
+
1411
+ Before:
1412
+
1413
+ ```markdown
1414
+ ## Current Position
1415
+
1416
+ Phase: 2 of 4 (Authentication)
1417
+ Plan: Not started
1418
+ Status: Ready to execute
1419
+ Last activity: 2025-01-18 - Phase 1 complete
1420
+
1421
+ Progress: ██████░░░░ 40%
1422
+ ```
1423
+
1424
+ After:
1425
+
1426
+ ```markdown
1427
+ ## Current Position
1428
+
1429
+ Phase: 2 of 4 (Authentication)
1430
+ Plan: 1 of 2 in current phase
1431
+ Status: In progress
1432
+ Last activity: 2025-01-19 - Completed 02-01-PLAN.md
1433
+
1434
+ Progress: ███████░░░ 50%
1435
+ ```
1436
+
1437
+ **Step complete when:**
1438
+
1439
+ - [ ] Phase number shows current phase (X of total)
1440
+ - [ ] Plan number shows plans complete in current phase (N of total-in-phase)
1441
+ - [ ] Status reflects current state (In progress / Phase complete)
1442
+ - [ ] Last activity shows today's date and the plan just completed
1443
+ - [ ] Progress bar calculated correctly from total completed plans
1444
+ </step>
1445
+
1446
+ <step name="extract_decisions_and_issues">
1447
+ Extract decisions, issues, and concerns from SUMMARY.md into STATE.md accumulated context.
1448
+
1449
+ **Decisions Made:**
1450
+
1451
+ - Read SUMMARY.md "## Decisions Made" section
1452
+ - If content exists (not "None"):
1453
+ - Add each decision to STATE.md Decisions table
1454
+ - Format: `| [phase number] | [decision summary] | [rationale] |`
1455
+
1456
+ **Blockers/Concerns:**
1457
+
1458
+ - Read SUMMARY.md "## Next Phase Readiness" section
1459
+ - If contains blockers or concerns:
1460
+ - Add to STATE.md "Blockers/Concerns Carried Forward"
1461
+ </step>
1462
+
1463
+ <step name="update_session_continuity">
1464
+ Update Session Continuity section in STATE.md to enable resumption in future sessions.
1465
+
1466
+ **Format:**
1467
+
1468
+ ```markdown
1469
+ Last session: [current date and time]
1470
+ Stopped at: Completed {phase}-{plan}-PLAN.md
1471
+ Resume file: [path to .continue-here if exists, else "None"]
1472
+ ```
1473
+
1474
+ **Size constraint note:** Keep STATE.md under 150 lines total.
1475
+ </step>
1476
+
1477
+ <step name="issues_review_gate">
1478
+ Before proceeding, check SUMMARY.md content.
1479
+
1480
+ If "Issues Encountered" is NOT "None":
1481
+
1482
+ <if mode="yolo">
1483
+ ```
1484
+ ⚡ Auto-approved: Issues acknowledgment
1485
+ ⚠️ Note: Issues were encountered during execution:
1486
+ - [Issue 1]
1487
+ - [Issue 2]
1488
+ (Logged - continuing in yolo mode)
1489
+ ```
1490
+
1491
+ Continue without waiting.
1492
+ </if>
1493
+
1494
+ <if mode="interactive" OR="custom with gates.issues_review true">
1495
+ Present issues and wait for acknowledgment before proceeding.
1496
+ </if>
1497
+ </step>
1498
+
1499
+ <step name="update_roadmap">
1500
+ Update the roadmap file:
1501
+
1502
+ ```bash
1503
+ ROADMAP_FILE=".relay/ROADMAP.md"
1504
+ ```
1505
+
1506
+ **If more plans remain in this phase:**
1507
+
1508
+ - Update plan count: "2/3 plans complete"
1509
+ - Keep phase status as "In progress"
1510
+
1511
+ **If this was the last plan in the phase:**
1512
+
1513
+ - Mark phase complete: status → "Complete"
1514
+ - Add completion date
1515
+ </step>
1516
+
1517
+ <step name="git_commit_metadata">
1518
+ Commit execution metadata (SUMMARY + STATE + ROADMAP):
1519
+
1520
+ **Note:** All task code has already been committed during execution (one commit per task).
1521
+ PLAN.md was already committed during plan-phase. This final commit captures execution results only.
1522
+
1523
+ **Check planning config:**
1524
+
1525
+ If `COMMIT_PLANNING_DOCS=false` (set in load_project_state):
1526
+ - Skip all git operations for .relay/ files
1527
+ - Planning docs exist locally but are gitignored
1528
+ - Log: "Skipping planning docs commit (commit_docs: false)"
1529
+ - Proceed to next step
1530
+
1531
+ If `COMMIT_PLANNING_DOCS=true` (default):
1532
+ - Continue with git operations below
1533
+
1534
+ **1. Stage execution artifacts:**
1535
+
1536
+ ```bash
1537
+ git add .relay/tickets/XX-name/{phase}-{plan}-SUMMARY.md
1538
+ git add .relay/STATE.md
1539
+ ```
1540
+
1541
+ **2. Stage roadmap:**
1542
+
1543
+ ```bash
1544
+ git add .relay/ROADMAP.md
1545
+ ```
1546
+
1547
+ **3. Verify staging:**
1548
+
1549
+ ```bash
1550
+ git status
1551
+ # Should show only execution artifacts (SUMMARY, STATE, ROADMAP), no code files
1552
+ ```
1553
+
1554
+ **4. Commit metadata:**
1555
+
1556
+ ```bash
1557
+ git commit -m "$(cat <<'EOF'
1558
+ docs({phase}-{plan}): complete [plan-name] plan
1559
+
1560
+ Tasks completed: [N]/[N]
1561
+ - [Task 1 name]
1562
+ - [Task 2 name]
1563
+ - [Task 3 name]
1564
+
1565
+ SUMMARY: .relay/tickets/XX-name/{phase}-{plan}-SUMMARY.md
1566
+ EOF
1567
+ )"
1568
+ ```
1569
+
1570
+ **Example:**
1571
+
1572
+ ```bash
1573
+ git commit -m "$(cat <<'EOF'
1574
+ docs(08-02): complete user registration plan
1575
+
1576
+ Tasks completed: 3/3
1577
+ - User registration endpoint
1578
+ - Password hashing with bcrypt
1579
+ - Email confirmation flow
1580
+
1581
+ SUMMARY: .relay/tickets/08-user-auth/08-02-registration-SUMMARY.md
1582
+ EOF
1583
+ )"
1584
+ ```
1585
+
1586
+ **Git log after plan execution:**
1587
+
1588
+ ```
1589
+ abc123f docs(08-02): complete user registration plan
1590
+ def456g feat(08-02): add email confirmation flow
1591
+ hij789k feat(08-02): implement password hashing with bcrypt
1592
+ lmn012o feat(08-02): create user registration endpoint
1593
+ ```
1594
+
1595
+ Each task has its own commit, followed by one metadata commit documenting plan completion.
1596
+
1597
+ See `git-integration.md` (loaded via required_reading) for commit message conventions.
1598
+ </step>
1599
+
1600
+ <step name="update_codebase_map">
1601
+ **If .relay/codebase/ exists:**
1602
+
1603
+ Check what changed across all task commits in this plan:
1604
+
1605
+ ```bash
1606
+ # Find first task commit (right after previous plan's docs commit)
1607
+ FIRST_TASK=$(git log --oneline --grep="feat({phase}-{plan}):" --grep="fix({phase}-{plan}):" --grep="test({phase}-{plan}):" --reverse | head -1 | cut -d' ' -f1)
1608
+
1609
+ # Get all changes from first task through now
1610
+ git diff --name-only ${FIRST_TASK}^..HEAD 2>/dev/null
1611
+ ```
1612
+
1613
+ **Update only if structural changes occurred:**
1614
+
1615
+ | Change Detected | Update Action |
1616
+ |-----------------|---------------|
1617
+ | New directory in src/ | STRUCTURE.md: Add to directory layout |
1618
+ | package.json deps changed | STACK.md: Add/remove from dependencies list |
1619
+ | New file pattern (e.g., first .test.ts) | CONVENTIONS.md: Note new pattern |
1620
+ | New external API client | INTEGRATIONS.md: Add service entry with file path |
1621
+ | Config file added/changed | STACK.md: Update configuration section |
1622
+ | File renamed/moved | Update paths in relevant docs |
1623
+
1624
+ **Skip update if only:**
1625
+ - Code changes within existing files
1626
+ - Bug fixes
1627
+ - Content changes (no structural impact)
1628
+
1629
+ **Update format:**
1630
+ Make single targeted edits - add a bullet point, update a path, or remove a stale entry. Don't rewrite sections.
1631
+
1632
+ ```bash
1633
+ git add .relay/codebase/*.md
1634
+ git commit --amend --no-edit # Include in metadata commit
1635
+ ```
1636
+
1637
+ **If .relay/codebase/ doesn't exist:**
1638
+ Skip this step.
1639
+ </step>
1640
+
1641
+ <step name="offer_next">
1642
+ **MANDATORY: Verify remaining work before presenting next steps.**
1643
+
1644
+ Do NOT skip this verification. Do NOT assume phase or milestone completion without checking.
1645
+
1646
+ **Step 0: Check for USER-SETUP.md**
1647
+
1648
+ If `USER_SETUP_CREATED=true` (from generate_user_setup step), always include this warning block at the TOP of completion output:
1649
+
1650
+ ```
1651
+ ⚠️ USER SETUP REQUIRED
1652
+
1653
+ This phase introduced external services requiring manual configuration:
1654
+
1655
+ 📋 .relay/tickets/{phase-dir}/{phase}-USER-SETUP.md
1656
+
1657
+ Quick view:
1658
+ - [ ] {ENV_VAR_1}
1659
+ - [ ] {ENV_VAR_2}
1660
+ - [ ] {Dashboard config task}
1661
+
1662
+ Complete this setup for the integration to function.
1663
+ Run `cat .relay/tickets/{phase-dir}/{phase}-USER-SETUP.md` for full details.
1664
+
1665
+ ---
1666
+ ```
1667
+
1668
+ This warning appears BEFORE "Plan complete" messaging. User sees setup requirements prominently.
1669
+
1670
+ **Step 1: Count plans and summaries in current phase**
1671
+
1672
+ List files in the phase directory:
1673
+
1674
+ ```bash
1675
+ ls -1 .relay/tickets/[current-phase-dir]/*-PLAN.md 2>/dev/null | wc -l
1676
+ ls -1 .relay/tickets/[current-phase-dir]/*-SUMMARY.md 2>/dev/null | wc -l
1677
+ ```
1678
+
1679
+ State the counts: "This phase has [X] plans and [Y] summaries."
1680
+
1681
+ **Step 2: Route based on plan completion**
1682
+
1683
+ Compare the counts from Step 1:
1684
+
1685
+ | Condition | Meaning | Action |
1686
+ |-----------|---------|--------|
1687
+ | summaries < plans | More plans remain | Go to **Route A** |
1688
+ | summaries = plans | Phase complete | Go to Step 3 |
1689
+
1690
+ ---
1691
+
1692
+ **Route A: More plans remain in this phase**
1693
+
1694
+ Identify the next unexecuted plan:
1695
+ - Find the first PLAN.md file that has no matching SUMMARY.md
1696
+ - Read its `<objective>` section
1697
+
1698
+ <if mode="yolo">
1699
+ ```
1700
+ Plan {phase}-{plan} complete.
1701
+ Summary: .relay/tickets/{phase-dir}/{phase}-{plan}-SUMMARY.md
1702
+
1703
+ {Y} of {X} plans complete for Phase {Z}.
1704
+
1705
+ ⚡ Auto-continuing: Execute next plan ({phase}-{next-plan})
1706
+ ```
1707
+
1708
+ Loop back to identify_plan step automatically.
1709
+ </if>
1710
+
1711
+ <if mode="interactive" OR="custom with gates.execute_next_plan true">
1712
+ ```
1713
+ Plan {phase}-{plan} complete.
1714
+ Summary: .relay/tickets/{phase-dir}/{phase}-{plan}-SUMMARY.md
1715
+
1716
+ {Y} of {X} plans complete for Phase {Z}.
1717
+
1718
+ ---
1719
+
1720
+ ## ▶ Next Up
1721
+
1722
+ **{phase}-{next-plan}: [Plan Name]** — [objective from next PLAN.md]
1723
+
1724
+ `/relay:execute-phase {phase}`
1725
+
1726
+ <sub>`/clear` first → fresh context window</sub>
1727
+
1728
+ ---
1729
+
1730
+ **Also available:**
1731
+ - `/relay:verify-work {phase}-{plan}` — manual acceptance testing before continuing
1732
+ - Review what was built before continuing
1733
+
1734
+ ---
1735
+ ```
1736
+
1737
+ Wait for user to clear and run next command.
1738
+ </if>
1739
+
1740
+ **STOP here if Route A applies. Do not continue to Step 3.**
1741
+
1742
+ ---
1743
+
1744
+ **Step 3: Check milestone status (only when all plans in phase are complete)**
1745
+
1746
+ Read ROADMAP.md and extract:
1747
+ 1. Current phase number (from the plan just completed)
1748
+ 2. All phase numbers listed in the current milestone section
1749
+
1750
+ To find phases in the current milestone, look for:
1751
+ - Phase headers: lines starting with `### Phase` or `#### Phase`
1752
+ - Phase list items: lines like `- [ ] **Phase X:` or `- [x] **Phase X:`
1753
+
1754
+ Count total phases in the current milestone and identify the highest phase number.
1755
+
1756
+ State: "Current phase is {X}. Milestone has {N} phases (highest: {Y})."
1757
+
1758
+ **Step 4: Route based on milestone status**
1759
+
1760
+ | Condition | Meaning | Action |
1761
+ |-----------|---------|--------|
1762
+ | current phase < highest phase | More phases remain | Go to **Route B** |
1763
+ | current phase = highest phase | Milestone complete | Go to **Route C** |
1764
+
1765
+ ---
1766
+
1767
+ **Route B: Phase complete, more phases remain in milestone**
1768
+
1769
+ Read ROADMAP.md to get the next phase's name and goal.
1770
+
1771
+ ```
1772
+ Plan {phase}-{plan} complete.
1773
+ Summary: .relay/tickets/{phase-dir}/{phase}-{plan}-SUMMARY.md
1774
+
1775
+ ## ✓ Phase {Z}: {Phase Name} Complete
1776
+
1777
+ All {Y} plans finished.
1778
+
1779
+ ---
1780
+
1781
+ ## ▶ Next Up
1782
+
1783
+ **Phase {Z+1}: {Next Phase Name}** — {Goal from ROADMAP.md}
1784
+
1785
+ `/relay:plan-phase {Z+1}`
1786
+
1787
+ <sub>`/clear` first → fresh context window</sub>
1788
+
1789
+ ---
1790
+
1791
+ **Also available:**
1792
+ - `/relay:verify-work {Z}` — manual acceptance testing before continuing
1793
+ - `/relay:discuss-phase {Z+1}` — gather context first
1794
+ - Review phase accomplishments before continuing
1795
+
1796
+ ---
1797
+ ```
1798
+
1799
+ ---
1800
+
1801
+ **Route C: Milestone complete (all phases done)**
1802
+
1803
+ ```
1804
+ 🎉 MILESTONE COMPLETE!
1805
+
1806
+ Plan {phase}-{plan} complete.
1807
+ Summary: .relay/tickets/{phase-dir}/{phase}-{plan}-SUMMARY.md
1808
+
1809
+ ## ✓ Phase {Z}: {Phase Name} Complete
1810
+
1811
+ All {Y} plans finished.
1812
+
1813
+ ╔═══════════════════════════════════════════════════════╗
1814
+ ║ All {N} phases complete! Milestone is 100% done. ║
1815
+ ╚═══════════════════════════════════════════════════════╝
1816
+
1817
+ ---
1818
+
1819
+ ## ▶ Next Up
1820
+
1821
+ **Complete Milestone** — archive and prepare for next
1822
+
1823
+ `/relay:complete-milestone`
1824
+
1825
+ <sub>`/clear` first → fresh context window</sub>
1826
+
1827
+ ---
1828
+
1829
+ **Also available:**
1830
+ - `/relay:verify-work` — manual acceptance testing before completing milestone
1831
+ - `/relay:add-phase <description>` — add another phase before completing
1832
+ - Review accomplishments before archiving
1833
+
1834
+ ---
1835
+ ```
1836
+
1837
+ </step>
1838
+
1839
+ </process>
1840
+
1841
+ <success_criteria>
1842
+
1843
+ - All tasks from PLAN.md completed
1844
+ - All verifications pass
1845
+ - USER-SETUP.md generated if user_setup in frontmatter
1846
+ - SUMMARY.md created with substantive content
1847
+ - STATE.md updated (position, decisions, issues, session)
1848
+ - ROADMAP.md updated
1849
+ - If codebase map exists: map updated with execution changes (or skipped if no significant changes)
1850
+ - If USER-SETUP.md created: prominently surfaced in completion output
1851
+ </success_criteria>