@snipcodeit/mgw 0.2.2 → 0.4.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.
@@ -0,0 +1,820 @@
1
+ ---
2
+ name: mgw:run/execute
3
+ description: Execute GSD pipeline (quick or milestone route) and post execution update
4
+ ---
5
+
6
+ <step name="execute_gsd_quick">
7
+ **Execute GSD pipeline (quick / quick --full route):**
8
+
9
+ Only run this step if gsd_route is "gsd:quick" or "gsd:quick --full".
10
+
11
+ **Retry loop initialization:**
12
+ ```bash
13
+ # Load retry state from .mgw/active/ state file
14
+ RETRY_COUNT=$(node -e "
15
+ const { loadActiveIssue } = require('./lib/state.cjs');
16
+ const state = loadActiveIssue(${ISSUE_NUMBER});
17
+ console.log((state && typeof state.retry_count === 'number') ? state.retry_count : 0);
18
+ " 2>/dev/null || echo "0")
19
+ EXECUTION_SUCCEEDED=false
20
+ ```
21
+
22
+ **Begin retry loop** — wraps the GSD quick execution (steps 1–11 below) with transient-failure retry:
23
+
24
+ ```
25
+ RETRY_LOOP:
26
+ while canRetry(issue_state) AND NOT EXECUTION_SUCCEEDED:
27
+ ```
28
+
29
+ Update pipeline_stage to "executing" in state file (at `${REPO_ROOT}/.mgw/active/`).
30
+
31
+ Determine flags:
32
+ - "gsd:quick" → $QUICK_FLAGS = ""
33
+ - "gsd:quick --full" → $QUICK_FLAGS = "--full"
34
+
35
+ Read the issue description to use as the GSD task description (full body, capped at 5000 chars for pathological issues):
36
+ ```
37
+ $TASK_DESCRIPTION = "Issue #${ISSUE_NUMBER}: ${issue_title}\n\n${issue_body}" # full body, max 5000 chars
38
+ ```
39
+
40
+ Execute the GSD quick workflow. Read and follow the quick workflow steps:
41
+
42
+ 1. **Init:** `node ~/.claude/get-shit-done/bin/gsd-tools.cjs init quick "$DESCRIPTION"`
43
+ Parse JSON for: planner_model, executor_model, checker_model, verifier_model, next_num, slug, date, quick_dir, task_dir.
44
+
45
+ **Handle missing .planning/:** Check `roadmap_exists` from init output. If false, do NOT
46
+ create GSD state files — .planning/ is owned by GSD. Only create the quick task
47
+ directory (GSD agents need it to store plans/summaries):
48
+ ```bash
49
+ if [ "$roadmap_exists" = "false" ]; then
50
+ echo "NOTE: No .planning/ directory found. GSD manages its own state files."
51
+ echo " To create a ROADMAP.md, run /gsd:new-milestone after this pipeline."
52
+ mkdir -p .planning/quick
53
+ fi
54
+ ```
55
+ MGW never writes config.json, ROADMAP.md, or STATE.md — those are GSD-owned files.
56
+
57
+ 2. **Create task directory:**
58
+ ```bash
59
+ QUICK_DIR=".planning/quick/${next_num}-${slug}"
60
+ mkdir -p "$QUICK_DIR"
61
+ ```
62
+
63
+ 3. **Assemble MGW context and spawn planner (task agent):**
64
+
65
+ Assemble multi-machine context from GitHub issue comments before spawning:
66
+ ```bash
67
+ MGW_CONTEXT=$(node -e "
68
+ const ic = require('${REPO_ROOT}/lib/issue-context.cjs');
69
+ ic.buildGSDPromptContext({
70
+ milestone: ${MILESTONE_NUM},
71
+ phase: ${PHASE_NUMBER},
72
+ issueNumber: ${ISSUE_NUMBER},
73
+ includeVision: true,
74
+ includePriorSummaries: true,
75
+ includeCurrentPlan: false
76
+ }).then(ctx => process.stdout.write(ctx));
77
+ " 2>/dev/null || echo "")
78
+ ```
79
+
80
+ ```
81
+ Task(
82
+ prompt="
83
+ <planning_context>
84
+
85
+ ${MGW_CONTEXT}
86
+
87
+ **Mode:** ${FULL_MODE ? 'quick-full' : 'quick'}
88
+ **Directory:** ${QUICK_DIR}
89
+ **Description:** ${TASK_DESCRIPTION}
90
+
91
+ <triage_context>
92
+ Scope: ${triage.scope.files} files across systems: ${triage.scope.systems}
93
+ Validity: ${triage.validity}
94
+ Security: ${triage.security_notes}
95
+ Conflicts: ${triage.conflicts}
96
+ GSD Route: ${gsd_route}
97
+ </triage_context>
98
+
99
+ <issue_comments>
100
+ ${recent_comments}
101
+ </issue_comments>
102
+
103
+ <files_to_read>
104
+ - ./CLAUDE.md (Project instructions — if exists, follow all guidelines)
105
+ - .agents/skills/ (Project skills — if dir exists, list skills, read SKILL.md for each, follow relevant rules)
106
+ </files_to_read>
107
+
108
+ </planning_context>
109
+
110
+ <constraints>
111
+ - Create a SINGLE plan with 1-3 focused tasks
112
+ - Quick tasks should be atomic and self-contained
113
+ - No research phase
114
+ ${FULL_MODE ? '- Target ~40% context usage (structured for verification)' : '- Target ~30% context usage (simple, focused)'}
115
+ ${FULL_MODE ? '- MUST generate must_haves in plan frontmatter (truths, artifacts, key_links)' : ''}
116
+ ${FULL_MODE ? '- Each task MUST have files, action, verify, done fields' : ''}
117
+ </constraints>
118
+
119
+ <output>
120
+ Write plan to: ${QUICK_DIR}/${next_num}-PLAN.md
121
+ Return: ## PLANNING COMPLETE with plan path
122
+ </output>
123
+ ",
124
+ subagent_type="gsd-planner",
125
+ model="{planner_model}",
126
+ description="Plan: ${issue_title}"
127
+ )
128
+ ```
129
+
130
+ 4. **Publish plan comment (non-blocking):**
131
+ ```bash
132
+ PLAN_FILE="${QUICK_DIR}/${next_num}-PLAN.md"
133
+ if [ -f "$PLAN_FILE" ]; then
134
+ node -e "
135
+ const ic = require('${REPO_ROOT}/lib/issue-context.cjs');
136
+ const fs = require('fs');
137
+ const content = fs.readFileSync('${PLAN_FILE}', 'utf-8');
138
+ ic.postPlanningComment(${ISSUE_NUMBER}, 'plan', content, { phase: ${next_num}, milestone: ${MILESTONE_NUM} })
139
+ .catch(e => console.error('WARNING: Failed to post plan comment:', e.message));
140
+ " 2>/dev/null || true
141
+ fi
142
+ ```
143
+
144
+ 5. **Verify plan exists** at `${QUICK_DIR}/${next_num}-PLAN.md`
145
+
146
+ 5. **Pre-flight plan structure check (gsd-tools):**
147
+ ```bash
148
+ PLAN_CHECK=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs verify plan-structure "${QUICK_DIR}/${next_num}-PLAN.md")
149
+ ```
150
+ Parse the JSON result. If structural issues found, include them in the plan-checker prompt below so it has concrete problems to evaluate rather than searching from scratch.
151
+
152
+ 6. **(If --full) Spawn plan-checker, handle revision loop (max 2 iterations):**
153
+ ```
154
+ Task(
155
+ prompt="
156
+ <files_to_read>
157
+ - ./CLAUDE.md (Project instructions — if exists, follow all guidelines)
158
+ - .agents/skills/ (Project skills — if dir exists, list skills, read SKILL.md for each, follow relevant rules)
159
+ - ${QUICK_DIR}/${next_num}-PLAN.md (Plan to verify)
160
+ </files_to_read>
161
+
162
+ <verification_context>
163
+ **Mode:** quick-full
164
+ **Task Description:** ${TASK_DESCRIPTION}
165
+
166
+ <structural_preflight>
167
+ ${PLAN_CHECK}
168
+ </structural_preflight>
169
+
170
+ **Scope:** This is a quick task, not a full phase. Skip checks that require a ROADMAP phase goal. If structural_preflight flagged issues, prioritize evaluating those.
171
+ </verification_context>
172
+
173
+ <check_dimensions>
174
+ - Requirement coverage: Does the plan address the task description?
175
+ - Task completeness: Do tasks have files, action, verify, done fields?
176
+ - Key links: Are referenced files real?
177
+ - Scope sanity: Is this appropriately sized for a quick task (1-3 tasks)?
178
+ - must_haves derivation: Are must_haves traceable to the task description?
179
+
180
+ Skip: context compliance (no CONTEXT.md), cross-plan deps (single plan), ROADMAP alignment
181
+ </check_dimensions>
182
+
183
+ <expected_output>
184
+ - ## VERIFICATION PASSED — all checks pass
185
+ - ## ISSUES FOUND — structured issue list
186
+ </expected_output>
187
+ ",
188
+ subagent_type="gsd-plan-checker",
189
+ model="{checker_model}",
190
+ description="Check quick plan: ${issue_title}"
191
+ )
192
+ ```
193
+
194
+ If issues found and iteration < 2: spawn planner revision, then re-check.
195
+ If iteration >= 2: offer force proceed or abort.
196
+
197
+ 7. **Spawn executor (task agent):**
198
+ ```
199
+ Task(
200
+ prompt="
201
+ <files_to_read>
202
+ - ./CLAUDE.md (Project instructions — if exists, follow all guidelines)
203
+ - .agents/skills/ (Project skills — if dir exists, list skills, read SKILL.md for each, follow relevant rules)
204
+ - ${QUICK_DIR}/${next_num}-PLAN.md (Plan)
205
+ </files_to_read>
206
+
207
+ Execute quick task ${next_num}.
208
+
209
+ <constraints>
210
+ - Execute all tasks in the plan
211
+ - Commit each task atomically
212
+ - Create summary at: ${QUICK_DIR}/${next_num}-SUMMARY.md
213
+ - Do NOT update ROADMAP.md or STATE.md (GSD owns .planning/ files)
214
+ </constraints>
215
+ ",
216
+ subagent_type="gsd-executor",
217
+ model="{executor_model}",
218
+ description="Execute: ${issue_title}"
219
+ )
220
+ ```
221
+
222
+ 8. **Publish summary comment (non-blocking):**
223
+ ```bash
224
+ SUMMARY_FILE="${QUICK_DIR}/${next_num}-SUMMARY.md"
225
+ if [ -f "$SUMMARY_FILE" ]; then
226
+ node -e "
227
+ const ic = require('${REPO_ROOT}/lib/issue-context.cjs');
228
+ const fs = require('fs');
229
+ const content = fs.readFileSync('${SUMMARY_FILE}', 'utf-8');
230
+ ic.postPlanningComment(${ISSUE_NUMBER}, 'summary', content, { phase: ${next_num}, milestone: ${MILESTONE_NUM} })
231
+ .catch(e => console.error('WARNING: Failed to post summary comment:', e.message));
232
+ " 2>/dev/null || true
233
+ fi
234
+ ```
235
+
236
+ 9. **Verify summary (gsd-tools):**
237
+ ```bash
238
+ VERIFY_RESULT=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs verify-summary "${QUICK_DIR}/${next_num}-SUMMARY.md")
239
+ ```
240
+ Parse JSON result. Use `passed` field for go/no-go. Checks summary existence, files created, and commits.
241
+
242
+ 9. **(If --full) Spawn verifier:**
243
+ ```
244
+ Task(
245
+ prompt="
246
+ <files_to_read>
247
+ - ./CLAUDE.md (Project instructions — if exists, follow all guidelines)
248
+ - .agents/skills/ (Project skills — if dir exists, list skills, read SKILL.md for each, follow relevant rules)
249
+ - ${QUICK_DIR}/${next_num}-PLAN.md (Plan)
250
+ </files_to_read>
251
+
252
+ Verify quick task goal achievement.
253
+ Task directory: ${QUICK_DIR}
254
+ Task goal: ${TASK_DESCRIPTION}
255
+
256
+ Check must_haves against actual codebase. Create VERIFICATION.md at ${QUICK_DIR}/${next_num}-VERIFICATION.md.",
257
+ subagent_type="gsd-verifier",
258
+ model="{verifier_model}",
259
+ description="Verify: ${issue_title}"
260
+ )
261
+ ```
262
+
263
+ 10. **Publish verification comment (non-blocking, --full only):**
264
+ ```bash
265
+ VERIFICATION_FILE="${QUICK_DIR}/${next_num}-VERIFICATION.md"
266
+ if [ -f "$VERIFICATION_FILE" ]; then
267
+ node -e "
268
+ const ic = require('${REPO_ROOT}/lib/issue-context.cjs');
269
+ const fs = require('fs');
270
+ const content = fs.readFileSync('${VERIFICATION_FILE}', 'utf-8');
271
+ ic.postPlanningComment(${ISSUE_NUMBER}, 'verification', content, { phase: ${next_num}, milestone: ${MILESTONE_NUM} })
272
+ .catch(e => console.error('WARNING: Failed to post verification comment:', e.message));
273
+ " 2>/dev/null || true
274
+ fi
275
+ ```
276
+
277
+ 11. **Post-execution artifact verification (non-blocking):**
278
+ ```bash
279
+ ARTIFACT_CHECK=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs verify artifacts "${QUICK_DIR}/${next_num}-PLAN.md" 2>/dev/null || echo '{"passed":true}')
280
+ KEYLINK_CHECK=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs verify key-links "${QUICK_DIR}/${next_num}-PLAN.md" 2>/dev/null || echo '{"passed":true}')
281
+ ```
282
+ Non-blocking: if either check flags issues, include them in the PR description as warnings. Do not halt the pipeline.
283
+
284
+ 11. **Commit artifacts:**
285
+ ```bash
286
+ node ~/.claude/get-shit-done/bin/gsd-tools.cjs commit "docs(quick-${next_num}): ${issue_title}" --files ${file_list}
287
+ ```
288
+
289
+ Update state (at `${REPO_ROOT}/.mgw/active/`): gsd_artifacts.path = $QUICK_DIR, pipeline_stage = "verifying".
290
+
291
+ **Retry loop — on execution failure:**
292
+
293
+ If any step above fails (executor or verifier agent returns error, summary missing, etc.), capture the error and apply retry logic:
294
+
295
+ ```bash
296
+ # On failure — classify and decide whether to retry
297
+ FAILURE_CLASS=$(node -e "
298
+ const { classifyFailure, canRetry, incrementRetry, getBackoffMs } = require('./lib/retry.cjs');
299
+ const { loadActiveIssue } = require('./lib/state.cjs');
300
+ const fs = require('fs'), path = require('path');
301
+
302
+ const activeDir = path.join(process.cwd(), '.mgw', 'active');
303
+ const files = fs.readdirSync(activeDir);
304
+ const file = files.find(f => f.startsWith('${ISSUE_NUMBER}-') && f.endsWith('.json'));
305
+ const filePath = path.join(activeDir, file);
306
+ let issueState = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
307
+
308
+ // Classify the failure from the error context
309
+ const error = { message: '${EXECUTION_ERROR_MESSAGE}' };
310
+ const result = classifyFailure(error);
311
+ console.error('Failure classified as: ' + result.class + ' — ' + result.reason);
312
+
313
+ // Persist failure class to state
314
+ issueState.last_failure_class = result.class;
315
+
316
+ if (result.class === 'transient' && canRetry(issueState)) {
317
+ const backoff = getBackoffMs(issueState.retry_count || 0);
318
+ issueState = incrementRetry(issueState);
319
+ fs.writeFileSync(filePath, JSON.stringify(issueState, null, 2));
320
+ // Output: backoff ms so shell can sleep
321
+ console.log('retry:' + backoff + ':' + result.class);
322
+ } else {
323
+ // Permanent failure or retries exhausted — dead-letter
324
+ issueState.dead_letter = true;
325
+ fs.writeFileSync(filePath, JSON.stringify(issueState, null, 2));
326
+ console.log('dead_letter:' + result.class);
327
+ }
328
+ ")
329
+
330
+ case "$FAILURE_CLASS" in
331
+ retry:*)
332
+ BACKOFF_MS=$(echo "$FAILURE_CLASS" | cut -d':' -f2)
333
+ BACKOFF_SEC=$(( (BACKOFF_MS + 999) / 1000 ))
334
+ echo "MGW: Transient failure detected — retrying in ${BACKOFF_SEC}s (retry ${RETRY_COUNT})..."
335
+ sleep "$BACKOFF_SEC"
336
+ RETRY_COUNT=$((RETRY_COUNT + 1))
337
+ # Loop back to retry
338
+ ;;
339
+ dead_letter:*)
340
+ FAILURE_CLASS_NAME=$(echo "$FAILURE_CLASS" | cut -d':' -f2)
341
+ EXECUTION_SUCCEEDED=false
342
+ # Break out of retry loop — handled in post_execution_update
343
+ break
344
+ ;;
345
+ esac
346
+ ```
347
+
348
+ On successful execution (EXECUTION_SUCCEEDED=true): break out of retry loop, clear last_failure_class:
349
+ ```bash
350
+ node -e "
351
+ const fs = require('fs'), path = require('path');
352
+ const activeDir = path.join(process.cwd(), '.mgw', 'active');
353
+ const files = fs.readdirSync(activeDir);
354
+ const file = files.find(f => f.startsWith('${ISSUE_NUMBER}-') && f.endsWith('.json'));
355
+ const filePath = path.join(activeDir, file);
356
+ const state = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
357
+ state.last_failure_class = null;
358
+ fs.writeFileSync(filePath, JSON.stringify(state, null, 2));
359
+ " 2>/dev/null || true
360
+ ```
361
+ </step>
362
+
363
+ <step name="execute_gsd_milestone">
364
+ **Execute GSD pipeline (new-milestone route):**
365
+
366
+ Only run this step if gsd_route is "gsd:new-milestone".
367
+
368
+ **Retry loop initialization** (same pattern as execute_gsd_quick):
369
+ ```bash
370
+ RETRY_COUNT=$(node -e "
371
+ const { loadActiveIssue } = require('./lib/state.cjs');
372
+ const state = loadActiveIssue(${ISSUE_NUMBER});
373
+ console.log((state && typeof state.retry_count === 'number') ? state.retry_count : 0);
374
+ " 2>/dev/null || echo "0")
375
+ EXECUTION_SUCCEEDED=false
376
+ ```
377
+
378
+ **Begin retry loop** — wraps the phase-execution loop (steps 2b–2e below) with transient-failure retry. Step 2 (milestone roadmap creation) is NOT wrapped in the retry loop — roadmap creation failures are always treated as permanent (require human intervention).
379
+
380
+ This is the most complex path. The orchestrator needs to:
381
+
382
+ **Resolve models for milestone agents:**
383
+ ```bash
384
+ PLANNER_MODEL=$(node -e "process.stdout.write(require('./lib/gsd-adapter.cjs').resolveModel('gsd-planner'))")
385
+ EXECUTOR_MODEL=$(node -e "process.stdout.write(require('./lib/gsd-adapter.cjs').resolveModel('gsd-executor'))")
386
+ VERIFIER_MODEL=$(node -e "process.stdout.write(require('./lib/gsd-adapter.cjs').resolveModel('gsd-verifier'))")
387
+ ```
388
+
389
+ 1. **Discussion phase trigger for large-scope issues:**
390
+
391
+ If the issue was triaged with large scope and `gsd_route == "gsd:new-milestone"`, post
392
+ a scope proposal comment and set the discussing stage before proceeding to phase execution:
393
+
394
+ ```bash
395
+ DISCUSS_TIMESTAMP=$(node -e "try{process.stdout.write(require('./lib/gsd-adapter.cjs').getTimestamp())}catch(e){process.stdout.write(new Date().toISOString().replace(/\\.\\d{3}Z$/,'Z'))}")
396
+
397
+ # Build scope breakdown from triage data
398
+ SCOPE_SIZE="${triage.scope.size}"
399
+ SCOPE_BREAKDOWN="${triage.scope.files formatted as table rows}"
400
+ PHASE_COUNT="TBD (determined by roadmapper)"
401
+
402
+ # Post scope proposal comment using template from github.md
403
+ # Use Scope Proposal Comment template from @~/.claude/commands/mgw/workflows/github.md
404
+ ```
405
+
406
+ Set pipeline_stage to "discussing" and apply "mgw:discussing" label:
407
+ ```bash
408
+ remove_mgw_labels_and_apply ${ISSUE_NUMBER} "mgw:discussing"
409
+ ```
410
+
411
+ Present to user:
412
+ ```
413
+ AskUserQuestion(
414
+ header: "Scope Proposal Posted",
415
+ question: "A scope proposal has been posted to GitHub. Proceed with autonomous roadmap creation, or wait for stakeholder feedback?",
416
+ options: [
417
+ { label: "Proceed", description: "Continue with roadmap creation now" },
418
+ { label: "Wait", description: "Pipeline paused until stakeholder approves scope" }
419
+ ]
420
+ )
421
+ ```
422
+
423
+ If wait: stop here. User will re-run /mgw:run after scope is approved.
424
+ If proceed: apply "mgw:approved" label and continue.
425
+
426
+ 2. **Create milestone:** Use `gsd-tools init new-milestone` to gather context, then attempt autonomous roadmap creation from issue data:
427
+
428
+ ```bash
429
+ MILESTONE_INIT=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs init new-milestone 2>/dev/null)
430
+ ```
431
+
432
+ Extract requirements from structured issue template fields (BLUF, What's Needed, What's Involved) if present.
433
+
434
+ If issue body contains sufficient detail (has clear requirements/scope):
435
+ - Spawn roadmapper agent with issue-derived requirements
436
+ - After roadmap generation, present to user for confirmation checkpoint:
437
+ ```
438
+ AskUserQuestion(
439
+ header: "Milestone Roadmap Generated",
440
+ question: "Review the generated ROADMAP.md. Proceed with execution, revise, or switch to interactive mode?",
441
+ followUp: "Enter: proceed, revise, or interactive"
442
+ )
443
+ ```
444
+
445
+ If issue body lacks sufficient detail (no clear structure or too vague):
446
+ - Fall back to interactive mode:
447
+ ```
448
+ The new-milestone route requires more detail than the issue provides.
449
+ Please run: /gsd:new-milestone
450
+
451
+ After the milestone is created, run /mgw:run ${ISSUE_NUMBER} again to
452
+ continue the pipeline through execution.
453
+ ```
454
+
455
+ Update pipeline_stage to "planning" (at `${REPO_ROOT}/.mgw/active/`).
456
+
457
+ **Verify ROADMAP.md was created:**
458
+ ```bash
459
+ if [ ! -f ".planning/ROADMAP.md" ]; then
460
+ echo "MGW ERROR: Roadmapper agent did not produce ROADMAP.md. Cannot proceed with milestone execution."
461
+ FAIL_TS=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs current-timestamp --raw 2>/dev/null || date -u +"%Y-%m-%dT%H:%M:%SZ")
462
+ gh issue comment ${ISSUE_NUMBER} --body "> **MGW** · \`pipeline-failed\` · ${FAIL_TS}
463
+ > Roadmapper agent did not produce ROADMAP.md. Pipeline cannot continue.
464
+ > Re-run with \`/mgw:run ${ISSUE_NUMBER}\` after investigating." 2>/dev/null || true
465
+ # Update pipeline_stage to failed (same pattern as post_execution_update dead_letter block)
466
+ node -e "
467
+ const fs = require('fs'), path = require('path');
468
+ const activeDir = path.join(process.cwd(), '.mgw', 'active');
469
+ const files = fs.readdirSync(activeDir);
470
+ const file = files.find(f => f.startsWith('${ISSUE_NUMBER}-') && f.endsWith('.json'));
471
+ if (file) {
472
+ const filePath = path.join(activeDir, file);
473
+ const state = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
474
+ state.pipeline_stage = 'failed';
475
+ fs.writeFileSync(filePath, JSON.stringify(state, null, 2));
476
+ }
477
+ " 2>/dev/null || true
478
+ exit 1
479
+ fi
480
+ ```
481
+
482
+ 2. **If resuming with pipeline_stage = "planning" and ROADMAP.md exists:**
483
+ Discover phases from ROADMAP and run the full per-phase GSD lifecycle:
484
+
485
+ ```bash
486
+ ROADMAP_ANALYSIS=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs roadmap analyze)
487
+ # Parse ROADMAP_ANALYSIS JSON for list of phases:
488
+ # Each phase has: phase_number, phase_name, phase_slug
489
+ PHASE_LIST=$(echo "$ROADMAP_ANALYSIS" | python3 -c "
490
+ import json, sys
491
+ data = json.load(sys.stdin)
492
+ for p in data.get('phases', []):
493
+ print(f\"{p['number']}|{p['name']}|{p.get('slug', '')}\")
494
+ ")
495
+ ```
496
+
497
+ For each phase in order:
498
+
499
+ **a. Scaffold phase directory, then init:**
500
+
501
+ `init plan-phase` requires the phase directory to exist before it can locate it.
502
+ Use `scaffold phase-dir` first (which creates the directory from ROADMAP data),
503
+ then call `init plan-phase` to get planner/checker model assignments.
504
+
505
+ ```bash
506
+ # Generate slug from phase name (lowercase, hyphens, no special chars)
507
+ PHASE_SLUG=$(echo "${PHASE_NAME}" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//')
508
+
509
+ # Scaffold creates the directory and returns the path
510
+ SCAFFOLD=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs scaffold phase-dir --phase "${PHASE_NUMBER}" --name "${PHASE_SLUG}")
511
+ phase_dir=$(echo "$SCAFFOLD" | python3 -c "import json,sys; print(json.load(sys.stdin)['directory'])")
512
+
513
+ # Now init plan-phase can find the directory for model resolution
514
+ PHASE_INIT=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs init plan-phase "${PHASE_NUMBER}")
515
+ # Parse PHASE_INIT JSON for: planner_model, checker_model
516
+ ```
517
+
518
+ **b. Assemble MGW context and spawn planner agent (gsd:plan-phase):**
519
+
520
+ Assemble multi-machine context from GitHub issue comments before spawning:
521
+ ```bash
522
+ MGW_CONTEXT=$(node -e "
523
+ const ic = require('${REPO_ROOT}/lib/issue-context.cjs');
524
+ ic.buildGSDPromptContext({
525
+ milestone: ${MILESTONE_NUM},
526
+ phase: ${PHASE_NUMBER},
527
+ issueNumber: ${ISSUE_NUMBER},
528
+ includeVision: true,
529
+ includePriorSummaries: true,
530
+ includeCurrentPlan: false
531
+ }).then(ctx => process.stdout.write(ctx));
532
+ " 2>/dev/null || echo "")
533
+ ```
534
+
535
+ ```
536
+ Task(
537
+ prompt="
538
+ <files_to_read>
539
+ - ./CLAUDE.md (Project instructions -- if exists, follow all guidelines)
540
+ - .agents/skills/ (Project skills -- if dir exists, list skills, read SKILL.md for each, follow relevant rules)
541
+ - .planning/ROADMAP.md (Phase definitions and requirements)
542
+ - .planning/STATE.md (If exists -- project state)
543
+ </files_to_read>
544
+
545
+ ${MGW_CONTEXT}
546
+
547
+ You are the GSD planner. Plan phase ${PHASE_NUMBER}: ${PHASE_NAME}.
548
+
549
+ Read and follow the plan-phase workflow:
550
+ @~/.claude/get-shit-done/workflows/plan-phase.md
551
+
552
+ Phase directory: ${phase_dir}
553
+ Phase number: ${PHASE_NUMBER}
554
+
555
+ Create PLAN.md file(s) in the phase directory. Each plan must have:
556
+ - Frontmatter with phase, plan, type, wave, depends_on, files_modified, autonomous, requirements, must_haves
557
+ - Objective, context, tasks, verification, success criteria, output sections
558
+ - Each task with files, action, verify, done fields
559
+
560
+ Commit the plan files when done.
561
+ ",
562
+ subagent_type="gsd-planner",
563
+ model="${PLANNER_MODEL}",
564
+ description="Plan phase ${PHASE_NUMBER}: ${PHASE_NAME}"
565
+ )
566
+ ```
567
+
568
+ **b2. Publish plan comment (non-blocking):**
569
+ ```bash
570
+ PLAN_FILES=$(ls ${phase_dir}/*-PLAN.md 2>/dev/null)
571
+ for PLAN_FILE in $PLAN_FILES; do
572
+ node -e "
573
+ const ic = require('${REPO_ROOT}/lib/issue-context.cjs');
574
+ const fs = require('fs');
575
+ const content = fs.readFileSync('${PLAN_FILE}', 'utf-8');
576
+ ic.postPlanningComment(${ISSUE_NUMBER}, 'plan', content, { phase: ${PHASE_NUMBER}, milestone: ${MILESTONE_NUM} })
577
+ .catch(e => console.error('WARNING: Failed to post plan comment:', e.message));
578
+ " 2>/dev/null || true
579
+ done
580
+ ```
581
+
582
+ **c. Verify plans exist:**
583
+ ```bash
584
+ PLAN_COUNT=$(ls ${phase_dir}/*-PLAN.md 2>/dev/null | wc -l)
585
+ if [ "$PLAN_COUNT" -eq 0 ]; then
586
+ echo "ERROR: No plans created for phase ${PHASE_NUMBER}. Skipping phase execution."
587
+ # Post error comment and continue to next phase
588
+ gh issue comment ${ISSUE_NUMBER} --body "> **MGW** \`phase-error\` Phase ${PHASE_NUMBER} planning produced no plans. Skipping." 2>/dev/null || true
589
+ continue
590
+ fi
591
+ ```
592
+
593
+ **d. Init execute-phase and spawn executor agent (gsd:execute-phase):**
594
+ ```bash
595
+ EXEC_INIT=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs init execute-phase "${PHASE_NUMBER}")
596
+ # Parse EXEC_INIT JSON for: executor_model, verifier_model, phase_dir, plans, incomplete_plans, plan_count
597
+ ```
598
+ ```
599
+ Task(
600
+ prompt="
601
+ <files_to_read>
602
+ - ./CLAUDE.md (Project instructions -- if exists, follow all guidelines)
603
+ - .agents/skills/ (Project skills -- if dir exists, list skills, read SKILL.md for each, follow relevant rules)
604
+ - ${phase_dir}/*-PLAN.md (Plans to execute)
605
+ </files_to_read>
606
+
607
+ You are the GSD executor. Execute all plans for phase ${PHASE_NUMBER}: ${PHASE_NAME}.
608
+
609
+ Read and follow the execute-phase workflow:
610
+ @~/.claude/get-shit-done/workflows/execute-phase.md
611
+
612
+ Phase: ${PHASE_NUMBER}
613
+ Phase directory: ${phase_dir}
614
+
615
+ Execute each plan's tasks in wave order. For each plan:
616
+ 1. Execute all tasks
617
+ 2. Commit each task atomically
618
+ 3. Create SUMMARY.md in the phase directory
619
+
620
+ Do NOT update ROADMAP.md or STATE.md directly -- those are managed by GSD tools.
621
+ ",
622
+ subagent_type="gsd-executor",
623
+ model="${EXECUTOR_MODEL}",
624
+ description="Execute phase ${PHASE_NUMBER}: ${PHASE_NAME}"
625
+ )
626
+ ```
627
+
628
+ **d2. Publish summary comment (non-blocking):**
629
+ ```bash
630
+ SUMMARY_FILES=$(ls ${phase_dir}/*-SUMMARY.md 2>/dev/null)
631
+ for SUMMARY_FILE in $SUMMARY_FILES; do
632
+ node -e "
633
+ const ic = require('${REPO_ROOT}/lib/issue-context.cjs');
634
+ const fs = require('fs');
635
+ const content = fs.readFileSync('${SUMMARY_FILE}', 'utf-8');
636
+ ic.postPlanningComment(${ISSUE_NUMBER}, 'summary', content, { phase: ${PHASE_NUMBER}, milestone: ${MILESTONE_NUM} })
637
+ .catch(e => console.error('WARNING: Failed to post summary comment:', e.message));
638
+ " 2>/dev/null || true
639
+ done
640
+ ```
641
+
642
+ **e. Spawn verifier agent (gsd:verify-phase):**
643
+ ```
644
+ Task(
645
+ prompt="
646
+ <files_to_read>
647
+ - ./CLAUDE.md (Project instructions -- if exists, follow all guidelines)
648
+ - .agents/skills/ (Project skills -- if dir exists, list skills, read SKILL.md for each, follow relevant rules)
649
+ - ${phase_dir}/*-PLAN.md (Plans with must_haves)
650
+ - ${phase_dir}/*-SUMMARY.md (Execution summaries)
651
+ </files_to_read>
652
+
653
+ Verify phase ${PHASE_NUMBER}: ${PHASE_NAME} goal achievement.
654
+
655
+ Read and follow the verify-phase workflow:
656
+ @~/.claude/get-shit-done/workflows/verify-phase.md
657
+
658
+ Phase: ${PHASE_NUMBER}
659
+ Phase directory: ${phase_dir}
660
+
661
+ Check must_haves from plan frontmatter against actual codebase.
662
+ Create VERIFICATION.md in the phase directory.
663
+ ",
664
+ subagent_type="gsd-verifier",
665
+ model="${VERIFIER_MODEL}",
666
+ description="Verify phase ${PHASE_NUMBER}: ${PHASE_NAME}"
667
+ )
668
+ ```
669
+
670
+ **e2. Publish verification comment (non-blocking):**
671
+ ```bash
672
+ VERIFICATION_FILES=$(ls ${phase_dir}/*-VERIFICATION.md 2>/dev/null)
673
+ for VERIFICATION_FILE in $VERIFICATION_FILES; do
674
+ node -e "
675
+ const ic = require('${REPO_ROOT}/lib/issue-context.cjs');
676
+ const fs = require('fs');
677
+ const content = fs.readFileSync('${VERIFICATION_FILE}', 'utf-8');
678
+ ic.postPlanningComment(${ISSUE_NUMBER}, 'verification', content, { phase: ${PHASE_NUMBER}, milestone: ${MILESTONE_NUM} })
679
+ .catch(e => console.error('WARNING: Failed to post verification comment:', e.message));
680
+ " 2>/dev/null || true
681
+ done
682
+ ```
683
+
684
+ **f. Post phase-complete comment directly (no sub-agent):**
685
+ ```bash
686
+ PHASE_TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
687
+ VERIFICATION_STATUS=$(grep -m1 "^## " "${phase_dir}/"*-VERIFICATION.md 2>/dev/null | head -1 || echo "Verification complete")
688
+ PHASE_BODY=$(cat <<COMMENTEOF
689
+ > **MGW** · \`phase-complete\` · ${PHASE_TIMESTAMP}
690
+ > ${MILESTONE_CONTEXT}
691
+
692
+ ### Phase ${PHASE_NUMBER} Complete — ${PHASE_NAME}
693
+
694
+ Execution complete. See ${phase_dir} for plans, summaries, and verification.
695
+
696
+ **Verification:** ${VERIFICATION_STATUS}
697
+ COMMENTEOF
698
+ )
699
+ gh issue comment ${ISSUE_NUMBER} --body "$PHASE_BODY" 2>/dev/null || true
700
+ ```
701
+
702
+ **Retry loop — on phase execution failure** (apply same pattern as execute_gsd_quick):
703
+
704
+ If a phase's executor or verifier fails, capture the error and apply retry logic via `classifyFailure()`, `canRetry()`, `incrementRetry()`, and `getBackoffMs()` from `lib/retry.cjs`. Only the failing phase is retried (restart from step 2b for that phase). If the failure is transient and `canRetry()` is true: sleep backoff, call `incrementRetry()`, loop. If permanent or retries exhausted: set `dead_letter = true`, set `last_failure_class`, break the retry loop.
705
+
706
+ On successful completion of all phases: clear `last_failure_class`, set `EXECUTION_SUCCEEDED=true`.
707
+
708
+ After ALL phases complete → update pipeline_stage to "verifying" (at `${REPO_ROOT}/.mgw/active/`).
709
+ </step>
710
+
711
+ <step name="post_execution_update">
712
+ **Post execution-complete comment on issue (or failure comment if dead_letter):**
713
+
714
+ Read `dead_letter` and `last_failure_class` from current issue state:
715
+ ```bash
716
+ DEAD_LETTER=$(node -e "
717
+ const { loadActiveIssue } = require('./lib/state.cjs');
718
+ const state = loadActiveIssue(${ISSUE_NUMBER});
719
+ console.log(state && state.dead_letter === true ? 'true' : 'false');
720
+ " 2>/dev/null || echo "false")
721
+
722
+ LAST_FAILURE_CLASS=$(node -e "
723
+ const { loadActiveIssue } = require('./lib/state.cjs');
724
+ const state = loadActiveIssue(${ISSUE_NUMBER});
725
+ console.log((state && state.last_failure_class) ? state.last_failure_class : 'unknown');
726
+ " 2>/dev/null || echo "unknown")
727
+ ```
728
+
729
+ **If dead_letter === true — post failure comment and halt:**
730
+ ```bash
731
+ if [ "$DEAD_LETTER" = "true" ]; then
732
+ FAIL_TIMESTAMP=$(node ~/.claude/get-shit-done/bin/gsd-tools.cjs current-timestamp --raw 2>/dev/null || date -u +"%Y-%m-%dT%H:%M:%SZ")
733
+ RETRY_COUNT_CURRENT=$(node -e "
734
+ const { loadActiveIssue } = require('./lib/state.cjs');
735
+ const state = loadActiveIssue(${ISSUE_NUMBER});
736
+ console.log((state && typeof state.retry_count === 'number') ? state.retry_count : 0);
737
+ " 2>/dev/null || echo "0")
738
+
739
+ FAIL_BODY=$(cat <<COMMENTEOF
740
+ > **MGW** · \`pipeline-failed\` · ${FAIL_TIMESTAMP}
741
+ > ${MILESTONE_CONTEXT}
742
+
743
+ ### Pipeline Failed
744
+
745
+ Issue #${ISSUE_NUMBER} — ${issue_title}
746
+
747
+ | | |
748
+ |---|---|
749
+ | **Failure class** | \`${LAST_FAILURE_CLASS}\` |
750
+ | **Retries attempted** | ${RETRY_COUNT_CURRENT} of 3 |
751
+ | **Status** | Dead-lettered — requires human intervention |
752
+
753
+ **Failure class meaning:**
754
+ - \`transient\` — retry exhausted (rate limit, network, or overload)
755
+ - \`permanent\` — unrecoverable (auth, missing deps, bad config)
756
+ - \`needs-info\` — issue is ambiguous or incomplete
757
+
758
+ **To retry after resolving root cause:**
759
+ \`\`\`
760
+ /mgw:run ${ISSUE_NUMBER} --retry
761
+ \`\`\`
762
+ COMMENTEOF
763
+ )
764
+
765
+ gh issue comment ${ISSUE_NUMBER} --body "$FAIL_BODY" 2>/dev/null || true
766
+ gh issue edit ${ISSUE_NUMBER} --add-label "pipeline-failed" 2>/dev/null || true
767
+ gh label create "pipeline-failed" --description "Pipeline execution failed" --color "d73a4a" --force 2>/dev/null || true
768
+
769
+ # Update pipeline_stage to failed
770
+ node -e "
771
+ const fs = require('fs'), path = require('path');
772
+ const activeDir = path.join(process.cwd(), '.mgw', 'active');
773
+ const files = fs.readdirSync(activeDir);
774
+ const file = files.find(f => f.startsWith('${ISSUE_NUMBER}-') && f.endsWith('.json'));
775
+ const filePath = path.join(activeDir, file);
776
+ const state = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
777
+ state.pipeline_stage = 'failed';
778
+ fs.writeFileSync(filePath, JSON.stringify(state, null, 2));
779
+ " 2>/dev/null || true
780
+
781
+ echo "MGW: Pipeline dead-lettered for #${ISSUE_NUMBER} (class: ${LAST_FAILURE_CLASS}). Use --retry after fixing root cause."
782
+ exit 1
783
+ fi
784
+ ```
785
+
786
+ **Otherwise — post execution-complete comment:**
787
+
788
+ After GSD execution completes successfully, post a structured update before creating the PR:
789
+
790
+ ```bash
791
+ COMMIT_COUNT=$(git rev-list ${DEFAULT_BRANCH}..HEAD --count 2>/dev/null || echo "0")
792
+ TEST_STATUS=$(npm test 2>&1 >/dev/null && echo "passing" || echo "failing")
793
+ FILE_CHANGES=$(git diff --stat ${DEFAULT_BRANCH}..HEAD 2>/dev/null | tail -1)
794
+ EXEC_TIMESTAMP=$(node -e "try{process.stdout.write(require('./lib/gsd-adapter.cjs').getTimestamp())}catch(e){process.stdout.write(new Date().toISOString().replace(/\\.\\d{3}Z$/,'Z'))}")
795
+ ```
796
+
797
+ Post the execution-complete comment directly (no sub-agent — guarantees it happens):
798
+
799
+ ```bash
800
+ EXEC_BODY=$(cat <<COMMENTEOF
801
+ > **MGW** · \`execution-complete\` · ${EXEC_TIMESTAMP}
802
+ > ${MILESTONE_CONTEXT}
803
+
804
+ ### Execution Complete
805
+
806
+ ${COMMIT_COUNT} atomic commit(s) on branch \`${BRANCH_NAME}\`.
807
+
808
+ **Changes:** ${FILE_CHANGES}
809
+
810
+ **Tests:** ${TEST_STATUS}
811
+
812
+ Preparing pull request.
813
+ COMMENTEOF
814
+ )
815
+
816
+ gh issue comment ${ISSUE_NUMBER} --body "$EXEC_BODY" 2>/dev/null || true
817
+ ```
818
+
819
+ Update pipeline_stage to "pr-pending" (at `${REPO_ROOT}/.mgw/active/`).
820
+ </step>