@loucompanion/forge-bridge 0.1.1-dev.f599637d804e → 0.1.3-dev.6e59f152916f

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.
@@ -22,6 +22,60 @@ export const qaCompletionGateOrder = [
22
22
  "qa_findings",
23
23
  "qa_verdict"
24
24
  ];
25
+ export const draftCompletionGateOrder = [
26
+ "draft_intent",
27
+ "draft_repo_context",
28
+ "draft_graph_context",
29
+ "draft_product_scope",
30
+ "draft_work_order_plan",
31
+ "draft_critic",
32
+ "draft_proposal"
33
+ ];
34
+ export const decomposeCompletionGateOrder = [
35
+ "decompose_subject_intake",
36
+ "decompose_context_review",
37
+ "decompose_breakdown_strategy",
38
+ "decompose_child_items",
39
+ "decompose_dependency_graph",
40
+ "decompose_critic",
41
+ "decompose_proposal"
42
+ ];
43
+ const decomposeGateFileNames = {
44
+ decompose_subject_intake: "decompose.subject-intake.json",
45
+ decompose_context_review: "decompose.context-review.json",
46
+ decompose_breakdown_strategy: "decompose.breakdown-strategy.json",
47
+ decompose_child_items: "decompose.child-items.json",
48
+ decompose_dependency_graph: "decompose.dependency-graph.json",
49
+ decompose_critic: "decompose.critic.json",
50
+ decompose_proposal: "decompose.proposal.json"
51
+ };
52
+ const decomposeGateToolNames = {
53
+ decompose_subject_intake: "complete_decompose_subject_intake",
54
+ decompose_context_review: "complete_decompose_context_review",
55
+ decompose_breakdown_strategy: "complete_decompose_breakdown_strategy",
56
+ decompose_child_items: "complete_decompose_child_items",
57
+ decompose_dependency_graph: "complete_decompose_dependency_graph",
58
+ decompose_critic: "complete_decompose_critic",
59
+ decompose_proposal: "complete_decompose_proposal"
60
+ };
61
+ const draftGateFileNames = {
62
+ draft_intent: "draft.intent.json",
63
+ draft_repo_context: "draft.repo-context.json",
64
+ draft_graph_context: "draft.graph-context.json",
65
+ draft_product_scope: "draft.product-scope.json",
66
+ draft_work_order_plan: "draft.work-order-plan.json",
67
+ draft_critic: "draft.critic.json",
68
+ draft_proposal: "draft.proposal.json"
69
+ };
70
+ const draftGateToolNames = {
71
+ draft_intent: "complete_draft_intent",
72
+ draft_repo_context: "complete_draft_repo_context",
73
+ draft_graph_context: "complete_draft_graph_context",
74
+ draft_product_scope: "complete_draft_product_scope",
75
+ draft_work_order_plan: "complete_draft_work_order_plan",
76
+ draft_critic: "complete_draft_critic",
77
+ draft_proposal: "complete_draft_proposal"
78
+ };
25
79
  const qaGateFileNames = {
26
80
  qa_plan: "qa.plan.json",
27
81
  qa_regression: "qa.regression.json",
@@ -95,6 +149,14 @@ const phaseFiles = {
95
149
  architect: {
96
150
  jsonFileName: "architect.verdict.json",
97
151
  reportFileName: "architect.report.md"
152
+ },
153
+ draft: {
154
+ jsonFileName: "draft.proposal.json",
155
+ reportFileName: "draft.report.md"
156
+ },
157
+ decompose: {
158
+ jsonFileName: "decompose.proposal.json",
159
+ reportFileName: "decompose.report.md"
98
160
  }
99
161
  };
100
162
  export function completionPhaseFromDispatch(dispatch) {
@@ -118,6 +180,12 @@ export function normalizeCompletionPhase(value) {
118
180
  if (normalized === "architect" || normalized === "architect_plan" || normalized === "planning" || normalized === "plan") {
119
181
  return "architect";
120
182
  }
183
+ if (normalized === "draft" || normalized === "drafting" || normalized === "draft_work_order") {
184
+ return "draft";
185
+ }
186
+ if (normalized === "decompose" || normalized === "decomposition" || normalized === "work_order_decomposition" || normalized === "feature_decomposition") {
187
+ return "decompose";
188
+ }
121
189
  return "implementation";
122
190
  }
123
191
  export function usesDevelopCycleCompletion(dispatch) {
@@ -154,6 +222,12 @@ export function usesArchitectCycleCompletion(dispatch) {
154
222
  return kind === "architect" || role === "architect" || lane === "architect";
155
223
  }
156
224
  export function completionToolNamesForPhase(phase) {
225
+ if (phase === "draft") {
226
+ return completionToolNamesForDraftGate("draft_proposal");
227
+ }
228
+ if (phase === "decompose") {
229
+ return completionToolNamesForDecomposeGate("decompose_proposal");
230
+ }
157
231
  if (isDebugCompletionPhase(phase)) {
158
232
  return completionToolNamesForDebugGate(phase);
159
233
  }
@@ -176,6 +250,14 @@ export function completionToolNamesForDebugGate(gate) {
176
250
  const base = debugGateToolNames[gate];
177
251
  return [`forge.${base}`, base];
178
252
  }
253
+ export function completionToolNamesForDraftGate(gate) {
254
+ const base = draftGateToolNames[gate];
255
+ return [`forge.${base}`, base];
256
+ }
257
+ export function completionToolNamesForDecomposeGate(gate) {
258
+ const base = decomposeGateToolNames[gate];
259
+ return [`forge.${base}`, base];
260
+ }
179
261
  export function expectedCompletionToolName(phase) {
180
262
  return completionToolNamesForPhase(phase)[0];
181
263
  }
@@ -185,6 +267,12 @@ export function expectedQaCompletionToolName(gate) {
185
267
  export function expectedDebugCompletionToolName(gate) {
186
268
  return completionToolNamesForDebugGate(gate)[0];
187
269
  }
270
+ export function expectedDraftCompletionToolName(gate) {
271
+ return completionToolNamesForDraftGate(gate)[0];
272
+ }
273
+ export function expectedDecomposeCompletionToolName(gate) {
274
+ return completionToolNamesForDecomposeGate(gate)[0];
275
+ }
188
276
  export function artifactRootFor(worktreePath, workItemId) {
189
277
  return path.join(worktreePath, ".forge", "work-items", safePathSegment(workItemId, "work item id"), "artifacts");
190
278
  }
@@ -219,7 +307,9 @@ export async function prepareCompletionToolRuntime(options) {
219
307
  developCycle: usesDevelopCycleCompletion(options.dispatch),
220
308
  qaCycle: usesQaCycleCompletion(options.dispatch),
221
309
  debugCycle: usesDebugCycleCompletion(options.dispatch),
222
- architectCycle: usesArchitectCycleCompletion(options.dispatch)
310
+ architectCycle: usesArchitectCycleCompletion(options.dispatch),
311
+ draftCycle: (options.dispatch.execution.lane.trim().toLowerCase() === "draft" || options.dispatch.cycleRun.kind.trim().toLowerCase() === "draft") && !isDecomposeDispatch(options.dispatch),
312
+ decomposeCycle: isDecomposeDispatch(options.dispatch)
223
313
  });
224
314
  const runtime = {
225
315
  serverName: toolServerName,
@@ -261,6 +351,12 @@ export function buildCompletionToolServerArgs(config) {
261
351
  if (config.architectCycle) {
262
352
  args.push("--architect-cycle");
263
353
  }
354
+ if (config.draftCycle) {
355
+ args.push("--draft-cycle");
356
+ }
357
+ if (config.decomposeCycle) {
358
+ args.push("--decompose-cycle");
359
+ }
264
360
  return args;
265
361
  }
266
362
  export function codexMcpConfigArgs(runtime) {
@@ -300,6 +396,7 @@ Do not write Architect artifacts by hand. When the plan is complete, call \`${to
300
396
  That tool writes \`.forge/work-items/{workItemId}/artifacts/implementation.plan.json\`, \`qa.plan.json\`, \`${artifactName}\`, and \`architect.report.md\`.
301
397
  The payload must put \`phases\`, \`tasks\`, \`dependencies\`, and \`phase_gates\` as top-level fields inside \`implementation_plan\`, for example:
302
398
  \`{ "status": "pass", "summary": "...", "implementation_plan": { "schema_version": 1, "plan_id": "plan-...", "phases": [{ "id": "phase-1", "tasks": ["task-1"], "gate": "gate-1" }], "tasks": [{ "id": "task-1", "tests": [{ "command": "npm test" }] }], "dependencies": [], "phase_gates": [{ "id": "gate-1", "phase": "phase-1" }] }, "qa_plan": { "schema_version": 1, "final_qa": [{ "id": "qa-1", "coverage": "..." }] }, "report_markdown": "# Architect Report" }\`.
399
+ \`implementation_plan.tasks\` are Develop child tasks only: each task must require a focused repo/product implementation change. Put parent-story QA, sign-off, child-count/materialization inventory, parent plan artifact checks, and final integrated acceptance proof in \`qa_plan.final_qa\`, not as child Develop tasks.
303
400
  Dependency entries use canonical \`before\` and \`after\` task ids, for example \`{ "before": "task-1", "after": "task-2" }\`. Forge accepts \`from\`/\`to\` only as aliases and normalizes them before writing artifacts.
304
401
  Use \`status: "pass"\` for a valid pending-approval plan, \`needs_revision\` when story/design input must change, or \`blocked\` with a concrete blocker.
305
402
  Forge will mirror only the tool-written Architect artifacts; reporting the plan in prose is not enough.`;
@@ -334,6 +431,35 @@ Use \`status: "skipped"\` with a reason for gates that are not applicable. If a
334
431
  The final verdict tool writes the canonical QA bundle under \`.forge/work-items/{workItemId}/artifacts/\`: \`qa.plan.json\`, \`qa.evidence.json\`, \`qa.findings.json\`, \`qa.verdict.json\`, and \`qa.report.md\`.
335
432
  The legacy \`forge.complete_qa\` one-shot tool is not available in normal QA-cycle mode. Reporting QA completion in prose is not enough.`;
336
433
  }
434
+ export function completionPromptForDraftCycle(currentGate = "draft_intent") {
435
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
436
+ Do not finish Draft by prose or raw JSON. The tool server enforces Draft gate order and starts at \`${currentGate}\`.
437
+ Complete the Draft cycle in order inside this same provider session:
438
+ 1. Call \`forge.complete_draft_intent(...)\` after interpreting user intent and non-goals.
439
+ 2. Follow the returned repo-context instruction, inspect selected project/repo assumptions, then call \`forge.complete_draft_repo_context(...)\`.
440
+ 3. Follow the returned graph-context instruction, account for DAG/dependency placement, then call \`forge.complete_draft_graph_context(...)\`.
441
+ 4. Follow the returned product-scope instruction, choose product scope for the selected project, then call \`forge.complete_draft_product_scope(...)\`.
442
+ 5. Follow the returned work-order-plan instruction, draft Work Order fields and candidate feature boundaries, then call \`forge.complete_draft_work_order_plan(...)\`.
443
+ 6. Follow the returned critic instruction, critique literalism, wrong-project scope, and decomposition quality, then call \`forge.complete_draft_critic(...)\`.
444
+ 7. Follow the returned proposal instruction, then call \`forge.complete_draft_proposal(...)\` with the final Work Order JSON in \`draft_json\`.
445
+ The final proposal tool writes \`draft.proposal.json\` under \`.forge/work-items/{workItemId}/artifacts/\`. Reporting Draft completion in prose is not enough.`;
446
+ }
447
+ export function completionPromptForDecomposeCycle(currentGate = "decompose_subject_intake") {
448
+ return `# Forge Decompose completion cycle
449
+ You must complete the Decompose gates in order using the Forge MCP tools. Reporting progress in prose is not enough.
450
+
451
+ Current gate: ${currentGate}
452
+
453
+ Required order:
454
+ 1. Call \`forge.complete_decompose_subject_intake(...)\` after identifying the Work Order/Feature subject, scope, and non-goals.
455
+ 2. Follow the returned context-review instruction, inspect injected project/repo/dependency context, then call \`forge.complete_decompose_context_review(...)\`.
456
+ 3. Follow the returned breakdown-strategy instruction, choose safe Feature/Story boundaries, then call \`forge.complete_decompose_breakdown_strategy(...)\`.
457
+ 4. Follow the returned child-items instruction, draft candidate child items, then call \`forge.complete_decompose_child_items(...)\`.
458
+ 5. Follow the returned dependency-graph instruction, validate keys/dependencies/order, then call \`forge.complete_decompose_dependency_graph(...)\`.
459
+ 6. Follow the returned critic instruction, critique scope, DAG safety, manual reconciliation risk, and missing acceptance detail, then call \`forge.complete_decompose_critic(...)\`.
460
+ 7. Follow the returned proposal instruction, then call \`forge.complete_decompose_proposal(...)\` with final JSON in \`proposal_json\`.
461
+ The final proposal tool writes \`decompose.proposal.json\` under \`.forge/work-items/{workItemId}/artifacts/\`. The proposal_json object must contain summary, optional blockedReason, and candidates.`;
462
+ }
337
463
  export function completionPromptForDebugCycle(currentGate = "debug_repro") {
338
464
  return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
339
465
  Do not write Debug artifacts by hand. The tool server enforces Debug gate order and starts this run at \`${currentGate}\`.
@@ -346,33 +472,43 @@ Each tool writes a canonical Debug artifact under \`.forge/work-items/{workItemI
346
472
  Use a non-pass status with explicit blockers when the current Debug gate cannot pass. Reporting Debug completion in prose is not enough; the relevant MCP completion tool is the transition request.`;
347
473
  }
348
474
  export function completionToolNamesForServer(config) {
349
- return config.debugCycle
350
- ? debugCompletionPhaseOrder.flatMap((gate) => completionToolNamesForDebugGate(gate))
351
- : config.qaCycle
352
- ? qaCompletionGateOrder.flatMap((gate) => completionToolNamesForQaGate(gate))
353
- : config.developCycle
354
- ? completionPhaseOrder.flatMap((phase) => completionToolNamesForPhase(phase))
355
- : config.architectCycle
356
- ? completionToolNamesForPhase("architect")
357
- : completionToolNamesForPhase(config.phase);
475
+ return config.decomposeCycle
476
+ ? decomposeCompletionGateOrder.flatMap((gate) => completionToolNamesForDecomposeGate(gate))
477
+ : config.draftCycle
478
+ ? draftCompletionGateOrder.flatMap((gate) => completionToolNamesForDraftGate(gate))
479
+ : config.debugCycle
480
+ ? debugCompletionPhaseOrder.flatMap((gate) => completionToolNamesForDebugGate(gate))
481
+ : config.qaCycle
482
+ ? qaCompletionGateOrder.flatMap((gate) => completionToolNamesForQaGate(gate))
483
+ : config.developCycle
484
+ ? completionPhaseOrder.flatMap((phase) => completionToolNamesForPhase(phase))
485
+ : config.architectCycle
486
+ ? completionToolNamesForPhase("architect")
487
+ : completionToolNamesForPhase(config.phase);
358
488
  }
359
489
  export class CompletionToolServerSession {
360
490
  config;
361
491
  currentPhase;
362
492
  currentQaGate = "qa_plan";
493
+ currentDraftGate = "draft_intent";
494
+ currentDecomposeGate = "decompose_subject_intake";
363
495
  completed = false;
364
496
  constructor(config) {
365
497
  this.config = config;
366
498
  this.currentPhase = config.phase;
367
499
  }
368
500
  get instructions() {
369
- return this.config.debugCycle
370
- ? completionPromptForDebugCycle(asDebugCompletionPhase(this.currentPhase))
371
- : this.config.qaCycle
372
- ? completionPromptForQaCycle(this.currentQaGate)
373
- : this.config.developCycle
374
- ? completionPromptForDevelopCycle(this.currentPhase)
375
- : completionPromptForPhase(this.currentPhase);
501
+ return this.config.decomposeCycle
502
+ ? completionPromptForDecomposeCycle(this.currentDecomposeGate)
503
+ : this.config.draftCycle
504
+ ? completionPromptForDraftCycle(this.currentDraftGate)
505
+ : this.config.debugCycle
506
+ ? completionPromptForDebugCycle(asDebugCompletionPhase(this.currentPhase))
507
+ : this.config.qaCycle
508
+ ? completionPromptForQaCycle(this.currentQaGate)
509
+ : this.config.developCycle
510
+ ? completionPromptForDevelopCycle(this.currentPhase)
511
+ : completionPromptForPhase(this.currentPhase);
376
512
  }
377
513
  toolDefinitions() {
378
514
  return completionToolNamesForServer(this.config).map((name) => toolDefinition(name, phaseFromToolName(name), qaGateFromToolName(name)));
@@ -382,6 +518,12 @@ export class CompletionToolServerSession {
382
518
  if (this.completed) {
383
519
  throw new Error("Forge completion cycle is already complete; no more completion calls are accepted.");
384
520
  }
521
+ if (this.config.decomposeCycle) {
522
+ return await this.callDecomposeGateTool(toolName, requestedPhase, input);
523
+ }
524
+ if (this.config.draftCycle) {
525
+ return await this.callDraftGateTool(toolName, requestedPhase, input);
526
+ }
385
527
  if (this.config.debugCycle) {
386
528
  return await this.callDebugGateTool(toolName, requestedPhase, input);
387
529
  }
@@ -422,6 +564,62 @@ export class CompletionToolServerSession {
422
564
  }
423
565
  };
424
566
  }
567
+ async callDecomposeGateTool(toolName, requestedPhase, input) {
568
+ const requestedGate = decomposeGateFromToolName(toolName);
569
+ if (requestedPhase !== "decompose" || !requestedGate) {
570
+ throw new Error(`Tool ${toolName} is not available in Decompose-cycle mode. Current Forge Decompose gate is ${this.currentDecomposeGate}.`);
571
+ }
572
+ if (requestedGate !== this.currentDecomposeGate) {
573
+ throw new Error(`Tool ${toolName} is out of order. Current Forge Decompose gate is ${this.currentDecomposeGate}.`);
574
+ }
575
+ const completedGate = this.currentDecomposeGate;
576
+ const reference = await writeDecomposeGateCompletionArtifact(this.config, completedGate, toolName, input);
577
+ const status = reference.status.trim().toLowerCase();
578
+ const pass = status === "pass";
579
+ const nextGate = pass ? this.advanceAfterDecomposeGate(completedGate) : completedGate;
580
+ const nextPhase = pass
581
+ ? (nextGate ? "decompose" : "sign_off_ready")
582
+ : "decompose";
583
+ const nextInstruction = completionToolNextInstructionForDecomposeGate(completedGate, status, nextGate);
584
+ const reason = pass
585
+ ? nextGate
586
+ ? `${completedGate} artifact accepted; continue to ${nextGate}.`
587
+ : `Decompose proposal artifact accepted with status ${status}.`
588
+ : `${completedGate} artifact recorded with status ${status}; rework is required before continuing.`;
589
+ return {
590
+ content: [{ type: "text", text: `Forge recorded ${completedGate} artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}). ${nextInstruction}` }],
591
+ structuredContent: {
592
+ ...reference,
593
+ gate: { phase: "decompose", decomposeGate: completedGate, status, allowed: pass, reason },
594
+ nextPhase,
595
+ nextInstruction
596
+ }
597
+ };
598
+ }
599
+ async callDraftGateTool(toolName, requestedPhase, input) {
600
+ const requestedGate = draftGateFromToolName(toolName);
601
+ if (requestedPhase !== "draft" || !requestedGate) {
602
+ throw new Error(`Tool ${toolName} is not available in Draft-cycle mode. Current Forge Draft gate is ${this.currentDraftGate}.`);
603
+ }
604
+ if (requestedGate !== this.currentDraftGate) {
605
+ throw new Error(`Tool ${toolName} is out of order. Current Forge Draft gate is ${this.currentDraftGate}.`);
606
+ }
607
+ const completedGate = this.currentDraftGate;
608
+ const reference = await writeDraftGateCompletionArtifact(this.config, completedGate, toolName, input);
609
+ const status = reference.status.trim().toLowerCase();
610
+ const nextGate = this.advanceAfterDraftGate(completedGate);
611
+ const nextPhase = nextGate ? "draft" : "sign_off_ready";
612
+ const nextInstruction = completionToolNextInstructionForDraftGate(completedGate, status, nextGate);
613
+ return {
614
+ content: [{ type: "text", text: `Forge recorded ${completedGate} artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}). ${nextInstruction}` }],
615
+ structuredContent: {
616
+ ...reference,
617
+ gate: { phase: "draft", draftGate: completedGate, status, allowed: status !== "blocked", reason: nextGate ? `${completedGate} artifact accepted; continue to ${nextGate}.` : `Draft proposal artifact accepted with status ${status}.` },
618
+ nextPhase,
619
+ nextInstruction
620
+ }
621
+ };
622
+ }
425
623
  async callDebugGateTool(toolName, requestedPhase, input) {
426
624
  const currentDebugGate = asDebugCompletionPhase(this.currentPhase);
427
625
  if (!isDebugCompletionPhase(requestedPhase)) {
@@ -518,6 +716,26 @@ export class CompletionToolServerSession {
518
716
  this.completed = true;
519
717
  return "dev_test_ready";
520
718
  }
719
+ advanceAfterDecomposeGate(gate) {
720
+ const index = decomposeCompletionGateOrder.indexOf(gate);
721
+ const next = index >= 0 ? decomposeCompletionGateOrder[index + 1] ?? null : null;
722
+ if (next) {
723
+ this.currentDecomposeGate = next;
724
+ return next;
725
+ }
726
+ this.completed = true;
727
+ return null;
728
+ }
729
+ advanceAfterDraftGate(gate) {
730
+ const index = draftCompletionGateOrder.indexOf(gate);
731
+ const next = index >= 0 ? draftCompletionGateOrder[index + 1] ?? null : null;
732
+ if (next) {
733
+ this.currentDraftGate = next;
734
+ return next;
735
+ }
736
+ this.completed = true;
737
+ return null;
738
+ }
521
739
  advanceAfterQaGate(gate) {
522
740
  const index = qaCompletionGateOrder.indexOf(gate);
523
741
  const next = index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
@@ -539,6 +757,77 @@ export class CompletionToolServerSession {
539
757
  return null;
540
758
  }
541
759
  }
760
+ async function writeDecomposeGateCompletionArtifact(config, gate, toolName, input) {
761
+ const payload = asRecord(input, "Decompose completion payload");
762
+ const status = normalizeDraftStatus(optionalString(payload, "status") ?? "pass");
763
+ if (gate === "decompose_proposal") {
764
+ const proposalJson = asRecord(payload["proposal_json"] ?? payload["decomposition_json"], "proposal_json");
765
+ if (!Array.isArray(proposalJson["candidates"])) {
766
+ throw new Error("proposal_json.candidates: expected array");
767
+ }
768
+ }
769
+ const redactedPayload = redactSecrets({ ...payload, status, phase: "decompose", gate, tool_name: toolName }, config.redactionSecrets ?? []);
770
+ const root = artifactRootFor(config.worktreePath, config.workItemId);
771
+ await fs.mkdir(root, { recursive: true });
772
+ const artifactPath = path.join(root, decomposeGateFileNames[gate]);
773
+ const reportPath = gate === "decompose_proposal" ? path.join(root, phaseFiles.decompose.reportFileName) : path.join(root, `${gate}.md`);
774
+ const verdictJson = jsonText(redactedPayload);
775
+ const report = optionalString(redactedPayload, "report_markdown") ?? `# ${gate.replace(/_/g, " ")}
776
+
777
+ ${optionalString(redactedPayload, "summary") ?? "Decompose gate recorded."}
778
+ `;
779
+ await writeFileAtomic(artifactPath, verdictJson);
780
+ await writeFileAtomic(reportPath, report);
781
+ return {
782
+ phase: "decompose",
783
+ workItemId: config.workItemId,
784
+ ownerType: config.ownerType,
785
+ ownerId: config.ownerId,
786
+ repoPath: path.resolve(config.worktreePath),
787
+ path: artifactPath,
788
+ reportPath,
789
+ contentHash: sha256(verdictJson),
790
+ status,
791
+ producedBy: config.producedBy ?? "forge-completion-tool"
792
+ };
793
+ }
794
+ async function writeDraftGateCompletionArtifact(config, gate, toolName, input) {
795
+ const payload = asRecord(input, "Draft completion payload");
796
+ const status = normalizeDraftStatus(optionalString(payload, "status") ?? "pass");
797
+ if (gate === "draft_proposal") {
798
+ const draftJson = asRecord(payload["draft_json"], "draft_json");
799
+ for (const key of ["title", "summary", "objective", "planningPacket", "decompositionContext"]) {
800
+ if (typeof draftJson[key] !== "string" || draftJson[key].trim().length === 0) {
801
+ throw new Error(`draft_json.${key}: expected non-empty string`);
802
+ }
803
+ }
804
+ }
805
+ const redactedPayload = redactSecrets({ ...payload, status, phase: "draft", gate, tool_name: toolName }, config.redactionSecrets ?? []);
806
+ const root = artifactRootFor(config.worktreePath, config.workItemId);
807
+ await fs.mkdir(root, { recursive: true });
808
+ const artifactPath = path.join(root, draftGateFileNames[gate]);
809
+ const reportPath = gate === "draft_proposal" ? path.join(root, phaseFiles.draft.reportFileName) : path.join(root, `${gate}.md`);
810
+ const verdictJson = jsonText(redactedPayload);
811
+ const report = optionalString(redactedPayload, "report_markdown") ?? `# ${gate.replace(/_/g, " ")}\n\n${optionalString(redactedPayload, "summary") ?? "Draft gate recorded."}\n`;
812
+ await writeFileAtomic(artifactPath, verdictJson);
813
+ await writeFileAtomic(reportPath, report);
814
+ return {
815
+ phase: "draft",
816
+ workItemId: config.workItemId,
817
+ ownerType: config.ownerType,
818
+ ownerId: config.ownerId,
819
+ repoPath: path.resolve(config.worktreePath),
820
+ path: artifactPath,
821
+ reportPath,
822
+ contentHash: sha256(verdictJson),
823
+ status,
824
+ producedBy: config.producedBy ?? "forge-completion-tool"
825
+ };
826
+ }
827
+ function normalizeDraftStatus(value) {
828
+ const normalized = value.trim().toLowerCase();
829
+ return normalized === "blocked" || normalized === "needs_revision" || normalized === "needs_rework" ? normalized : "pass";
830
+ }
542
831
  export async function writeCompletionArtifact(config, toolName, input) {
543
832
  const phase = phaseFromToolName(toolName);
544
833
  if (phase !== config.phase) {
@@ -550,7 +839,10 @@ export async function writeCompletionArtifact(config, toolName, input) {
550
839
  }
551
840
  const payload = asRecord(input, "completion payload");
552
841
  const status = normalizeCompletionStatus(requiredString(payload, "status"), phase);
553
- const validationPayload = { ...payload, status };
842
+ let validationPayload = { ...payload, status };
843
+ if (config.qaCycle && qaGate === "qa_verdict") {
844
+ validationPayload = await synthesizeQaCycleVerdictPayload(config, validationPayload, status);
845
+ }
554
846
  validatePayloadShape(phase, validationPayload);
555
847
  validateOptionalWorkItemId(validationPayload, config.workItemId);
556
848
  const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
@@ -793,6 +1085,133 @@ async function writeQaCompletionArtifact(config, payload, status, producedBy) {
793
1085
  producedBy
794
1086
  };
795
1087
  }
1088
+ async function synthesizeQaCycleVerdictPayload(config, payload, status) {
1089
+ const qaPlan = await readQaGateArtifact(config, "qa_plan");
1090
+ const qaRegression = await readQaGateArtifact(config, "qa_regression");
1091
+ const qaApi = await readQaGateArtifact(config, "qa_api");
1092
+ const qaManualWeb = await readQaGateArtifact(config, "qa_manual_web");
1093
+ const qaBugRepro = await readQaGateArtifact(config, "qa_bug_repro");
1094
+ const qaFindings = await readQaGateArtifact(config, "qa_findings");
1095
+ const evidenceGates = [qaRegression, qaApi, qaManualWeb, qaBugRepro];
1096
+ const payloadEvidence = qaEvidenceSource(payload);
1097
+ const merged = { ...payload };
1098
+ const checklist = qaStringArray(payload, "checklist");
1099
+ if (checklist.length === 0) {
1100
+ const plannedChecklist = qaStringArray(qaPlan, "checklist");
1101
+ merged.checklist = plannedChecklist.length > 0 ? plannedChecklist : defaultQaChecklist(status);
1102
+ }
1103
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
1104
+ if (testedAcceptanceCriteria.length === 0) {
1105
+ const plannedAcceptanceCriteria = qaStringArray(qaPlan, "acceptance_criteria");
1106
+ const payloadAcceptanceCriteria = qaStringArray(payload, "acceptance_criteria");
1107
+ const acceptanceCriteria = plannedAcceptanceCriteria.length > 0 ? plannedAcceptanceCriteria : payloadAcceptanceCriteria;
1108
+ if (acceptanceCriteria.length > 0) {
1109
+ merged.tested_acceptance_criteria = acceptanceCriteria;
1110
+ }
1111
+ }
1112
+ const payloadCommands = qaArray(payload, "commands", payloadEvidence);
1113
+ const inheritedCommands = evidenceGates.flatMap((gate) => qaArray(gate, "commands"));
1114
+ const inheritedDiagnosticCommandNotes = status === "pass"
1115
+ ? qaNonPassingCommandNotes(inheritedCommands)
1116
+ : [];
1117
+ merged.commands = dedupeUnknownArray([
1118
+ ...payloadCommands,
1119
+ ...(status === "pass" ? inheritedCommands.filter(isQaPassingCommandEvidence) : inheritedCommands)
1120
+ ]);
1121
+ merged.browser_checks = dedupeUnknownArray([
1122
+ ...qaArray(payload, "browser_checks", payloadEvidence),
1123
+ ...evidenceGates.flatMap((gate) => qaArray(gate, "browser_checks"))
1124
+ ]);
1125
+ merged.sidecars = dedupeUnknownArray([
1126
+ ...qaArray(payload, "sidecars", payloadEvidence),
1127
+ ...evidenceGates.flatMap((gate) => qaArray(gate, "sidecars"))
1128
+ ]);
1129
+ const notes = dedupeStrings([
1130
+ optionalString(payload, "notes"),
1131
+ optionalString(payloadEvidence, "notes"),
1132
+ ...evidenceGates.map((gate) => optionalString(gate, "notes")),
1133
+ ...inheritedDiagnosticCommandNotes
1134
+ ]);
1135
+ if (notes.length > 0) {
1136
+ merged.notes = notes.join("\n");
1137
+ }
1138
+ merged.findings = mergeQaObjectArraysById(qaObjectArray(payload, "findings"), qaObjectArray(qaFindings, "findings"));
1139
+ merged.candidate_bugs = mergeQaObjectArraysById(qaObjectArray(payload, "candidate_bugs"), qaObjectArray(qaFindings, "candidate_bugs"));
1140
+ return merged;
1141
+ }
1142
+ async function readQaGateArtifact(config, gate) {
1143
+ const ownerFields = artifactOwnerFields(config);
1144
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
1145
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
1146
+ : artifactRootFor(config.worktreePath, config.workItemId);
1147
+ const artifactPath = path.join(artifactRoot, qaGateFileNames[gate]);
1148
+ const content = await readOptionalFile(artifactPath);
1149
+ return content === null ? {} : parseOptionalJsonObject(content, qaGateFileNames[gate]);
1150
+ }
1151
+ function dedupeUnknownArray(values) {
1152
+ const seen = new Set();
1153
+ const deduped = [];
1154
+ for (const value of values) {
1155
+ const key = stableStringify(value);
1156
+ if (seen.has(key)) {
1157
+ continue;
1158
+ }
1159
+ seen.add(key);
1160
+ deduped.push(value);
1161
+ }
1162
+ return deduped;
1163
+ }
1164
+ function isQaPassingCommandEvidence(value) {
1165
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1166
+ return false;
1167
+ }
1168
+ const record = value;
1169
+ return record.exit_code === 0 && normalizedString(record.status) === "pass";
1170
+ }
1171
+ function qaNonPassingCommandNotes(values) {
1172
+ return values
1173
+ .filter((value) => !isQaPassingCommandEvidence(value))
1174
+ .map((value, index) => {
1175
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1176
+ return `QA diagnostic command ${index + 1} was omitted from pass evidence because it was not a structured passing command.`;
1177
+ }
1178
+ const record = value;
1179
+ const command = optionalString(record, "command") ?? "<missing command>";
1180
+ const status = optionalString(record, "status") ?? "<missing status>";
1181
+ const exitCode = typeof record.exit_code === "number" && Number.isFinite(record.exit_code)
1182
+ ? String(record.exit_code)
1183
+ : "<missing exit_code>";
1184
+ const summary = optionalString(record, "summary");
1185
+ return `QA diagnostic command omitted from pass evidence: ${command} (status ${status}, exit_code ${exitCode})${summary ? ` — ${summary}` : ""}.`;
1186
+ });
1187
+ }
1188
+ function mergeQaObjectArraysById(primary, fallback) {
1189
+ const seen = new Set();
1190
+ const merged = [];
1191
+ for (const value of [...primary, ...fallback]) {
1192
+ const id = optionalString(value, "id");
1193
+ const key = id ? `id:${id}` : stableStringify(value);
1194
+ if (seen.has(key)) {
1195
+ continue;
1196
+ }
1197
+ seen.add(key);
1198
+ merged.push(value);
1199
+ }
1200
+ return merged;
1201
+ }
1202
+ function dedupeStrings(values) {
1203
+ const seen = new Set();
1204
+ const deduped = [];
1205
+ for (const value of values) {
1206
+ const trimmed = value?.trim();
1207
+ if (!trimmed || seen.has(trimmed)) {
1208
+ continue;
1209
+ }
1210
+ seen.add(trimmed);
1211
+ deduped.push(trimmed);
1212
+ }
1213
+ return deduped;
1214
+ }
796
1215
  async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, ownerType, ownerId) {
797
1216
  if (sidecars.length === 0) {
798
1217
  return [];
@@ -855,10 +1274,19 @@ export async function readCompletionArtifact(worktreePath, workItemId, phase, ow
855
1274
  }
856
1275
  const parsed = parseJsonObject(verdictJson, artifactPath);
857
1276
  const report = await readOptionalFile(reportPath) ?? fallbackReport(parsed, phase, artifactPath);
1277
+ const artifactRoot = path.dirname(artifactPath);
1278
+ const implementationPlanJson = phase === "architect"
1279
+ ? await readOptionalFile(path.join(artifactRoot, "implementation.plan.json"))
1280
+ : null;
1281
+ const qaPlanJson = phase === "architect"
1282
+ ? await readOptionalFile(path.join(artifactRoot, "qa.plan.json"))
1283
+ : null;
858
1284
  return {
859
1285
  repoPath: path.resolve(worktreePath),
860
1286
  path: artifactPath,
861
1287
  verdictJson,
1288
+ implementationPlanJson,
1289
+ qaPlanJson,
862
1290
  report,
863
1291
  producedBy: optionalString(parsed, "produced_by") ?? optionalString(parsed, "producedBy") ?? "forge-completion-tool",
864
1292
  status: optionalString(parsed, "status") ?? "unknown",
@@ -897,6 +1325,8 @@ export function parseCompletionMcpArgs(argv) {
897
1325
  let qaCycle = false;
898
1326
  let debugCycle = false;
899
1327
  let architectCycle = false;
1328
+ let draftCycle = false;
1329
+ let decomposeCycle = false;
900
1330
  for (let index = 1; index < argv.length; index += 1) {
901
1331
  const arg = argv[index];
902
1332
  if (arg === "--worktree") {
@@ -918,7 +1348,7 @@ export function parseCompletionMcpArgs(argv) {
918
1348
  const rawPhase = argv[++index];
919
1349
  const parsedPhase = parseStrictCompletionPhase(rawPhase);
920
1350
  if (!parsedPhase) {
921
- return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation, qa, architect, debug-repro, debug-root-cause, debug-fix, debug-regression." };
1351
+ return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation, qa, architect, draft, debug-repro, debug-root-cause, debug-fix, debug-regression." };
922
1352
  }
923
1353
  phase = parsedPhase;
924
1354
  }
@@ -937,6 +1367,12 @@ export function parseCompletionMcpArgs(argv) {
937
1367
  else if (arg === "--architect-cycle") {
938
1368
  architectCycle = true;
939
1369
  }
1370
+ else if (arg === "--draft-cycle") {
1371
+ draftCycle = true;
1372
+ }
1373
+ else if (arg === "--decompose-cycle") {
1374
+ decomposeCycle = true;
1375
+ }
940
1376
  else {
941
1377
  return { ok: false, error: `Unknown mcp argument: ${arg}` };
942
1378
  }
@@ -944,7 +1380,7 @@ export function parseCompletionMcpArgs(argv) {
944
1380
  if (!worktreePath?.trim() || !workItemId?.trim()) {
945
1381
  return { ok: false, error: "mcp requires --worktree and --work-item-id." };
946
1382
  }
947
- if ([developCycle, qaCycle, debugCycle, architectCycle].filter(Boolean).length > 1) {
1383
+ if ([developCycle, qaCycle, debugCycle, architectCycle, draftCycle, decomposeCycle].filter(Boolean).length > 1) {
948
1384
  return { ok: false, error: "mcp accepts only one cycle mode." };
949
1385
  }
950
1386
  if (developCycle && !isDevelopCompletionPhase(phase)) {
@@ -959,6 +1395,12 @@ export function parseCompletionMcpArgs(argv) {
959
1395
  if (architectCycle && phase !== "architect") {
960
1396
  return { ok: false, error: "mcp --architect-cycle requires --phase architect." };
961
1397
  }
1398
+ if (draftCycle && phase !== "draft") {
1399
+ return { ok: false, error: "mcp --draft-cycle requires --phase draft." };
1400
+ }
1401
+ if (decomposeCycle && phase !== "decompose") {
1402
+ return { ok: false, error: "mcp --decompose-cycle requires --phase decompose." };
1403
+ }
962
1404
  return {
963
1405
  ok: true,
964
1406
  config: {
@@ -972,7 +1414,9 @@ export function parseCompletionMcpArgs(argv) {
972
1414
  developCycle,
973
1415
  qaCycle,
974
1416
  debugCycle,
975
- architectCycle
1417
+ architectCycle,
1418
+ draftCycle,
1419
+ decomposeCycle
976
1420
  }
977
1421
  };
978
1422
  }
@@ -1110,6 +1554,24 @@ function completionToolNextInstruction(completedPhase, status, nextPhase) {
1110
1554
  }
1111
1555
  return "Validation accepted. Forge has the structured evidence needed to move this work item to QA.";
1112
1556
  }
1557
+ function completionToolNextInstructionForDraftGate(completedGate, status, nextGate) {
1558
+ if (status === "blocked") {
1559
+ return `Stay in ${completedGate}; record the blocker and retry the same Draft gate when unblocked.`;
1560
+ }
1561
+ if (!nextGate) {
1562
+ return "Draft proposal accepted. Forge has the structured Work Order draft JSON needed to populate the form.";
1563
+ }
1564
+ const instructions = {
1565
+ draft_intent: "Capture intent/non-goals, then call forge.complete_draft_intent.",
1566
+ draft_repo_context: "Inspect selected repo/project assumptions, then call forge.complete_draft_repo_context.",
1567
+ draft_graph_context: "Account for DAG dependencies and placement, then call forge.complete_draft_graph_context.",
1568
+ draft_product_scope: "Choose product scope for the selected project, then call forge.complete_draft_product_scope.",
1569
+ draft_work_order_plan: "Draft Work Order fields and candidate Feature boundaries, then call forge.complete_draft_work_order_plan.",
1570
+ draft_critic: "Critique literalism/wrong-project scope/decomposition risk, then call forge.complete_draft_critic.",
1571
+ draft_proposal: "Submit final draft_json through forge.complete_draft_proposal."
1572
+ };
1573
+ return `${completedGate} accepted. Continue to ${nextGate}. ${instructions[nextGate]}`;
1574
+ }
1113
1575
  function completionToolNextInstructionForQaGate(completedGate, status, nextGate) {
1114
1576
  if (!nextGate) {
1115
1577
  if (status === "blocked") {
@@ -1129,6 +1591,24 @@ function completionToolNextInstructionForQaGate(completedGate, status, nextGate)
1129
1591
  : `${completedGate} accepted. Continue to ${nextGate}.`;
1130
1592
  return `${prefix} ${qaGateInstruction(nextGate)}`;
1131
1593
  }
1594
+ function completionToolNextInstructionForDecomposeGate(completedGate, status, nextGate) {
1595
+ if (status !== "pass") {
1596
+ return `Stay in ${completedGate}, address the recorded blockers/rework, then call ${expectedDecomposeCompletionToolName(completedGate)} again.`;
1597
+ }
1598
+ if (!nextGate) {
1599
+ return "Decompose proposal accepted. Forge has the structured child-item proposal JSON needed to populate the proposal row.";
1600
+ }
1601
+ const nextInstructions = {
1602
+ decompose_subject_intake: "Capture subject/scope, then call forge.complete_decompose_subject_intake.",
1603
+ decompose_context_review: "Review project/repo/dependency context, then call forge.complete_decompose_context_review.",
1604
+ decompose_breakdown_strategy: "Choose safe child boundaries, then call forge.complete_decompose_breakdown_strategy.",
1605
+ decompose_child_items: "Draft child candidates, then call forge.complete_decompose_child_items.",
1606
+ decompose_dependency_graph: "Validate dependency DAG, then call forge.complete_decompose_dependency_graph.",
1607
+ decompose_critic: "Critique the decomposition, then call forge.complete_decompose_critic.",
1608
+ decompose_proposal: "Submit final proposal_json through forge.complete_decompose_proposal."
1609
+ };
1610
+ return `${completedGate} accepted. ${nextInstructions[nextGate]}`;
1611
+ }
1132
1612
  function completionToolNextInstructionForDebugGate(completedGate, status, nextGate) {
1133
1613
  if (status !== "pass") {
1134
1614
  return `Stay in ${completedGate}, address the recorded blockers, then call ${expectedDebugCompletionToolName(completedGate)} again.`;
@@ -1232,7 +1712,7 @@ function toolInputSchema(phase, qaGate = null) {
1232
1712
  },
1233
1713
  tests_added_or_updated: {
1234
1714
  type: "array",
1235
- description: "Required for pass. Use an object explaining why no tests were needed for docs/config-only work if empty would be ambiguous.",
1715
+ description: "Required for pass. Use an object explaining why no tests were needed for documentation/config-only work if empty would be ambiguous.",
1236
1716
  items: evidenceObjectSchema(["path", "summary"], {
1237
1717
  path: { type: "string" },
1238
1718
  summary: { type: "string" }
@@ -1425,7 +1905,7 @@ function toolInputSchema(phase, qaGate = null) {
1425
1905
  },
1426
1906
  tasks: {
1427
1907
  type: "array",
1428
- description: "Required task list. Each task must include id and a non-empty tests array.",
1908
+ description: "Required Develop child task list. Each task must include id and a non-empty tests array, and must require a focused repo/product implementation change. Do not put parent-story QA/sign-off, child-count/materialization inventory, parent plan artifact checks, or final acceptance proof here; those belong in qa_plan.final_qa.",
1429
1909
  items: { type: "object", additionalProperties: true }
1430
1910
  },
1431
1911
  dependencies: {
@@ -1881,6 +2361,7 @@ function validateQaGatePayloadShape(gate, payload, status) {
1881
2361
  if (commands.length === 0) {
1882
2362
  throw new Error(`${qaGateToolNames[gate]} pass requires commands with at least one entry.`);
1883
2363
  }
2364
+ validateQaGatePassingCommands(commands);
1884
2365
  }
1885
2366
  if (gate === "qa_manual_web" && status === "pass") {
1886
2367
  const browserChecks = qaArray(payload, "browser_checks");
@@ -1890,6 +2371,24 @@ function validateQaGatePayloadShape(gate, payload, status) {
1890
2371
  }
1891
2372
  }
1892
2373
  }
2374
+ function validateQaGatePassingCommands(commands) {
2375
+ for (const [index, command] of commands.entries()) {
2376
+ requireEvidenceRecord(command, `commands[${index}]`);
2377
+ const record = command;
2378
+ requireNonEmptyStringRecord(record, "command", `commands[${index}].`);
2379
+ requireNonEmptyStringRecord(record, "status", `commands[${index}].`);
2380
+ requireNonEmptyStringRecord(record, "summary", `commands[${index}].`);
2381
+ if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
2382
+ throw new Error(`commands[${index}].exit_code is required.`);
2383
+ }
2384
+ if (record.exit_code !== 0) {
2385
+ throw new Error(`commands[${index}].exit_code must be 0 when QA gate status is pass.`);
2386
+ }
2387
+ if (normalizedString(record.status) !== "pass") {
2388
+ throw new Error(`commands[${index}].status must be pass when QA gate status is pass.`);
2389
+ }
2390
+ }
2391
+ }
1893
2392
  function validateArchitectPayloadShape(payload, status) {
1894
2393
  if (status !== "pass") {
1895
2394
  requireArchitectNonPassEvidence(payload);
@@ -1918,6 +2417,7 @@ function validateArchitectPayloadShape(payload, status) {
1918
2417
  throw new Error(`implementation_plan.tasks: duplicate task id '${taskId}'.`);
1919
2418
  }
1920
2419
  taskIds.add(taskId);
2420
+ validateArchitectTaskDevelopScope(taskRecord, taskId);
1921
2421
  requireArchitectArray(taskRecord, "tests", payload, { path: `implementation_plan.tasks[${optionalString(taskRecord, "id") ?? "?"}].tests` });
1922
2422
  if (arrayLength(taskRecord, "tests") === 0) {
1923
2423
  throw new Error(`implementation_plan.tasks[${optionalString(taskRecord, "id") ?? "?"}].tests: expected non-empty array; correction: include task-specific verification.`);
@@ -1930,6 +2430,124 @@ function validateArchitectPayloadShape(payload, status) {
1930
2430
  throw new Error("qa_plan.final_qa: expected non-empty array; correction: include final QA coverage for the completed plan.");
1931
2431
  }
1932
2432
  }
2433
+ function validateArchitectTaskDevelopScope(task, taskId) {
2434
+ const explicitScope = firstOptionalString(task, ["execution_scope", "scope", "task_scope", "task_type", "lane", "kind", "type"]);
2435
+ if (isStoryQaScope(explicitScope)) {
2436
+ throw new Error(`implementation_plan.tasks[${taskId}]: story QA/sign-off work must not be materialized as a Develop child task; correction: move this coverage to qa_plan.final_qa and keep implementation_plan.tasks limited to repo/product changes.`);
2437
+ }
2438
+ if (looksLikeStoryLevelVerificationTask(architectTaskScopeText(task))) {
2439
+ throw new Error(`implementation_plan.tasks[${taskId}]: parent-story materialization or sign-off verification belongs in qa_plan.final_qa, not implementation_plan.tasks; correction: keep child tasks focused on implementation work and put child-count/parent-plan artifact checks in final QA coverage.`);
2440
+ }
2441
+ }
2442
+ function firstOptionalString(record, keys) {
2443
+ for (const key of keys) {
2444
+ const value = optionalString(record, key);
2445
+ if (value) {
2446
+ return value;
2447
+ }
2448
+ }
2449
+ return null;
2450
+ }
2451
+ function isStoryQaScope(value) {
2452
+ if (!value) {
2453
+ return false;
2454
+ }
2455
+ const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_");
2456
+ return [
2457
+ "qa",
2458
+ "story_qa",
2459
+ "final_qa",
2460
+ "sign_off",
2461
+ "signoff",
2462
+ "story_sign_off",
2463
+ "story_verification",
2464
+ "story_validation"
2465
+ ].includes(normalized);
2466
+ }
2467
+ function architectTaskScopeText(task) {
2468
+ const parts = [];
2469
+ for (const key of ["id", "title", "summary", "phase", "phase_id"]) {
2470
+ appendOptionalString(parts, task, key);
2471
+ }
2472
+ for (const key of ["acceptance_criteria", "expected_paths", "touched_surfaces", "implementation_notes"]) {
2473
+ appendOptionalStringArray(parts, task, key);
2474
+ }
2475
+ const tests = task.tests;
2476
+ if (Array.isArray(tests)) {
2477
+ for (const test of tests) {
2478
+ if (!test || typeof test !== "object" || Array.isArray(test)) {
2479
+ continue;
2480
+ }
2481
+ const record = test;
2482
+ for (const key of ["id", "command", "purpose", "target", "expected"]) {
2483
+ appendOptionalString(parts, record, key);
2484
+ }
2485
+ appendOptionalStringArray(parts, record, "steps");
2486
+ }
2487
+ }
2488
+ return parts.join(" ");
2489
+ }
2490
+ function appendOptionalString(parts, record, key) {
2491
+ const value = optionalString(record, key);
2492
+ if (value) {
2493
+ parts.push(value);
2494
+ }
2495
+ }
2496
+ function appendOptionalStringArray(parts, record, key) {
2497
+ const value = record[key];
2498
+ if (!Array.isArray(value)) {
2499
+ return;
2500
+ }
2501
+ for (const entry of value) {
2502
+ if (typeof entry === "string" && entry.trim().length > 0) {
2503
+ parts.push(entry.trim());
2504
+ }
2505
+ }
2506
+ }
2507
+ function looksLikeStoryLevelVerificationTask(text) {
2508
+ if (!text.trim()) {
2509
+ return false;
2510
+ }
2511
+ const normalized = text.toLowerCase();
2512
+ const verificationWords = [
2513
+ "verify",
2514
+ "verification",
2515
+ "validate",
2516
+ "validation",
2517
+ "inspect",
2518
+ "audit",
2519
+ "check",
2520
+ "confirm",
2521
+ "prove",
2522
+ "evidence",
2523
+ "sign-off",
2524
+ "sign off"
2525
+ ];
2526
+ if (!verificationWords.some((word) => normalized.includes(word))) {
2527
+ return false;
2528
+ }
2529
+ return [
2530
+ "materialization",
2531
+ "materialized child",
2532
+ "child inventory",
2533
+ "child work-item",
2534
+ "child work item",
2535
+ "created task count",
2536
+ "created_task_count",
2537
+ "parent plan",
2538
+ "parent story",
2539
+ "story sign-off",
2540
+ "story sign off",
2541
+ ".forge/work-items",
2542
+ ".forge\\work-items",
2543
+ ".forge/stories",
2544
+ ".forge\\stories",
2545
+ "implementation.plan.json",
2546
+ "qa.plan.json",
2547
+ "architect plan artifact",
2548
+ "child spec"
2549
+ ].some((needle) => normalized.includes(needle));
2550
+ }
1933
2551
  function validateAndNormalizeArchitectDependencies(implementationPlan, taskIds) {
1934
2552
  const dependencies = implementationPlan.dependencies;
1935
2553
  const edges = new Map();
@@ -2251,6 +2869,12 @@ function parseStrictCompletionPhase(value) {
2251
2869
  if (normalized === "architect" || normalized === "architect_plan" || normalized === "planning" || normalized === "plan") {
2252
2870
  return "architect";
2253
2871
  }
2872
+ if (normalized === "draft" || normalized === "drafting" || normalized === "draft_work_order") {
2873
+ return "draft";
2874
+ }
2875
+ if (normalized === "decompose" || normalized === "decomposition" || normalized === "work_order_decomposition" || normalized === "feature_decomposition") {
2876
+ return "decompose";
2877
+ }
2254
2878
  return null;
2255
2879
  }
2256
2880
  function normalizeDebugCompletionPhase(value) {
@@ -2322,6 +2946,12 @@ function phaseFromToolName(toolName) {
2322
2946
  if (normalized === "forge.complete_architect_plan" || normalized === "complete_architect_plan") {
2323
2947
  return "architect";
2324
2948
  }
2949
+ if (draftGateFromToolName(toolName)) {
2950
+ return "draft";
2951
+ }
2952
+ if (decomposeGateFromToolName(toolName)) {
2953
+ return "decompose";
2954
+ }
2325
2955
  const debugGate = debugGateFromToolName(toolName);
2326
2956
  if (debugGate) {
2327
2957
  return debugGate;
@@ -2331,6 +2961,32 @@ function phaseFromToolName(toolName) {
2331
2961
  }
2332
2962
  throw new Error(`Unknown Forge completion tool: ${toolName}`);
2333
2963
  }
2964
+ function draftGateFromToolName(toolName) {
2965
+ const normalized = toolName.trim().toLowerCase();
2966
+ for (const gate of draftCompletionGateOrder) {
2967
+ const base = draftGateToolNames[gate];
2968
+ if (normalized === `forge.${base}` || normalized === base) {
2969
+ return gate;
2970
+ }
2971
+ }
2972
+ return null;
2973
+ }
2974
+ function decomposeGateFromToolName(toolName) {
2975
+ for (const gate of decomposeCompletionGateOrder) {
2976
+ const base = decomposeGateToolNames[gate];
2977
+ if (toolName === base || toolName === `forge.${base}`) {
2978
+ return gate;
2979
+ }
2980
+ }
2981
+ return null;
2982
+ }
2983
+ function isDecomposeDispatch(dispatch) {
2984
+ const draftKind = dispatch.draft?.kind?.trim().toLowerCase();
2985
+ return dispatch.execution.lane.trim().toLowerCase() === "decompose"
2986
+ || dispatch.session.lane.trim().toLowerCase() === "decompose"
2987
+ || draftKind === "work_order_decomposition"
2988
+ || draftKind === "feature_decomposition";
2989
+ }
2334
2990
  function debugGateFromToolName(toolName) {
2335
2991
  const normalized = toolName.trim().toLowerCase();
2336
2992
  for (const gate of debugCompletionPhaseOrder) {