@loucompanion/forge-bridge 0.1.1-dev.ac486debe210 → 0.1.1-dev.ac656b52f9c6

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,15 +518,42 @@ 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"));
224
- const validationPayload = { ...payload, status };
552
+ const status = normalizeCompletionStatus(requiredString(payload, "status"), phase);
553
+ let validationPayload = { ...payload, status };
554
+ if (config.qaCycle && qaGate === "qa_verdict") {
555
+ validationPayload = await synthesizeQaCycleVerdictPayload(config, validationPayload, status);
556
+ }
225
557
  validatePayloadShape(phase, validationPayload);
226
558
  validateOptionalWorkItemId(validationPayload, config.workItemId);
227
559
  const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
@@ -229,9 +561,17 @@ export async function writeCompletionArtifact(config, toolName, input) {
229
561
  ?? optionalString(redactedPayload, "producedBy")
230
562
  ?? config.producedBy
231
563
  ?? "forge-completion-tool";
564
+ if (phase === "qa") {
565
+ return await writeQaCompletionArtifact(config, redactedPayload, status, producedBy);
566
+ }
567
+ if (phase === "architect") {
568
+ return await writeArchitectCompletionArtifact(config, redactedPayload, status, producedBy);
569
+ }
232
570
  const artifactWithoutHash = normalizeArtifactPayload(redactedPayload, {
233
571
  phase,
234
572
  workItemId: config.workItemId,
573
+ ownerType: config.ownerType,
574
+ ownerId: config.ownerId,
235
575
  producedBy,
236
576
  status
237
577
  });
@@ -250,6 +590,93 @@ export async function writeCompletionArtifact(config, toolName, input) {
250
590
  return {
251
591
  phase,
252
592
  workItemId: config.workItemId,
593
+ ...artifactReferenceOwnerFields(config),
594
+ repoPath: path.resolve(config.worktreePath),
595
+ path: artifactPath,
596
+ reportPath,
597
+ contentHash,
598
+ status,
599
+ producedBy
600
+ };
601
+ }
602
+ async function writeArchitectCompletionArtifact(config, payload, status, producedBy) {
603
+ const ownerFields = artifactOwnerFields(config);
604
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
605
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
606
+ : artifactRootFor(config.worktreePath, config.workItemId);
607
+ const implementationPlanPath = path.join(artifactRoot, "implementation.plan.json");
608
+ const qaPlanPath = path.join(artifactRoot, "qa.plan.json");
609
+ const verdictPath = path.join(artifactRoot, "architect.verdict.json");
610
+ const reportPath = path.join(artifactRoot, "architect.report.md");
611
+ const implementationPlan = requiredRecord(payload, "implementation_plan");
612
+ const qaPlan = requiredRecord(payload, "qa_plan");
613
+ const report = optionalString(payload, "report") ?? optionalString(payload, "report_markdown") ?? reportMarkdown(payload, "architect", status, producedBy, "pending");
614
+ const artifactWithoutHash = normalizeArtifactPayload(payload, {
615
+ phase: "architect",
616
+ workItemId: config.workItemId,
617
+ ownerType: config.ownerType,
618
+ ownerId: config.ownerId,
619
+ producedBy,
620
+ status
621
+ });
622
+ const contentHash = sha256(stableStringify(artifactWithoutHash));
623
+ const verdict = {
624
+ ...artifactWithoutHash,
625
+ content_hash: contentHash
626
+ };
627
+ await fs.mkdir(artifactRoot, { recursive: true });
628
+ await writeFileAtomic(implementationPlanPath, jsonText(implementationPlan));
629
+ await writeFileAtomic(qaPlanPath, jsonText(qaPlan));
630
+ await writeFileAtomic(verdictPath, jsonText(verdict));
631
+ await writeFileAtomic(reportPath, `${report.trim()}\n`);
632
+ return {
633
+ phase: "architect",
634
+ workItemId: config.workItemId,
635
+ ...artifactReferenceOwnerFields(config),
636
+ repoPath: path.resolve(config.worktreePath),
637
+ path: verdictPath,
638
+ reportPath,
639
+ contentHash,
640
+ status,
641
+ producedBy
642
+ };
643
+ }
644
+ async function writeQaGateCompletionArtifact(config, gate, input) {
645
+ const payload = asRecord(input, "QA gate completion payload");
646
+ const status = normalizeQaGateStatus(requiredString(payload, "status"));
647
+ validateQaGatePayloadShape(gate, payload, status);
648
+ validateOptionalWorkItemId(payload, config.workItemId);
649
+ const redactedPayload = redactSecrets({ ...payload, status }, config.redactionSecrets ?? []);
650
+ const producedBy = optionalString(redactedPayload, "produced_by")
651
+ ?? optionalString(redactedPayload, "producedBy")
652
+ ?? config.producedBy
653
+ ?? "forge-completion-tool";
654
+ const ownerFields = artifactOwnerFields(config);
655
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
656
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
657
+ : artifactRootFor(config.worktreePath, config.workItemId);
658
+ const fileName = qaGateFileNames[gate];
659
+ const artifactPath = path.join(artifactRoot, fileName);
660
+ const reportPath = path.join(artifactRoot, "qa.report.md");
661
+ const artifactWithoutHash = normalizeQaGateArtifactPayload(redactedPayload, {
662
+ gate,
663
+ workItemId: config.workItemId,
664
+ ownerType: config.ownerType,
665
+ ownerId: config.ownerId,
666
+ producedBy,
667
+ status
668
+ });
669
+ const contentHash = sha256(stableStringify(artifactWithoutHash));
670
+ const artifact = {
671
+ ...artifactWithoutHash,
672
+ content_hash: contentHash
673
+ };
674
+ await fs.mkdir(artifactRoot, { recursive: true });
675
+ await writeFileAtomic(artifactPath, jsonText(artifact));
676
+ return {
677
+ phase: "qa",
678
+ workItemId: config.workItemId,
679
+ ...artifactReferenceOwnerFields(config),
253
680
  repoPath: path.resolve(config.worktreePath),
254
681
  path: artifactPath,
255
682
  reportPath,
@@ -258,19 +685,289 @@ export async function writeCompletionArtifact(config, toolName, input) {
258
685
  producedBy
259
686
  };
260
687
  }
261
- export async function readCompletionArtifact(worktreePath, workItemId, phase) {
262
- const artifactPath = completionArtifactJsonPath(worktreePath, workItemId, phase);
263
- const reportPath = completionArtifactReportPath(worktreePath, workItemId, phase);
688
+ async function writeQaCompletionArtifact(config, payload, status, producedBy) {
689
+ const ownerFields = artifactOwnerFields(config);
690
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
691
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
692
+ : artifactRootFor(config.worktreePath, config.workItemId);
693
+ const planPath = path.join(artifactRoot, "qa.plan.json");
694
+ const evidencePath = path.join(artifactRoot, "qa.evidence.json");
695
+ const findingsPath = path.join(artifactRoot, "qa.findings.json");
696
+ const verdictPath = path.join(artifactRoot, "qa.verdict.json");
697
+ const reportPath = path.join(artifactRoot, "qa.report.md");
698
+ const relativeEvidencePath = ownerFields.owner_type && ownerFields.owner_id
699
+ ? qaArtifactRelativePathForOwner(ownerFields.owner_type, ownerFields.owner_id, "qa.evidence.json")
700
+ : qaArtifactRelativePath(config.workItemId, "qa.evidence.json");
701
+ const relativeFindingsPath = ownerFields.owner_type && ownerFields.owner_id
702
+ ? qaArtifactRelativePathForOwner(ownerFields.owner_type, ownerFields.owner_id, "qa.findings.json")
703
+ : qaArtifactRelativePath(config.workItemId, "qa.findings.json");
704
+ const relativeReportPath = ownerFields.owner_type && ownerFields.owner_id
705
+ ? qaArtifactRelativePathForOwner(ownerFields.owner_type, ownerFields.owner_id, "qa.report.md")
706
+ : qaArtifactRelativePath(config.workItemId, "qa.report.md");
707
+ const evidenceSource = qaEvidenceSource(payload);
708
+ const commands = qaArray(payload, "commands", evidenceSource);
709
+ const browserChecks = qaArray(payload, "browser_checks", evidenceSource);
710
+ const sidecars = await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(payload, "sidecars", evidenceSource), ownerFields.owner_type, ownerFields.owner_id);
711
+ const notes = optionalString(payload, "notes") ?? optionalString(evidenceSource, "notes") ?? "";
712
+ const findings = qaObjectArray(payload, "findings");
713
+ const candidateBugs = qaObjectArray(payload, "candidate_bugs");
714
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
715
+ const explicitFindingIds = qaStringArray(payload, "finding_ids");
716
+ const explicitCandidateBugIds = qaStringArray(payload, "candidate_bug_ids");
717
+ const blockerReason = optionalString(payload, "blocker_reason");
718
+ const checklist = qaStringArray(payload, "checklist");
719
+ const planJson = jsonText({
720
+ schema_version: 1,
721
+ phase: "qa",
722
+ ...ownerFields,
723
+ checklist: checklist.length > 0 ? checklist : defaultQaChecklist(status),
724
+ acceptance_criteria: testedAcceptanceCriteria
725
+ });
726
+ const evidenceJson = jsonText({
727
+ schema_version: 1,
728
+ phase: "qa",
729
+ ...ownerFields,
730
+ commands,
731
+ browser_checks: browserChecks,
732
+ sidecars,
733
+ notes
734
+ });
735
+ const findingsJson = jsonText({
736
+ schema_version: 1,
737
+ phase: "qa",
738
+ ...ownerFields,
739
+ findings,
740
+ candidate_bugs: candidateBugs
741
+ });
742
+ const findingIds = status === "pass"
743
+ ? []
744
+ : explicitFindingIds.length > 0
745
+ ? explicitFindingIds
746
+ : findings
747
+ .filter((finding) => normalizedString(finding.scope) === "in_scope")
748
+ .map((finding) => optionalString(finding, "id"))
749
+ .filter((id) => Boolean(id));
750
+ const candidateBugIds = explicitCandidateBugIds.length > 0
751
+ ? explicitCandidateBugIds
752
+ : candidateBugs
753
+ .map((candidateBug) => optionalString(candidateBug, "id"))
754
+ .filter((id) => Boolean(id));
755
+ const verdictWithoutHash = {
756
+ schema_version: numberOrDefault(payload.schema_version, 1),
757
+ phase: "qa",
758
+ ...ownerFields,
759
+ status,
760
+ summary: requiredString(payload, "summary"),
761
+ tested_acceptance_criteria: testedAcceptanceCriteria,
762
+ finding_ids: findingIds,
763
+ candidate_bug_ids: candidateBugIds,
764
+ blocker_reason: status === "blocked" ? normalizedString(blockerReason) : null,
765
+ evidence_path: relativeEvidencePath,
766
+ findings_path: relativeFindingsPath,
767
+ report_path: relativeReportPath,
768
+ produced_by: producedBy
769
+ };
770
+ const contentHash = sha256(stableStringify({
771
+ plan: JSON.parse(planJson),
772
+ evidence: JSON.parse(evidenceJson),
773
+ findings: JSON.parse(findingsJson),
774
+ verdict: verdictWithoutHash
775
+ }));
776
+ const verdictJson = jsonText({
777
+ ...verdictWithoutHash,
778
+ content_hash: contentHash
779
+ });
780
+ const finalReport = reportMarkdown(payload, "qa", status, producedBy, contentHash);
781
+ await fs.mkdir(artifactRoot, { recursive: true });
782
+ await writeFileAtomic(planPath, planJson);
783
+ await writeFileAtomic(evidencePath, evidenceJson);
784
+ await writeFileAtomic(findingsPath, findingsJson);
785
+ await writeFileAtomic(verdictPath, verdictJson);
786
+ await writeFileAtomic(reportPath, finalReport);
787
+ return {
788
+ phase: "qa",
789
+ workItemId: config.workItemId,
790
+ ...artifactReferenceOwnerFields(config),
791
+ repoPath: path.resolve(config.worktreePath),
792
+ path: verdictPath,
793
+ reportPath,
794
+ contentHash,
795
+ status,
796
+ producedBy
797
+ };
798
+ }
799
+ async function synthesizeQaCycleVerdictPayload(config, payload, status) {
800
+ const qaPlan = await readQaGateArtifact(config, "qa_plan");
801
+ const qaRegression = await readQaGateArtifact(config, "qa_regression");
802
+ const qaApi = await readQaGateArtifact(config, "qa_api");
803
+ const qaManualWeb = await readQaGateArtifact(config, "qa_manual_web");
804
+ const qaBugRepro = await readQaGateArtifact(config, "qa_bug_repro");
805
+ const qaFindings = await readQaGateArtifact(config, "qa_findings");
806
+ const evidenceGates = [qaRegression, qaApi, qaManualWeb, qaBugRepro];
807
+ const payloadEvidence = qaEvidenceSource(payload);
808
+ const merged = { ...payload };
809
+ const checklist = qaStringArray(payload, "checklist");
810
+ if (checklist.length === 0) {
811
+ const plannedChecklist = qaStringArray(qaPlan, "checklist");
812
+ merged.checklist = plannedChecklist.length > 0 ? plannedChecklist : defaultQaChecklist(status);
813
+ }
814
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
815
+ if (testedAcceptanceCriteria.length === 0) {
816
+ const plannedAcceptanceCriteria = qaStringArray(qaPlan, "acceptance_criteria");
817
+ const payloadAcceptanceCriteria = qaStringArray(payload, "acceptance_criteria");
818
+ const acceptanceCriteria = plannedAcceptanceCriteria.length > 0 ? plannedAcceptanceCriteria : payloadAcceptanceCriteria;
819
+ if (acceptanceCriteria.length > 0) {
820
+ merged.tested_acceptance_criteria = acceptanceCriteria;
821
+ }
822
+ }
823
+ merged.commands = dedupeUnknownArray([
824
+ ...qaArray(payload, "commands", payloadEvidence),
825
+ ...evidenceGates.flatMap((gate) => qaArray(gate, "commands"))
826
+ ]);
827
+ merged.browser_checks = dedupeUnknownArray([
828
+ ...qaArray(payload, "browser_checks", payloadEvidence),
829
+ ...evidenceGates.flatMap((gate) => qaArray(gate, "browser_checks"))
830
+ ]);
831
+ merged.sidecars = dedupeUnknownArray([
832
+ ...qaArray(payload, "sidecars", payloadEvidence),
833
+ ...evidenceGates.flatMap((gate) => qaArray(gate, "sidecars"))
834
+ ]);
835
+ const notes = dedupeStrings([
836
+ optionalString(payload, "notes"),
837
+ optionalString(payloadEvidence, "notes"),
838
+ ...evidenceGates.map((gate) => optionalString(gate, "notes"))
839
+ ]);
840
+ if (notes.length > 0) {
841
+ merged.notes = notes.join("\n");
842
+ }
843
+ merged.findings = mergeQaObjectArraysById(qaObjectArray(payload, "findings"), qaObjectArray(qaFindings, "findings"));
844
+ merged.candidate_bugs = mergeQaObjectArraysById(qaObjectArray(payload, "candidate_bugs"), qaObjectArray(qaFindings, "candidate_bugs"));
845
+ return merged;
846
+ }
847
+ async function readQaGateArtifact(config, gate) {
848
+ const ownerFields = artifactOwnerFields(config);
849
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
850
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
851
+ : artifactRootFor(config.worktreePath, config.workItemId);
852
+ const artifactPath = path.join(artifactRoot, qaGateFileNames[gate]);
853
+ const content = await readOptionalFile(artifactPath);
854
+ return content === null ? {} : parseOptionalJsonObject(content, qaGateFileNames[gate]);
855
+ }
856
+ function dedupeUnknownArray(values) {
857
+ const seen = new Set();
858
+ const deduped = [];
859
+ for (const value of values) {
860
+ const key = stableStringify(value);
861
+ if (seen.has(key)) {
862
+ continue;
863
+ }
864
+ seen.add(key);
865
+ deduped.push(value);
866
+ }
867
+ return deduped;
868
+ }
869
+ function mergeQaObjectArraysById(primary, fallback) {
870
+ const seen = new Set();
871
+ const merged = [];
872
+ for (const value of [...primary, ...fallback]) {
873
+ const id = optionalString(value, "id");
874
+ const key = id ? `id:${id}` : stableStringify(value);
875
+ if (seen.has(key)) {
876
+ continue;
877
+ }
878
+ seen.add(key);
879
+ merged.push(value);
880
+ }
881
+ return merged;
882
+ }
883
+ function dedupeStrings(values) {
884
+ const seen = new Set();
885
+ const deduped = [];
886
+ for (const value of values) {
887
+ const trimmed = value?.trim();
888
+ if (!trimmed || seen.has(trimmed)) {
889
+ continue;
890
+ }
891
+ seen.add(trimmed);
892
+ deduped.push(trimmed);
893
+ }
894
+ return deduped;
895
+ }
896
+ async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, ownerType, ownerId) {
897
+ if (sidecars.length === 0) {
898
+ return [];
899
+ }
900
+ const artifactRoot = ownerType && ownerId
901
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
902
+ : artifactRootFor(worktreePath, workItemId);
903
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
904
+ const validated = [];
905
+ for (const [index, sidecar] of sidecars.entries()) {
906
+ if (!sidecar || typeof sidecar !== "object" || Array.isArray(sidecar)) {
907
+ throw new Error(`sidecars[${index}] must be an object.`);
908
+ }
909
+ const record = sidecar;
910
+ const sidecarPath = optionalString(record, "path");
911
+ const contentHash = optionalString(record, "content_hash");
912
+ const bytes = record.bytes;
913
+ if (!sidecarPath || !contentHash || typeof bytes !== "number" || !Number.isFinite(bytes) || bytes <= 0) {
914
+ throw new Error(`sidecars[${index}] must include path, content_hash, and positive bytes.`);
915
+ }
916
+ if (path.isAbsolute(sidecarPath)) {
917
+ throw new Error(`sidecars[${index}].path must be relative to the worktree.`);
918
+ }
919
+ const fullPath = path.resolve(worktreePath, sidecarPath);
920
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
921
+ throw new Error(`sidecars[${index}].path must be under ${artifactOwnerRelativeRoot(ownerType, ownerId, workItemId)}/qa/.`);
922
+ }
923
+ const stat = await fs.lstat(fullPath).catch((error) => {
924
+ if (isNodeError(error) && error.code === "ENOENT") {
925
+ throw new Error(`sidecars[${index}].path does not exist: ${sidecarPath}`);
926
+ }
927
+ throw error;
928
+ });
929
+ if (!stat.isFile() || stat.isSymbolicLink()) {
930
+ throw new Error(`sidecars[${index}].path must reference a regular file.`);
931
+ }
932
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `sidecars[${index}].path must not traverse symbolic links.`);
933
+ if (stat.size !== bytes) {
934
+ throw new Error(`sidecars[${index}].bytes does not match the referenced file.`);
935
+ }
936
+ const actualHash = await sha256File(fullPath);
937
+ if (actualHash !== contentHash.trim().toLowerCase()) {
938
+ throw new Error(`sidecars[${index}].content_hash does not match the referenced file.`);
939
+ }
940
+ validated.push({
941
+ ...record,
942
+ path: path.relative(worktreePath, fullPath).split(path.sep).join("/"),
943
+ content_hash: actualHash,
944
+ bytes: stat.size
945
+ });
946
+ }
947
+ return validated;
948
+ }
949
+ export async function readCompletionArtifact(worktreePath, workItemId, phase, ownerType, ownerId) {
950
+ const artifactPath = completionArtifactJsonPath(worktreePath, workItemId, phase, ownerType, ownerId);
951
+ const reportPath = completionArtifactReportPath(worktreePath, workItemId, phase, ownerType, ownerId);
264
952
  const verdictJson = await readOptionalFile(artifactPath);
265
953
  if (verdictJson === null) {
266
954
  return null;
267
955
  }
268
956
  const parsed = parseJsonObject(verdictJson, artifactPath);
269
957
  const report = await readOptionalFile(reportPath) ?? fallbackReport(parsed, phase, artifactPath);
958
+ const artifactRoot = path.dirname(artifactPath);
959
+ const implementationPlanJson = phase === "architect"
960
+ ? await readOptionalFile(path.join(artifactRoot, "implementation.plan.json"))
961
+ : null;
962
+ const qaPlanJson = phase === "architect"
963
+ ? await readOptionalFile(path.join(artifactRoot, "qa.plan.json"))
964
+ : null;
270
965
  return {
271
966
  repoPath: path.resolve(worktreePath),
272
967
  path: artifactPath,
273
968
  verdictJson,
969
+ implementationPlanJson,
970
+ qaPlanJson,
274
971
  report,
275
972
  producedBy: optionalString(parsed, "produced_by") ?? optionalString(parsed, "producedBy") ?? "forge-completion-tool",
276
973
  status: optionalString(parsed, "status") ?? "unknown",
@@ -302,8 +999,13 @@ export function parseCompletionMcpArgs(argv) {
302
999
  let worktreePath = null;
303
1000
  let workItemId = null;
304
1001
  let phase = "implementation";
1002
+ let ownerType;
1003
+ let ownerId;
305
1004
  let producedBy;
306
1005
  let developCycle = false;
1006
+ let qaCycle = false;
1007
+ let debugCycle = false;
1008
+ let architectCycle = false;
307
1009
  for (let index = 1; index < argv.length; index += 1) {
308
1010
  const arg = argv[index];
309
1011
  if (arg === "--worktree") {
@@ -312,11 +1014,20 @@ export function parseCompletionMcpArgs(argv) {
312
1014
  else if (arg === "--work-item-id") {
313
1015
  workItemId = argv[++index] ?? null;
314
1016
  }
1017
+ else if (arg === "--owner-type") {
1018
+ ownerType = normalizedOwnerType(argv[++index]);
1019
+ if (!ownerType) {
1020
+ return { ok: false, error: "mcp --owner-type must be work_item or story." };
1021
+ }
1022
+ }
1023
+ else if (arg === "--owner-id") {
1024
+ ownerId = argv[++index] ?? undefined;
1025
+ }
315
1026
  else if (arg === "--phase") {
316
1027
  const rawPhase = argv[++index];
317
1028
  const parsedPhase = parseStrictCompletionPhase(rawPhase);
318
1029
  if (!parsedPhase) {
319
- return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation." };
1030
+ 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
1031
  }
321
1032
  phase = parsedPhase;
322
1033
  }
@@ -326,6 +1037,15 @@ export function parseCompletionMcpArgs(argv) {
326
1037
  else if (arg === "--develop-cycle") {
327
1038
  developCycle = true;
328
1039
  }
1040
+ else if (arg === "--qa-cycle") {
1041
+ qaCycle = true;
1042
+ }
1043
+ else if (arg === "--debug-cycle") {
1044
+ debugCycle = true;
1045
+ }
1046
+ else if (arg === "--architect-cycle") {
1047
+ architectCycle = true;
1048
+ }
329
1049
  else {
330
1050
  return { ok: false, error: `Unknown mcp argument: ${arg}` };
331
1051
  }
@@ -333,15 +1053,35 @@ export function parseCompletionMcpArgs(argv) {
333
1053
  if (!worktreePath?.trim() || !workItemId?.trim()) {
334
1054
  return { ok: false, error: "mcp requires --worktree and --work-item-id." };
335
1055
  }
1056
+ if ([developCycle, qaCycle, debugCycle, architectCycle].filter(Boolean).length > 1) {
1057
+ return { ok: false, error: "mcp accepts only one cycle mode." };
1058
+ }
1059
+ if (developCycle && !isDevelopCompletionPhase(phase)) {
1060
+ return { ok: false, error: "mcp --develop-cycle requires --phase implementation, self-review, or validation." };
1061
+ }
1062
+ if (qaCycle && phase !== "qa") {
1063
+ return { ok: false, error: "mcp --qa-cycle requires --phase qa." };
1064
+ }
1065
+ if (debugCycle && !isDebugCompletionPhase(phase)) {
1066
+ return { ok: false, error: "mcp --debug-cycle requires --phase debug-repro, debug-root-cause, debug-fix, or debug-regression." };
1067
+ }
1068
+ if (architectCycle && phase !== "architect") {
1069
+ return { ok: false, error: "mcp --architect-cycle requires --phase architect." };
1070
+ }
336
1071
  return {
337
1072
  ok: true,
338
1073
  config: {
339
1074
  worktreePath: path.resolve(worktreePath),
340
1075
  workItemId,
1076
+ ownerType,
1077
+ ownerId,
341
1078
  phase,
342
1079
  producedBy,
343
1080
  redactionSecrets: parseCompletionRedactionSecrets(process.env[completionRedactionSecretsEnv]),
344
- developCycle
1081
+ developCycle,
1082
+ qaCycle,
1083
+ debugCycle,
1084
+ architectCycle
345
1085
  }
346
1086
  };
347
1087
  }
@@ -436,21 +1176,41 @@ async function handleJsonRpcRequest(session, method, params) {
436
1176
  }
437
1177
  throw new Error(`Unsupported MCP method: ${method}`);
438
1178
  }
439
- function toolDefinition(name, phase) {
1179
+ function toolDefinition(name, phase, qaGate = null) {
440
1180
  return {
441
1181
  name,
442
- description: toolDescription(phase),
443
- inputSchema: toolInputSchema(phase)
1182
+ description: toolDescription(phase, qaGate),
1183
+ inputSchema: toolInputSchema(phase, qaGate)
444
1184
  };
445
1185
  }
446
1186
  function nextPhaseAfter(phase) {
1187
+ if (!isDevelopCompletionPhase(phase)) {
1188
+ return null;
1189
+ }
447
1190
  const index = completionPhaseOrder.indexOf(phase);
448
1191
  return index >= 0 ? completionPhaseOrder[index + 1] ?? null : null;
449
1192
  }
1193
+ function nextDebugPhaseAfter(phase) {
1194
+ const index = debugCompletionPhaseOrder.indexOf(phase);
1195
+ return index >= 0 ? debugCompletionPhaseOrder[index + 1] ?? null : null;
1196
+ }
450
1197
  function completionToolNextInstruction(completedPhase, status, nextPhase) {
1198
+ if (completedPhase === "qa") {
1199
+ if (status === "blocked") {
1200
+ return "QA blocked. Forge recorded the blocker reason and will surface the run for human attention.";
1201
+ }
1202
+ if (status === "needs_rework") {
1203
+ return "QA findings recorded. Forge has the structured evidence needed to route this work back for implementation rework.";
1204
+ }
1205
+ return "QA accepted. Forge has the structured evidence needed to move this work item to Sign-Off.";
1206
+ }
451
1207
  if (status !== "pass") {
452
1208
  return `Stay in ${completedPhase}, address the recorded blockers, then call ${expectedCompletionToolName(completedPhase)} again.`;
453
1209
  }
1210
+ if (isDebugCompletionPhase(completedPhase)) {
1211
+ const debugNext = isDebugCompletionPhase(nextPhase) ? nextPhase : null;
1212
+ return completionToolNextInstructionForDebugGate(completedPhase, status, debugNext);
1213
+ }
454
1214
  if (nextPhase === "self_review") {
455
1215
  return "Implementation accepted. Begin self-review: inspect the diff, apply safe fixes, and call forge.complete_self_review with review evidence.";
456
1216
  }
@@ -459,16 +1219,82 @@ function completionToolNextInstruction(completedPhase, status, nextPhase) {
459
1219
  }
460
1220
  return "Validation accepted. Forge has the structured evidence needed to move this work item to QA.";
461
1221
  }
462
- function toolDescription(phase) {
1222
+ function completionToolNextInstructionForQaGate(completedGate, status, nextGate) {
1223
+ if (!nextGate) {
1224
+ if (status === "blocked") {
1225
+ return "QA blocked. Forge recorded the blocker reason and will surface the run for human attention.";
1226
+ }
1227
+ if (status === "needs_rework") {
1228
+ return "QA findings recorded. Forge has the structured evidence needed to route this work back for implementation rework.";
1229
+ }
1230
+ return "QA accepted. Forge has the structured evidence needed to move this work item to Sign-Off.";
1231
+ }
1232
+ const skipped = status === "skipped";
1233
+ const blocked = status === "blocked";
1234
+ const prefix = blocked
1235
+ ? `${completedGate} recorded a blocker. Continue through ${nextGate} and mark downstream gates skipped if the blocker prevents evidence collection.`
1236
+ : skipped
1237
+ ? `${completedGate} skipped. Continue to ${nextGate}.`
1238
+ : `${completedGate} accepted. Continue to ${nextGate}.`;
1239
+ return `${prefix} ${qaGateInstruction(nextGate)}`;
1240
+ }
1241
+ function completionToolNextInstructionForDebugGate(completedGate, status, nextGate) {
1242
+ if (status !== "pass") {
1243
+ return `Stay in ${completedGate}, address the recorded blockers, then call ${expectedDebugCompletionToolName(completedGate)} again.`;
1244
+ }
1245
+ if (nextGate === "debug_root_cause") {
1246
+ return "Debug repro accepted. Begin root-cause analysis: connect the observed failure to code evidence and call forge.complete_debug_root_cause.";
1247
+ }
1248
+ if (nextGate === "debug_fix") {
1249
+ return "Debug root cause accepted. Apply the smallest safe fix with regression coverage where practical, then call forge.complete_debug_fix.";
1250
+ }
1251
+ if (nextGate === "debug_regression") {
1252
+ return "Debug fix accepted. Prove the original repro is negative, run targeted regression checks, and call forge.complete_debug_regression.";
1253
+ }
1254
+ return "Debug regression accepted. Forge has the structured evidence needed to move this bug fix to QA.";
1255
+ }
1256
+ function qaGateInstruction(gate) {
1257
+ switch (gate) {
1258
+ case "qa_regression":
1259
+ return "Run or explicitly skip applicable regression/build/lint/typecheck/e2e checks, then call forge.complete_qa_regression.";
1260
+ case "qa_api":
1261
+ return "Run or explicitly skip applicable API/backend contract checks, then call forge.complete_qa_api.";
1262
+ case "qa_manual_web":
1263
+ return "Run or explicitly skip applicable browser/manual web checks, then call forge.complete_qa_manual_web.";
1264
+ case "qa_bug_repro":
1265
+ return "Reproduce or explicitly skip relevant defects/candidate bugs, then call forge.complete_qa_bug_repro.";
1266
+ case "qa_findings":
1267
+ return "Normalize observations into findings and candidate bugs, then call forge.complete_qa_findings.";
1268
+ case "qa_verdict":
1269
+ return "Assemble the final QA verdict from all prior gate evidence, then call forge.complete_qa_verdict.";
1270
+ case "qa_plan":
1271
+ return "Prepare the QA checklist, then call forge.complete_qa_plan.";
1272
+ }
1273
+ }
1274
+ function toolDescription(phase, qaGate = null) {
1275
+ if (qaGate) {
1276
+ return qaGate === "qa_verdict"
1277
+ ? "Complete the final Forge QA verdict by writing the canonical QA bundle with pass, needs_rework, or blocked evidence."
1278
+ : `Complete the ${qaGate.replace(/_/g, " ")} QA gate by writing ${qaGateFileNames[qaGate]} before continuing to the next QA gate.`;
1279
+ }
1280
+ if (isDebugCompletionPhase(phase)) {
1281
+ return `Complete the ${phase.replace(/_/g, " ")} Debug gate by writing ${phaseFiles[phase].jsonFileName} with structured bug-fix evidence before continuing.`;
1282
+ }
463
1283
  if (phase === "implementation") {
464
1284
  return "Complete Forge implementation by writing implementation.completeness.json with scoped changed-file, verification, acceptance-criteria, gap, and next-phase evidence.";
465
1285
  }
466
1286
  if (phase === "self_review") {
467
1287
  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
1288
  }
1289
+ if (phase === "qa") {
1290
+ 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.";
1291
+ }
1292
+ if (phase === "architect") {
1293
+ 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.";
1294
+ }
469
1295
  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
1296
  }
471
- function toolInputSchema(phase) {
1297
+ function toolInputSchema(phase, qaGate = null) {
472
1298
  const baseProperties = {
473
1299
  status: {
474
1300
  type: "string",
@@ -487,6 +1313,12 @@ function toolInputSchema(phase) {
487
1313
  })
488
1314
  }
489
1315
  };
1316
+ if (qaGate && qaGate !== "qa_verdict") {
1317
+ return qaGateToolInputSchema(qaGate);
1318
+ }
1319
+ if (isDebugCompletionPhase(phase)) {
1320
+ return debugToolInputSchema(phase, baseProperties);
1321
+ }
490
1322
  if (phase === "implementation") {
491
1323
  return objectToolSchema({
492
1324
  ...baseProperties,
@@ -509,7 +1341,7 @@ function toolInputSchema(phase) {
509
1341
  },
510
1342
  tests_added_or_updated: {
511
1343
  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.",
1344
+ description: "Required for pass. Use an object explaining why no tests were needed for documentation/config-only work if empty would be ambiguous.",
513
1345
  items: evidenceObjectSchema(["path", "summary"], {
514
1346
  path: { type: "string" },
515
1347
  summary: { type: "string" }
@@ -540,6 +1372,11 @@ function toolInputSchema(phase) {
540
1372
  },
541
1373
  next_phase_context: {
542
1374
  description: "Required for pass. Context the self-review phase should carry forward."
1375
+ },
1376
+ resolved_findings: {
1377
+ type: "array",
1378
+ description: "Required for QA rework. Each entry must use status resolved, disputed, or not_reproduced.",
1379
+ items: resolvedFindingSchema()
543
1380
  }
544
1381
  }, ["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
1382
  }
@@ -588,6 +1425,170 @@ function toolInputSchema(phase) {
588
1425
  }
589
1426
  }, ["status", "summary"], "For status pass, include reviewed_diff, findings, security_review, edge_case_review, design_review, deterministic_comparison, fixes_applied, and remaining_risks.");
590
1427
  }
1428
+ if (phase === "qa") {
1429
+ return objectToolSchema({
1430
+ ...baseProperties,
1431
+ status: {
1432
+ type: "string",
1433
+ enum: ["pass", "needs_rework", "blocked"],
1434
+ description: "Use pass only when QA evidence satisfies acceptance criteria, needs_rework for actionable in-scope defects, or blocked for an inconclusive QA blocker."
1435
+ },
1436
+ checklist: {
1437
+ type: "array",
1438
+ description: "QA plan/checklist. Forge writes this to qa.plan.json; a default checklist is generated if omitted.",
1439
+ items: { type: "string" }
1440
+ },
1441
+ tested_acceptance_criteria: {
1442
+ type: "array",
1443
+ description: "Required and non-empty for pass/needs_rework. Criteria actually tested by QA.",
1444
+ items: { type: "string" }
1445
+ },
1446
+ commands: {
1447
+ type: "array",
1448
+ description: "Command evidence written to qa.evidence.json.",
1449
+ items: commandEvidenceSchema()
1450
+ },
1451
+ browser_checks: {
1452
+ type: "array",
1453
+ description: "Browser/manual UI checks with URL or route, action, observed result, screenshot/trace references, console/network notes, and status.",
1454
+ items: evidenceObjectSchema(["summary", "status"], {
1455
+ summary: { type: "string" },
1456
+ url: { type: "string" },
1457
+ route: { type: "string" },
1458
+ status: { type: "string" },
1459
+ screenshot: { type: "string" },
1460
+ trace: { type: "string" }
1461
+ })
1462
+ },
1463
+ sidecars: {
1464
+ type: "array",
1465
+ description: "Optional QA sidecar files already written under .forge/work-items/<id>/artifacts/qa/ with path/content_hash/bytes metadata.",
1466
+ items: evidenceObjectSchema(["path", "content_hash", "bytes"], {
1467
+ path: { type: "string" },
1468
+ content_hash: { type: "string" },
1469
+ bytes: { type: "number" }
1470
+ })
1471
+ },
1472
+ notes: { type: "string", description: "Additional QA evidence notes." },
1473
+ evidence: {
1474
+ type: "object",
1475
+ description: "Optional wrapper containing commands, browser_checks, and notes when a client prefers nested evidence."
1476
+ },
1477
+ findings: {
1478
+ type: "array",
1479
+ description: "QA findings. needs_rework requires at least one actionable in_scope finding.",
1480
+ items: evidenceObjectSchema(["id", "severity", "scope", "title"], {
1481
+ id: { type: "string" },
1482
+ severity: { type: "string", enum: ["critical", "major", "minor"] },
1483
+ scope: { type: "string", enum: ["in_scope", "out_of_scope", "unclear"] },
1484
+ title: { type: "string" },
1485
+ acceptance_criteria: { type: "array", items: { type: "string" } },
1486
+ repro_steps: { type: "array", items: { type: "string" } },
1487
+ expected: { type: "string" },
1488
+ actual: { type: "string" },
1489
+ evidence: { type: "object" },
1490
+ likely_area: { type: "array", items: { type: "string" } },
1491
+ required_fix: { type: "string" },
1492
+ required_regression: { type: "string" }
1493
+ })
1494
+ },
1495
+ candidate_bugs: {
1496
+ type: "array",
1497
+ description: "Out-of-scope/follow-up bug candidates. They do not block the current item unless attached as in-scope findings.",
1498
+ items: evidenceObjectSchema(["id", "title", "suggested_action"], {
1499
+ id: { type: "string" },
1500
+ title: { type: "string" },
1501
+ severity: { type: "string" },
1502
+ scope_reason: { type: "string" },
1503
+ repro_steps: { type: "array", items: { type: "string" } },
1504
+ evidence: { type: "object" },
1505
+ suggested_action: { type: "string", enum: ["create_bug", "create_follow_up", "accept_risk", "attach_to_current_item"] }
1506
+ })
1507
+ },
1508
+ blocker_reason: {
1509
+ type: "string",
1510
+ enum: [...qaBlockerReasons],
1511
+ description: "Required when status is blocked."
1512
+ }
1513
+ }, ["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.");
1514
+ }
1515
+ if (phase === "architect") {
1516
+ return objectToolSchema({
1517
+ status: {
1518
+ type: "string",
1519
+ enum: ["pass", "needs_revision", "blocked"],
1520
+ 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."
1521
+ },
1522
+ summary: { type: "string", description: "Concise Architect plan verdict summary." },
1523
+ implementation_plan: {
1524
+ type: "object",
1525
+ description: "Required for pass. Top-level fields inside this object must include schema_version, plan_id, phases, tasks, dependencies, and phase_gates.",
1526
+ additionalProperties: true,
1527
+ properties: {
1528
+ schema_version: { type: "number", enum: [1] },
1529
+ plan_id: { type: "string" },
1530
+ phases: {
1531
+ type: "array",
1532
+ description: "Required top-level implementation_plan.phases array.",
1533
+ items: { type: "object", additionalProperties: true }
1534
+ },
1535
+ tasks: {
1536
+ type: "array",
1537
+ description: "Required task list. Each task must include id and a non-empty tests array.",
1538
+ items: { type: "object", additionalProperties: true }
1539
+ },
1540
+ dependencies: {
1541
+ type: "array",
1542
+ 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.",
1543
+ items: {
1544
+ type: "object",
1545
+ additionalProperties: true,
1546
+ properties: {
1547
+ id: { type: "string" },
1548
+ before: { type: "string", description: "Task id that must complete first." },
1549
+ after: { type: "string", description: "Task id that depends on before." },
1550
+ from: { type: "string", description: "Alias for before." },
1551
+ to: { type: "string", description: "Alias for after." },
1552
+ type: { type: "string" },
1553
+ rationale: { type: "string" }
1554
+ }
1555
+ }
1556
+ },
1557
+ phase_gates: {
1558
+ type: "array",
1559
+ description: "Required non-empty phase gate array.",
1560
+ items: { type: "object", additionalProperties: true }
1561
+ }
1562
+ }
1563
+ },
1564
+ qa_plan: {
1565
+ type: "object",
1566
+ description: "Required for pass. Must include schema_version: 1 and non-empty final_qa coverage.",
1567
+ additionalProperties: true,
1568
+ properties: {
1569
+ schema_version: { type: "number", enum: [1] },
1570
+ final_qa: {
1571
+ type: "array",
1572
+ description: "Required non-empty final QA coverage array.",
1573
+ items: { type: "object", additionalProperties: true }
1574
+ }
1575
+ }
1576
+ },
1577
+ report_markdown: { type: "string", description: "Human-readable Architect report. Use report as an alias only when the client cannot send report_markdown." },
1578
+ report: { type: "string", description: "Alias for report_markdown." },
1579
+ blockers: baseProperties.blockers,
1580
+ revision_questions: {
1581
+ type: "array",
1582
+ description: "Required for needs_revision when blockers are not used.",
1583
+ items: { type: "string" }
1584
+ },
1585
+ revision_reasons: {
1586
+ type: "array",
1587
+ description: "Concrete reasons that prevent pass status.",
1588
+ items: { type: "string" }
1589
+ }
1590
+ }, ["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.");
1591
+ }
591
1592
  return objectToolSchema({
592
1593
  ...baseProperties,
593
1594
  commands: {
@@ -612,9 +1613,147 @@ function toolInputSchema(phase) {
612
1613
  ready_for_dev_test: { type: "boolean", description: "Required for pass and must be true." }
613
1614
  }, ["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
1615
  }
615
- function objectToolSchema(properties, required, description) {
616
- return {
617
- type: "object",
1616
+ function debugToolInputSchema(phase, baseProperties) {
1617
+ if (phase === "debug_repro") {
1618
+ return objectToolSchema({
1619
+ ...baseProperties,
1620
+ repro_steps: {
1621
+ type: "array",
1622
+ description: "Required for pass. Minimal reproduction or characterization steps.",
1623
+ items: { type: "string" }
1624
+ },
1625
+ observed: { type: "string", description: "Observed failure behavior." },
1626
+ expected: { type: "string", description: "Expected behavior." },
1627
+ evidence: {
1628
+ type: "array",
1629
+ description: "Required for pass. Concrete logs, commands, screenshots, file refs, or characterization notes.",
1630
+ items: { type: "object", additionalProperties: true }
1631
+ }
1632
+ }, ["status", "summary"], "For status pass, include repro_steps, observed, expected, and evidence.");
1633
+ }
1634
+ if (phase === "debug_root_cause") {
1635
+ return objectToolSchema({
1636
+ ...baseProperties,
1637
+ root_cause: { type: "string", description: "Likely root cause tied to code or config evidence." },
1638
+ evidence: {
1639
+ type: "array",
1640
+ description: "Required for pass. Concrete code/log/test evidence supporting the root cause.",
1641
+ items: { type: "object", additionalProperties: true }
1642
+ },
1643
+ eliminated_alternatives: {
1644
+ type: "array",
1645
+ description: "Required for pass. Plausible alternatives checked or ruled out.",
1646
+ items: { type: "object", additionalProperties: true }
1647
+ },
1648
+ risk_area: { type: "string", description: "Subsystem or behavior most at risk from the fix." }
1649
+ }, ["status", "summary"], "For status pass, include root_cause, evidence, eliminated_alternatives, and risk_area.");
1650
+ }
1651
+ if (phase === "debug_fix") {
1652
+ return objectToolSchema({
1653
+ ...baseProperties,
1654
+ changed_files: {
1655
+ type: "array",
1656
+ description: "Required for pass. Files changed by the bug fix.",
1657
+ items: evidenceObjectSchema(["path", "summary"], { path: { type: "string" }, summary: { type: "string" } })
1658
+ },
1659
+ tests_added_or_updated: {
1660
+ type: "array",
1661
+ description: "Required for pass. Regression tests or checks added/updated, or justify omission in remaining_risks.",
1662
+ items: evidenceObjectSchema(["path", "summary"], { path: { type: "string" }, summary: { type: "string" } })
1663
+ },
1664
+ remaining_risks: {
1665
+ type: "array",
1666
+ description: "Required for pass, even when empty. Include why no regression coverage changed when tests_added_or_updated is empty.",
1667
+ items: evidenceObjectSchema(["summary"], { summary: { type: "string" }, mitigation: { type: "string" } })
1668
+ },
1669
+ resolved_findings: {
1670
+ type: "array",
1671
+ description: "Required for QA rework. Each entry must use status resolved, disputed, or not_reproduced.",
1672
+ items: resolvedFindingSchema()
1673
+ }
1674
+ }, ["status", "summary"], "For status pass, include changed_files, tests_added_or_updated, and remaining_risks.");
1675
+ }
1676
+ return objectToolSchema({
1677
+ ...baseProperties,
1678
+ commands: {
1679
+ type: "array",
1680
+ description: "Required for pass. Targeted regression/repro-negative commands with exit_code: 0 and status: pass.",
1681
+ items: commandEvidenceSchema()
1682
+ },
1683
+ required_regressions: {
1684
+ type: "array",
1685
+ description: "Required for pass. Repro-negative and regression coverage checklist.",
1686
+ items: { type: "string" }
1687
+ },
1688
+ build_status: { type: "string", description: "Required for pass. pass or not_applicable." },
1689
+ test_status: { type: "string", description: "Required for pass. pass or not_applicable." },
1690
+ repro_negative: { type: "boolean", description: "Required for pass and must be true after the original repro no longer fails." },
1691
+ qa_ready: { type: "boolean", description: "Required for pass and must be true." }
1692
+ }, ["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.");
1693
+ }
1694
+ function qaGateToolInputSchema(gate) {
1695
+ const baseProperties = {
1696
+ status: {
1697
+ type: "string",
1698
+ enum: ["pass", "skipped", "blocked"],
1699
+ description: "Use pass when this QA gate produced evidence, skipped when not applicable, or blocked when a prerequisite prevents this gate."
1700
+ },
1701
+ summary: { type: "string", description: "Concise QA gate summary." },
1702
+ reason: { type: "string", description: "Required for skipped or blocked gates." },
1703
+ blocker_reason: {
1704
+ type: "string",
1705
+ enum: [...qaBlockerReasons],
1706
+ description: "Required when status is blocked."
1707
+ }
1708
+ };
1709
+ if (gate === "qa_plan") {
1710
+ return objectToolSchema({
1711
+ ...baseProperties,
1712
+ checklist: {
1713
+ type: "array",
1714
+ description: "Required for pass. QA checklist entries planned for this work item.",
1715
+ items: { type: "string" }
1716
+ },
1717
+ acceptance_criteria: {
1718
+ type: "array",
1719
+ description: "Acceptance criteria selected for QA.",
1720
+ items: { type: "string" }
1721
+ }
1722
+ }, ["status", "summary"], "Record the QA plan gate. Pass requires a non-empty checklist.");
1723
+ }
1724
+ if (gate === "qa_findings") {
1725
+ return objectToolSchema({
1726
+ ...baseProperties,
1727
+ findings: {
1728
+ type: "array",
1729
+ description: "Normalized in-scope and out-of-scope QA findings.",
1730
+ items: { type: "object", additionalProperties: true }
1731
+ },
1732
+ candidate_bugs: {
1733
+ type: "array",
1734
+ description: "Out-of-scope or follow-up candidates.",
1735
+ items: { type: "object", additionalProperties: true }
1736
+ }
1737
+ }, ["status", "summary"], "Record normalized QA findings. Pass or skipped requires findings and candidate_bugs arrays, even when empty.");
1738
+ }
1739
+ return objectToolSchema({
1740
+ ...baseProperties,
1741
+ commands: {
1742
+ type: "array",
1743
+ description: "Command evidence for this gate when applicable.",
1744
+ items: commandEvidenceSchema()
1745
+ },
1746
+ browser_checks: {
1747
+ type: "array",
1748
+ description: "Browser/manual evidence for this gate when applicable.",
1749
+ items: { type: "object", additionalProperties: true }
1750
+ },
1751
+ notes: { type: "string", description: "Evidence notes for this gate." }
1752
+ }, ["status", "summary"], "Record this QA evidence gate. Use skipped with a reason when the gate is not applicable.");
1753
+ }
1754
+ function objectToolSchema(properties, required, description) {
1755
+ return {
1756
+ type: "object",
618
1757
  additionalProperties: true,
619
1758
  description,
620
1759
  properties,
@@ -637,6 +1776,29 @@ function commandEvidenceSchema() {
637
1776
  summary: { type: "string" }
638
1777
  });
639
1778
  }
1779
+ function resolvedFindingSchema() {
1780
+ return evidenceObjectSchema([
1781
+ "qa_id",
1782
+ "status",
1783
+ "summary",
1784
+ "evidence",
1785
+ "changed_files",
1786
+ "tests_added_or_updated",
1787
+ "regression_evidence"
1788
+ ], {
1789
+ qa_id: { type: "string" },
1790
+ status: {
1791
+ type: "string",
1792
+ enum: [...resolvedFindingStatusValues],
1793
+ description: "Use resolved when fixed, disputed when the QA finding is incorrect/out-of-scope, or not_reproduced when retesting cannot reproduce it."
1794
+ },
1795
+ summary: { type: "string" },
1796
+ evidence: { description: "Concrete evidence for the resolution." },
1797
+ changed_files: { type: "array", description: "Required and non-empty when status is resolved." },
1798
+ tests_added_or_updated: { type: "array", description: "Required and non-empty when status is resolved." },
1799
+ regression_evidence: { description: "Concrete regression evidence for this QA finding." }
1800
+ });
1801
+ }
640
1802
  function acceptanceCriteriaSchema() {
641
1803
  return {
642
1804
  type: "array",
@@ -662,8 +1824,22 @@ function reviewSectionProperties() {
662
1824
  notes: { type: "string" }
663
1825
  };
664
1826
  }
665
- function normalizeCompletionStatus(value) {
1827
+ function normalizeCompletionStatus(value, phase) {
666
1828
  const normalized = value.trim().toLowerCase().replace(/-/g, "_");
1829
+ if (phase === "qa") {
1830
+ const canonical = normalized === "needsrework" ? "needs_rework" : normalized;
1831
+ if (canonical !== "pass" && canonical !== "needs_rework" && canonical !== "blocked") {
1832
+ throw new Error("QA status must be pass, needs_rework, or blocked.");
1833
+ }
1834
+ return canonical;
1835
+ }
1836
+ if (phase === "architect") {
1837
+ const canonical = normalized === "needsrevision" ? "needs_revision" : normalized;
1838
+ if (canonical !== "pass" && canonical !== "needs_revision" && canonical !== "blocked") {
1839
+ throw new Error("Architect status must be pass, needs_revision, or blocked.");
1840
+ }
1841
+ return canonical;
1842
+ }
667
1843
  const canonical = normalized === "blocked" || normalized === "needsrework"
668
1844
  ? "needs_rework"
669
1845
  : normalized === "failed"
@@ -674,17 +1850,36 @@ function normalizeCompletionStatus(value) {
674
1850
  }
675
1851
  return canonical;
676
1852
  }
1853
+ function normalizeQaGateStatus(value) {
1854
+ const normalized = value.trim().toLowerCase().replace(/-/g, "_");
1855
+ if (normalized !== "pass" && normalized !== "skipped" && normalized !== "blocked") {
1856
+ throw new Error("QA gate status must be pass, skipped, or blocked.");
1857
+ }
1858
+ return normalized;
1859
+ }
677
1860
  function validatePayloadShape(phase, payload) {
678
- const status = normalizeCompletionStatus(requiredString(payload, "status"));
1861
+ const status = normalizeCompletionStatus(requiredString(payload, "status"), phase);
679
1862
  if (!status) {
680
1863
  throw new Error("status is required.");
681
1864
  }
682
- const pass = status === "pass";
683
1865
  requireField(payload, "summary");
1866
+ if (phase === "qa") {
1867
+ validateQaPayloadShape(payload, status);
1868
+ return;
1869
+ }
1870
+ if (phase === "architect") {
1871
+ validateArchitectPayloadShape(payload, status);
1872
+ return;
1873
+ }
1874
+ const pass = status === "pass";
684
1875
  if (!pass) {
685
1876
  requireNonPassEvidence(payload);
686
1877
  return;
687
1878
  }
1879
+ if (isDebugCompletionPhase(phase)) {
1880
+ validateDebugPayloadShape(phase, payload);
1881
+ return;
1882
+ }
688
1883
  if (phase === "implementation") {
689
1884
  requireArray(payload, "plan");
690
1885
  requireArray(payload, "changed_files");
@@ -695,6 +1890,7 @@ function validatePayloadShape(phase, payload) {
695
1890
  requireField(payload, "next_phase_context");
696
1891
  requireImplementationEvidence(payload);
697
1892
  requireSatisfiedAcceptanceCriteria(payload);
1893
+ validateResolvedFindings(payload);
698
1894
  return;
699
1895
  }
700
1896
  if (phase === "self_review") {
@@ -722,6 +1918,366 @@ function validatePayloadShape(phase, payload) {
722
1918
  requirePassingCommands(payload);
723
1919
  requireSatisfiedAcceptanceCriteria(payload);
724
1920
  }
1921
+ function validateDebugPayloadShape(phase, payload) {
1922
+ if (phase === "debug_repro") {
1923
+ requireArray(payload, "repro_steps");
1924
+ requireField(payload, "observed");
1925
+ requireField(payload, "expected");
1926
+ requireArray(payload, "evidence");
1927
+ requireNonEmptyArray(payload, "repro_steps");
1928
+ requireNonEmptyArray(payload, "evidence");
1929
+ return;
1930
+ }
1931
+ if (phase === "debug_root_cause") {
1932
+ requireField(payload, "root_cause");
1933
+ requireArray(payload, "evidence");
1934
+ requireArray(payload, "eliminated_alternatives");
1935
+ requireField(payload, "risk_area");
1936
+ requireNonEmptyArray(payload, "evidence");
1937
+ return;
1938
+ }
1939
+ if (phase === "debug_fix") {
1940
+ requireArray(payload, "changed_files");
1941
+ requireArray(payload, "tests_added_or_updated");
1942
+ requireArray(payload, "remaining_risks");
1943
+ requireNonEmptyArray(payload, "changed_files");
1944
+ if (arrayLength(payload, "tests_added_or_updated") === 0 && arrayLength(payload, "remaining_risks") === 0) {
1945
+ throw new Error("tests_added_or_updated is empty; remaining_risks must explain why no regression coverage changed.");
1946
+ }
1947
+ validateResolvedFindings(payload);
1948
+ return;
1949
+ }
1950
+ requireArray(payload, "commands");
1951
+ requireArray(payload, "required_regressions");
1952
+ requireField(payload, "build_status");
1953
+ requireField(payload, "test_status");
1954
+ requireBoolean(payload, "repro_negative");
1955
+ requireBoolean(payload, "qa_ready");
1956
+ if (payload.repro_negative !== true) {
1957
+ throw new Error("debug_regression pass requires repro_negative: true.");
1958
+ }
1959
+ if (payload.qa_ready !== true) {
1960
+ throw new Error("debug_regression pass requires qa_ready: true.");
1961
+ }
1962
+ requireAllowedStatus(payload, "build_status", ["pass", "not_applicable"]);
1963
+ requireAllowedStatus(payload, "test_status", ["pass", "not_applicable"]);
1964
+ requireNonEmptyArray(payload, "required_regressions");
1965
+ requirePassingCommands(payload);
1966
+ }
1967
+ function validateQaGatePayloadShape(gate, payload, status) {
1968
+ requireField(payload, "summary");
1969
+ if (status === "skipped") {
1970
+ requireField(payload, "reason");
1971
+ }
1972
+ if (status === "blocked") {
1973
+ const reason = normalizedString(optionalString(payload, "blocker_reason"));
1974
+ if (!qaBlockerReasons.has(reason)) {
1975
+ 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.");
1976
+ }
1977
+ }
1978
+ if (gate === "qa_plan" && status === "pass") {
1979
+ const checklist = qaStringArray(payload, "checklist");
1980
+ if (checklist.length === 0) {
1981
+ throw new Error("complete_qa_plan pass requires checklist with at least one entry.");
1982
+ }
1983
+ }
1984
+ if (gate === "qa_findings" && status !== "blocked") {
1985
+ qaObjectArray(payload, "findings");
1986
+ qaObjectArray(payload, "candidate_bugs");
1987
+ }
1988
+ if ((gate === "qa_regression" || gate === "qa_api") && status === "pass") {
1989
+ const commands = qaArray(payload, "commands");
1990
+ if (commands.length === 0) {
1991
+ throw new Error(`${qaGateToolNames[gate]} pass requires commands with at least one entry.`);
1992
+ }
1993
+ }
1994
+ if (gate === "qa_manual_web" && status === "pass") {
1995
+ const browserChecks = qaArray(payload, "browser_checks");
1996
+ const notes = optionalString(payload, "notes");
1997
+ if (browserChecks.length === 0 && !notes) {
1998
+ throw new Error(`${qaGateToolNames[gate]} pass requires browser_checks or notes.`);
1999
+ }
2000
+ }
2001
+ }
2002
+ function validateArchitectPayloadShape(payload, status) {
2003
+ if (status !== "pass") {
2004
+ requireArchitectNonPassEvidence(payload);
2005
+ return;
2006
+ }
2007
+ const implementationPlan = requiredRecord(payload, "implementation_plan");
2008
+ const qaPlan = requiredRecord(payload, "qa_plan");
2009
+ requireNumericOne(implementationPlan, "schema_version", "implementation_plan.schema_version");
2010
+ requireNonEmptyStringRecord(implementationPlan, "plan_id", "implementation_plan.");
2011
+ requireArchitectArray(implementationPlan, "phases", payload);
2012
+ requireArchitectArray(implementationPlan, "tasks", payload);
2013
+ requireArchitectArray(implementationPlan, "dependencies", payload, { allowEmpty: true });
2014
+ requireArchitectArray(implementationPlan, "phase_gates", payload);
2015
+ if (arrayLength(implementationPlan, "tasks") === 0) {
2016
+ throw new Error("implementation_plan.tasks: expected non-empty array; correction: include at least one task with id and tests.");
2017
+ }
2018
+ const taskIds = new Set();
2019
+ for (const task of implementationPlan.tasks) {
2020
+ if (!task || typeof task !== "object" || Array.isArray(task)) {
2021
+ throw new Error("implementation_plan.tasks[]: expected object entries; correction: each task must be an object with id and tests.");
2022
+ }
2023
+ const taskRecord = task;
2024
+ requireNonEmptyStringRecord(taskRecord, "id", "implementation_plan.tasks[].");
2025
+ const taskId = optionalString(taskRecord, "id") ?? "";
2026
+ if (taskIds.has(taskId)) {
2027
+ throw new Error(`implementation_plan.tasks: duplicate task id '${taskId}'.`);
2028
+ }
2029
+ taskIds.add(taskId);
2030
+ requireArchitectArray(taskRecord, "tests", payload, { path: `implementation_plan.tasks[${optionalString(taskRecord, "id") ?? "?"}].tests` });
2031
+ if (arrayLength(taskRecord, "tests") === 0) {
2032
+ throw new Error(`implementation_plan.tasks[${optionalString(taskRecord, "id") ?? "?"}].tests: expected non-empty array; correction: include task-specific verification.`);
2033
+ }
2034
+ }
2035
+ validateAndNormalizeArchitectDependencies(implementationPlan, taskIds);
2036
+ requireNumericOne(qaPlan, "schema_version", "qa_plan.schema_version");
2037
+ requireArchitectArray(qaPlan, "final_qa", payload, { path: "qa_plan.final_qa" });
2038
+ if (arrayLength(qaPlan, "final_qa") === 0) {
2039
+ throw new Error("qa_plan.final_qa: expected non-empty array; correction: include final QA coverage for the completed plan.");
2040
+ }
2041
+ }
2042
+ function validateAndNormalizeArchitectDependencies(implementationPlan, taskIds) {
2043
+ const dependencies = implementationPlan.dependencies;
2044
+ const edges = new Map();
2045
+ for (const taskId of taskIds) {
2046
+ edges.set(taskId, []);
2047
+ }
2048
+ const normalizedDependencies = [];
2049
+ for (const [index, dependency] of dependencies.entries()) {
2050
+ if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) {
2051
+ throw new Error("implementation_plan.dependencies[]: expected object entries; correction: each dependency must be an object with before and after task ids.");
2052
+ }
2053
+ const record = dependency;
2054
+ const before = architectDependencyEndpoint(record, index, "before", "from");
2055
+ const after = architectDependencyEndpoint(record, index, "after", "to");
2056
+ if (!taskIds.has(before) || !taskIds.has(after)) {
2057
+ throw new Error("implementation_plan.dependencies: dependency references an unknown task id.");
2058
+ }
2059
+ const normalized = stripUndefined({
2060
+ ...record,
2061
+ before,
2062
+ after,
2063
+ from: undefined,
2064
+ to: undefined
2065
+ });
2066
+ normalizedDependencies.push(normalized);
2067
+ edges.get(before)?.push(after);
2068
+ }
2069
+ implementationPlan.dependencies = normalizedDependencies;
2070
+ if (hasArchitectDependencyCycle(edges)) {
2071
+ throw new Error("implementation_plan.dependencies: expected acyclic graph; correction: remove or revise cyclic task dependencies.");
2072
+ }
2073
+ }
2074
+ function architectDependencyEndpoint(dependency, index, canonicalKey, aliasKey) {
2075
+ const canonical = optionalString(dependency, canonicalKey);
2076
+ const alias = optionalString(dependency, aliasKey);
2077
+ if (canonical && alias && canonical !== alias) {
2078
+ throw new Error(`implementation_plan.dependencies[${index}].${canonicalKey}: conflicts with ${aliasKey}; correction: use one task id for ${canonicalKey}.`);
2079
+ }
2080
+ const value = canonical ?? alias;
2081
+ if (!value) {
2082
+ throw new Error(`implementation_plan.dependencies[${index}].${canonicalKey}: expected string; correction: use before and after task ids for each dependency.`);
2083
+ }
2084
+ return value;
2085
+ }
2086
+ function hasArchitectDependencyCycle(edges) {
2087
+ const visiting = new Set();
2088
+ const visited = new Set();
2089
+ const visit = (node) => {
2090
+ if (visited.has(node)) {
2091
+ return false;
2092
+ }
2093
+ if (visiting.has(node)) {
2094
+ return true;
2095
+ }
2096
+ visiting.add(node);
2097
+ for (const next of edges.get(node) ?? []) {
2098
+ if (visit(next)) {
2099
+ return true;
2100
+ }
2101
+ }
2102
+ visiting.delete(node);
2103
+ visited.add(node);
2104
+ return false;
2105
+ };
2106
+ for (const node of edges.keys()) {
2107
+ if (visit(node)) {
2108
+ return true;
2109
+ }
2110
+ }
2111
+ return false;
2112
+ }
2113
+ function requireArchitectNonPassEvidence(payload) {
2114
+ const evidenceKeys = ["blockers", "revision_questions", "revision_reasons", "known_gaps", "findings", "remaining_risks", "failures"];
2115
+ const hasEvidence = evidenceKeys.some((key) => {
2116
+ const value = payload[key];
2117
+ if (typeof value === "string") {
2118
+ return value.trim().length > 0;
2119
+ }
2120
+ if (Array.isArray(value)) {
2121
+ return value.length > 0;
2122
+ }
2123
+ return Boolean(value && typeof value === "object");
2124
+ });
2125
+ if (!hasEvidence) {
2126
+ 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.");
2127
+ }
2128
+ }
2129
+ function requireArchitectArray(source, key, rootPayload, options = {}) {
2130
+ const pathLabel = options.path ?? `implementation_plan.${key}`;
2131
+ if (!Array.isArray(source[key])) {
2132
+ const nestedHint = architectNestedArrayHint(rootPayload, key);
2133
+ 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"}.`}`);
2134
+ }
2135
+ if (!options.allowEmpty && arrayLength(source, key) === 0) {
2136
+ throw new Error(`${pathLabel}: expected non-empty array; correction: include at least one entry.`);
2137
+ }
2138
+ }
2139
+ function architectNestedArrayHint(rootPayload, key) {
2140
+ if (Array.isArray(rootPayload[key])) {
2141
+ return `move top-level ${key} into implementation_plan.${key}.`;
2142
+ }
2143
+ const implementationPlan = rootPayload.implementation_plan;
2144
+ if (!implementationPlan || typeof implementationPlan !== "object" || Array.isArray(implementationPlan)) {
2145
+ return null;
2146
+ }
2147
+ const plan = implementationPlan;
2148
+ for (const container of ["plan", "dag", "implementation_dag", "implementationPlan", "implementation_plan"]) {
2149
+ const nested = plan[container];
2150
+ if (nested && typeof nested === "object" && !Array.isArray(nested) && Array.isArray(nested[key])) {
2151
+ return `move implementation_plan.${container}.${key} to implementation_plan.${key}.`;
2152
+ }
2153
+ }
2154
+ return null;
2155
+ }
2156
+ function validateQaPayloadShape(payload, status) {
2157
+ const evidenceSource = qaEvidenceSource(payload);
2158
+ const commands = qaArray(payload, "commands", evidenceSource);
2159
+ const browserChecks = qaArray(payload, "browser_checks", evidenceSource);
2160
+ const sidecars = qaArray(payload, "sidecars", evidenceSource);
2161
+ const notes = optionalString(payload, "notes") ?? optionalString(evidenceSource, "notes") ?? "";
2162
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
2163
+ const findings = qaObjectArray(payload, "findings");
2164
+ const candidateBugs = qaObjectArray(payload, "candidate_bugs");
2165
+ const explicitFindingIds = qaStringArray(payload, "finding_ids");
2166
+ const explicitCandidateBugIds = qaStringArray(payload, "candidate_bug_ids");
2167
+ if (payload.schema_version !== undefined && payload.schema_version !== 1) {
2168
+ throw new Error("QA schema_version must be numeric 1 when provided.");
2169
+ }
2170
+ if (status === "pass" || status === "needs_rework") {
2171
+ if (testedAcceptanceCriteria.length === 0) {
2172
+ throw new Error("QA pass/needs_rework requires tested_acceptance_criteria with at least one criterion.");
2173
+ }
2174
+ if (commands.length === 0 && browserChecks.length === 0 && notes.length === 0) {
2175
+ throw new Error("QA pass/needs_rework requires at least one command, browser check, or evidence note.");
2176
+ }
2177
+ }
2178
+ for (const [index, command] of commands.entries()) {
2179
+ requireEvidenceRecord(command, `commands[${index}]`);
2180
+ const record = command;
2181
+ requireNonEmptyStringRecord(record, "command", `commands[${index}].`);
2182
+ requireNonEmptyStringRecord(record, "status", `commands[${index}].`);
2183
+ requireNonEmptyStringRecord(record, "summary", `commands[${index}].`);
2184
+ if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
2185
+ throw new Error(`commands[${index}].exit_code is required.`);
2186
+ }
2187
+ if (status === "pass" && record.exit_code !== 0) {
2188
+ throw new Error(`commands[${index}].exit_code must be 0 when QA status is pass.`);
2189
+ }
2190
+ if (status === "pass" && normalizedString(record.status) !== "pass") {
2191
+ throw new Error(`commands[${index}].status must be pass when QA status is pass.`);
2192
+ }
2193
+ }
2194
+ for (const [index, browserCheck] of browserChecks.entries()) {
2195
+ requireEvidenceRecord(browserCheck, `browser_checks[${index}]`);
2196
+ const record = browserCheck;
2197
+ requireNonEmptyStringRecord(record, "summary", `browser_checks[${index}].`);
2198
+ requireNonEmptyStringRecord(record, "status", `browser_checks[${index}].`);
2199
+ const checkStatus = optionalString(record, "status");
2200
+ if (status === "pass" && checkStatus && normalizedString(checkStatus) !== "pass") {
2201
+ throw new Error(`browser_checks[${index}].status must be pass when QA status is pass.`);
2202
+ }
2203
+ if (!optionalString(record, "url") && !optionalString(record, "route")) {
2204
+ throw new Error(`browser_checks[${index}] must include url or route.`);
2205
+ }
2206
+ }
2207
+ for (const [index, sidecar] of sidecars.entries()) {
2208
+ requireEvidenceRecord(sidecar, `sidecars[${index}]`);
2209
+ const record = sidecar;
2210
+ requireNonEmptyStringRecord(record, "path", `sidecars[${index}].`);
2211
+ requireNonEmptyStringRecord(record, "content_hash", `sidecars[${index}].`);
2212
+ if (typeof record.bytes !== "number" || !Number.isFinite(record.bytes) || record.bytes <= 0) {
2213
+ throw new Error(`sidecars[${index}].bytes must be greater than 0.`);
2214
+ }
2215
+ }
2216
+ for (const [index, finding] of findings.entries()) {
2217
+ requireNonEmptyStringRecord(finding, "id", `findings[${index}].`);
2218
+ requireNonEmptyStringRecord(finding, "title", `findings[${index}].`);
2219
+ requireKnownStringRecord(finding, "severity", qaFindingSeverities, `findings[${index}].`);
2220
+ requireKnownStringRecord(finding, "scope", qaFindingScopes, `findings[${index}].`);
2221
+ if (normalizedString(finding.scope) === "in_scope") {
2222
+ validateActionableQaFinding(finding, index);
2223
+ }
2224
+ }
2225
+ for (const [index, candidateBug] of candidateBugs.entries()) {
2226
+ requireNonEmptyStringRecord(candidateBug, "id", `candidate_bugs[${index}].`);
2227
+ requireNonEmptyStringRecord(candidateBug, "title", `candidate_bugs[${index}].`);
2228
+ requireKnownStringRecord(candidateBug, "suggested_action", qaCandidateBugActions, `candidate_bugs[${index}].`);
2229
+ }
2230
+ const inScopeFindingIds = findings
2231
+ .filter((finding) => normalizedString(finding.scope) === "in_scope")
2232
+ .map((finding) => optionalString(finding, "id"))
2233
+ .filter((id) => Boolean(id));
2234
+ for (const findingId of explicitFindingIds) {
2235
+ if (!inScopeFindingIds.includes(findingId)) {
2236
+ throw new Error(`QA finding_ids contains '${findingId}', but findings has no matching in-scope finding.`);
2237
+ }
2238
+ }
2239
+ const candidateBugIds = candidateBugs
2240
+ .map((candidateBug) => optionalString(candidateBug, "id"))
2241
+ .filter((id) => Boolean(id));
2242
+ for (const candidateBugId of explicitCandidateBugIds) {
2243
+ if (!candidateBugIds.includes(candidateBugId)) {
2244
+ throw new Error(`QA candidate_bug_ids contains '${candidateBugId}', but candidate_bugs has no matching candidate bug.`);
2245
+ }
2246
+ }
2247
+ if (status === "pass") {
2248
+ if (explicitFindingIds.length > 0 || inScopeFindingIds.length > 0) {
2249
+ throw new Error("QA pass must not include in-scope finding_ids or in-scope findings.");
2250
+ }
2251
+ if (optionalString(payload, "blocker_reason")) {
2252
+ throw new Error("QA pass must not include blocker_reason.");
2253
+ }
2254
+ }
2255
+ if (status === "needs_rework") {
2256
+ if (inScopeFindingIds.length === 0) {
2257
+ throw new Error("QA needs_rework requires at least one actionable in-scope finding.");
2258
+ }
2259
+ if (optionalString(payload, "blocker_reason")) {
2260
+ throw new Error("QA needs_rework must not include blocker_reason.");
2261
+ }
2262
+ }
2263
+ if (status === "blocked") {
2264
+ const reason = normalizedString(optionalString(payload, "blocker_reason"));
2265
+ if (!qaBlockerReasons.has(reason)) {
2266
+ 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.");
2267
+ }
2268
+ }
2269
+ }
2270
+ function validateActionableQaFinding(finding, index) {
2271
+ const prefix = `findings[${index}].`;
2272
+ requireNonEmptyStringArrayRecord(finding, "acceptance_criteria", prefix);
2273
+ requireNonEmptyStringArrayRecord(finding, "repro_steps", prefix);
2274
+ requireNonEmptyStringRecord(finding, "expected", prefix);
2275
+ requireNonEmptyStringRecord(finding, "actual", prefix);
2276
+ requireSubstantiveEvidenceRecord(finding, prefix);
2277
+ requireNonEmptyStringArrayRecord(finding, "likely_area", prefix);
2278
+ requireNonEmptyStringRecord(finding, "required_fix", prefix);
2279
+ requireNonEmptyStringRecord(finding, "required_regression", prefix);
2280
+ }
725
2281
  function validateOptionalWorkItemId(payload, expectedWorkItemId) {
726
2282
  const actual = optionalString(payload, "work_item_id") ?? optionalString(payload, "workItemId");
727
2283
  if (actual && actual !== expectedWorkItemId) {
@@ -736,8 +2292,34 @@ function normalizeArtifactPayload(payload, defaults) {
736
2292
  normalized.schema_version = numberOrDefault(normalized.schema_version, 1);
737
2293
  normalized.phase = defaults.phase;
738
2294
  normalized.work_item_id = defaults.workItemId;
2295
+ const ownerFields = artifactOwnerFields(defaults);
2296
+ Object.assign(normalized, ownerFields);
2297
+ normalized.status = defaults.status;
2298
+ normalized.produced_by = defaults.producedBy;
2299
+ return normalized;
2300
+ }
2301
+ function normalizeQaGateArtifactPayload(payload, defaults) {
2302
+ const normalized = stripUndefined({ ...payload });
2303
+ delete normalized.report_markdown;
2304
+ delete normalized.content_hash;
2305
+ delete normalized.contentHash;
2306
+ normalized.schema_version = numberOrDefault(normalized.schema_version, 1);
2307
+ normalized.phase = "qa";
2308
+ normalized.gate = defaults.gate;
2309
+ normalized.work_item_id = defaults.workItemId;
2310
+ const ownerFields = artifactOwnerFields(defaults);
2311
+ Object.assign(normalized, ownerFields);
739
2312
  normalized.status = defaults.status;
740
2313
  normalized.produced_by = defaults.producedBy;
2314
+ if (defaults.gate === "qa_plan") {
2315
+ const checklist = qaStringArray(normalized, "checklist");
2316
+ normalized.checklist = checklist.length > 0 ? checklist : defaultQaChecklist(defaults.status);
2317
+ normalized.acceptance_criteria = qaStringArray(normalized, "acceptance_criteria");
2318
+ }
2319
+ if (defaults.gate === "qa_findings") {
2320
+ normalized.findings = qaObjectArray(normalized, "findings");
2321
+ normalized.candidate_bugs = qaObjectArray(normalized, "candidate_bugs");
2322
+ }
741
2323
  return normalized;
742
2324
  }
743
2325
  function reportMarkdown(payload, phase, status, producedBy, contentHash) {
@@ -759,6 +2341,10 @@ ${summary}
759
2341
  }
760
2342
  function parseStrictCompletionPhase(value) {
761
2343
  const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
2344
+ const debugPhase = normalizeDebugCompletionPhase(normalized);
2345
+ if (debugPhase) {
2346
+ return debugPhase;
2347
+ }
762
2348
  if (normalized === "implementation" || normalized === "implement" || normalized === "develop") {
763
2349
  return "implementation";
764
2350
  }
@@ -768,8 +2354,51 @@ function parseStrictCompletionPhase(value) {
768
2354
  if (normalized === "validate" || normalized === "validation") {
769
2355
  return "validation";
770
2356
  }
2357
+ if (normalized === "qa" || normalized === "quality_assurance" || normalized === "qualityassurance") {
2358
+ return "qa";
2359
+ }
2360
+ if (normalized === "architect" || normalized === "architect_plan" || normalized === "planning" || normalized === "plan") {
2361
+ return "architect";
2362
+ }
771
2363
  return null;
772
2364
  }
2365
+ function normalizeDebugCompletionPhase(value) {
2366
+ const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
2367
+ switch (normalized) {
2368
+ case "debug_repro":
2369
+ case "debugrepro":
2370
+ case "repro":
2371
+ case "reproduce":
2372
+ return "debug_repro";
2373
+ case "debug_root_cause":
2374
+ case "debugrootcause":
2375
+ case "root_cause":
2376
+ case "rootcause":
2377
+ return "debug_root_cause";
2378
+ case "debug_fix":
2379
+ case "debugfix":
2380
+ case "fix":
2381
+ return "debug_fix";
2382
+ case "debug_regression":
2383
+ case "debugregression":
2384
+ case "regression":
2385
+ return "debug_regression";
2386
+ default:
2387
+ return null;
2388
+ }
2389
+ }
2390
+ function isDevelopCompletionPhase(phase) {
2391
+ return phase === "implementation" || phase === "self_review" || phase === "validation";
2392
+ }
2393
+ function isDebugCompletionPhase(phase) {
2394
+ return debugCompletionPhaseOrder.includes(phase);
2395
+ }
2396
+ function asDebugCompletionPhase(phase) {
2397
+ if (isDebugCompletionPhase(phase)) {
2398
+ return phase;
2399
+ }
2400
+ throw new Error(`Expected Debug completion phase, got ${phase}.`);
2401
+ }
773
2402
  function parseCompletionRedactionSecrets(raw) {
774
2403
  if (!raw?.trim()) {
775
2404
  return [];
@@ -796,8 +2425,41 @@ function phaseFromToolName(toolName) {
796
2425
  if (normalized === "forge.complete_validation" || normalized === "complete_validation") {
797
2426
  return "validation";
798
2427
  }
2428
+ if (normalized === "forge.complete_qa" || normalized === "complete_qa") {
2429
+ return "qa";
2430
+ }
2431
+ if (normalized === "forge.complete_architect_plan" || normalized === "complete_architect_plan") {
2432
+ return "architect";
2433
+ }
2434
+ const debugGate = debugGateFromToolName(toolName);
2435
+ if (debugGate) {
2436
+ return debugGate;
2437
+ }
2438
+ if (qaGateFromToolName(toolName)) {
2439
+ return "qa";
2440
+ }
799
2441
  throw new Error(`Unknown Forge completion tool: ${toolName}`);
800
2442
  }
2443
+ function debugGateFromToolName(toolName) {
2444
+ const normalized = toolName.trim().toLowerCase();
2445
+ for (const gate of debugCompletionPhaseOrder) {
2446
+ const base = debugGateToolNames[gate];
2447
+ if (normalized === `forge.${base}` || normalized === base) {
2448
+ return gate;
2449
+ }
2450
+ }
2451
+ return null;
2452
+ }
2453
+ function qaGateFromToolName(toolName) {
2454
+ const normalized = toolName.trim().toLowerCase();
2455
+ for (const gate of qaCompletionGateOrder) {
2456
+ const base = qaGateToolNames[gate];
2457
+ if (normalized === `forge.${base}` || normalized === base) {
2458
+ return gate;
2459
+ }
2460
+ }
2461
+ return null;
2462
+ }
801
2463
  function requireField(payload, key) {
802
2464
  if (payload[key] === undefined || payload[key] === null || (typeof payload[key] === "string" && payload[key].trim().length === 0)) {
803
2465
  throw new Error(`${key} is required.`);
@@ -865,17 +2527,42 @@ function requireArray(payload, key) {
865
2527
  throw new Error(`${key} must be an array.`);
866
2528
  }
867
2529
  }
2530
+ function requireNonEmptyArray(payload, key) {
2531
+ requireArray(payload, key);
2532
+ if (arrayLength(payload, key) === 0) {
2533
+ throw new Error(`${key} must include at least one value.`);
2534
+ }
2535
+ }
2536
+ function arrayLength(payload, key) {
2537
+ const value = payload[key];
2538
+ return Array.isArray(value) ? value.length : 0;
2539
+ }
2540
+ function requireAllowedStatus(payload, key, allowed) {
2541
+ const value = normalizedString(optionalString(payload, key));
2542
+ if (!allowed.includes(value)) {
2543
+ throw new Error(`${key} must be one of ${allowed.join(", ")}.`);
2544
+ }
2545
+ }
868
2546
  function requireObject(payload, key) {
869
2547
  const value = payload[key];
870
2548
  if (!value || typeof value !== "object" || Array.isArray(value)) {
871
2549
  throw new Error(`${key} must be an object.`);
872
2550
  }
873
2551
  }
2552
+ function requiredRecord(payload, key) {
2553
+ requireObject(payload, key);
2554
+ return payload[key];
2555
+ }
874
2556
  function requireBoolean(payload, key) {
875
2557
  if (typeof payload[key] !== "boolean") {
876
2558
  throw new Error(`${key} must be a boolean.`);
877
2559
  }
878
2560
  }
2561
+ function requireNumericOne(payload, key, pathLabel) {
2562
+ if (payload[key] !== 1) {
2563
+ throw new Error(`${pathLabel}: expected numeric 1; correction: set ${pathLabel} to 1.`);
2564
+ }
2565
+ }
879
2566
  function requireSatisfiedAcceptanceCriteria(payload) {
880
2567
  const criteria = payload.acceptance_criteria;
881
2568
  if (!Array.isArray(criteria)) {
@@ -893,6 +2580,183 @@ function requireSatisfiedAcceptanceCriteria(payload) {
893
2580
  }
894
2581
  }
895
2582
  }
2583
+ function validateResolvedFindings(payload) {
2584
+ const resolvedFindings = payload.resolved_findings;
2585
+ if (resolvedFindings === undefined || resolvedFindings === null) {
2586
+ return;
2587
+ }
2588
+ if (!Array.isArray(resolvedFindings)) {
2589
+ throw new Error("resolved_findings must be an array.");
2590
+ }
2591
+ for (const [index, finding] of resolvedFindings.entries()) {
2592
+ const prefix = `resolved_findings[${index}].`;
2593
+ if (!finding || typeof finding !== "object" || Array.isArray(finding)) {
2594
+ throw new Error(`resolved_findings[${index}] must be an object.`);
2595
+ }
2596
+ const record = finding;
2597
+ requireNonEmptyStringRecord(record, "qa_id", prefix);
2598
+ requireKnownStringRecord(record, "status", resolvedFindingStatuses, prefix);
2599
+ requireNonEmptyStringRecord(record, "summary", prefix);
2600
+ requireSubstantiveValueRecord(record, "evidence", prefix);
2601
+ requireArrayRecord(record, "changed_files", prefix);
2602
+ requireArrayRecord(record, "tests_added_or_updated", prefix);
2603
+ requireSubstantiveValueRecord(record, "regression_evidence", prefix);
2604
+ if (normalizedString(record.status) === "resolved") {
2605
+ if (record.changed_files.length === 0) {
2606
+ throw new Error(`${prefix}changed_files must include at least one changed file for resolved QA findings.`);
2607
+ }
2608
+ if (record.tests_added_or_updated.length === 0) {
2609
+ throw new Error(`${prefix}tests_added_or_updated must include at least one regression test for resolved QA findings.`);
2610
+ }
2611
+ }
2612
+ }
2613
+ }
2614
+ function qaEvidenceSource(payload) {
2615
+ const evidence = payload.evidence;
2616
+ return evidence && typeof evidence === "object" && !Array.isArray(evidence)
2617
+ ? evidence
2618
+ : {};
2619
+ }
2620
+ function qaArray(payload, key, fallback = {}) {
2621
+ const value = payload[key] ?? fallback[key];
2622
+ if (value === undefined || value === null) {
2623
+ return [];
2624
+ }
2625
+ if (!Array.isArray(value)) {
2626
+ throw new Error(`${key} must be an array.`);
2627
+ }
2628
+ return value;
2629
+ }
2630
+ function qaObjectArray(payload, key) {
2631
+ return qaArray(payload, key).map((entry, index) => {
2632
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
2633
+ throw new Error(`${key}[${index}] must be an object.`);
2634
+ }
2635
+ return entry;
2636
+ });
2637
+ }
2638
+ function qaStringArray(payload, key) {
2639
+ const value = payload[key];
2640
+ if (value === undefined || value === null) {
2641
+ return [];
2642
+ }
2643
+ if (!Array.isArray(value)) {
2644
+ throw new Error(`${key} must be an array.`);
2645
+ }
2646
+ return value.map((entry, index) => {
2647
+ if (typeof entry !== "string" || entry.trim().length === 0) {
2648
+ throw new Error(`${key}[${index}] must be a non-empty string.`);
2649
+ }
2650
+ return entry;
2651
+ });
2652
+ }
2653
+ function requireEvidenceRecord(value, label) {
2654
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2655
+ throw new Error(`${label} must be an object.`);
2656
+ }
2657
+ }
2658
+ function requireNonEmptyStringRecord(source, key, prefix = "") {
2659
+ if (!optionalString(source, key)) {
2660
+ throw new Error(`${prefix}${key} is required.`);
2661
+ }
2662
+ }
2663
+ function requireArrayRecord(source, key, prefix = "") {
2664
+ if (!Array.isArray(source[key])) {
2665
+ throw new Error(`${prefix}${key} must be an array.`);
2666
+ }
2667
+ }
2668
+ function requireKnownStringRecord(source, key, allowed, prefix = "") {
2669
+ const value = normalizedString(optionalString(source, key));
2670
+ if (!allowed.has(value)) {
2671
+ throw new Error(`${prefix}${key} must be one of ${[...allowed].sort().join(", ")}.`);
2672
+ }
2673
+ }
2674
+ function requireNonEmptyStringArrayRecord(source, key, prefix = "") {
2675
+ const value = source[key];
2676
+ if (!Array.isArray(value) || value.length === 0) {
2677
+ throw new Error(`${prefix}${key} must include at least one value.`);
2678
+ }
2679
+ for (const [index, entry] of value.entries()) {
2680
+ if (typeof entry !== "string" || entry.trim().length === 0) {
2681
+ throw new Error(`${prefix}${key}[${index}] must be a non-empty string.`);
2682
+ }
2683
+ }
2684
+ }
2685
+ function requireSubstantiveValueRecord(source, key, prefix = "") {
2686
+ if (!hasSubstantiveJsonValue(source[key])) {
2687
+ throw new Error(`${prefix}${key} must include at least one concrete evidence reference or summary.`);
2688
+ }
2689
+ }
2690
+ function requireSubstantiveEvidenceRecord(source, prefix = "") {
2691
+ const evidence = source.evidence;
2692
+ if (!evidence || typeof evidence !== "object" || Array.isArray(evidence)) {
2693
+ throw new Error(`${prefix}evidence must be an object.`);
2694
+ }
2695
+ if (!Object.values(evidence).some(hasSubstantiveJsonValue)) {
2696
+ throw new Error(`${prefix}evidence must include at least one concrete evidence reference or summary.`);
2697
+ }
2698
+ }
2699
+ function hasSubstantiveJsonValue(value) {
2700
+ if (typeof value === "string") {
2701
+ return value.trim().length > 0;
2702
+ }
2703
+ if (Array.isArray(value)) {
2704
+ return value.length > 0;
2705
+ }
2706
+ if (value && typeof value === "object") {
2707
+ return Object.keys(value).length > 0;
2708
+ }
2709
+ return false;
2710
+ }
2711
+ function normalizedString(value) {
2712
+ return typeof value === "string" ? value.trim().toLowerCase().replace(/-/g, "_") : "";
2713
+ }
2714
+ function normalizedOwnerType(value) {
2715
+ const normalized = normalizedString(value);
2716
+ return normalized === "work_item" || normalized === "story" ? normalized : undefined;
2717
+ }
2718
+ function artifactOwnerFields(config) {
2719
+ const ownerType = normalizedOwnerType(config.ownerType);
2720
+ const ownerId = config.ownerId?.trim();
2721
+ if (!ownerType && !ownerId) {
2722
+ return {};
2723
+ }
2724
+ return {
2725
+ owner_type: ownerType ?? "work_item",
2726
+ owner_id: ownerId || config.workItemId
2727
+ };
2728
+ }
2729
+ function artifactReferenceOwnerFields(config) {
2730
+ const owner = artifactOwnerFields(config);
2731
+ return owner.owner_type && owner.owner_id
2732
+ ? { ownerType: owner.owner_type, ownerId: owner.owner_id }
2733
+ : {};
2734
+ }
2735
+ function artifactOwnerDirectory(ownerType) {
2736
+ return normalizedOwnerType(ownerType) === "story" ? "stories" : "work-items";
2737
+ }
2738
+ function artifactOwnerRelativeRoot(ownerType, ownerId, workItemId) {
2739
+ const owner = artifactOwnerFields({ workItemId, ownerType, ownerId });
2740
+ return owner.owner_type && owner.owner_id
2741
+ ? [".forge", artifactOwnerDirectory(owner.owner_type), owner.owner_id, "artifacts"].join("/")
2742
+ : [".forge", "work-items", workItemId, "artifacts"].join("/");
2743
+ }
2744
+ function defaultQaChecklist(status) {
2745
+ return [
2746
+ "Review the validated work item against acceptance criteria.",
2747
+ "Inspect implementation, self-review, and validation evidence when available.",
2748
+ status === "blocked" ? "Record the blocker reason preventing a conclusive QA verdict." : "Record concrete QA evidence and findings."
2749
+ ];
2750
+ }
2751
+ function qaArtifactRelativePath(workItemId, fileName) {
2752
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
2753
+ }
2754
+ function qaArtifactRelativePathForOwner(ownerType, ownerId, fileName) {
2755
+ return [".forge", artifactOwnerDirectory(ownerType), ownerId, "artifacts", fileName].join("/");
2756
+ }
2757
+ function jsonText(value) {
2758
+ return `${JSON.stringify(value, null, 2)}\n`;
2759
+ }
896
2760
  function fallbackReport(parsed, phase, artifactPath) {
897
2761
  return `# Forge ${phase.replace(/_/g, " ")} completion
898
2762
 
@@ -905,7 +2769,7 @@ function parseJsonObject(content, label) {
905
2769
  return asRecord(JSON.parse(content), label);
906
2770
  }
907
2771
  catch (error) {
908
- throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`);
2772
+ throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`, { cause: error });
909
2773
  }
910
2774
  }
911
2775
  function parseOptionalJsonObject(content, label) {