@loucompanion/forge-bridge 0.1.1-dev.4f31cdd58cac → 0.1.1-dev.5b0a0fe4307c

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.
@@ -3,9 +3,62 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { redactSecrets } from "../shared/redaction/redaction.js";
6
+ import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
6
7
  const toolServerName = "forge";
7
8
  const completionRedactionSecretsEnv = "FORGE_COMPLETION_REDACTION_SECRETS";
8
9
  const completionPhaseOrder = ["implementation", "self_review", "validation"];
10
+ export const debugCompletionPhaseOrder = [
11
+ "debug_repro",
12
+ "debug_root_cause",
13
+ "debug_fix",
14
+ "debug_regression"
15
+ ];
16
+ export const qaCompletionGateOrder = [
17
+ "qa_plan",
18
+ "qa_regression",
19
+ "qa_api",
20
+ "qa_manual_web",
21
+ "qa_bug_repro",
22
+ "qa_findings",
23
+ "qa_verdict"
24
+ ];
25
+ const qaGateFileNames = {
26
+ qa_plan: "qa.plan.json",
27
+ qa_regression: "qa.regression.json",
28
+ qa_api: "qa.api.json",
29
+ qa_manual_web: "qa.manual-web.json",
30
+ qa_bug_repro: "qa.bug-repro.json",
31
+ qa_findings: "qa.findings.json",
32
+ qa_verdict: "qa.verdict.json"
33
+ };
34
+ const qaGateToolNames = {
35
+ qa_plan: "complete_qa_plan",
36
+ qa_regression: "complete_qa_regression",
37
+ qa_api: "complete_qa_api",
38
+ qa_manual_web: "complete_qa_manual_web",
39
+ qa_bug_repro: "complete_qa_bug_repro",
40
+ qa_findings: "complete_qa_findings",
41
+ qa_verdict: "complete_qa_verdict"
42
+ };
43
+ const debugGateToolNames = {
44
+ debug_repro: "complete_debug_repro",
45
+ debug_root_cause: "complete_debug_root_cause",
46
+ debug_fix: "complete_debug_fix",
47
+ debug_regression: "complete_debug_regression"
48
+ };
49
+ const qaBlockerReasons = new Set([
50
+ "missing_app_launch_target",
51
+ "inconclusive",
52
+ "environment_failure",
53
+ "missing_validation_evidence",
54
+ "missing_worktree",
55
+ "runner_failure"
56
+ ]);
57
+ const resolvedFindingStatusValues = ["resolved", "disputed", "not_reproduced"];
58
+ const resolvedFindingStatuses = new Set(resolvedFindingStatusValues);
59
+ const qaFindingSeverities = new Set(["critical", "major", "minor"]);
60
+ const qaFindingScopes = new Set(["in_scope", "out_of_scope", "unclear"]);
61
+ const qaCandidateBugActions = new Set(["create_bug", "create_follow_up", "accept_risk", "attach_to_current_item"]);
9
62
  const phaseFiles = {
10
63
  implementation: {
11
64
  jsonFileName: "implementation.completeness.json",
@@ -18,6 +71,30 @@ const phaseFiles = {
18
71
  validation: {
19
72
  jsonFileName: "validation.verdict.json",
20
73
  reportFileName: "validation.report.md"
74
+ },
75
+ qa: {
76
+ jsonFileName: "qa.verdict.json",
77
+ reportFileName: "qa.report.md"
78
+ },
79
+ debug_repro: {
80
+ jsonFileName: "debug.repro.json",
81
+ reportFileName: "debug.report.md"
82
+ },
83
+ debug_root_cause: {
84
+ jsonFileName: "debug.root-cause.json",
85
+ reportFileName: "debug.report.md"
86
+ },
87
+ debug_fix: {
88
+ jsonFileName: "debug.fix.json",
89
+ reportFileName: "debug.report.md"
90
+ },
91
+ debug_regression: {
92
+ jsonFileName: "debug.regression.json",
93
+ reportFileName: "debug.report.md"
94
+ },
95
+ architect: {
96
+ jsonFileName: "architect.verdict.json",
97
+ reportFileName: "architect.report.md"
21
98
  }
22
99
  };
23
100
  export function completionPhaseFromDispatch(dispatch) {
@@ -25,12 +102,22 @@ export function completionPhaseFromDispatch(dispatch) {
25
102
  }
26
103
  export function normalizeCompletionPhase(value) {
27
104
  const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
105
+ const debugPhase = normalizeDebugCompletionPhase(normalized);
106
+ if (debugPhase) {
107
+ return debugPhase;
108
+ }
28
109
  if (normalized === "self_review" || normalized === "selfreview" || normalized === "review") {
29
110
  return "self_review";
30
111
  }
31
112
  if (normalized === "validate" || normalized === "validation") {
32
113
  return "validation";
33
114
  }
115
+ if (normalized === "qa" || normalized === "quality_assurance" || normalized === "qualityassurance") {
116
+ return "qa";
117
+ }
118
+ if (normalized === "architect" || normalized === "architect_plan" || normalized === "planning" || normalized === "plan") {
119
+ return "architect";
120
+ }
34
121
  return "implementation";
35
122
  }
36
123
  export function usesDevelopCycleCompletion(dispatch) {
@@ -42,36 +129,97 @@ export function usesDevelopCycleCompletion(dispatch) {
42
129
  && lane === "develop"
43
130
  && completionPhaseFromDispatch(dispatch) === "implementation";
44
131
  }
132
+ export function usesQaCycleCompletion(dispatch) {
133
+ const kind = dispatch.cycleRun.kind.trim().toLowerCase();
134
+ const role = dispatch.execution.role.trim().toLowerCase();
135
+ const lane = dispatch.execution.lane.trim().toLowerCase();
136
+ return kind === "qa"
137
+ && role === "qa"
138
+ && lane === "qa"
139
+ && completionPhaseFromDispatch(dispatch) === "qa";
140
+ }
141
+ export function usesDebugCycleCompletion(dispatch) {
142
+ const kind = dispatch.cycleRun.kind.trim().toLowerCase();
143
+ const role = dispatch.execution.role.trim().toLowerCase();
144
+ const lane = dispatch.execution.lane.trim().toLowerCase();
145
+ return kind === "debug"
146
+ && role === "debug"
147
+ && lane === "debug"
148
+ && isDebugCompletionPhase(completionPhaseFromDispatch(dispatch));
149
+ }
150
+ export function usesArchitectCycleCompletion(dispatch) {
151
+ const kind = dispatch.cycleRun.kind.trim().toLowerCase();
152
+ const role = dispatch.execution.role.trim().toLowerCase();
153
+ const lane = dispatch.execution.lane.trim().toLowerCase();
154
+ return kind === "architect" || role === "architect" || lane === "architect";
155
+ }
45
156
  export function completionToolNamesForPhase(phase) {
157
+ if (isDebugCompletionPhase(phase)) {
158
+ return completionToolNamesForDebugGate(phase);
159
+ }
46
160
  const base = phase === "implementation"
47
161
  ? "complete_implementation"
48
162
  : phase === "self_review"
49
163
  ? "complete_self_review"
50
- : "complete_validation";
164
+ : phase === "validation"
165
+ ? "complete_validation"
166
+ : phase === "architect"
167
+ ? "complete_architect_plan"
168
+ : "complete_qa";
169
+ return [`forge.${base}`, base];
170
+ }
171
+ export function completionToolNamesForQaGate(gate) {
172
+ const base = qaGateToolNames[gate];
173
+ return [`forge.${base}`, base];
174
+ }
175
+ export function completionToolNamesForDebugGate(gate) {
176
+ const base = debugGateToolNames[gate];
51
177
  return [`forge.${base}`, base];
52
178
  }
53
179
  export function expectedCompletionToolName(phase) {
54
180
  return completionToolNamesForPhase(phase)[0];
55
181
  }
182
+ export function expectedQaCompletionToolName(gate) {
183
+ return completionToolNamesForQaGate(gate)[0];
184
+ }
185
+ export function expectedDebugCompletionToolName(gate) {
186
+ return completionToolNamesForDebugGate(gate)[0];
187
+ }
56
188
  export function artifactRootFor(worktreePath, workItemId) {
57
189
  return path.join(worktreePath, ".forge", "work-items", safePathSegment(workItemId, "work item id"), "artifacts");
58
190
  }
59
- export function completionArtifactJsonPath(worktreePath, workItemId, phase) {
60
- return path.join(artifactRootFor(worktreePath, workItemId), phaseFiles[phase].jsonFileName);
191
+ export function artifactRootForOwner(worktreePath, ownerType, ownerId) {
192
+ return path.join(worktreePath, ".forge", artifactOwnerDirectory(ownerType), safePathSegment(ownerId, "owner id"), "artifacts");
193
+ }
194
+ export function completionArtifactJsonPath(worktreePath, workItemId, phase, ownerType, ownerId) {
195
+ const artifactRoot = ownerType && ownerId
196
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
197
+ : artifactRootFor(worktreePath, workItemId);
198
+ return path.join(artifactRoot, phaseFiles[phase].jsonFileName);
61
199
  }
62
- export function completionArtifactReportPath(worktreePath, workItemId, phase) {
63
- return path.join(artifactRootFor(worktreePath, workItemId), phaseFiles[phase].reportFileName);
200
+ export function completionArtifactReportPath(worktreePath, workItemId, phase, ownerType, ownerId) {
201
+ const artifactRoot = ownerType && ownerId
202
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
203
+ : artifactRootFor(worktreePath, workItemId);
204
+ return path.join(artifactRoot, phaseFiles[phase].reportFileName);
64
205
  }
65
206
  export async function prepareCompletionToolRuntime(options) {
66
207
  const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
67
208
  const worktreePath = path.resolve(options.worktree.worktreePath);
68
209
  const workItemId = options.dispatch.workItem.id;
210
+ const ownerType = normalizedOwnerType(options.dispatch.cycleRun.ownerType) ?? "work_item";
211
+ const ownerId = options.dispatch.cycleRun.ownerId ?? workItemId;
69
212
  const mcpArgs = buildCompletionToolServerArgs({
70
213
  worktreePath,
71
214
  workItemId,
215
+ ownerType,
216
+ ownerId,
72
217
  phase,
73
218
  producedBy: `${options.dispatch.execution.provider}-cli`,
74
- developCycle: usesDevelopCycleCompletion(options.dispatch)
219
+ developCycle: usesDevelopCycleCompletion(options.dispatch),
220
+ qaCycle: usesQaCycleCompletion(options.dispatch),
221
+ debugCycle: usesDebugCycleCompletion(options.dispatch),
222
+ architectCycle: usesArchitectCycleCompletion(options.dispatch)
75
223
  });
76
224
  const runtime = {
77
225
  serverName: toolServerName,
@@ -97,9 +245,22 @@ export function buildCompletionToolServerArgs(config) {
97
245
  "--produced-by",
98
246
  config.producedBy ?? "forge-completion-tool"
99
247
  ];
248
+ if (config.ownerType || config.ownerId) {
249
+ args.push("--owner-type", normalizedOwnerType(config.ownerType) ?? "work_item");
250
+ args.push("--owner-id", config.ownerId ?? config.workItemId);
251
+ }
100
252
  if (config.developCycle) {
101
253
  args.push("--develop-cycle");
102
254
  }
255
+ if (config.qaCycle) {
256
+ args.push("--qa-cycle");
257
+ }
258
+ if (config.debugCycle) {
259
+ args.push("--debug-cycle");
260
+ }
261
+ if (config.architectCycle) {
262
+ args.push("--architect-cycle");
263
+ }
103
264
  return args;
104
265
  }
105
266
  export function codexMcpConfigArgs(runtime) {
@@ -126,6 +287,23 @@ export function completionPromptForPhase(phase) {
126
287
  const toolName = expectedCompletionToolName(phase);
127
288
  const alias = completionToolNamesForPhase(phase).find((name) => name !== toolName);
128
289
  const artifactName = phaseFiles[phase].jsonFileName;
290
+ if (phase === "qa") {
291
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
292
+ Do not write QA artifacts by hand. When QA is complete, call \`${toolName}(...)\`${alias ? ` (or \`${alias}\` if your client shows unqualified MCP tool names)` : ""} with the required structured QA payload.
293
+ That tool writes the durable QA bundle under \`.forge/work-items/{workItemId}/artifacts/\`: \`qa.plan.json\`, \`qa.evidence.json\`, \`qa.findings.json\`, \`${artifactName}\`, and \`qa.report.md\`.
294
+ Use \`status: "pass"\` only when the validated changes satisfy acceptance criteria with concrete evidence. Use \`status: "needs_rework"\` with actionable in-scope findings, or \`status: "blocked"\` with a concrete blocker_reason.
295
+ Forge will mirror only the tool-written QA artifacts; reporting QA completion in prose is not enough.`;
296
+ }
297
+ if (phase === "architect") {
298
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
299
+ Do not write Architect artifacts by hand. When the plan is complete, call \`${toolName}(...)\`${alias ? ` (or \`${alias}\` if your client shows unqualified MCP tool names)` : ""} with the full structured Architect planning payload.
300
+ That tool writes \`.forge/work-items/{workItemId}/artifacts/implementation.plan.json\`, \`qa.plan.json\`, \`${artifactName}\`, and \`architect.report.md\`.
301
+ The payload must put \`phases\`, \`tasks\`, \`dependencies\`, and \`phase_gates\` as top-level fields inside \`implementation_plan\`, for example:
302
+ \`{ "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" }\`.
303
+ 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
+ Use \`status: "pass"\` for a valid pending-approval plan, \`needs_revision\` when story/design input must change, or \`blocked\` with a concrete blocker.
305
+ Forge will mirror only the tool-written Architect artifacts; reporting the plan in prose is not enough.`;
306
+ }
129
307
  return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
130
308
  Do not write phase artifacts by hand. When the phase is complete, call \`${toolName}(...)\`${alias ? ` (or \`${alias}\` if your client shows unqualified MCP tool names)` : ""} with the required evidence payload.
131
309
  That tool writes \`.forge/work-items/{workItemId}/artifacts/${artifactName}\` and returns the artifact reference that Forge will mirror through the existing phase-artifact pipeline.
@@ -141,31 +319,74 @@ Complete the dev cycle in order inside this same provider session:
141
319
  Each tool writes the canonical artifact under \`.forge/work-items/{workItemId}/artifacts/\` and returns the next-phase instruction Forge expects you to follow.
142
320
  If the current phase cannot pass, call the current phase tool with a non-pass status and explicit blockers instead of reporting completion in prose only.`;
143
321
  }
322
+ export function completionPromptForQaCycle(currentGate = "qa_plan") {
323
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
324
+ Do not write QA artifacts by hand. The tool server enforces QA gate order and starts this run at \`${currentGate}\`.
325
+ Complete the QA cycle in order inside this same provider session:
326
+ 1. Call \`forge.complete_qa_plan(...)\` after the QA test plan/checklist is ready.
327
+ 2. Follow the returned regression instruction, then call \`forge.complete_qa_regression(...)\`.
328
+ 3. Follow the returned API/backend instruction, then call \`forge.complete_qa_api(...)\`.
329
+ 4. Follow the returned manual web instruction, then call \`forge.complete_qa_manual_web(...)\`.
330
+ 5. Follow the returned bug reproduction instruction, then call \`forge.complete_qa_bug_repro(...)\`.
331
+ 6. Follow the returned findings instruction, then call \`forge.complete_qa_findings(...)\`.
332
+ 7. Follow the returned verdict instruction, then call \`forge.complete_qa_verdict(...)\`.
333
+ Use \`status: "skipped"\` with a reason for gates that are not applicable. If a gate is blocked, keep moving through later gates as skipped due to the blocker and finish with a blocked verdict.
334
+ 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
+ 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
+ }
337
+ export function completionPromptForDebugCycle(currentGate = "debug_repro") {
338
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
339
+ Do not write Debug artifacts by hand. The tool server enforces Debug gate order and starts this run at \`${currentGate}\`.
340
+ Complete the Debug cycle in order inside this same provider session:
341
+ 1. Reproduce or tightly characterize the bug, then call \`forge.complete_debug_repro(...)\`.
342
+ 2. Follow the returned root-cause instruction, isolate evidence, then call \`forge.complete_debug_root_cause(...)\`.
343
+ 3. Follow the returned fix instruction, apply the smallest safe fix with regression coverage when practical, then call \`forge.complete_debug_fix(...)\`.
344
+ 4. Follow the returned regression instruction, prove the original repro is negative and the fix is QA-ready, then call \`forge.complete_debug_regression(...)\`.
345
+ Each tool writes a canonical Debug artifact under \`.forge/work-items/{workItemId}/artifacts/\`: \`debug.repro.json\`, \`debug.root-cause.json\`, \`debug.fix.json\`, and \`debug.regression.json\` plus \`debug.report.md\` when report text is provided or generated.
346
+ 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
+ }
144
348
  export function completionToolNamesForServer(config) {
145
- return config.developCycle
146
- ? completionPhaseOrder.flatMap((phase) => completionToolNamesForPhase(phase))
147
- : completionToolNamesForPhase(config.phase);
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);
148
358
  }
149
359
  export class CompletionToolServerSession {
150
360
  config;
151
361
  currentPhase;
362
+ currentQaGate = "qa_plan";
152
363
  completed = false;
153
364
  constructor(config) {
154
365
  this.config = config;
155
366
  this.currentPhase = config.phase;
156
367
  }
157
368
  get instructions() {
158
- return this.config.developCycle
159
- ? completionPromptForDevelopCycle(this.currentPhase)
160
- : completionPromptForPhase(this.currentPhase);
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);
161
376
  }
162
377
  toolDefinitions() {
163
- return completionToolNamesForServer(this.config).map((name) => toolDefinition(name, phaseFromToolName(name)));
378
+ return completionToolNamesForServer(this.config).map((name) => toolDefinition(name, phaseFromToolName(name), qaGateFromToolName(name)));
164
379
  }
165
380
  async callTool(toolName, input) {
166
381
  const requestedPhase = phaseFromToolName(toolName);
167
382
  if (this.completed) {
168
- throw new Error("Forge develop cycle is already complete; no more phase completion calls are accepted.");
383
+ throw new Error("Forge completion cycle is already complete; no more completion calls are accepted.");
384
+ }
385
+ if (this.config.debugCycle) {
386
+ return await this.callDebugGateTool(toolName, requestedPhase, input);
387
+ }
388
+ if (this.config.qaCycle) {
389
+ return await this.callQaGateTool(toolName, requestedPhase, input);
169
390
  }
170
391
  if (requestedPhase !== this.currentPhase) {
171
392
  throw new Error(`Tool ${toolName} is out of order. Current Forge phase is ${this.currentPhase}.`);
@@ -201,7 +422,91 @@ export class CompletionToolServerSession {
201
422
  }
202
423
  };
203
424
  }
425
+ async callDebugGateTool(toolName, requestedPhase, input) {
426
+ const currentDebugGate = asDebugCompletionPhase(this.currentPhase);
427
+ if (!isDebugCompletionPhase(requestedPhase)) {
428
+ throw new Error(`Tool ${toolName} is not available in Debug-cycle mode. Current Forge Debug gate is ${currentDebugGate}.`);
429
+ }
430
+ if (requestedPhase !== currentDebugGate) {
431
+ throw new Error(`Tool ${toolName} is out of order. Current Forge Debug gate is ${currentDebugGate}.`);
432
+ }
433
+ const completedGate = currentDebugGate;
434
+ const reference = await writeCompletionArtifact({ ...this.config, phase: completedGate }, toolName, input);
435
+ const status = reference.status.trim().toLowerCase();
436
+ const pass = status === "pass";
437
+ const nextGate = pass ? this.advanceAfterDebugGate(completedGate) : completedGate;
438
+ const nextPhase = nextGate ?? "qa_ready";
439
+ const nextInstruction = completionToolNextInstructionForDebugGate(completedGate, status, nextGate);
440
+ const reason = pass
441
+ ? `${completedGate} artifact accepted${nextGate ? `; continue to ${nextGate}.` : "; Debug regression is QA-ready."}`
442
+ : `${completedGate} artifact recorded with status ${status}; rework is required before Debug progression.`;
443
+ return {
444
+ content: [
445
+ {
446
+ type: "text",
447
+ text: `Forge recorded ${completedGate} artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}). ${nextInstruction}`
448
+ }
449
+ ],
450
+ structuredContent: {
451
+ ...reference,
452
+ gate: {
453
+ phase: completedGate,
454
+ status,
455
+ allowed: pass,
456
+ reason
457
+ },
458
+ nextPhase,
459
+ nextInstruction
460
+ }
461
+ };
462
+ }
463
+ async callQaGateTool(toolName, requestedPhase, input) {
464
+ const requestedGate = qaGateFromToolName(toolName);
465
+ if (requestedPhase !== "qa" || !requestedGate) {
466
+ throw new Error(`Tool ${toolName} is not available in QA-cycle mode. Current Forge QA gate is ${this.currentQaGate}.`);
467
+ }
468
+ if (requestedGate !== this.currentQaGate) {
469
+ throw new Error(`Tool ${toolName} is out of order. Current Forge QA gate is ${this.currentQaGate}.`);
470
+ }
471
+ const completedGate = this.currentQaGate;
472
+ const reference = await writeCompletionArtifact({ ...this.config, phase: "qa" }, toolName, input);
473
+ const status = reference.status.trim().toLowerCase();
474
+ const nextGate = this.advanceAfterQaGate(completedGate);
475
+ const nextPhase = nextGate ? "qa" : "sign_off_ready";
476
+ const nextInstruction = completionToolNextInstructionForQaGate(completedGate, status, nextGate);
477
+ const allowed = status !== "blocked";
478
+ const reason = nextGate
479
+ ? `${completedGate} artifact accepted; continue to ${nextGate}.`
480
+ : `QA verdict artifact accepted with status ${status}.`;
481
+ return {
482
+ content: [
483
+ {
484
+ type: "text",
485
+ text: `Forge recorded ${completedGate} artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}). ${nextInstruction}`
486
+ }
487
+ ],
488
+ structuredContent: {
489
+ ...reference,
490
+ gate: {
491
+ phase: "qa",
492
+ qaGate: completedGate,
493
+ status,
494
+ allowed,
495
+ reason
496
+ },
497
+ nextPhase,
498
+ nextInstruction
499
+ }
500
+ };
501
+ }
204
502
  advanceAfterPass(phase) {
503
+ if (phase === "qa") {
504
+ this.completed = true;
505
+ return "sign_off_ready";
506
+ }
507
+ if (isDebugCompletionPhase(phase)) {
508
+ return nextDebugPhaseAfter(phase) ?? "qa_ready";
509
+ }
205
510
  const next = nextPhaseAfter(phase);
206
511
  if (!this.config.developCycle) {
207
512
  return next ?? "dev_test_ready";
@@ -213,14 +518,38 @@ export class CompletionToolServerSession {
213
518
  this.completed = true;
214
519
  return "dev_test_ready";
215
520
  }
521
+ advanceAfterQaGate(gate) {
522
+ const index = qaCompletionGateOrder.indexOf(gate);
523
+ const next = index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
524
+ if (next) {
525
+ this.currentQaGate = next;
526
+ return next;
527
+ }
528
+ this.completed = true;
529
+ return null;
530
+ }
531
+ advanceAfterDebugGate(gate) {
532
+ const index = debugCompletionPhaseOrder.indexOf(gate);
533
+ const next = index >= 0 ? debugCompletionPhaseOrder[index + 1] ?? null : null;
534
+ if (next) {
535
+ this.currentPhase = next;
536
+ return next;
537
+ }
538
+ this.completed = true;
539
+ return null;
540
+ }
216
541
  }
217
542
  export async function writeCompletionArtifact(config, toolName, input) {
218
543
  const phase = phaseFromToolName(toolName);
219
544
  if (phase !== config.phase) {
220
545
  throw new Error(`Tool ${toolName} is not allowed for phase ${config.phase}.`);
221
546
  }
547
+ const qaGate = qaGateFromToolName(toolName);
548
+ if (qaGate && qaGate !== "qa_verdict") {
549
+ return await writeQaGateCompletionArtifact(config, qaGate, input);
550
+ }
222
551
  const payload = asRecord(input, "completion payload");
223
- const status = normalizeCompletionStatus(requiredString(payload, "status"));
552
+ const status = normalizeCompletionStatus(requiredString(payload, "status"), phase);
224
553
  const validationPayload = { ...payload, status };
225
554
  validatePayloadShape(phase, validationPayload);
226
555
  validateOptionalWorkItemId(validationPayload, config.workItemId);
@@ -229,9 +558,17 @@ export async function writeCompletionArtifact(config, toolName, input) {
229
558
  ?? optionalString(redactedPayload, "producedBy")
230
559
  ?? config.producedBy
231
560
  ?? "forge-completion-tool";
561
+ if (phase === "qa") {
562
+ return await writeQaCompletionArtifact(config, redactedPayload, status, producedBy);
563
+ }
564
+ if (phase === "architect") {
565
+ return await writeArchitectCompletionArtifact(config, redactedPayload, status, producedBy);
566
+ }
232
567
  const artifactWithoutHash = normalizeArtifactPayload(redactedPayload, {
233
568
  phase,
234
569
  workItemId: config.workItemId,
570
+ ownerType: config.ownerType,
571
+ ownerId: config.ownerId,
235
572
  producedBy,
236
573
  status
237
574
  });
@@ -250,6 +587,93 @@ export async function writeCompletionArtifact(config, toolName, input) {
250
587
  return {
251
588
  phase,
252
589
  workItemId: config.workItemId,
590
+ ...artifactReferenceOwnerFields(config),
591
+ repoPath: path.resolve(config.worktreePath),
592
+ path: artifactPath,
593
+ reportPath,
594
+ contentHash,
595
+ status,
596
+ producedBy
597
+ };
598
+ }
599
+ async function writeArchitectCompletionArtifact(config, payload, status, producedBy) {
600
+ const ownerFields = artifactOwnerFields(config);
601
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
602
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
603
+ : artifactRootFor(config.worktreePath, config.workItemId);
604
+ const implementationPlanPath = path.join(artifactRoot, "implementation.plan.json");
605
+ const qaPlanPath = path.join(artifactRoot, "qa.plan.json");
606
+ const verdictPath = path.join(artifactRoot, "architect.verdict.json");
607
+ const reportPath = path.join(artifactRoot, "architect.report.md");
608
+ const implementationPlan = requiredRecord(payload, "implementation_plan");
609
+ const qaPlan = requiredRecord(payload, "qa_plan");
610
+ const report = optionalString(payload, "report") ?? optionalString(payload, "report_markdown") ?? reportMarkdown(payload, "architect", status, producedBy, "pending");
611
+ const artifactWithoutHash = normalizeArtifactPayload(payload, {
612
+ phase: "architect",
613
+ workItemId: config.workItemId,
614
+ ownerType: config.ownerType,
615
+ ownerId: config.ownerId,
616
+ producedBy,
617
+ status
618
+ });
619
+ const contentHash = sha256(stableStringify(artifactWithoutHash));
620
+ const verdict = {
621
+ ...artifactWithoutHash,
622
+ content_hash: contentHash
623
+ };
624
+ await fs.mkdir(artifactRoot, { recursive: true });
625
+ await writeFileAtomic(implementationPlanPath, jsonText(implementationPlan));
626
+ await writeFileAtomic(qaPlanPath, jsonText(qaPlan));
627
+ await writeFileAtomic(verdictPath, jsonText(verdict));
628
+ await writeFileAtomic(reportPath, `${report.trim()}\n`);
629
+ return {
630
+ phase: "architect",
631
+ workItemId: config.workItemId,
632
+ ...artifactReferenceOwnerFields(config),
633
+ repoPath: path.resolve(config.worktreePath),
634
+ path: verdictPath,
635
+ reportPath,
636
+ contentHash,
637
+ status,
638
+ producedBy
639
+ };
640
+ }
641
+ async function writeQaGateCompletionArtifact(config, gate, input) {
642
+ const payload = asRecord(input, "QA gate completion payload");
643
+ const status = normalizeQaGateStatus(requiredString(payload, "status"));
644
+ validateQaGatePayloadShape(gate, payload, status);
645
+ validateOptionalWorkItemId(payload, config.workItemId);
646
+ const redactedPayload = redactSecrets({ ...payload, status }, config.redactionSecrets ?? []);
647
+ const producedBy = optionalString(redactedPayload, "produced_by")
648
+ ?? optionalString(redactedPayload, "producedBy")
649
+ ?? config.producedBy
650
+ ?? "forge-completion-tool";
651
+ const ownerFields = artifactOwnerFields(config);
652
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
653
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
654
+ : artifactRootFor(config.worktreePath, config.workItemId);
655
+ const fileName = qaGateFileNames[gate];
656
+ const artifactPath = path.join(artifactRoot, fileName);
657
+ const reportPath = path.join(artifactRoot, "qa.report.md");
658
+ const artifactWithoutHash = normalizeQaGateArtifactPayload(redactedPayload, {
659
+ gate,
660
+ workItemId: config.workItemId,
661
+ ownerType: config.ownerType,
662
+ ownerId: config.ownerId,
663
+ producedBy,
664
+ status
665
+ });
666
+ const contentHash = sha256(stableStringify(artifactWithoutHash));
667
+ const artifact = {
668
+ ...artifactWithoutHash,
669
+ content_hash: contentHash
670
+ };
671
+ await fs.mkdir(artifactRoot, { recursive: true });
672
+ await writeFileAtomic(artifactPath, jsonText(artifact));
673
+ return {
674
+ phase: "qa",
675
+ workItemId: config.workItemId,
676
+ ...artifactReferenceOwnerFields(config),
253
677
  repoPath: path.resolve(config.worktreePath),
254
678
  path: artifactPath,
255
679
  reportPath,
@@ -258,9 +682,173 @@ export async function writeCompletionArtifact(config, toolName, input) {
258
682
  producedBy
259
683
  };
260
684
  }
261
- export async function readCompletionArtifact(worktreePath, workItemId, phase) {
262
- const artifactPath = completionArtifactJsonPath(worktreePath, workItemId, phase);
263
- const reportPath = completionArtifactReportPath(worktreePath, workItemId, phase);
685
+ async function writeQaCompletionArtifact(config, payload, status, producedBy) {
686
+ const ownerFields = artifactOwnerFields(config);
687
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
688
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
689
+ : artifactRootFor(config.worktreePath, config.workItemId);
690
+ const planPath = path.join(artifactRoot, "qa.plan.json");
691
+ const evidencePath = path.join(artifactRoot, "qa.evidence.json");
692
+ const findingsPath = path.join(artifactRoot, "qa.findings.json");
693
+ const verdictPath = path.join(artifactRoot, "qa.verdict.json");
694
+ const reportPath = path.join(artifactRoot, "qa.report.md");
695
+ const relativeEvidencePath = ownerFields.owner_type && ownerFields.owner_id
696
+ ? qaArtifactRelativePathForOwner(ownerFields.owner_type, ownerFields.owner_id, "qa.evidence.json")
697
+ : qaArtifactRelativePath(config.workItemId, "qa.evidence.json");
698
+ const relativeFindingsPath = ownerFields.owner_type && ownerFields.owner_id
699
+ ? qaArtifactRelativePathForOwner(ownerFields.owner_type, ownerFields.owner_id, "qa.findings.json")
700
+ : qaArtifactRelativePath(config.workItemId, "qa.findings.json");
701
+ const relativeReportPath = ownerFields.owner_type && ownerFields.owner_id
702
+ ? qaArtifactRelativePathForOwner(ownerFields.owner_type, ownerFields.owner_id, "qa.report.md")
703
+ : qaArtifactRelativePath(config.workItemId, "qa.report.md");
704
+ const evidenceSource = qaEvidenceSource(payload);
705
+ const commands = qaArray(payload, "commands", evidenceSource);
706
+ const browserChecks = qaArray(payload, "browser_checks", evidenceSource);
707
+ const sidecars = await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(payload, "sidecars", evidenceSource), ownerFields.owner_type, ownerFields.owner_id);
708
+ const notes = optionalString(payload, "notes") ?? optionalString(evidenceSource, "notes") ?? "";
709
+ const findings = qaObjectArray(payload, "findings");
710
+ const candidateBugs = qaObjectArray(payload, "candidate_bugs");
711
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
712
+ const explicitFindingIds = qaStringArray(payload, "finding_ids");
713
+ const explicitCandidateBugIds = qaStringArray(payload, "candidate_bug_ids");
714
+ const blockerReason = optionalString(payload, "blocker_reason");
715
+ const checklist = qaStringArray(payload, "checklist");
716
+ const planJson = jsonText({
717
+ schema_version: 1,
718
+ phase: "qa",
719
+ ...ownerFields,
720
+ checklist: checklist.length > 0 ? checklist : defaultQaChecklist(status),
721
+ acceptance_criteria: testedAcceptanceCriteria
722
+ });
723
+ const evidenceJson = jsonText({
724
+ schema_version: 1,
725
+ phase: "qa",
726
+ ...ownerFields,
727
+ commands,
728
+ browser_checks: browserChecks,
729
+ sidecars,
730
+ notes
731
+ });
732
+ const findingsJson = jsonText({
733
+ schema_version: 1,
734
+ phase: "qa",
735
+ ...ownerFields,
736
+ findings,
737
+ candidate_bugs: candidateBugs
738
+ });
739
+ const findingIds = status === "pass"
740
+ ? []
741
+ : explicitFindingIds.length > 0
742
+ ? explicitFindingIds
743
+ : findings
744
+ .filter((finding) => normalizedString(finding.scope) === "in_scope")
745
+ .map((finding) => optionalString(finding, "id"))
746
+ .filter((id) => Boolean(id));
747
+ const candidateBugIds = explicitCandidateBugIds.length > 0
748
+ ? explicitCandidateBugIds
749
+ : candidateBugs
750
+ .map((candidateBug) => optionalString(candidateBug, "id"))
751
+ .filter((id) => Boolean(id));
752
+ const verdictWithoutHash = {
753
+ schema_version: numberOrDefault(payload.schema_version, 1),
754
+ phase: "qa",
755
+ ...ownerFields,
756
+ status,
757
+ summary: requiredString(payload, "summary"),
758
+ tested_acceptance_criteria: testedAcceptanceCriteria,
759
+ finding_ids: findingIds,
760
+ candidate_bug_ids: candidateBugIds,
761
+ blocker_reason: status === "blocked" ? normalizedString(blockerReason) : null,
762
+ evidence_path: relativeEvidencePath,
763
+ findings_path: relativeFindingsPath,
764
+ report_path: relativeReportPath,
765
+ produced_by: producedBy
766
+ };
767
+ const contentHash = sha256(stableStringify({
768
+ plan: JSON.parse(planJson),
769
+ evidence: JSON.parse(evidenceJson),
770
+ findings: JSON.parse(findingsJson),
771
+ verdict: verdictWithoutHash
772
+ }));
773
+ const verdictJson = jsonText({
774
+ ...verdictWithoutHash,
775
+ content_hash: contentHash
776
+ });
777
+ const finalReport = reportMarkdown(payload, "qa", status, producedBy, contentHash);
778
+ await fs.mkdir(artifactRoot, { recursive: true });
779
+ await writeFileAtomic(planPath, planJson);
780
+ await writeFileAtomic(evidencePath, evidenceJson);
781
+ await writeFileAtomic(findingsPath, findingsJson);
782
+ await writeFileAtomic(verdictPath, verdictJson);
783
+ await writeFileAtomic(reportPath, finalReport);
784
+ return {
785
+ phase: "qa",
786
+ workItemId: config.workItemId,
787
+ ...artifactReferenceOwnerFields(config),
788
+ repoPath: path.resolve(config.worktreePath),
789
+ path: verdictPath,
790
+ reportPath,
791
+ contentHash,
792
+ status,
793
+ producedBy
794
+ };
795
+ }
796
+ async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, ownerType, ownerId) {
797
+ if (sidecars.length === 0) {
798
+ return [];
799
+ }
800
+ const artifactRoot = ownerType && ownerId
801
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
802
+ : artifactRootFor(worktreePath, workItemId);
803
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
804
+ const validated = [];
805
+ for (const [index, sidecar] of sidecars.entries()) {
806
+ if (!sidecar || typeof sidecar !== "object" || Array.isArray(sidecar)) {
807
+ throw new Error(`sidecars[${index}] must be an object.`);
808
+ }
809
+ const record = sidecar;
810
+ const sidecarPath = optionalString(record, "path");
811
+ const contentHash = optionalString(record, "content_hash");
812
+ const bytes = record.bytes;
813
+ if (!sidecarPath || !contentHash || typeof bytes !== "number" || !Number.isFinite(bytes) || bytes <= 0) {
814
+ throw new Error(`sidecars[${index}] must include path, content_hash, and positive bytes.`);
815
+ }
816
+ if (path.isAbsolute(sidecarPath)) {
817
+ throw new Error(`sidecars[${index}].path must be relative to the worktree.`);
818
+ }
819
+ const fullPath = path.resolve(worktreePath, sidecarPath);
820
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
821
+ throw new Error(`sidecars[${index}].path must be under ${artifactOwnerRelativeRoot(ownerType, ownerId, workItemId)}/qa/.`);
822
+ }
823
+ const stat = await fs.lstat(fullPath).catch((error) => {
824
+ if (isNodeError(error) && error.code === "ENOENT") {
825
+ throw new Error(`sidecars[${index}].path does not exist: ${sidecarPath}`);
826
+ }
827
+ throw error;
828
+ });
829
+ if (!stat.isFile() || stat.isSymbolicLink()) {
830
+ throw new Error(`sidecars[${index}].path must reference a regular file.`);
831
+ }
832
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `sidecars[${index}].path must not traverse symbolic links.`);
833
+ if (stat.size !== bytes) {
834
+ throw new Error(`sidecars[${index}].bytes does not match the referenced file.`);
835
+ }
836
+ const actualHash = await sha256File(fullPath);
837
+ if (actualHash !== contentHash.trim().toLowerCase()) {
838
+ throw new Error(`sidecars[${index}].content_hash does not match the referenced file.`);
839
+ }
840
+ validated.push({
841
+ ...record,
842
+ path: path.relative(worktreePath, fullPath).split(path.sep).join("/"),
843
+ content_hash: actualHash,
844
+ bytes: stat.size
845
+ });
846
+ }
847
+ return validated;
848
+ }
849
+ export async function readCompletionArtifact(worktreePath, workItemId, phase, ownerType, ownerId) {
850
+ const artifactPath = completionArtifactJsonPath(worktreePath, workItemId, phase, ownerType, ownerId);
851
+ const reportPath = completionArtifactReportPath(worktreePath, workItemId, phase, ownerType, ownerId);
264
852
  const verdictJson = await readOptionalFile(artifactPath);
265
853
  if (verdictJson === null) {
266
854
  return null;
@@ -302,8 +890,13 @@ export function parseCompletionMcpArgs(argv) {
302
890
  let worktreePath = null;
303
891
  let workItemId = null;
304
892
  let phase = "implementation";
893
+ let ownerType;
894
+ let ownerId;
305
895
  let producedBy;
306
896
  let developCycle = false;
897
+ let qaCycle = false;
898
+ let debugCycle = false;
899
+ let architectCycle = false;
307
900
  for (let index = 1; index < argv.length; index += 1) {
308
901
  const arg = argv[index];
309
902
  if (arg === "--worktree") {
@@ -312,11 +905,20 @@ export function parseCompletionMcpArgs(argv) {
312
905
  else if (arg === "--work-item-id") {
313
906
  workItemId = argv[++index] ?? null;
314
907
  }
908
+ else if (arg === "--owner-type") {
909
+ ownerType = normalizedOwnerType(argv[++index]);
910
+ if (!ownerType) {
911
+ return { ok: false, error: "mcp --owner-type must be work_item or story." };
912
+ }
913
+ }
914
+ else if (arg === "--owner-id") {
915
+ ownerId = argv[++index] ?? undefined;
916
+ }
315
917
  else if (arg === "--phase") {
316
918
  const rawPhase = argv[++index];
317
919
  const parsedPhase = parseStrictCompletionPhase(rawPhase);
318
920
  if (!parsedPhase) {
319
- return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation." };
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." };
320
922
  }
321
923
  phase = parsedPhase;
322
924
  }
@@ -326,6 +928,15 @@ export function parseCompletionMcpArgs(argv) {
326
928
  else if (arg === "--develop-cycle") {
327
929
  developCycle = true;
328
930
  }
931
+ else if (arg === "--qa-cycle") {
932
+ qaCycle = true;
933
+ }
934
+ else if (arg === "--debug-cycle") {
935
+ debugCycle = true;
936
+ }
937
+ else if (arg === "--architect-cycle") {
938
+ architectCycle = true;
939
+ }
329
940
  else {
330
941
  return { ok: false, error: `Unknown mcp argument: ${arg}` };
331
942
  }
@@ -333,15 +944,35 @@ export function parseCompletionMcpArgs(argv) {
333
944
  if (!worktreePath?.trim() || !workItemId?.trim()) {
334
945
  return { ok: false, error: "mcp requires --worktree and --work-item-id." };
335
946
  }
947
+ if ([developCycle, qaCycle, debugCycle, architectCycle].filter(Boolean).length > 1) {
948
+ return { ok: false, error: "mcp accepts only one cycle mode." };
949
+ }
950
+ if (developCycle && !isDevelopCompletionPhase(phase)) {
951
+ return { ok: false, error: "mcp --develop-cycle requires --phase implementation, self-review, or validation." };
952
+ }
953
+ if (qaCycle && phase !== "qa") {
954
+ return { ok: false, error: "mcp --qa-cycle requires --phase qa." };
955
+ }
956
+ if (debugCycle && !isDebugCompletionPhase(phase)) {
957
+ return { ok: false, error: "mcp --debug-cycle requires --phase debug-repro, debug-root-cause, debug-fix, or debug-regression." };
958
+ }
959
+ if (architectCycle && phase !== "architect") {
960
+ return { ok: false, error: "mcp --architect-cycle requires --phase architect." };
961
+ }
336
962
  return {
337
963
  ok: true,
338
964
  config: {
339
965
  worktreePath: path.resolve(worktreePath),
340
966
  workItemId,
967
+ ownerType,
968
+ ownerId,
341
969
  phase,
342
970
  producedBy,
343
971
  redactionSecrets: parseCompletionRedactionSecrets(process.env[completionRedactionSecretsEnv]),
344
- developCycle
972
+ developCycle,
973
+ qaCycle,
974
+ debugCycle,
975
+ architectCycle
345
976
  }
346
977
  };
347
978
  }
@@ -436,39 +1067,125 @@ async function handleJsonRpcRequest(session, method, params) {
436
1067
  }
437
1068
  throw new Error(`Unsupported MCP method: ${method}`);
438
1069
  }
439
- function toolDefinition(name, phase) {
1070
+ function toolDefinition(name, phase, qaGate = null) {
440
1071
  return {
441
1072
  name,
442
- description: toolDescription(phase),
443
- inputSchema: toolInputSchema(phase)
1073
+ description: toolDescription(phase, qaGate),
1074
+ inputSchema: toolInputSchema(phase, qaGate)
444
1075
  };
445
1076
  }
446
1077
  function nextPhaseAfter(phase) {
1078
+ if (!isDevelopCompletionPhase(phase)) {
1079
+ return null;
1080
+ }
447
1081
  const index = completionPhaseOrder.indexOf(phase);
448
1082
  return index >= 0 ? completionPhaseOrder[index + 1] ?? null : null;
449
1083
  }
1084
+ function nextDebugPhaseAfter(phase) {
1085
+ const index = debugCompletionPhaseOrder.indexOf(phase);
1086
+ return index >= 0 ? debugCompletionPhaseOrder[index + 1] ?? null : null;
1087
+ }
450
1088
  function completionToolNextInstruction(completedPhase, status, nextPhase) {
1089
+ if (completedPhase === "qa") {
1090
+ if (status === "blocked") {
1091
+ return "QA blocked. Forge recorded the blocker reason and will surface the run for human attention.";
1092
+ }
1093
+ if (status === "needs_rework") {
1094
+ return "QA findings recorded. Forge has the structured evidence needed to route this work back for implementation rework.";
1095
+ }
1096
+ return "QA accepted. Forge has the structured evidence needed to move this work item to Sign-Off.";
1097
+ }
451
1098
  if (status !== "pass") {
452
1099
  return `Stay in ${completedPhase}, address the recorded blockers, then call ${expectedCompletionToolName(completedPhase)} again.`;
453
1100
  }
1101
+ if (isDebugCompletionPhase(completedPhase)) {
1102
+ const debugNext = isDebugCompletionPhase(nextPhase) ? nextPhase : null;
1103
+ return completionToolNextInstructionForDebugGate(completedPhase, status, debugNext);
1104
+ }
454
1105
  if (nextPhase === "self_review") {
455
1106
  return "Implementation accepted. Begin self-review: inspect the diff, apply safe fixes, and call forge.complete_self_review with review evidence.";
456
1107
  }
457
1108
  if (nextPhase === "validation") {
458
1109
  return "Self-review accepted. Begin validation: run deterministic checks, prove acceptance criteria, and call forge.complete_validation with command evidence.";
459
1110
  }
460
- return "Validation accepted. Forge has the structured evidence needed to move this work item to Dev Test.";
1111
+ return "Validation accepted. Forge has the structured evidence needed to move this work item to QA.";
461
1112
  }
462
- function toolDescription(phase) {
1113
+ function completionToolNextInstructionForQaGate(completedGate, status, nextGate) {
1114
+ if (!nextGate) {
1115
+ if (status === "blocked") {
1116
+ return "QA blocked. Forge recorded the blocker reason and will surface the run for human attention.";
1117
+ }
1118
+ if (status === "needs_rework") {
1119
+ return "QA findings recorded. Forge has the structured evidence needed to route this work back for implementation rework.";
1120
+ }
1121
+ return "QA accepted. Forge has the structured evidence needed to move this work item to Sign-Off.";
1122
+ }
1123
+ const skipped = status === "skipped";
1124
+ const blocked = status === "blocked";
1125
+ const prefix = blocked
1126
+ ? `${completedGate} recorded a blocker. Continue through ${nextGate} and mark downstream gates skipped if the blocker prevents evidence collection.`
1127
+ : skipped
1128
+ ? `${completedGate} skipped. Continue to ${nextGate}.`
1129
+ : `${completedGate} accepted. Continue to ${nextGate}.`;
1130
+ return `${prefix} ${qaGateInstruction(nextGate)}`;
1131
+ }
1132
+ function completionToolNextInstructionForDebugGate(completedGate, status, nextGate) {
1133
+ if (status !== "pass") {
1134
+ return `Stay in ${completedGate}, address the recorded blockers, then call ${expectedDebugCompletionToolName(completedGate)} again.`;
1135
+ }
1136
+ if (nextGate === "debug_root_cause") {
1137
+ return "Debug repro accepted. Begin root-cause analysis: connect the observed failure to code evidence and call forge.complete_debug_root_cause.";
1138
+ }
1139
+ if (nextGate === "debug_fix") {
1140
+ return "Debug root cause accepted. Apply the smallest safe fix with regression coverage where practical, then call forge.complete_debug_fix.";
1141
+ }
1142
+ if (nextGate === "debug_regression") {
1143
+ return "Debug fix accepted. Prove the original repro is negative, run targeted regression checks, and call forge.complete_debug_regression.";
1144
+ }
1145
+ return "Debug regression accepted. Forge has the structured evidence needed to move this bug fix to QA.";
1146
+ }
1147
+ function qaGateInstruction(gate) {
1148
+ switch (gate) {
1149
+ case "qa_regression":
1150
+ return "Run or explicitly skip applicable regression/build/lint/typecheck/e2e checks, then call forge.complete_qa_regression.";
1151
+ case "qa_api":
1152
+ return "Run or explicitly skip applicable API/backend contract checks, then call forge.complete_qa_api.";
1153
+ case "qa_manual_web":
1154
+ return "Run or explicitly skip applicable browser/manual web checks, then call forge.complete_qa_manual_web.";
1155
+ case "qa_bug_repro":
1156
+ return "Reproduce or explicitly skip relevant defects/candidate bugs, then call forge.complete_qa_bug_repro.";
1157
+ case "qa_findings":
1158
+ return "Normalize observations into findings and candidate bugs, then call forge.complete_qa_findings.";
1159
+ case "qa_verdict":
1160
+ return "Assemble the final QA verdict from all prior gate evidence, then call forge.complete_qa_verdict.";
1161
+ case "qa_plan":
1162
+ return "Prepare the QA checklist, then call forge.complete_qa_plan.";
1163
+ }
1164
+ }
1165
+ function toolDescription(phase, qaGate = null) {
1166
+ if (qaGate) {
1167
+ return qaGate === "qa_verdict"
1168
+ ? "Complete the final Forge QA verdict by writing the canonical QA bundle with pass, needs_rework, or blocked evidence."
1169
+ : `Complete the ${qaGate.replace(/_/g, " ")} QA gate by writing ${qaGateFileNames[qaGate]} before continuing to the next QA gate.`;
1170
+ }
1171
+ if (isDebugCompletionPhase(phase)) {
1172
+ return `Complete the ${phase.replace(/_/g, " ")} Debug gate by writing ${phaseFiles[phase].jsonFileName} with structured bug-fix evidence before continuing.`;
1173
+ }
463
1174
  if (phase === "implementation") {
464
1175
  return "Complete Forge implementation by writing implementation.completeness.json with scoped changed-file, verification, acceptance-criteria, gap, and next-phase evidence.";
465
1176
  }
466
1177
  if (phase === "self_review") {
467
1178
  return "Complete Forge self-review by writing self-review.report.json with diff review, findings, security, edge-case, design, deterministic-comparison, fixes, and remaining-risk evidence.";
468
1179
  }
1180
+ if (phase === "qa") {
1181
+ return "Complete Forge QA by writing qa.plan.json, qa.evidence.json, qa.findings.json, qa.verdict.json, and qa.report.md with structured pass, needs-rework, or blocked evidence.";
1182
+ }
1183
+ if (phase === "architect") {
1184
+ return "Complete Forge Architect planning by writing implementation.plan.json, qa.plan.json, architect.verdict.json, and architect.report.md with a pending-approval plan or explicit revision/blocker reasons.";
1185
+ }
469
1186
  return "Complete Forge validation by writing validation.verdict.json with command, build/test/lint/design, drift, acceptance-criteria, and ready-for-dev-test evidence.";
470
1187
  }
471
- function toolInputSchema(phase) {
1188
+ function toolInputSchema(phase, qaGate = null) {
472
1189
  const baseProperties = {
473
1190
  status: {
474
1191
  type: "string",
@@ -487,6 +1204,12 @@ function toolInputSchema(phase) {
487
1204
  })
488
1205
  }
489
1206
  };
1207
+ if (qaGate && qaGate !== "qa_verdict") {
1208
+ return qaGateToolInputSchema(qaGate);
1209
+ }
1210
+ if (isDebugCompletionPhase(phase)) {
1211
+ return debugToolInputSchema(phase, baseProperties);
1212
+ }
490
1213
  if (phase === "implementation") {
491
1214
  return objectToolSchema({
492
1215
  ...baseProperties,
@@ -509,7 +1232,7 @@ function toolInputSchema(phase) {
509
1232
  },
510
1233
  tests_added_or_updated: {
511
1234
  type: "array",
512
- description: "Required for pass. Use an object explaining why no tests were needed for docs/config-only work if empty would be ambiguous.",
1235
+ description: "Required for pass. Use an object explaining why no tests were needed for documentation/config-only work if empty would be ambiguous.",
513
1236
  items: evidenceObjectSchema(["path", "summary"], {
514
1237
  path: { type: "string" },
515
1238
  summary: { type: "string" }
@@ -540,6 +1263,11 @@ function toolInputSchema(phase) {
540
1263
  },
541
1264
  next_phase_context: {
542
1265
  description: "Required for pass. Context the self-review phase should carry forward."
1266
+ },
1267
+ resolved_findings: {
1268
+ type: "array",
1269
+ description: "Required for QA rework. Each entry must use status resolved, disputed, or not_reproduced.",
1270
+ items: resolvedFindingSchema()
543
1271
  }
544
1272
  }, ["status", "summary"], "For status pass, include plan, changed_files, tests_added_or_updated, docs_added_or_updated, acceptance_criteria, known_gaps, and next_phase_context. Acceptance criteria entries must use status: satisfied plus evidence.");
545
1273
  }
@@ -588,6 +1316,170 @@ function toolInputSchema(phase) {
588
1316
  }
589
1317
  }, ["status", "summary"], "For status pass, include reviewed_diff, findings, security_review, edge_case_review, design_review, deterministic_comparison, fixes_applied, and remaining_risks.");
590
1318
  }
1319
+ if (phase === "qa") {
1320
+ return objectToolSchema({
1321
+ ...baseProperties,
1322
+ status: {
1323
+ type: "string",
1324
+ enum: ["pass", "needs_rework", "blocked"],
1325
+ description: "Use pass only when QA evidence satisfies acceptance criteria, needs_rework for actionable in-scope defects, or blocked for an inconclusive QA blocker."
1326
+ },
1327
+ checklist: {
1328
+ type: "array",
1329
+ description: "QA plan/checklist. Forge writes this to qa.plan.json; a default checklist is generated if omitted.",
1330
+ items: { type: "string" }
1331
+ },
1332
+ tested_acceptance_criteria: {
1333
+ type: "array",
1334
+ description: "Required and non-empty for pass/needs_rework. Criteria actually tested by QA.",
1335
+ items: { type: "string" }
1336
+ },
1337
+ commands: {
1338
+ type: "array",
1339
+ description: "Command evidence written to qa.evidence.json.",
1340
+ items: commandEvidenceSchema()
1341
+ },
1342
+ browser_checks: {
1343
+ type: "array",
1344
+ description: "Browser/manual UI checks with URL or route, action, observed result, screenshot/trace references, console/network notes, and status.",
1345
+ items: evidenceObjectSchema(["summary", "status"], {
1346
+ summary: { type: "string" },
1347
+ url: { type: "string" },
1348
+ route: { type: "string" },
1349
+ status: { type: "string" },
1350
+ screenshot: { type: "string" },
1351
+ trace: { type: "string" }
1352
+ })
1353
+ },
1354
+ sidecars: {
1355
+ type: "array",
1356
+ description: "Optional QA sidecar files already written under .forge/work-items/<id>/artifacts/qa/ with path/content_hash/bytes metadata.",
1357
+ items: evidenceObjectSchema(["path", "content_hash", "bytes"], {
1358
+ path: { type: "string" },
1359
+ content_hash: { type: "string" },
1360
+ bytes: { type: "number" }
1361
+ })
1362
+ },
1363
+ notes: { type: "string", description: "Additional QA evidence notes." },
1364
+ evidence: {
1365
+ type: "object",
1366
+ description: "Optional wrapper containing commands, browser_checks, and notes when a client prefers nested evidence."
1367
+ },
1368
+ findings: {
1369
+ type: "array",
1370
+ description: "QA findings. needs_rework requires at least one actionable in_scope finding.",
1371
+ items: evidenceObjectSchema(["id", "severity", "scope", "title"], {
1372
+ id: { type: "string" },
1373
+ severity: { type: "string", enum: ["critical", "major", "minor"] },
1374
+ scope: { type: "string", enum: ["in_scope", "out_of_scope", "unclear"] },
1375
+ title: { type: "string" },
1376
+ acceptance_criteria: { type: "array", items: { type: "string" } },
1377
+ repro_steps: { type: "array", items: { type: "string" } },
1378
+ expected: { type: "string" },
1379
+ actual: { type: "string" },
1380
+ evidence: { type: "object" },
1381
+ likely_area: { type: "array", items: { type: "string" } },
1382
+ required_fix: { type: "string" },
1383
+ required_regression: { type: "string" }
1384
+ })
1385
+ },
1386
+ candidate_bugs: {
1387
+ type: "array",
1388
+ description: "Out-of-scope/follow-up bug candidates. They do not block the current item unless attached as in-scope findings.",
1389
+ items: evidenceObjectSchema(["id", "title", "suggested_action"], {
1390
+ id: { type: "string" },
1391
+ title: { type: "string" },
1392
+ severity: { type: "string" },
1393
+ scope_reason: { type: "string" },
1394
+ repro_steps: { type: "array", items: { type: "string" } },
1395
+ evidence: { type: "object" },
1396
+ suggested_action: { type: "string", enum: ["create_bug", "create_follow_up", "accept_risk", "attach_to_current_item"] }
1397
+ })
1398
+ },
1399
+ blocker_reason: {
1400
+ type: "string",
1401
+ enum: [...qaBlockerReasons],
1402
+ description: "Required when status is blocked."
1403
+ }
1404
+ }, ["status", "summary"], "For pass, include tested_acceptance_criteria plus concrete command/browser/note evidence. For needs_rework, include at least one actionable in_scope finding. For blocked, include blocker_reason.");
1405
+ }
1406
+ if (phase === "architect") {
1407
+ return objectToolSchema({
1408
+ status: {
1409
+ type: "string",
1410
+ enum: ["pass", "needs_revision", "blocked"],
1411
+ description: "Use pass only for a complete pending-approval Architect plan. Use needs_revision for fixable story/design/repo gaps, or blocked for missing required context or decisions."
1412
+ },
1413
+ summary: { type: "string", description: "Concise Architect plan verdict summary." },
1414
+ implementation_plan: {
1415
+ type: "object",
1416
+ description: "Required for pass. Top-level fields inside this object must include schema_version, plan_id, phases, tasks, dependencies, and phase_gates.",
1417
+ additionalProperties: true,
1418
+ properties: {
1419
+ schema_version: { type: "number", enum: [1] },
1420
+ plan_id: { type: "string" },
1421
+ phases: {
1422
+ type: "array",
1423
+ description: "Required top-level implementation_plan.phases array.",
1424
+ items: { type: "object", additionalProperties: true }
1425
+ },
1426
+ tasks: {
1427
+ type: "array",
1428
+ description: "Required task list. Each task must include id and a non-empty tests array.",
1429
+ items: { type: "object", additionalProperties: true }
1430
+ },
1431
+ dependencies: {
1432
+ type: "array",
1433
+ description: "Required dependency edge array. Use [] when no task dependencies exist. Each edge should use before and after task ids; from/to are accepted only as aliases and normalized before writing artifacts.",
1434
+ items: {
1435
+ type: "object",
1436
+ additionalProperties: true,
1437
+ properties: {
1438
+ id: { type: "string" },
1439
+ before: { type: "string", description: "Task id that must complete first." },
1440
+ after: { type: "string", description: "Task id that depends on before." },
1441
+ from: { type: "string", description: "Alias for before." },
1442
+ to: { type: "string", description: "Alias for after." },
1443
+ type: { type: "string" },
1444
+ rationale: { type: "string" }
1445
+ }
1446
+ }
1447
+ },
1448
+ phase_gates: {
1449
+ type: "array",
1450
+ description: "Required non-empty phase gate array.",
1451
+ items: { type: "object", additionalProperties: true }
1452
+ }
1453
+ }
1454
+ },
1455
+ qa_plan: {
1456
+ type: "object",
1457
+ description: "Required for pass. Must include schema_version: 1 and non-empty final_qa coverage.",
1458
+ additionalProperties: true,
1459
+ properties: {
1460
+ schema_version: { type: "number", enum: [1] },
1461
+ final_qa: {
1462
+ type: "array",
1463
+ description: "Required non-empty final QA coverage array.",
1464
+ items: { type: "object", additionalProperties: true }
1465
+ }
1466
+ }
1467
+ },
1468
+ report_markdown: { type: "string", description: "Human-readable Architect report. Use report as an alias only when the client cannot send report_markdown." },
1469
+ report: { type: "string", description: "Alias for report_markdown." },
1470
+ blockers: baseProperties.blockers,
1471
+ revision_questions: {
1472
+ type: "array",
1473
+ description: "Required for needs_revision when blockers are not used.",
1474
+ items: { type: "string" }
1475
+ },
1476
+ revision_reasons: {
1477
+ type: "array",
1478
+ description: "Concrete reasons that prevent pass status.",
1479
+ items: { type: "string" }
1480
+ }
1481
+ }, ["status", "summary"], "For status pass, include implementation_plan and qa_plan at the top level of the MCP tool arguments. implementation_plan.phases must be a top-level array inside implementation_plan, not nested under another object.");
1482
+ }
591
1483
  return objectToolSchema({
592
1484
  ...baseProperties,
593
1485
  commands: {
@@ -612,17 +1504,155 @@ function toolInputSchema(phase) {
612
1504
  ready_for_dev_test: { type: "boolean", description: "Required for pass and must be true." }
613
1505
  }, ["status", "summary"], "For status pass, commands must include at least one passing deterministic command, acceptance criteria entries must use status: satisfied plus evidence, and ready_for_dev_test must be true.");
614
1506
  }
615
- function objectToolSchema(properties, required, description) {
616
- return {
617
- type: "object",
618
- additionalProperties: true,
619
- description,
620
- properties,
621
- required: [...required]
622
- };
623
- }
624
- function evidenceObjectSchema(required, properties) {
625
- return {
1507
+ function debugToolInputSchema(phase, baseProperties) {
1508
+ if (phase === "debug_repro") {
1509
+ return objectToolSchema({
1510
+ ...baseProperties,
1511
+ repro_steps: {
1512
+ type: "array",
1513
+ description: "Required for pass. Minimal reproduction or characterization steps.",
1514
+ items: { type: "string" }
1515
+ },
1516
+ observed: { type: "string", description: "Observed failure behavior." },
1517
+ expected: { type: "string", description: "Expected behavior." },
1518
+ evidence: {
1519
+ type: "array",
1520
+ description: "Required for pass. Concrete logs, commands, screenshots, file refs, or characterization notes.",
1521
+ items: { type: "object", additionalProperties: true }
1522
+ }
1523
+ }, ["status", "summary"], "For status pass, include repro_steps, observed, expected, and evidence.");
1524
+ }
1525
+ if (phase === "debug_root_cause") {
1526
+ return objectToolSchema({
1527
+ ...baseProperties,
1528
+ root_cause: { type: "string", description: "Likely root cause tied to code or config evidence." },
1529
+ evidence: {
1530
+ type: "array",
1531
+ description: "Required for pass. Concrete code/log/test evidence supporting the root cause.",
1532
+ items: { type: "object", additionalProperties: true }
1533
+ },
1534
+ eliminated_alternatives: {
1535
+ type: "array",
1536
+ description: "Required for pass. Plausible alternatives checked or ruled out.",
1537
+ items: { type: "object", additionalProperties: true }
1538
+ },
1539
+ risk_area: { type: "string", description: "Subsystem or behavior most at risk from the fix." }
1540
+ }, ["status", "summary"], "For status pass, include root_cause, evidence, eliminated_alternatives, and risk_area.");
1541
+ }
1542
+ if (phase === "debug_fix") {
1543
+ return objectToolSchema({
1544
+ ...baseProperties,
1545
+ changed_files: {
1546
+ type: "array",
1547
+ description: "Required for pass. Files changed by the bug fix.",
1548
+ items: evidenceObjectSchema(["path", "summary"], { path: { type: "string" }, summary: { type: "string" } })
1549
+ },
1550
+ tests_added_or_updated: {
1551
+ type: "array",
1552
+ description: "Required for pass. Regression tests or checks added/updated, or justify omission in remaining_risks.",
1553
+ items: evidenceObjectSchema(["path", "summary"], { path: { type: "string" }, summary: { type: "string" } })
1554
+ },
1555
+ remaining_risks: {
1556
+ type: "array",
1557
+ description: "Required for pass, even when empty. Include why no regression coverage changed when tests_added_or_updated is empty.",
1558
+ items: evidenceObjectSchema(["summary"], { summary: { type: "string" }, mitigation: { type: "string" } })
1559
+ },
1560
+ resolved_findings: {
1561
+ type: "array",
1562
+ description: "Required for QA rework. Each entry must use status resolved, disputed, or not_reproduced.",
1563
+ items: resolvedFindingSchema()
1564
+ }
1565
+ }, ["status", "summary"], "For status pass, include changed_files, tests_added_or_updated, and remaining_risks.");
1566
+ }
1567
+ return objectToolSchema({
1568
+ ...baseProperties,
1569
+ commands: {
1570
+ type: "array",
1571
+ description: "Required for pass. Targeted regression/repro-negative commands with exit_code: 0 and status: pass.",
1572
+ items: commandEvidenceSchema()
1573
+ },
1574
+ required_regressions: {
1575
+ type: "array",
1576
+ description: "Required for pass. Repro-negative and regression coverage checklist.",
1577
+ items: { type: "string" }
1578
+ },
1579
+ build_status: { type: "string", description: "Required for pass. pass or not_applicable." },
1580
+ test_status: { type: "string", description: "Required for pass. pass or not_applicable." },
1581
+ repro_negative: { type: "boolean", description: "Required for pass and must be true after the original repro no longer fails." },
1582
+ qa_ready: { type: "boolean", description: "Required for pass and must be true." }
1583
+ }, ["status", "summary"], "For status pass, commands must include at least one passing deterministic debug regression check, repro_negative must be true, and qa_ready must be true.");
1584
+ }
1585
+ function qaGateToolInputSchema(gate) {
1586
+ const baseProperties = {
1587
+ status: {
1588
+ type: "string",
1589
+ enum: ["pass", "skipped", "blocked"],
1590
+ description: "Use pass when this QA gate produced evidence, skipped when not applicable, or blocked when a prerequisite prevents this gate."
1591
+ },
1592
+ summary: { type: "string", description: "Concise QA gate summary." },
1593
+ reason: { type: "string", description: "Required for skipped or blocked gates." },
1594
+ blocker_reason: {
1595
+ type: "string",
1596
+ enum: [...qaBlockerReasons],
1597
+ description: "Required when status is blocked."
1598
+ }
1599
+ };
1600
+ if (gate === "qa_plan") {
1601
+ return objectToolSchema({
1602
+ ...baseProperties,
1603
+ checklist: {
1604
+ type: "array",
1605
+ description: "Required for pass. QA checklist entries planned for this work item.",
1606
+ items: { type: "string" }
1607
+ },
1608
+ acceptance_criteria: {
1609
+ type: "array",
1610
+ description: "Acceptance criteria selected for QA.",
1611
+ items: { type: "string" }
1612
+ }
1613
+ }, ["status", "summary"], "Record the QA plan gate. Pass requires a non-empty checklist.");
1614
+ }
1615
+ if (gate === "qa_findings") {
1616
+ return objectToolSchema({
1617
+ ...baseProperties,
1618
+ findings: {
1619
+ type: "array",
1620
+ description: "Normalized in-scope and out-of-scope QA findings.",
1621
+ items: { type: "object", additionalProperties: true }
1622
+ },
1623
+ candidate_bugs: {
1624
+ type: "array",
1625
+ description: "Out-of-scope or follow-up candidates.",
1626
+ items: { type: "object", additionalProperties: true }
1627
+ }
1628
+ }, ["status", "summary"], "Record normalized QA findings. Pass or skipped requires findings and candidate_bugs arrays, even when empty.");
1629
+ }
1630
+ return objectToolSchema({
1631
+ ...baseProperties,
1632
+ commands: {
1633
+ type: "array",
1634
+ description: "Command evidence for this gate when applicable.",
1635
+ items: commandEvidenceSchema()
1636
+ },
1637
+ browser_checks: {
1638
+ type: "array",
1639
+ description: "Browser/manual evidence for this gate when applicable.",
1640
+ items: { type: "object", additionalProperties: true }
1641
+ },
1642
+ notes: { type: "string", description: "Evidence notes for this gate." }
1643
+ }, ["status", "summary"], "Record this QA evidence gate. Use skipped with a reason when the gate is not applicable.");
1644
+ }
1645
+ function objectToolSchema(properties, required, description) {
1646
+ return {
1647
+ type: "object",
1648
+ additionalProperties: true,
1649
+ description,
1650
+ properties,
1651
+ required: [...required]
1652
+ };
1653
+ }
1654
+ function evidenceObjectSchema(required, properties) {
1655
+ return {
626
1656
  type: "object",
627
1657
  additionalProperties: true,
628
1658
  properties,
@@ -637,6 +1667,29 @@ function commandEvidenceSchema() {
637
1667
  summary: { type: "string" }
638
1668
  });
639
1669
  }
1670
+ function resolvedFindingSchema() {
1671
+ return evidenceObjectSchema([
1672
+ "qa_id",
1673
+ "status",
1674
+ "summary",
1675
+ "evidence",
1676
+ "changed_files",
1677
+ "tests_added_or_updated",
1678
+ "regression_evidence"
1679
+ ], {
1680
+ qa_id: { type: "string" },
1681
+ status: {
1682
+ type: "string",
1683
+ enum: [...resolvedFindingStatusValues],
1684
+ description: "Use resolved when fixed, disputed when the QA finding is incorrect/out-of-scope, or not_reproduced when retesting cannot reproduce it."
1685
+ },
1686
+ summary: { type: "string" },
1687
+ evidence: { description: "Concrete evidence for the resolution." },
1688
+ changed_files: { type: "array", description: "Required and non-empty when status is resolved." },
1689
+ tests_added_or_updated: { type: "array", description: "Required and non-empty when status is resolved." },
1690
+ regression_evidence: { description: "Concrete regression evidence for this QA finding." }
1691
+ });
1692
+ }
640
1693
  function acceptanceCriteriaSchema() {
641
1694
  return {
642
1695
  type: "array",
@@ -662,8 +1715,22 @@ function reviewSectionProperties() {
662
1715
  notes: { type: "string" }
663
1716
  };
664
1717
  }
665
- function normalizeCompletionStatus(value) {
1718
+ function normalizeCompletionStatus(value, phase) {
666
1719
  const normalized = value.trim().toLowerCase().replace(/-/g, "_");
1720
+ if (phase === "qa") {
1721
+ const canonical = normalized === "needsrework" ? "needs_rework" : normalized;
1722
+ if (canonical !== "pass" && canonical !== "needs_rework" && canonical !== "blocked") {
1723
+ throw new Error("QA status must be pass, needs_rework, or blocked.");
1724
+ }
1725
+ return canonical;
1726
+ }
1727
+ if (phase === "architect") {
1728
+ const canonical = normalized === "needsrevision" ? "needs_revision" : normalized;
1729
+ if (canonical !== "pass" && canonical !== "needs_revision" && canonical !== "blocked") {
1730
+ throw new Error("Architect status must be pass, needs_revision, or blocked.");
1731
+ }
1732
+ return canonical;
1733
+ }
667
1734
  const canonical = normalized === "blocked" || normalized === "needsrework"
668
1735
  ? "needs_rework"
669
1736
  : normalized === "failed"
@@ -674,17 +1741,36 @@ function normalizeCompletionStatus(value) {
674
1741
  }
675
1742
  return canonical;
676
1743
  }
1744
+ function normalizeQaGateStatus(value) {
1745
+ const normalized = value.trim().toLowerCase().replace(/-/g, "_");
1746
+ if (normalized !== "pass" && normalized !== "skipped" && normalized !== "blocked") {
1747
+ throw new Error("QA gate status must be pass, skipped, or blocked.");
1748
+ }
1749
+ return normalized;
1750
+ }
677
1751
  function validatePayloadShape(phase, payload) {
678
- const status = normalizeCompletionStatus(requiredString(payload, "status"));
1752
+ const status = normalizeCompletionStatus(requiredString(payload, "status"), phase);
679
1753
  if (!status) {
680
1754
  throw new Error("status is required.");
681
1755
  }
682
- const pass = status === "pass";
683
1756
  requireField(payload, "summary");
1757
+ if (phase === "qa") {
1758
+ validateQaPayloadShape(payload, status);
1759
+ return;
1760
+ }
1761
+ if (phase === "architect") {
1762
+ validateArchitectPayloadShape(payload, status);
1763
+ return;
1764
+ }
1765
+ const pass = status === "pass";
684
1766
  if (!pass) {
685
1767
  requireNonPassEvidence(payload);
686
1768
  return;
687
1769
  }
1770
+ if (isDebugCompletionPhase(phase)) {
1771
+ validateDebugPayloadShape(phase, payload);
1772
+ return;
1773
+ }
688
1774
  if (phase === "implementation") {
689
1775
  requireArray(payload, "plan");
690
1776
  requireArray(payload, "changed_files");
@@ -695,6 +1781,7 @@ function validatePayloadShape(phase, payload) {
695
1781
  requireField(payload, "next_phase_context");
696
1782
  requireImplementationEvidence(payload);
697
1783
  requireSatisfiedAcceptanceCriteria(payload);
1784
+ validateResolvedFindings(payload);
698
1785
  return;
699
1786
  }
700
1787
  if (phase === "self_review") {
@@ -722,6 +1809,366 @@ function validatePayloadShape(phase, payload) {
722
1809
  requirePassingCommands(payload);
723
1810
  requireSatisfiedAcceptanceCriteria(payload);
724
1811
  }
1812
+ function validateDebugPayloadShape(phase, payload) {
1813
+ if (phase === "debug_repro") {
1814
+ requireArray(payload, "repro_steps");
1815
+ requireField(payload, "observed");
1816
+ requireField(payload, "expected");
1817
+ requireArray(payload, "evidence");
1818
+ requireNonEmptyArray(payload, "repro_steps");
1819
+ requireNonEmptyArray(payload, "evidence");
1820
+ return;
1821
+ }
1822
+ if (phase === "debug_root_cause") {
1823
+ requireField(payload, "root_cause");
1824
+ requireArray(payload, "evidence");
1825
+ requireArray(payload, "eliminated_alternatives");
1826
+ requireField(payload, "risk_area");
1827
+ requireNonEmptyArray(payload, "evidence");
1828
+ return;
1829
+ }
1830
+ if (phase === "debug_fix") {
1831
+ requireArray(payload, "changed_files");
1832
+ requireArray(payload, "tests_added_or_updated");
1833
+ requireArray(payload, "remaining_risks");
1834
+ requireNonEmptyArray(payload, "changed_files");
1835
+ if (arrayLength(payload, "tests_added_or_updated") === 0 && arrayLength(payload, "remaining_risks") === 0) {
1836
+ throw new Error("tests_added_or_updated is empty; remaining_risks must explain why no regression coverage changed.");
1837
+ }
1838
+ validateResolvedFindings(payload);
1839
+ return;
1840
+ }
1841
+ requireArray(payload, "commands");
1842
+ requireArray(payload, "required_regressions");
1843
+ requireField(payload, "build_status");
1844
+ requireField(payload, "test_status");
1845
+ requireBoolean(payload, "repro_negative");
1846
+ requireBoolean(payload, "qa_ready");
1847
+ if (payload.repro_negative !== true) {
1848
+ throw new Error("debug_regression pass requires repro_negative: true.");
1849
+ }
1850
+ if (payload.qa_ready !== true) {
1851
+ throw new Error("debug_regression pass requires qa_ready: true.");
1852
+ }
1853
+ requireAllowedStatus(payload, "build_status", ["pass", "not_applicable"]);
1854
+ requireAllowedStatus(payload, "test_status", ["pass", "not_applicable"]);
1855
+ requireNonEmptyArray(payload, "required_regressions");
1856
+ requirePassingCommands(payload);
1857
+ }
1858
+ function validateQaGatePayloadShape(gate, payload, status) {
1859
+ requireField(payload, "summary");
1860
+ if (status === "skipped") {
1861
+ requireField(payload, "reason");
1862
+ }
1863
+ if (status === "blocked") {
1864
+ const reason = normalizedString(optionalString(payload, "blocker_reason"));
1865
+ if (!qaBlockerReasons.has(reason)) {
1866
+ throw new Error("QA gate blocked requires blocker_reason to be one of missing_app_launch_target, inconclusive, environment_failure, missing_validation_evidence, missing_worktree, or runner_failure.");
1867
+ }
1868
+ }
1869
+ if (gate === "qa_plan" && status === "pass") {
1870
+ const checklist = qaStringArray(payload, "checklist");
1871
+ if (checklist.length === 0) {
1872
+ throw new Error("complete_qa_plan pass requires checklist with at least one entry.");
1873
+ }
1874
+ }
1875
+ if (gate === "qa_findings" && status !== "blocked") {
1876
+ qaObjectArray(payload, "findings");
1877
+ qaObjectArray(payload, "candidate_bugs");
1878
+ }
1879
+ if ((gate === "qa_regression" || gate === "qa_api") && status === "pass") {
1880
+ const commands = qaArray(payload, "commands");
1881
+ if (commands.length === 0) {
1882
+ throw new Error(`${qaGateToolNames[gate]} pass requires commands with at least one entry.`);
1883
+ }
1884
+ }
1885
+ if (gate === "qa_manual_web" && status === "pass") {
1886
+ const browserChecks = qaArray(payload, "browser_checks");
1887
+ const notes = optionalString(payload, "notes");
1888
+ if (browserChecks.length === 0 && !notes) {
1889
+ throw new Error(`${qaGateToolNames[gate]} pass requires browser_checks or notes.`);
1890
+ }
1891
+ }
1892
+ }
1893
+ function validateArchitectPayloadShape(payload, status) {
1894
+ if (status !== "pass") {
1895
+ requireArchitectNonPassEvidence(payload);
1896
+ return;
1897
+ }
1898
+ const implementationPlan = requiredRecord(payload, "implementation_plan");
1899
+ const qaPlan = requiredRecord(payload, "qa_plan");
1900
+ requireNumericOne(implementationPlan, "schema_version", "implementation_plan.schema_version");
1901
+ requireNonEmptyStringRecord(implementationPlan, "plan_id", "implementation_plan.");
1902
+ requireArchitectArray(implementationPlan, "phases", payload);
1903
+ requireArchitectArray(implementationPlan, "tasks", payload);
1904
+ requireArchitectArray(implementationPlan, "dependencies", payload, { allowEmpty: true });
1905
+ requireArchitectArray(implementationPlan, "phase_gates", payload);
1906
+ if (arrayLength(implementationPlan, "tasks") === 0) {
1907
+ throw new Error("implementation_plan.tasks: expected non-empty array; correction: include at least one task with id and tests.");
1908
+ }
1909
+ const taskIds = new Set();
1910
+ for (const task of implementationPlan.tasks) {
1911
+ if (!task || typeof task !== "object" || Array.isArray(task)) {
1912
+ throw new Error("implementation_plan.tasks[]: expected object entries; correction: each task must be an object with id and tests.");
1913
+ }
1914
+ const taskRecord = task;
1915
+ requireNonEmptyStringRecord(taskRecord, "id", "implementation_plan.tasks[].");
1916
+ const taskId = optionalString(taskRecord, "id") ?? "";
1917
+ if (taskIds.has(taskId)) {
1918
+ throw new Error(`implementation_plan.tasks: duplicate task id '${taskId}'.`);
1919
+ }
1920
+ taskIds.add(taskId);
1921
+ requireArchitectArray(taskRecord, "tests", payload, { path: `implementation_plan.tasks[${optionalString(taskRecord, "id") ?? "?"}].tests` });
1922
+ if (arrayLength(taskRecord, "tests") === 0) {
1923
+ throw new Error(`implementation_plan.tasks[${optionalString(taskRecord, "id") ?? "?"}].tests: expected non-empty array; correction: include task-specific verification.`);
1924
+ }
1925
+ }
1926
+ validateAndNormalizeArchitectDependencies(implementationPlan, taskIds);
1927
+ requireNumericOne(qaPlan, "schema_version", "qa_plan.schema_version");
1928
+ requireArchitectArray(qaPlan, "final_qa", payload, { path: "qa_plan.final_qa" });
1929
+ if (arrayLength(qaPlan, "final_qa") === 0) {
1930
+ throw new Error("qa_plan.final_qa: expected non-empty array; correction: include final QA coverage for the completed plan.");
1931
+ }
1932
+ }
1933
+ function validateAndNormalizeArchitectDependencies(implementationPlan, taskIds) {
1934
+ const dependencies = implementationPlan.dependencies;
1935
+ const edges = new Map();
1936
+ for (const taskId of taskIds) {
1937
+ edges.set(taskId, []);
1938
+ }
1939
+ const normalizedDependencies = [];
1940
+ for (const [index, dependency] of dependencies.entries()) {
1941
+ if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) {
1942
+ throw new Error("implementation_plan.dependencies[]: expected object entries; correction: each dependency must be an object with before and after task ids.");
1943
+ }
1944
+ const record = dependency;
1945
+ const before = architectDependencyEndpoint(record, index, "before", "from");
1946
+ const after = architectDependencyEndpoint(record, index, "after", "to");
1947
+ if (!taskIds.has(before) || !taskIds.has(after)) {
1948
+ throw new Error("implementation_plan.dependencies: dependency references an unknown task id.");
1949
+ }
1950
+ const normalized = stripUndefined({
1951
+ ...record,
1952
+ before,
1953
+ after,
1954
+ from: undefined,
1955
+ to: undefined
1956
+ });
1957
+ normalizedDependencies.push(normalized);
1958
+ edges.get(before)?.push(after);
1959
+ }
1960
+ implementationPlan.dependencies = normalizedDependencies;
1961
+ if (hasArchitectDependencyCycle(edges)) {
1962
+ throw new Error("implementation_plan.dependencies: expected acyclic graph; correction: remove or revise cyclic task dependencies.");
1963
+ }
1964
+ }
1965
+ function architectDependencyEndpoint(dependency, index, canonicalKey, aliasKey) {
1966
+ const canonical = optionalString(dependency, canonicalKey);
1967
+ const alias = optionalString(dependency, aliasKey);
1968
+ if (canonical && alias && canonical !== alias) {
1969
+ throw new Error(`implementation_plan.dependencies[${index}].${canonicalKey}: conflicts with ${aliasKey}; correction: use one task id for ${canonicalKey}.`);
1970
+ }
1971
+ const value = canonical ?? alias;
1972
+ if (!value) {
1973
+ throw new Error(`implementation_plan.dependencies[${index}].${canonicalKey}: expected string; correction: use before and after task ids for each dependency.`);
1974
+ }
1975
+ return value;
1976
+ }
1977
+ function hasArchitectDependencyCycle(edges) {
1978
+ const visiting = new Set();
1979
+ const visited = new Set();
1980
+ const visit = (node) => {
1981
+ if (visited.has(node)) {
1982
+ return false;
1983
+ }
1984
+ if (visiting.has(node)) {
1985
+ return true;
1986
+ }
1987
+ visiting.add(node);
1988
+ for (const next of edges.get(node) ?? []) {
1989
+ if (visit(next)) {
1990
+ return true;
1991
+ }
1992
+ }
1993
+ visiting.delete(node);
1994
+ visited.add(node);
1995
+ return false;
1996
+ };
1997
+ for (const node of edges.keys()) {
1998
+ if (visit(node)) {
1999
+ return true;
2000
+ }
2001
+ }
2002
+ return false;
2003
+ }
2004
+ function requireArchitectNonPassEvidence(payload) {
2005
+ const evidenceKeys = ["blockers", "revision_questions", "revision_reasons", "known_gaps", "findings", "remaining_risks", "failures"];
2006
+ const hasEvidence = evidenceKeys.some((key) => {
2007
+ const value = payload[key];
2008
+ if (typeof value === "string") {
2009
+ return value.trim().length > 0;
2010
+ }
2011
+ if (Array.isArray(value)) {
2012
+ return value.length > 0;
2013
+ }
2014
+ return Boolean(value && typeof value === "object");
2015
+ });
2016
+ if (!hasEvidence) {
2017
+ throw new Error("status: non-pass Architect completion requires blockers, revision_questions, revision_reasons, findings, failures, or known_gaps; correction: explain why the plan cannot pass.");
2018
+ }
2019
+ }
2020
+ function requireArchitectArray(source, key, rootPayload, options = {}) {
2021
+ const pathLabel = options.path ?? `implementation_plan.${key}`;
2022
+ if (!Array.isArray(source[key])) {
2023
+ const nestedHint = architectNestedArrayHint(rootPayload, key);
2024
+ throw new Error(`${pathLabel}: expected array${key === "phases" ? " as a top-level field inside implementation_plan" : ""}; correction: ${nestedHint ?? `set ${pathLabel} to an array${options.allowEmpty ? " (use [] when none exist)" : " with at least one entry"}.`}`);
2025
+ }
2026
+ if (!options.allowEmpty && arrayLength(source, key) === 0) {
2027
+ throw new Error(`${pathLabel}: expected non-empty array; correction: include at least one entry.`);
2028
+ }
2029
+ }
2030
+ function architectNestedArrayHint(rootPayload, key) {
2031
+ if (Array.isArray(rootPayload[key])) {
2032
+ return `move top-level ${key} into implementation_plan.${key}.`;
2033
+ }
2034
+ const implementationPlan = rootPayload.implementation_plan;
2035
+ if (!implementationPlan || typeof implementationPlan !== "object" || Array.isArray(implementationPlan)) {
2036
+ return null;
2037
+ }
2038
+ const plan = implementationPlan;
2039
+ for (const container of ["plan", "dag", "implementation_dag", "implementationPlan", "implementation_plan"]) {
2040
+ const nested = plan[container];
2041
+ if (nested && typeof nested === "object" && !Array.isArray(nested) && Array.isArray(nested[key])) {
2042
+ return `move implementation_plan.${container}.${key} to implementation_plan.${key}.`;
2043
+ }
2044
+ }
2045
+ return null;
2046
+ }
2047
+ function validateQaPayloadShape(payload, status) {
2048
+ const evidenceSource = qaEvidenceSource(payload);
2049
+ const commands = qaArray(payload, "commands", evidenceSource);
2050
+ const browserChecks = qaArray(payload, "browser_checks", evidenceSource);
2051
+ const sidecars = qaArray(payload, "sidecars", evidenceSource);
2052
+ const notes = optionalString(payload, "notes") ?? optionalString(evidenceSource, "notes") ?? "";
2053
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
2054
+ const findings = qaObjectArray(payload, "findings");
2055
+ const candidateBugs = qaObjectArray(payload, "candidate_bugs");
2056
+ const explicitFindingIds = qaStringArray(payload, "finding_ids");
2057
+ const explicitCandidateBugIds = qaStringArray(payload, "candidate_bug_ids");
2058
+ if (payload.schema_version !== undefined && payload.schema_version !== 1) {
2059
+ throw new Error("QA schema_version must be numeric 1 when provided.");
2060
+ }
2061
+ if (status === "pass" || status === "needs_rework") {
2062
+ if (testedAcceptanceCriteria.length === 0) {
2063
+ throw new Error("QA pass/needs_rework requires tested_acceptance_criteria with at least one criterion.");
2064
+ }
2065
+ if (commands.length === 0 && browserChecks.length === 0 && notes.length === 0) {
2066
+ throw new Error("QA pass/needs_rework requires at least one command, browser check, or evidence note.");
2067
+ }
2068
+ }
2069
+ for (const [index, command] of commands.entries()) {
2070
+ requireEvidenceRecord(command, `commands[${index}]`);
2071
+ const record = command;
2072
+ requireNonEmptyStringRecord(record, "command", `commands[${index}].`);
2073
+ requireNonEmptyStringRecord(record, "status", `commands[${index}].`);
2074
+ requireNonEmptyStringRecord(record, "summary", `commands[${index}].`);
2075
+ if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
2076
+ throw new Error(`commands[${index}].exit_code is required.`);
2077
+ }
2078
+ if (status === "pass" && record.exit_code !== 0) {
2079
+ throw new Error(`commands[${index}].exit_code must be 0 when QA status is pass.`);
2080
+ }
2081
+ if (status === "pass" && normalizedString(record.status) !== "pass") {
2082
+ throw new Error(`commands[${index}].status must be pass when QA status is pass.`);
2083
+ }
2084
+ }
2085
+ for (const [index, browserCheck] of browserChecks.entries()) {
2086
+ requireEvidenceRecord(browserCheck, `browser_checks[${index}]`);
2087
+ const record = browserCheck;
2088
+ requireNonEmptyStringRecord(record, "summary", `browser_checks[${index}].`);
2089
+ requireNonEmptyStringRecord(record, "status", `browser_checks[${index}].`);
2090
+ const checkStatus = optionalString(record, "status");
2091
+ if (status === "pass" && checkStatus && normalizedString(checkStatus) !== "pass") {
2092
+ throw new Error(`browser_checks[${index}].status must be pass when QA status is pass.`);
2093
+ }
2094
+ if (!optionalString(record, "url") && !optionalString(record, "route")) {
2095
+ throw new Error(`browser_checks[${index}] must include url or route.`);
2096
+ }
2097
+ }
2098
+ for (const [index, sidecar] of sidecars.entries()) {
2099
+ requireEvidenceRecord(sidecar, `sidecars[${index}]`);
2100
+ const record = sidecar;
2101
+ requireNonEmptyStringRecord(record, "path", `sidecars[${index}].`);
2102
+ requireNonEmptyStringRecord(record, "content_hash", `sidecars[${index}].`);
2103
+ if (typeof record.bytes !== "number" || !Number.isFinite(record.bytes) || record.bytes <= 0) {
2104
+ throw new Error(`sidecars[${index}].bytes must be greater than 0.`);
2105
+ }
2106
+ }
2107
+ for (const [index, finding] of findings.entries()) {
2108
+ requireNonEmptyStringRecord(finding, "id", `findings[${index}].`);
2109
+ requireNonEmptyStringRecord(finding, "title", `findings[${index}].`);
2110
+ requireKnownStringRecord(finding, "severity", qaFindingSeverities, `findings[${index}].`);
2111
+ requireKnownStringRecord(finding, "scope", qaFindingScopes, `findings[${index}].`);
2112
+ if (normalizedString(finding.scope) === "in_scope") {
2113
+ validateActionableQaFinding(finding, index);
2114
+ }
2115
+ }
2116
+ for (const [index, candidateBug] of candidateBugs.entries()) {
2117
+ requireNonEmptyStringRecord(candidateBug, "id", `candidate_bugs[${index}].`);
2118
+ requireNonEmptyStringRecord(candidateBug, "title", `candidate_bugs[${index}].`);
2119
+ requireKnownStringRecord(candidateBug, "suggested_action", qaCandidateBugActions, `candidate_bugs[${index}].`);
2120
+ }
2121
+ const inScopeFindingIds = findings
2122
+ .filter((finding) => normalizedString(finding.scope) === "in_scope")
2123
+ .map((finding) => optionalString(finding, "id"))
2124
+ .filter((id) => Boolean(id));
2125
+ for (const findingId of explicitFindingIds) {
2126
+ if (!inScopeFindingIds.includes(findingId)) {
2127
+ throw new Error(`QA finding_ids contains '${findingId}', but findings has no matching in-scope finding.`);
2128
+ }
2129
+ }
2130
+ const candidateBugIds = candidateBugs
2131
+ .map((candidateBug) => optionalString(candidateBug, "id"))
2132
+ .filter((id) => Boolean(id));
2133
+ for (const candidateBugId of explicitCandidateBugIds) {
2134
+ if (!candidateBugIds.includes(candidateBugId)) {
2135
+ throw new Error(`QA candidate_bug_ids contains '${candidateBugId}', but candidate_bugs has no matching candidate bug.`);
2136
+ }
2137
+ }
2138
+ if (status === "pass") {
2139
+ if (explicitFindingIds.length > 0 || inScopeFindingIds.length > 0) {
2140
+ throw new Error("QA pass must not include in-scope finding_ids or in-scope findings.");
2141
+ }
2142
+ if (optionalString(payload, "blocker_reason")) {
2143
+ throw new Error("QA pass must not include blocker_reason.");
2144
+ }
2145
+ }
2146
+ if (status === "needs_rework") {
2147
+ if (inScopeFindingIds.length === 0) {
2148
+ throw new Error("QA needs_rework requires at least one actionable in-scope finding.");
2149
+ }
2150
+ if (optionalString(payload, "blocker_reason")) {
2151
+ throw new Error("QA needs_rework must not include blocker_reason.");
2152
+ }
2153
+ }
2154
+ if (status === "blocked") {
2155
+ const reason = normalizedString(optionalString(payload, "blocker_reason"));
2156
+ if (!qaBlockerReasons.has(reason)) {
2157
+ throw new Error("QA blocked requires blocker_reason to be one of missing_app_launch_target, inconclusive, environment_failure, missing_validation_evidence, missing_worktree, or runner_failure.");
2158
+ }
2159
+ }
2160
+ }
2161
+ function validateActionableQaFinding(finding, index) {
2162
+ const prefix = `findings[${index}].`;
2163
+ requireNonEmptyStringArrayRecord(finding, "acceptance_criteria", prefix);
2164
+ requireNonEmptyStringArrayRecord(finding, "repro_steps", prefix);
2165
+ requireNonEmptyStringRecord(finding, "expected", prefix);
2166
+ requireNonEmptyStringRecord(finding, "actual", prefix);
2167
+ requireSubstantiveEvidenceRecord(finding, prefix);
2168
+ requireNonEmptyStringArrayRecord(finding, "likely_area", prefix);
2169
+ requireNonEmptyStringRecord(finding, "required_fix", prefix);
2170
+ requireNonEmptyStringRecord(finding, "required_regression", prefix);
2171
+ }
725
2172
  function validateOptionalWorkItemId(payload, expectedWorkItemId) {
726
2173
  const actual = optionalString(payload, "work_item_id") ?? optionalString(payload, "workItemId");
727
2174
  if (actual && actual !== expectedWorkItemId) {
@@ -736,8 +2183,34 @@ function normalizeArtifactPayload(payload, defaults) {
736
2183
  normalized.schema_version = numberOrDefault(normalized.schema_version, 1);
737
2184
  normalized.phase = defaults.phase;
738
2185
  normalized.work_item_id = defaults.workItemId;
2186
+ const ownerFields = artifactOwnerFields(defaults);
2187
+ Object.assign(normalized, ownerFields);
2188
+ normalized.status = defaults.status;
2189
+ normalized.produced_by = defaults.producedBy;
2190
+ return normalized;
2191
+ }
2192
+ function normalizeQaGateArtifactPayload(payload, defaults) {
2193
+ const normalized = stripUndefined({ ...payload });
2194
+ delete normalized.report_markdown;
2195
+ delete normalized.content_hash;
2196
+ delete normalized.contentHash;
2197
+ normalized.schema_version = numberOrDefault(normalized.schema_version, 1);
2198
+ normalized.phase = "qa";
2199
+ normalized.gate = defaults.gate;
2200
+ normalized.work_item_id = defaults.workItemId;
2201
+ const ownerFields = artifactOwnerFields(defaults);
2202
+ Object.assign(normalized, ownerFields);
739
2203
  normalized.status = defaults.status;
740
2204
  normalized.produced_by = defaults.producedBy;
2205
+ if (defaults.gate === "qa_plan") {
2206
+ const checklist = qaStringArray(normalized, "checklist");
2207
+ normalized.checklist = checklist.length > 0 ? checklist : defaultQaChecklist(defaults.status);
2208
+ normalized.acceptance_criteria = qaStringArray(normalized, "acceptance_criteria");
2209
+ }
2210
+ if (defaults.gate === "qa_findings") {
2211
+ normalized.findings = qaObjectArray(normalized, "findings");
2212
+ normalized.candidate_bugs = qaObjectArray(normalized, "candidate_bugs");
2213
+ }
741
2214
  return normalized;
742
2215
  }
743
2216
  function reportMarkdown(payload, phase, status, producedBy, contentHash) {
@@ -759,6 +2232,10 @@ ${summary}
759
2232
  }
760
2233
  function parseStrictCompletionPhase(value) {
761
2234
  const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
2235
+ const debugPhase = normalizeDebugCompletionPhase(normalized);
2236
+ if (debugPhase) {
2237
+ return debugPhase;
2238
+ }
762
2239
  if (normalized === "implementation" || normalized === "implement" || normalized === "develop") {
763
2240
  return "implementation";
764
2241
  }
@@ -768,8 +2245,51 @@ function parseStrictCompletionPhase(value) {
768
2245
  if (normalized === "validate" || normalized === "validation") {
769
2246
  return "validation";
770
2247
  }
2248
+ if (normalized === "qa" || normalized === "quality_assurance" || normalized === "qualityassurance") {
2249
+ return "qa";
2250
+ }
2251
+ if (normalized === "architect" || normalized === "architect_plan" || normalized === "planning" || normalized === "plan") {
2252
+ return "architect";
2253
+ }
771
2254
  return null;
772
2255
  }
2256
+ function normalizeDebugCompletionPhase(value) {
2257
+ const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
2258
+ switch (normalized) {
2259
+ case "debug_repro":
2260
+ case "debugrepro":
2261
+ case "repro":
2262
+ case "reproduce":
2263
+ return "debug_repro";
2264
+ case "debug_root_cause":
2265
+ case "debugrootcause":
2266
+ case "root_cause":
2267
+ case "rootcause":
2268
+ return "debug_root_cause";
2269
+ case "debug_fix":
2270
+ case "debugfix":
2271
+ case "fix":
2272
+ return "debug_fix";
2273
+ case "debug_regression":
2274
+ case "debugregression":
2275
+ case "regression":
2276
+ return "debug_regression";
2277
+ default:
2278
+ return null;
2279
+ }
2280
+ }
2281
+ function isDevelopCompletionPhase(phase) {
2282
+ return phase === "implementation" || phase === "self_review" || phase === "validation";
2283
+ }
2284
+ function isDebugCompletionPhase(phase) {
2285
+ return debugCompletionPhaseOrder.includes(phase);
2286
+ }
2287
+ function asDebugCompletionPhase(phase) {
2288
+ if (isDebugCompletionPhase(phase)) {
2289
+ return phase;
2290
+ }
2291
+ throw new Error(`Expected Debug completion phase, got ${phase}.`);
2292
+ }
773
2293
  function parseCompletionRedactionSecrets(raw) {
774
2294
  if (!raw?.trim()) {
775
2295
  return [];
@@ -796,8 +2316,41 @@ function phaseFromToolName(toolName) {
796
2316
  if (normalized === "forge.complete_validation" || normalized === "complete_validation") {
797
2317
  return "validation";
798
2318
  }
2319
+ if (normalized === "forge.complete_qa" || normalized === "complete_qa") {
2320
+ return "qa";
2321
+ }
2322
+ if (normalized === "forge.complete_architect_plan" || normalized === "complete_architect_plan") {
2323
+ return "architect";
2324
+ }
2325
+ const debugGate = debugGateFromToolName(toolName);
2326
+ if (debugGate) {
2327
+ return debugGate;
2328
+ }
2329
+ if (qaGateFromToolName(toolName)) {
2330
+ return "qa";
2331
+ }
799
2332
  throw new Error(`Unknown Forge completion tool: ${toolName}`);
800
2333
  }
2334
+ function debugGateFromToolName(toolName) {
2335
+ const normalized = toolName.trim().toLowerCase();
2336
+ for (const gate of debugCompletionPhaseOrder) {
2337
+ const base = debugGateToolNames[gate];
2338
+ if (normalized === `forge.${base}` || normalized === base) {
2339
+ return gate;
2340
+ }
2341
+ }
2342
+ return null;
2343
+ }
2344
+ function qaGateFromToolName(toolName) {
2345
+ const normalized = toolName.trim().toLowerCase();
2346
+ for (const gate of qaCompletionGateOrder) {
2347
+ const base = qaGateToolNames[gate];
2348
+ if (normalized === `forge.${base}` || normalized === base) {
2349
+ return gate;
2350
+ }
2351
+ }
2352
+ return null;
2353
+ }
801
2354
  function requireField(payload, key) {
802
2355
  if (payload[key] === undefined || payload[key] === null || (typeof payload[key] === "string" && payload[key].trim().length === 0)) {
803
2356
  throw new Error(`${key} is required.`);
@@ -865,17 +2418,42 @@ function requireArray(payload, key) {
865
2418
  throw new Error(`${key} must be an array.`);
866
2419
  }
867
2420
  }
2421
+ function requireNonEmptyArray(payload, key) {
2422
+ requireArray(payload, key);
2423
+ if (arrayLength(payload, key) === 0) {
2424
+ throw new Error(`${key} must include at least one value.`);
2425
+ }
2426
+ }
2427
+ function arrayLength(payload, key) {
2428
+ const value = payload[key];
2429
+ return Array.isArray(value) ? value.length : 0;
2430
+ }
2431
+ function requireAllowedStatus(payload, key, allowed) {
2432
+ const value = normalizedString(optionalString(payload, key));
2433
+ if (!allowed.includes(value)) {
2434
+ throw new Error(`${key} must be one of ${allowed.join(", ")}.`);
2435
+ }
2436
+ }
868
2437
  function requireObject(payload, key) {
869
2438
  const value = payload[key];
870
2439
  if (!value || typeof value !== "object" || Array.isArray(value)) {
871
2440
  throw new Error(`${key} must be an object.`);
872
2441
  }
873
2442
  }
2443
+ function requiredRecord(payload, key) {
2444
+ requireObject(payload, key);
2445
+ return payload[key];
2446
+ }
874
2447
  function requireBoolean(payload, key) {
875
2448
  if (typeof payload[key] !== "boolean") {
876
2449
  throw new Error(`${key} must be a boolean.`);
877
2450
  }
878
2451
  }
2452
+ function requireNumericOne(payload, key, pathLabel) {
2453
+ if (payload[key] !== 1) {
2454
+ throw new Error(`${pathLabel}: expected numeric 1; correction: set ${pathLabel} to 1.`);
2455
+ }
2456
+ }
879
2457
  function requireSatisfiedAcceptanceCriteria(payload) {
880
2458
  const criteria = payload.acceptance_criteria;
881
2459
  if (!Array.isArray(criteria)) {
@@ -893,6 +2471,183 @@ function requireSatisfiedAcceptanceCriteria(payload) {
893
2471
  }
894
2472
  }
895
2473
  }
2474
+ function validateResolvedFindings(payload) {
2475
+ const resolvedFindings = payload.resolved_findings;
2476
+ if (resolvedFindings === undefined || resolvedFindings === null) {
2477
+ return;
2478
+ }
2479
+ if (!Array.isArray(resolvedFindings)) {
2480
+ throw new Error("resolved_findings must be an array.");
2481
+ }
2482
+ for (const [index, finding] of resolvedFindings.entries()) {
2483
+ const prefix = `resolved_findings[${index}].`;
2484
+ if (!finding || typeof finding !== "object" || Array.isArray(finding)) {
2485
+ throw new Error(`resolved_findings[${index}] must be an object.`);
2486
+ }
2487
+ const record = finding;
2488
+ requireNonEmptyStringRecord(record, "qa_id", prefix);
2489
+ requireKnownStringRecord(record, "status", resolvedFindingStatuses, prefix);
2490
+ requireNonEmptyStringRecord(record, "summary", prefix);
2491
+ requireSubstantiveValueRecord(record, "evidence", prefix);
2492
+ requireArrayRecord(record, "changed_files", prefix);
2493
+ requireArrayRecord(record, "tests_added_or_updated", prefix);
2494
+ requireSubstantiveValueRecord(record, "regression_evidence", prefix);
2495
+ if (normalizedString(record.status) === "resolved") {
2496
+ if (record.changed_files.length === 0) {
2497
+ throw new Error(`${prefix}changed_files must include at least one changed file for resolved QA findings.`);
2498
+ }
2499
+ if (record.tests_added_or_updated.length === 0) {
2500
+ throw new Error(`${prefix}tests_added_or_updated must include at least one regression test for resolved QA findings.`);
2501
+ }
2502
+ }
2503
+ }
2504
+ }
2505
+ function qaEvidenceSource(payload) {
2506
+ const evidence = payload.evidence;
2507
+ return evidence && typeof evidence === "object" && !Array.isArray(evidence)
2508
+ ? evidence
2509
+ : {};
2510
+ }
2511
+ function qaArray(payload, key, fallback = {}) {
2512
+ const value = payload[key] ?? fallback[key];
2513
+ if (value === undefined || value === null) {
2514
+ return [];
2515
+ }
2516
+ if (!Array.isArray(value)) {
2517
+ throw new Error(`${key} must be an array.`);
2518
+ }
2519
+ return value;
2520
+ }
2521
+ function qaObjectArray(payload, key) {
2522
+ return qaArray(payload, key).map((entry, index) => {
2523
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
2524
+ throw new Error(`${key}[${index}] must be an object.`);
2525
+ }
2526
+ return entry;
2527
+ });
2528
+ }
2529
+ function qaStringArray(payload, key) {
2530
+ const value = payload[key];
2531
+ if (value === undefined || value === null) {
2532
+ return [];
2533
+ }
2534
+ if (!Array.isArray(value)) {
2535
+ throw new Error(`${key} must be an array.`);
2536
+ }
2537
+ return value.map((entry, index) => {
2538
+ if (typeof entry !== "string" || entry.trim().length === 0) {
2539
+ throw new Error(`${key}[${index}] must be a non-empty string.`);
2540
+ }
2541
+ return entry;
2542
+ });
2543
+ }
2544
+ function requireEvidenceRecord(value, label) {
2545
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2546
+ throw new Error(`${label} must be an object.`);
2547
+ }
2548
+ }
2549
+ function requireNonEmptyStringRecord(source, key, prefix = "") {
2550
+ if (!optionalString(source, key)) {
2551
+ throw new Error(`${prefix}${key} is required.`);
2552
+ }
2553
+ }
2554
+ function requireArrayRecord(source, key, prefix = "") {
2555
+ if (!Array.isArray(source[key])) {
2556
+ throw new Error(`${prefix}${key} must be an array.`);
2557
+ }
2558
+ }
2559
+ function requireKnownStringRecord(source, key, allowed, prefix = "") {
2560
+ const value = normalizedString(optionalString(source, key));
2561
+ if (!allowed.has(value)) {
2562
+ throw new Error(`${prefix}${key} must be one of ${[...allowed].sort().join(", ")}.`);
2563
+ }
2564
+ }
2565
+ function requireNonEmptyStringArrayRecord(source, key, prefix = "") {
2566
+ const value = source[key];
2567
+ if (!Array.isArray(value) || value.length === 0) {
2568
+ throw new Error(`${prefix}${key} must include at least one value.`);
2569
+ }
2570
+ for (const [index, entry] of value.entries()) {
2571
+ if (typeof entry !== "string" || entry.trim().length === 0) {
2572
+ throw new Error(`${prefix}${key}[${index}] must be a non-empty string.`);
2573
+ }
2574
+ }
2575
+ }
2576
+ function requireSubstantiveValueRecord(source, key, prefix = "") {
2577
+ if (!hasSubstantiveJsonValue(source[key])) {
2578
+ throw new Error(`${prefix}${key} must include at least one concrete evidence reference or summary.`);
2579
+ }
2580
+ }
2581
+ function requireSubstantiveEvidenceRecord(source, prefix = "") {
2582
+ const evidence = source.evidence;
2583
+ if (!evidence || typeof evidence !== "object" || Array.isArray(evidence)) {
2584
+ throw new Error(`${prefix}evidence must be an object.`);
2585
+ }
2586
+ if (!Object.values(evidence).some(hasSubstantiveJsonValue)) {
2587
+ throw new Error(`${prefix}evidence must include at least one concrete evidence reference or summary.`);
2588
+ }
2589
+ }
2590
+ function hasSubstantiveJsonValue(value) {
2591
+ if (typeof value === "string") {
2592
+ return value.trim().length > 0;
2593
+ }
2594
+ if (Array.isArray(value)) {
2595
+ return value.length > 0;
2596
+ }
2597
+ if (value && typeof value === "object") {
2598
+ return Object.keys(value).length > 0;
2599
+ }
2600
+ return false;
2601
+ }
2602
+ function normalizedString(value) {
2603
+ return typeof value === "string" ? value.trim().toLowerCase().replace(/-/g, "_") : "";
2604
+ }
2605
+ function normalizedOwnerType(value) {
2606
+ const normalized = normalizedString(value);
2607
+ return normalized === "work_item" || normalized === "story" ? normalized : undefined;
2608
+ }
2609
+ function artifactOwnerFields(config) {
2610
+ const ownerType = normalizedOwnerType(config.ownerType);
2611
+ const ownerId = config.ownerId?.trim();
2612
+ if (!ownerType && !ownerId) {
2613
+ return {};
2614
+ }
2615
+ return {
2616
+ owner_type: ownerType ?? "work_item",
2617
+ owner_id: ownerId || config.workItemId
2618
+ };
2619
+ }
2620
+ function artifactReferenceOwnerFields(config) {
2621
+ const owner = artifactOwnerFields(config);
2622
+ return owner.owner_type && owner.owner_id
2623
+ ? { ownerType: owner.owner_type, ownerId: owner.owner_id }
2624
+ : {};
2625
+ }
2626
+ function artifactOwnerDirectory(ownerType) {
2627
+ return normalizedOwnerType(ownerType) === "story" ? "stories" : "work-items";
2628
+ }
2629
+ function artifactOwnerRelativeRoot(ownerType, ownerId, workItemId) {
2630
+ const owner = artifactOwnerFields({ workItemId, ownerType, ownerId });
2631
+ return owner.owner_type && owner.owner_id
2632
+ ? [".forge", artifactOwnerDirectory(owner.owner_type), owner.owner_id, "artifacts"].join("/")
2633
+ : [".forge", "work-items", workItemId, "artifacts"].join("/");
2634
+ }
2635
+ function defaultQaChecklist(status) {
2636
+ return [
2637
+ "Review the validated work item against acceptance criteria.",
2638
+ "Inspect implementation, self-review, and validation evidence when available.",
2639
+ status === "blocked" ? "Record the blocker reason preventing a conclusive QA verdict." : "Record concrete QA evidence and findings."
2640
+ ];
2641
+ }
2642
+ function qaArtifactRelativePath(workItemId, fileName) {
2643
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
2644
+ }
2645
+ function qaArtifactRelativePathForOwner(ownerType, ownerId, fileName) {
2646
+ return [".forge", artifactOwnerDirectory(ownerType), ownerId, "artifacts", fileName].join("/");
2647
+ }
2648
+ function jsonText(value) {
2649
+ return `${JSON.stringify(value, null, 2)}\n`;
2650
+ }
896
2651
  function fallbackReport(parsed, phase, artifactPath) {
897
2652
  return `# Forge ${phase.replace(/_/g, " ")} completion
898
2653
 
@@ -905,7 +2660,7 @@ function parseJsonObject(content, label) {
905
2660
  return asRecord(JSON.parse(content), label);
906
2661
  }
907
2662
  catch (error) {
908
- throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`);
2663
+ throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`, { cause: error });
909
2664
  }
910
2665
  }
911
2666
  function parseOptionalJsonObject(content, label) {