@loucompanion/forge-bridge 0.1.1-dev.af36c7fa102b → 0.1.1-dev.cada6731ecc7

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