@loucompanion/forge-bridge 0.1.1-dev.615630fb4618 → 0.1.1-dev.718bdb0018b9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,21 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { redactSecrets } from "../shared/redaction/redaction.js";
6
+ import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
6
7
  const toolServerName = "forge";
7
8
  const completionRedactionSecretsEnv = "FORGE_COMPLETION_REDACTION_SECRETS";
9
+ const completionPhaseOrder = ["implementation", "self_review", "validation"];
10
+ const qaBlockerReasons = new Set([
11
+ "missing_app_launch_target",
12
+ "inconclusive",
13
+ "environment_failure",
14
+ "missing_validation_evidence",
15
+ "missing_worktree",
16
+ "runner_failure"
17
+ ]);
18
+ const qaFindingSeverities = new Set(["critical", "major", "minor"]);
19
+ const qaFindingScopes = new Set(["in_scope", "out_of_scope", "unclear"]);
20
+ const qaCandidateBugActions = new Set(["create_bug", "create_follow_up", "accept_risk", "attach_to_current_item"]);
8
21
  const phaseFiles = {
9
22
  implementation: {
10
23
  jsonFileName: "implementation.completeness.json",
@@ -17,6 +30,10 @@ const phaseFiles = {
17
30
  validation: {
18
31
  jsonFileName: "validation.verdict.json",
19
32
  reportFileName: "validation.report.md"
33
+ },
34
+ qa: {
35
+ jsonFileName: "qa.verdict.json",
36
+ reportFileName: "qa.report.md"
20
37
  }
21
38
  };
22
39
  export function completionPhaseFromDispatch(dispatch) {
@@ -30,14 +47,28 @@ export function normalizeCompletionPhase(value) {
30
47
  if (normalized === "validate" || normalized === "validation") {
31
48
  return "validation";
32
49
  }
50
+ if (normalized === "qa" || normalized === "quality_assurance" || normalized === "qualityassurance") {
51
+ return "qa";
52
+ }
33
53
  return "implementation";
34
54
  }
55
+ export function usesDevelopCycleCompletion(dispatch) {
56
+ const kind = dispatch.cycleRun.kind.trim().toLowerCase();
57
+ const role = dispatch.execution.role.trim().toLowerCase();
58
+ const lane = dispatch.execution.lane.trim().toLowerCase();
59
+ return kind === "develop"
60
+ && role === "develop"
61
+ && lane === "develop"
62
+ && completionPhaseFromDispatch(dispatch) === "implementation";
63
+ }
35
64
  export function completionToolNamesForPhase(phase) {
36
65
  const base = phase === "implementation"
37
66
  ? "complete_implementation"
38
67
  : phase === "self_review"
39
68
  ? "complete_self_review"
40
- : "complete_validation";
69
+ : phase === "validation"
70
+ ? "complete_validation"
71
+ : "complete_qa";
41
72
  return [`forge.${base}`, base];
42
73
  }
43
74
  export function expectedCompletionToolName(phase) {
@@ -60,7 +91,8 @@ export async function prepareCompletionToolRuntime(options) {
60
91
  worktreePath,
61
92
  workItemId,
62
93
  phase,
63
- producedBy: `${options.dispatch.execution.provider}-cli`
94
+ producedBy: `${options.dispatch.execution.provider}-cli`,
95
+ developCycle: usesDevelopCycleCompletion(options.dispatch)
64
96
  });
65
97
  const runtime = {
66
98
  serverName: toolServerName,
@@ -75,7 +107,7 @@ export async function prepareCompletionToolRuntime(options) {
75
107
  return await prepareCursorCompletionToolRuntime(worktreePath, runtime);
76
108
  }
77
109
  export function buildCompletionToolServerArgs(config) {
78
- return [
110
+ const args = [
79
111
  "mcp",
80
112
  "--worktree",
81
113
  path.resolve(config.worktreePath),
@@ -86,6 +118,10 @@ export function buildCompletionToolServerArgs(config) {
86
118
  "--produced-by",
87
119
  config.producedBy ?? "forge-completion-tool"
88
120
  ];
121
+ if (config.developCycle) {
122
+ args.push("--develop-cycle");
123
+ }
124
+ return args;
89
125
  }
90
126
  export function codexMcpConfigArgs(runtime) {
91
127
  const prefix = `mcp_servers.${runtime.serverName}`;
@@ -111,25 +147,122 @@ export function completionPromptForPhase(phase) {
111
147
  const toolName = expectedCompletionToolName(phase);
112
148
  const alias = completionToolNamesForPhase(phase).find((name) => name !== toolName);
113
149
  const artifactName = phaseFiles[phase].jsonFileName;
150
+ if (phase === "qa") {
151
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
152
+ 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.
153
+ 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\`.
154
+ 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.
155
+ Forge will mirror only the tool-written QA artifacts; reporting QA completion in prose is not enough.`;
156
+ }
114
157
  return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
115
158
  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.
116
159
  That tool writes \`.forge/work-items/{workItemId}/artifacts/${artifactName}\` and returns the artifact reference that Forge will mirror through the existing phase-artifact pipeline.
117
160
  If the work cannot pass, call the same tool with a non-pass status and explicit blockers instead of reporting completion in prose only.`;
118
161
  }
162
+ export function completionPromptForDevelopCycle(phase) {
163
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
164
+ Do not write phase artifacts by hand. The tool server enforces phase order and starts this run in \`${phase}\`.
165
+ Complete the dev cycle in order inside this same provider session:
166
+ 1. Call \`forge.complete_implementation(...)\` when implementation evidence is ready.
167
+ 2. Follow the returned self-review instruction, then call \`forge.complete_self_review(...)\`.
168
+ 3. Follow the returned validation instruction, then call \`forge.complete_validation(...)\`.
169
+ Each tool writes the canonical artifact under \`.forge/work-items/{workItemId}/artifacts/\` and returns the next-phase instruction Forge expects you to follow.
170
+ 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.`;
171
+ }
172
+ export function completionToolNamesForServer(config) {
173
+ return config.developCycle
174
+ ? completionPhaseOrder.flatMap((phase) => completionToolNamesForPhase(phase))
175
+ : completionToolNamesForPhase(config.phase);
176
+ }
177
+ export class CompletionToolServerSession {
178
+ config;
179
+ currentPhase;
180
+ completed = false;
181
+ constructor(config) {
182
+ this.config = config;
183
+ this.currentPhase = config.phase;
184
+ }
185
+ get instructions() {
186
+ return this.config.developCycle
187
+ ? completionPromptForDevelopCycle(this.currentPhase)
188
+ : completionPromptForPhase(this.currentPhase);
189
+ }
190
+ toolDefinitions() {
191
+ return completionToolNamesForServer(this.config).map((name) => toolDefinition(name, phaseFromToolName(name)));
192
+ }
193
+ async callTool(toolName, input) {
194
+ const requestedPhase = phaseFromToolName(toolName);
195
+ if (this.completed) {
196
+ throw new Error("Forge develop cycle is already complete; no more phase completion calls are accepted.");
197
+ }
198
+ if (requestedPhase !== this.currentPhase) {
199
+ throw new Error(`Tool ${toolName} is out of order. Current Forge phase is ${this.currentPhase}.`);
200
+ }
201
+ const completedPhase = this.currentPhase;
202
+ const reference = await writeCompletionArtifact({ ...this.config, phase: completedPhase }, toolName, input);
203
+ const status = reference.status.trim().toLowerCase();
204
+ const pass = status === "pass";
205
+ const nextPhase = pass
206
+ ? this.advanceAfterPass(completedPhase)
207
+ : completedPhase;
208
+ const nextInstruction = completionToolNextInstruction(completedPhase, status, nextPhase);
209
+ const reason = pass
210
+ ? `${completedPhase} completion artifact accepted.`
211
+ : `${completedPhase} completion artifact recorded with status ${status}; rework is required before phase progression.`;
212
+ return {
213
+ content: [
214
+ {
215
+ type: "text",
216
+ text: `Forge recorded ${reference.phase} completion artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}). ${nextInstruction}`
217
+ }
218
+ ],
219
+ structuredContent: {
220
+ ...reference,
221
+ gate: {
222
+ phase: completedPhase,
223
+ status,
224
+ allowed: pass,
225
+ reason
226
+ },
227
+ nextPhase,
228
+ nextInstruction
229
+ }
230
+ };
231
+ }
232
+ advanceAfterPass(phase) {
233
+ if (phase === "qa") {
234
+ return "sign_off_ready";
235
+ }
236
+ const next = nextPhaseAfter(phase);
237
+ if (!this.config.developCycle) {
238
+ return next ?? "dev_test_ready";
239
+ }
240
+ if (next) {
241
+ this.currentPhase = next;
242
+ return next;
243
+ }
244
+ this.completed = true;
245
+ return "dev_test_ready";
246
+ }
247
+ }
119
248
  export async function writeCompletionArtifact(config, toolName, input) {
120
249
  const phase = phaseFromToolName(toolName);
121
250
  if (phase !== config.phase) {
122
251
  throw new Error(`Tool ${toolName} is not allowed for phase ${config.phase}.`);
123
252
  }
124
253
  const payload = asRecord(input, "completion payload");
125
- validatePayloadShape(phase, payload);
126
- validateOptionalWorkItemId(payload, config.workItemId);
127
- const redactedPayload = redactSecrets(payload, config.redactionSecrets ?? []);
254
+ const status = normalizeCompletionStatus(requiredString(payload, "status"), phase);
255
+ const validationPayload = { ...payload, status };
256
+ validatePayloadShape(phase, validationPayload);
257
+ validateOptionalWorkItemId(validationPayload, config.workItemId);
258
+ const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
128
259
  const producedBy = optionalString(redactedPayload, "produced_by")
129
260
  ?? optionalString(redactedPayload, "producedBy")
130
261
  ?? config.producedBy
131
262
  ?? "forge-completion-tool";
132
- const status = requiredString(redactedPayload, "status").trim().toLowerCase();
263
+ if (phase === "qa") {
264
+ return await writeQaCompletionArtifact(config, redactedPayload, status, producedBy);
265
+ }
133
266
  const artifactWithoutHash = normalizeArtifactPayload(redactedPayload, {
134
267
  phase,
135
268
  workItemId: config.workItemId,
@@ -159,6 +292,154 @@ export async function writeCompletionArtifact(config, toolName, input) {
159
292
  producedBy
160
293
  };
161
294
  }
295
+ async function writeQaCompletionArtifact(config, payload, status, producedBy) {
296
+ const artifactRoot = artifactRootFor(config.worktreePath, config.workItemId);
297
+ const planPath = path.join(artifactRoot, "qa.plan.json");
298
+ const evidencePath = path.join(artifactRoot, "qa.evidence.json");
299
+ const findingsPath = path.join(artifactRoot, "qa.findings.json");
300
+ const verdictPath = path.join(artifactRoot, "qa.verdict.json");
301
+ const reportPath = path.join(artifactRoot, "qa.report.md");
302
+ const relativeEvidencePath = qaArtifactRelativePath(config.workItemId, "qa.evidence.json");
303
+ const relativeFindingsPath = qaArtifactRelativePath(config.workItemId, "qa.findings.json");
304
+ const relativeReportPath = qaArtifactRelativePath(config.workItemId, "qa.report.md");
305
+ const evidenceSource = qaEvidenceSource(payload);
306
+ const commands = qaArray(payload, "commands", evidenceSource);
307
+ const browserChecks = qaArray(payload, "browser_checks", evidenceSource);
308
+ const sidecars = await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(payload, "sidecars", evidenceSource));
309
+ const notes = optionalString(payload, "notes") ?? optionalString(evidenceSource, "notes") ?? "";
310
+ const findings = qaObjectArray(payload, "findings");
311
+ const candidateBugs = qaObjectArray(payload, "candidate_bugs");
312
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
313
+ const explicitFindingIds = qaStringArray(payload, "finding_ids");
314
+ const explicitCandidateBugIds = qaStringArray(payload, "candidate_bug_ids");
315
+ const blockerReason = optionalString(payload, "blocker_reason");
316
+ const checklist = qaStringArray(payload, "checklist");
317
+ const planJson = jsonText({
318
+ schema_version: 1,
319
+ phase: "qa",
320
+ checklist: checklist.length > 0 ? checklist : defaultQaChecklist(status),
321
+ acceptance_criteria: testedAcceptanceCriteria
322
+ });
323
+ const evidenceJson = jsonText({
324
+ schema_version: 1,
325
+ phase: "qa",
326
+ commands,
327
+ browser_checks: browserChecks,
328
+ sidecars,
329
+ notes
330
+ });
331
+ const findingsJson = jsonText({
332
+ schema_version: 1,
333
+ phase: "qa",
334
+ findings,
335
+ candidate_bugs: candidateBugs
336
+ });
337
+ const findingIds = status === "pass"
338
+ ? []
339
+ : explicitFindingIds.length > 0
340
+ ? explicitFindingIds
341
+ : findings
342
+ .filter((finding) => normalizedString(finding.scope) === "in_scope")
343
+ .map((finding) => optionalString(finding, "id"))
344
+ .filter((id) => Boolean(id));
345
+ const candidateBugIds = explicitCandidateBugIds.length > 0
346
+ ? explicitCandidateBugIds
347
+ : candidateBugs
348
+ .map((candidateBug) => optionalString(candidateBug, "id"))
349
+ .filter((id) => Boolean(id));
350
+ const verdictWithoutHash = {
351
+ schema_version: numberOrDefault(payload.schema_version, 1),
352
+ phase: "qa",
353
+ status,
354
+ summary: requiredString(payload, "summary"),
355
+ tested_acceptance_criteria: testedAcceptanceCriteria,
356
+ finding_ids: findingIds,
357
+ candidate_bug_ids: candidateBugIds,
358
+ blocker_reason: status === "blocked" ? normalizedString(blockerReason) : null,
359
+ evidence_path: relativeEvidencePath,
360
+ findings_path: relativeFindingsPath,
361
+ report_path: relativeReportPath,
362
+ produced_by: producedBy
363
+ };
364
+ const contentHash = sha256(stableStringify({
365
+ plan: JSON.parse(planJson),
366
+ evidence: JSON.parse(evidenceJson),
367
+ findings: JSON.parse(findingsJson),
368
+ verdict: verdictWithoutHash
369
+ }));
370
+ const verdictJson = jsonText({
371
+ ...verdictWithoutHash,
372
+ content_hash: contentHash
373
+ });
374
+ const finalReport = reportMarkdown(payload, "qa", status, producedBy, contentHash);
375
+ await fs.mkdir(artifactRoot, { recursive: true });
376
+ await writeFileAtomic(planPath, planJson);
377
+ await writeFileAtomic(evidencePath, evidenceJson);
378
+ await writeFileAtomic(findingsPath, findingsJson);
379
+ await writeFileAtomic(verdictPath, verdictJson);
380
+ await writeFileAtomic(reportPath, finalReport);
381
+ return {
382
+ phase: "qa",
383
+ workItemId: config.workItemId,
384
+ repoPath: path.resolve(config.worktreePath),
385
+ path: verdictPath,
386
+ reportPath,
387
+ contentHash,
388
+ status,
389
+ producedBy
390
+ };
391
+ }
392
+ async function validateQaSidecarReferences(worktreePath, workItemId, sidecars) {
393
+ if (sidecars.length === 0) {
394
+ return [];
395
+ }
396
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
397
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
398
+ const validated = [];
399
+ for (const [index, sidecar] of sidecars.entries()) {
400
+ if (!sidecar || typeof sidecar !== "object" || Array.isArray(sidecar)) {
401
+ throw new Error(`sidecars[${index}] must be an object.`);
402
+ }
403
+ const record = sidecar;
404
+ const sidecarPath = optionalString(record, "path");
405
+ const contentHash = optionalString(record, "content_hash");
406
+ const bytes = record.bytes;
407
+ if (!sidecarPath || !contentHash || typeof bytes !== "number" || !Number.isFinite(bytes) || bytes <= 0) {
408
+ throw new Error(`sidecars[${index}] must include path, content_hash, and positive bytes.`);
409
+ }
410
+ if (path.isAbsolute(sidecarPath)) {
411
+ throw new Error(`sidecars[${index}].path must be relative to the worktree.`);
412
+ }
413
+ const fullPath = path.resolve(worktreePath, sidecarPath);
414
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
415
+ throw new Error(`sidecars[${index}].path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
416
+ }
417
+ const stat = await fs.lstat(fullPath).catch((error) => {
418
+ if (isNodeError(error) && error.code === "ENOENT") {
419
+ throw new Error(`sidecars[${index}].path does not exist: ${sidecarPath}`);
420
+ }
421
+ throw error;
422
+ });
423
+ if (!stat.isFile() || stat.isSymbolicLink()) {
424
+ throw new Error(`sidecars[${index}].path must reference a regular file.`);
425
+ }
426
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `sidecars[${index}].path must not traverse symbolic links.`);
427
+ if (stat.size !== bytes) {
428
+ throw new Error(`sidecars[${index}].bytes does not match the referenced file.`);
429
+ }
430
+ const actualHash = await sha256File(fullPath);
431
+ if (actualHash !== contentHash.trim().toLowerCase()) {
432
+ throw new Error(`sidecars[${index}].content_hash does not match the referenced file.`);
433
+ }
434
+ validated.push({
435
+ ...record,
436
+ path: path.relative(worktreePath, fullPath).split(path.sep).join("/"),
437
+ content_hash: actualHash,
438
+ bytes: stat.size
439
+ });
440
+ }
441
+ return validated;
442
+ }
162
443
  export async function readCompletionArtifact(worktreePath, workItemId, phase) {
163
444
  const artifactPath = completionArtifactJsonPath(worktreePath, workItemId, phase);
164
445
  const reportPath = completionArtifactReportPath(worktreePath, workItemId, phase);
@@ -179,6 +460,7 @@ export async function readCompletionArtifact(worktreePath, workItemId, phase) {
179
460
  };
180
461
  }
181
462
  export async function runCompletionMcpServer(config) {
463
+ const session = new CompletionToolServerSession(config);
182
464
  process.stdin.setEncoding("utf8");
183
465
  let buffer = "";
184
466
  for await (const chunk of process.stdin) {
@@ -188,14 +470,14 @@ export async function runCompletionMcpServer(config) {
188
470
  const rawLine = buffer.slice(0, newlineIndex).trim();
189
471
  buffer = buffer.slice(newlineIndex + 1);
190
472
  if (rawLine.length > 0) {
191
- await handleJsonRpcLine(config, rawLine);
473
+ await handleJsonRpcLine(session, rawLine);
192
474
  }
193
475
  newlineIndex = buffer.indexOf("\n");
194
476
  }
195
477
  }
196
478
  const trailing = buffer.trim();
197
479
  if (trailing.length > 0) {
198
- await handleJsonRpcLine(config, trailing);
480
+ await handleJsonRpcLine(session, trailing);
199
481
  }
200
482
  }
201
483
  export function parseCompletionMcpArgs(argv) {
@@ -203,6 +485,7 @@ export function parseCompletionMcpArgs(argv) {
203
485
  let workItemId = null;
204
486
  let phase = "implementation";
205
487
  let producedBy;
488
+ let developCycle = false;
206
489
  for (let index = 1; index < argv.length; index += 1) {
207
490
  const arg = argv[index];
208
491
  if (arg === "--worktree") {
@@ -215,13 +498,16 @@ export function parseCompletionMcpArgs(argv) {
215
498
  const rawPhase = argv[++index];
216
499
  const parsedPhase = parseStrictCompletionPhase(rawPhase);
217
500
  if (!parsedPhase) {
218
- return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation." };
501
+ return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation, qa." };
219
502
  }
220
503
  phase = parsedPhase;
221
504
  }
222
505
  else if (arg === "--produced-by") {
223
506
  producedBy = argv[++index] ?? undefined;
224
507
  }
508
+ else if (arg === "--develop-cycle") {
509
+ developCycle = true;
510
+ }
225
511
  else {
226
512
  return { ok: false, error: `Unknown mcp argument: ${arg}` };
227
513
  }
@@ -236,7 +522,8 @@ export function parseCompletionMcpArgs(argv) {
236
522
  workItemId,
237
523
  phase,
238
524
  producedBy,
239
- redactionSecrets: parseCompletionRedactionSecrets(process.env[completionRedactionSecretsEnv])
525
+ redactionSecrets: parseCompletionRedactionSecrets(process.env[completionRedactionSecretsEnv]),
526
+ developCycle
240
527
  }
241
528
  };
242
529
  }
@@ -273,7 +560,7 @@ async function prepareCursorCompletionToolRuntime(worktreePath, runtime) {
273
560
  }
274
561
  };
275
562
  }
276
- async function handleJsonRpcLine(config, rawLine) {
563
+ async function handleJsonRpcLine(session, rawLine) {
277
564
  let message;
278
565
  try {
279
566
  message = JSON.parse(rawLine);
@@ -291,14 +578,14 @@ async function handleJsonRpcLine(config, rawLine) {
291
578
  return;
292
579
  }
293
580
  try {
294
- const result = await handleJsonRpcRequest(config, request.method, request.params);
581
+ const result = await handleJsonRpcRequest(session, request.method, request.params);
295
582
  writeJsonRpc({ jsonrpc: "2.0", id: request.id, result });
296
583
  }
297
584
  catch (error) {
298
585
  writeJsonRpc({ jsonrpc: "2.0", id: request.id, error: rpcError(-32000, errorMessage(error)) });
299
586
  }
300
587
  }
301
- async function handleJsonRpcRequest(config, method, params) {
588
+ async function handleJsonRpcRequest(session, method, params) {
302
589
  if (method === "initialize") {
303
590
  const initializeParams = params && typeof params === "object" && !Array.isArray(params)
304
591
  ? params
@@ -312,7 +599,7 @@ async function handleJsonRpcRequest(config, method, params) {
312
599
  name: "forge-completion-tools",
313
600
  version: "0.1.0"
314
601
  },
315
- instructions: completionPromptForPhase(config.phase)
602
+ instructions: session.instructions
316
603
  };
317
604
  }
318
605
  if (method === "ping") {
@@ -320,23 +607,14 @@ async function handleJsonRpcRequest(config, method, params) {
320
607
  }
321
608
  if (method === "tools/list") {
322
609
  return {
323
- tools: completionToolNamesForPhase(config.phase).map((name) => toolDefinition(name, config.phase))
610
+ tools: session.toolDefinitions()
324
611
  };
325
612
  }
326
613
  if (method === "tools/call") {
327
614
  const call = asRecord(params, "tools/call params");
328
615
  const name = requiredString(call, "name");
329
616
  const args = call.arguments ?? {};
330
- const reference = await writeCompletionArtifact(config, name, args);
331
- return {
332
- content: [
333
- {
334
- type: "text",
335
- text: `Forge recorded ${reference.phase} completion artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}).`
336
- }
337
- ],
338
- structuredContent: reference
339
- };
617
+ return await session.callTool(name, args);
340
618
  }
341
619
  throw new Error(`Unsupported MCP method: ${method}`);
342
620
  }
@@ -347,6 +625,31 @@ function toolDefinition(name, phase) {
347
625
  inputSchema: toolInputSchema(phase)
348
626
  };
349
627
  }
628
+ function nextPhaseAfter(phase) {
629
+ const index = completionPhaseOrder.indexOf(phase);
630
+ return index >= 0 ? completionPhaseOrder[index + 1] ?? null : null;
631
+ }
632
+ function completionToolNextInstruction(completedPhase, status, nextPhase) {
633
+ if (completedPhase === "qa") {
634
+ if (status === "blocked") {
635
+ return "QA blocked. Forge recorded the blocker reason and will surface the run for human attention.";
636
+ }
637
+ if (status === "needs_rework") {
638
+ return "QA findings recorded. Forge has the structured evidence needed to route this work back for implementation rework.";
639
+ }
640
+ return "QA accepted. Forge has the structured evidence needed to move this work item to Sign-Off.";
641
+ }
642
+ if (status !== "pass") {
643
+ return `Stay in ${completedPhase}, address the recorded blockers, then call ${expectedCompletionToolName(completedPhase)} again.`;
644
+ }
645
+ if (nextPhase === "self_review") {
646
+ return "Implementation accepted. Begin self-review: inspect the diff, apply safe fixes, and call forge.complete_self_review with review evidence.";
647
+ }
648
+ if (nextPhase === "validation") {
649
+ return "Self-review accepted. Begin validation: run deterministic checks, prove acceptance criteria, and call forge.complete_validation with command evidence.";
650
+ }
651
+ return "Validation accepted. Forge has the structured evidence needed to move this work item to QA.";
652
+ }
350
653
  function toolDescription(phase) {
351
654
  if (phase === "implementation") {
352
655
  return "Complete Forge implementation by writing implementation.completeness.json with scoped changed-file, verification, acceptance-criteria, gap, and next-phase evidence.";
@@ -354,77 +657,322 @@ function toolDescription(phase) {
354
657
  if (phase === "self_review") {
355
658
  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.";
356
659
  }
660
+ if (phase === "qa") {
661
+ 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.";
662
+ }
357
663
  return "Complete Forge validation by writing validation.verdict.json with command, build/test/lint/design, drift, acceptance-criteria, and ready-for-dev-test evidence.";
358
664
  }
359
665
  function toolInputSchema(phase) {
360
- const base = {
361
- type: "object",
362
- additionalProperties: true,
363
- properties: {
364
- status: { type: "string", enum: ["pass", "blocked", "fail", "failed"] },
365
- summary: { type: "string" },
366
- report_markdown: { type: "string" },
367
- blockers: { type: "array" }
666
+ const baseProperties = {
667
+ status: {
668
+ type: "string",
669
+ enum: ["pass", "needs_rework", "fail", "failed"],
670
+ description: "Use pass only when the phase evidence satisfies Forge's gate. Use needs_rework/fail/failed with explicit blockers or findings otherwise."
368
671
  },
369
- required: ["status", "summary"]
672
+ summary: { type: "string", description: "Concise phase summary." },
673
+ report_markdown: { type: "string", description: "Optional human-readable report. Forge will generate a fallback report if omitted." },
674
+ blockers: {
675
+ type: "array",
676
+ description: "Required for non-pass status unless findings, failures, known_gaps, remaining_risks, or commands provide explicit evidence.",
677
+ items: evidenceObjectSchema(["reason"], {
678
+ reason: { type: "string" },
679
+ owner: { type: "string" },
680
+ next_step: { type: "string" }
681
+ })
682
+ }
370
683
  };
371
684
  if (phase === "implementation") {
372
- return {
373
- ...base,
374
- properties: {
375
- ...base.properties,
376
- plan: { type: "array" },
377
- changed_files: { type: "array" },
378
- tests_added_or_updated: { type: "array" },
379
- docs_added_or_updated: { type: "array" },
380
- verification: { type: "array" },
381
- acceptance_criteria: { type: "array" },
382
- known_gaps: { type: "array" },
383
- next_phase_context: {}
685
+ return objectToolSchema({
686
+ ...baseProperties,
687
+ plan: {
688
+ type: "array",
689
+ description: "Required for pass. Ordered implementation steps with status.",
690
+ items: evidenceObjectSchema(["step", "status"], {
691
+ step: { type: "string" },
692
+ status: { type: "string" },
693
+ evidence: { type: "string" }
694
+ })
384
695
  },
385
- required: ["status", "summary"]
386
- };
696
+ changed_files: {
697
+ type: "array",
698
+ description: "Required for pass. Must be non-empty unless known_gaps explains why.",
699
+ items: evidenceObjectSchema(["path", "summary"], {
700
+ path: { type: "string" },
701
+ summary: { type: "string" }
702
+ })
703
+ },
704
+ tests_added_or_updated: {
705
+ type: "array",
706
+ description: "Required for pass. Use an object explaining why no tests were needed for docs/config-only work if empty would be ambiguous.",
707
+ items: evidenceObjectSchema(["path", "summary"], {
708
+ path: { type: "string" },
709
+ summary: { type: "string" }
710
+ })
711
+ },
712
+ docs_added_or_updated: {
713
+ type: "array",
714
+ description: "Required for pass. Use an object explaining why no docs changed when appropriate.",
715
+ items: evidenceObjectSchema(["path", "summary"], {
716
+ path: { type: "string" },
717
+ summary: { type: "string" }
718
+ })
719
+ },
720
+ verification: {
721
+ type: "array",
722
+ description: "Implementation verification evidence. Objects should include command, exit_code, status, and summary when command-based.",
723
+ items: commandEvidenceSchema()
724
+ },
725
+ acceptance_criteria: acceptanceCriteriaSchema(),
726
+ known_gaps: {
727
+ type: "array",
728
+ description: "Required for pass, even when empty. If changed_files/tests/docs arrays are empty, explain why here.",
729
+ items: evidenceObjectSchema(["summary"], {
730
+ summary: { type: "string" },
731
+ impact: { type: "string" },
732
+ follow_up: { type: "string" }
733
+ })
734
+ },
735
+ next_phase_context: {
736
+ description: "Required for pass. Context the self-review phase should carry forward."
737
+ }
738
+ }, ["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.");
387
739
  }
388
740
  if (phase === "self_review") {
389
- return {
390
- ...base,
391
- properties: {
392
- ...base.properties,
393
- reviewed_diff: { type: "boolean" },
394
- findings: { type: "array" },
395
- security_review: { type: "object" },
396
- edge_case_review: { type: "object" },
397
- design_review: { type: "object" },
398
- deterministic_comparison: { type: "object" },
399
- fixes_applied: { type: "array" },
400
- remaining_risks: { type: "array" }
741
+ return objectToolSchema({
742
+ ...baseProperties,
743
+ reviewed_diff: { type: "boolean", description: "Required for pass. True after reviewing the implementation diff." },
744
+ findings: {
745
+ type: "array",
746
+ description: "Required for pass, even when empty. Include finding objects for issues discovered during review.",
747
+ items: evidenceObjectSchema(["severity", "summary", "status"], {
748
+ severity: { type: "string" },
749
+ summary: { type: "string" },
750
+ status: { type: "string" },
751
+ file: { type: "string" }
752
+ })
401
753
  },
402
- required: ["status", "summary"]
403
- };
754
+ security_review: reviewSectionSchema(),
755
+ edge_case_review: reviewSectionSchema(),
756
+ design_review: {
757
+ ...reviewSectionSchema(),
758
+ properties: {
759
+ ...reviewSectionProperties(),
760
+ screenshots: { type: "array", items: evidenceObjectSchema(["path"], { path: { type: "string" }, summary: { type: "string" } }) }
761
+ }
762
+ },
763
+ deterministic_comparison: {
764
+ type: "object",
765
+ description: "Required for pass. Evidence that the reviewed diff matches the intended deterministic change.",
766
+ additionalProperties: true,
767
+ properties: {
768
+ status: { type: "string" },
769
+ command_or_tool: { type: "string" },
770
+ notes: { type: "string" }
771
+ }
772
+ },
773
+ fixes_applied: {
774
+ type: "array",
775
+ description: "Required for pass, even when empty.",
776
+ items: evidenceObjectSchema(["summary"], { summary: { type: "string" }, path: { type: "string" } })
777
+ },
778
+ remaining_risks: {
779
+ type: "array",
780
+ description: "Required for pass, even when empty.",
781
+ items: evidenceObjectSchema(["summary"], { summary: { type: "string" }, mitigation: { type: "string" } })
782
+ }
783
+ }, ["status", "summary"], "For status pass, include reviewed_diff, findings, security_review, edge_case_review, design_review, deterministic_comparison, fixes_applied, and remaining_risks.");
404
784
  }
405
- return {
406
- ...base,
407
- properties: {
408
- ...base.properties,
409
- commands: { type: "array" },
410
- acceptance_criteria: { type: "array" },
411
- build_status: { type: "string" },
412
- test_status: { type: "string" },
413
- lint_status: { type: "string" },
414
- design_status: { type: "string" },
415
- drift_checks: { type: "array" },
416
- ready_for_dev_test: { type: "boolean" }
785
+ if (phase === "qa") {
786
+ return objectToolSchema({
787
+ ...baseProperties,
788
+ status: {
789
+ type: "string",
790
+ enum: ["pass", "needs_rework", "blocked"],
791
+ description: "Use pass only when QA evidence satisfies acceptance criteria, needs_rework for actionable in-scope defects, or blocked for an inconclusive QA blocker."
792
+ },
793
+ checklist: {
794
+ type: "array",
795
+ description: "QA plan/checklist. Forge writes this to qa.plan.json; a default checklist is generated if omitted.",
796
+ items: { type: "string" }
797
+ },
798
+ tested_acceptance_criteria: {
799
+ type: "array",
800
+ description: "Required and non-empty for pass/needs_rework. Criteria actually tested by QA.",
801
+ items: { type: "string" }
802
+ },
803
+ commands: {
804
+ type: "array",
805
+ description: "Command evidence written to qa.evidence.json.",
806
+ items: commandEvidenceSchema()
807
+ },
808
+ browser_checks: {
809
+ type: "array",
810
+ description: "Browser/manual UI checks with URL or route, action, observed result, screenshot/trace references, console/network notes, and status.",
811
+ items: evidenceObjectSchema(["summary", "status"], {
812
+ summary: { type: "string" },
813
+ url: { type: "string" },
814
+ route: { type: "string" },
815
+ status: { type: "string" },
816
+ screenshot: { type: "string" },
817
+ trace: { type: "string" }
818
+ })
819
+ },
820
+ sidecars: {
821
+ type: "array",
822
+ description: "Optional QA sidecar files already written under .forge/work-items/<id>/artifacts/qa/ with path/content_hash/bytes metadata.",
823
+ items: evidenceObjectSchema(["path", "content_hash", "bytes"], {
824
+ path: { type: "string" },
825
+ content_hash: { type: "string" },
826
+ bytes: { type: "number" }
827
+ })
828
+ },
829
+ notes: { type: "string", description: "Additional QA evidence notes." },
830
+ evidence: {
831
+ type: "object",
832
+ description: "Optional wrapper containing commands, browser_checks, and notes when a client prefers nested evidence."
833
+ },
834
+ findings: {
835
+ type: "array",
836
+ description: "QA findings. needs_rework requires at least one actionable in_scope finding.",
837
+ items: evidenceObjectSchema(["id", "severity", "scope", "title"], {
838
+ id: { type: "string" },
839
+ severity: { type: "string", enum: ["critical", "major", "minor"] },
840
+ scope: { type: "string", enum: ["in_scope", "out_of_scope", "unclear"] },
841
+ title: { type: "string" },
842
+ acceptance_criteria: { type: "array", items: { type: "string" } },
843
+ repro_steps: { type: "array", items: { type: "string" } },
844
+ expected: { type: "string" },
845
+ actual: { type: "string" },
846
+ evidence: { type: "object" },
847
+ likely_area: { type: "array", items: { type: "string" } },
848
+ required_fix: { type: "string" },
849
+ required_regression: { type: "string" }
850
+ })
851
+ },
852
+ candidate_bugs: {
853
+ type: "array",
854
+ description: "Out-of-scope/follow-up bug candidates. They do not block the current item unless attached as in-scope findings.",
855
+ items: evidenceObjectSchema(["id", "title", "suggested_action"], {
856
+ id: { type: "string" },
857
+ title: { type: "string" },
858
+ severity: { type: "string" },
859
+ scope_reason: { type: "string" },
860
+ repro_steps: { type: "array", items: { type: "string" } },
861
+ evidence: { type: "object" },
862
+ suggested_action: { type: "string", enum: ["create_bug", "create_follow_up", "accept_risk", "attach_to_current_item"] }
863
+ })
864
+ },
865
+ blocker_reason: {
866
+ type: "string",
867
+ enum: [...qaBlockerReasons],
868
+ description: "Required when status is blocked."
869
+ }
870
+ }, ["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.");
871
+ }
872
+ return objectToolSchema({
873
+ ...baseProperties,
874
+ commands: {
875
+ type: "array",
876
+ description: "Required for pass. Include at least one deterministic validation command with exit_code: 0 and status: pass.",
877
+ items: commandEvidenceSchema()
417
878
  },
418
- required: ["status", "summary"]
879
+ acceptance_criteria: acceptanceCriteriaSchema(),
880
+ build_status: { type: "string", description: "Required for pass. pass/fail/needs_rework/not_applicable." },
881
+ test_status: { type: "string", description: "Required for pass. pass/fail/needs_rework/not_applicable." },
882
+ lint_status: { type: "string", description: "Required for pass. pass/fail/needs_rework/not_applicable." },
883
+ design_status: { type: "string", description: "Required for pass. pass/fail/needs_rework/not_applicable." },
884
+ drift_checks: {
885
+ type: "array",
886
+ description: "Required for pass. Deterministic checks for unintended drift.",
887
+ items: evidenceObjectSchema(["command_or_tool", "status", "summary"], {
888
+ command_or_tool: { type: "string" },
889
+ status: { type: "string" },
890
+ summary: { type: "string" }
891
+ })
892
+ },
893
+ ready_for_dev_test: { type: "boolean", description: "Required for pass and must be true." }
894
+ }, ["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.");
895
+ }
896
+ function objectToolSchema(properties, required, description) {
897
+ return {
898
+ type: "object",
899
+ additionalProperties: true,
900
+ description,
901
+ properties,
902
+ required: [...required]
903
+ };
904
+ }
905
+ function evidenceObjectSchema(required, properties) {
906
+ return {
907
+ type: "object",
908
+ additionalProperties: true,
909
+ properties,
910
+ required: [...required]
911
+ };
912
+ }
913
+ function commandEvidenceSchema() {
914
+ return evidenceObjectSchema(["command", "exit_code", "status", "summary"], {
915
+ command: { type: "string" },
916
+ exit_code: { type: "number" },
917
+ status: { type: "string" },
918
+ summary: { type: "string" }
919
+ });
920
+ }
921
+ function acceptanceCriteriaSchema() {
922
+ return {
923
+ type: "array",
924
+ description: "Required for pass. Every entry must be an object with status: satisfied and non-empty evidence.",
925
+ items: evidenceObjectSchema(["criterion", "evidence", "status"], {
926
+ criterion: { type: "string" },
927
+ evidence: { type: "string" },
928
+ status: { type: "string", enum: ["satisfied"] }
929
+ })
930
+ };
931
+ }
932
+ function reviewSectionSchema() {
933
+ return {
934
+ type: "object",
935
+ description: "Required for pass. Use status pass/fail/needs_rework/not_applicable plus notes.",
936
+ additionalProperties: true,
937
+ properties: reviewSectionProperties()
419
938
  };
420
939
  }
940
+ function reviewSectionProperties() {
941
+ return {
942
+ status: { type: "string" },
943
+ notes: { type: "string" }
944
+ };
945
+ }
946
+ function normalizeCompletionStatus(value, phase) {
947
+ const normalized = value.trim().toLowerCase().replace(/-/g, "_");
948
+ if (phase === "qa") {
949
+ const canonical = normalized === "needsrework" ? "needs_rework" : normalized;
950
+ if (canonical !== "pass" && canonical !== "needs_rework" && canonical !== "blocked") {
951
+ throw new Error("QA status must be pass, needs_rework, or blocked.");
952
+ }
953
+ return canonical;
954
+ }
955
+ const canonical = normalized === "blocked" || normalized === "needsrework"
956
+ ? "needs_rework"
957
+ : normalized === "failed"
958
+ ? "fail"
959
+ : normalized;
960
+ if (canonical !== "pass" && canonical !== "fail" && canonical !== "needs_rework") {
961
+ throw new Error("status must be pass, fail, or needs_rework.");
962
+ }
963
+ return canonical;
964
+ }
421
965
  function validatePayloadShape(phase, payload) {
422
- const status = requiredString(payload, "status").trim().toLowerCase();
966
+ const status = normalizeCompletionStatus(requiredString(payload, "status"), phase);
423
967
  if (!status) {
424
968
  throw new Error("status is required.");
425
969
  }
426
- const pass = status === "pass";
427
970
  requireField(payload, "summary");
971
+ if (phase === "qa") {
972
+ validateQaPayloadShape(payload, status);
973
+ return;
974
+ }
975
+ const pass = status === "pass";
428
976
  if (!pass) {
429
977
  requireNonPassEvidence(payload);
430
978
  return;
@@ -466,6 +1014,131 @@ function validatePayloadShape(phase, payload) {
466
1014
  requirePassingCommands(payload);
467
1015
  requireSatisfiedAcceptanceCriteria(payload);
468
1016
  }
1017
+ function validateQaPayloadShape(payload, status) {
1018
+ const evidenceSource = qaEvidenceSource(payload);
1019
+ const commands = qaArray(payload, "commands", evidenceSource);
1020
+ const browserChecks = qaArray(payload, "browser_checks", evidenceSource);
1021
+ const sidecars = qaArray(payload, "sidecars", evidenceSource);
1022
+ const notes = optionalString(payload, "notes") ?? optionalString(evidenceSource, "notes") ?? "";
1023
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
1024
+ const findings = qaObjectArray(payload, "findings");
1025
+ const candidateBugs = qaObjectArray(payload, "candidate_bugs");
1026
+ const explicitFindingIds = qaStringArray(payload, "finding_ids");
1027
+ const explicitCandidateBugIds = qaStringArray(payload, "candidate_bug_ids");
1028
+ if (payload.schema_version !== undefined && payload.schema_version !== 1) {
1029
+ throw new Error("QA schema_version must be numeric 1 when provided.");
1030
+ }
1031
+ if (status === "pass" || status === "needs_rework") {
1032
+ if (testedAcceptanceCriteria.length === 0) {
1033
+ throw new Error("QA pass/needs_rework requires tested_acceptance_criteria with at least one criterion.");
1034
+ }
1035
+ if (commands.length === 0 && browserChecks.length === 0 && notes.length === 0) {
1036
+ throw new Error("QA pass/needs_rework requires at least one command, browser check, or evidence note.");
1037
+ }
1038
+ }
1039
+ for (const [index, command] of commands.entries()) {
1040
+ requireEvidenceRecord(command, `commands[${index}]`);
1041
+ const record = command;
1042
+ requireNonEmptyStringRecord(record, "command", `commands[${index}].`);
1043
+ requireNonEmptyStringRecord(record, "status", `commands[${index}].`);
1044
+ requireNonEmptyStringRecord(record, "summary", `commands[${index}].`);
1045
+ if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
1046
+ throw new Error(`commands[${index}].exit_code is required.`);
1047
+ }
1048
+ if (status === "pass" && record.exit_code !== 0) {
1049
+ throw new Error(`commands[${index}].exit_code must be 0 when QA status is pass.`);
1050
+ }
1051
+ if (status === "pass" && normalizedString(record.status) !== "pass") {
1052
+ throw new Error(`commands[${index}].status must be pass when QA status is pass.`);
1053
+ }
1054
+ }
1055
+ for (const [index, browserCheck] of browserChecks.entries()) {
1056
+ requireEvidenceRecord(browserCheck, `browser_checks[${index}]`);
1057
+ const record = browserCheck;
1058
+ requireNonEmptyStringRecord(record, "summary", `browser_checks[${index}].`);
1059
+ requireNonEmptyStringRecord(record, "status", `browser_checks[${index}].`);
1060
+ const checkStatus = optionalString(record, "status");
1061
+ if (status === "pass" && checkStatus && normalizedString(checkStatus) !== "pass") {
1062
+ throw new Error(`browser_checks[${index}].status must be pass when QA status is pass.`);
1063
+ }
1064
+ if (!optionalString(record, "url") && !optionalString(record, "route")) {
1065
+ throw new Error(`browser_checks[${index}] must include url or route.`);
1066
+ }
1067
+ }
1068
+ for (const [index, sidecar] of sidecars.entries()) {
1069
+ requireEvidenceRecord(sidecar, `sidecars[${index}]`);
1070
+ const record = sidecar;
1071
+ requireNonEmptyStringRecord(record, "path", `sidecars[${index}].`);
1072
+ requireNonEmptyStringRecord(record, "content_hash", `sidecars[${index}].`);
1073
+ if (typeof record.bytes !== "number" || !Number.isFinite(record.bytes) || record.bytes <= 0) {
1074
+ throw new Error(`sidecars[${index}].bytes must be greater than 0.`);
1075
+ }
1076
+ }
1077
+ for (const [index, finding] of findings.entries()) {
1078
+ requireNonEmptyStringRecord(finding, "id", `findings[${index}].`);
1079
+ requireNonEmptyStringRecord(finding, "title", `findings[${index}].`);
1080
+ requireKnownStringRecord(finding, "severity", qaFindingSeverities, `findings[${index}].`);
1081
+ requireKnownStringRecord(finding, "scope", qaFindingScopes, `findings[${index}].`);
1082
+ if (normalizedString(finding.scope) === "in_scope") {
1083
+ validateActionableQaFinding(finding, index);
1084
+ }
1085
+ }
1086
+ for (const [index, candidateBug] of candidateBugs.entries()) {
1087
+ requireNonEmptyStringRecord(candidateBug, "id", `candidate_bugs[${index}].`);
1088
+ requireNonEmptyStringRecord(candidateBug, "title", `candidate_bugs[${index}].`);
1089
+ requireKnownStringRecord(candidateBug, "suggested_action", qaCandidateBugActions, `candidate_bugs[${index}].`);
1090
+ }
1091
+ const inScopeFindingIds = findings
1092
+ .filter((finding) => normalizedString(finding.scope) === "in_scope")
1093
+ .map((finding) => optionalString(finding, "id"))
1094
+ .filter((id) => Boolean(id));
1095
+ for (const findingId of explicitFindingIds) {
1096
+ if (!inScopeFindingIds.includes(findingId)) {
1097
+ throw new Error(`QA finding_ids contains '${findingId}', but findings has no matching in-scope finding.`);
1098
+ }
1099
+ }
1100
+ const candidateBugIds = candidateBugs
1101
+ .map((candidateBug) => optionalString(candidateBug, "id"))
1102
+ .filter((id) => Boolean(id));
1103
+ for (const candidateBugId of explicitCandidateBugIds) {
1104
+ if (!candidateBugIds.includes(candidateBugId)) {
1105
+ throw new Error(`QA candidate_bug_ids contains '${candidateBugId}', but candidate_bugs has no matching candidate bug.`);
1106
+ }
1107
+ }
1108
+ if (status === "pass") {
1109
+ if (explicitFindingIds.length > 0 || inScopeFindingIds.length > 0) {
1110
+ throw new Error("QA pass must not include in-scope finding_ids or in-scope findings.");
1111
+ }
1112
+ if (optionalString(payload, "blocker_reason")) {
1113
+ throw new Error("QA pass must not include blocker_reason.");
1114
+ }
1115
+ }
1116
+ if (status === "needs_rework") {
1117
+ if (inScopeFindingIds.length === 0) {
1118
+ throw new Error("QA needs_rework requires at least one actionable in-scope finding.");
1119
+ }
1120
+ if (optionalString(payload, "blocker_reason")) {
1121
+ throw new Error("QA needs_rework must not include blocker_reason.");
1122
+ }
1123
+ }
1124
+ if (status === "blocked") {
1125
+ const reason = normalizedString(optionalString(payload, "blocker_reason"));
1126
+ if (!qaBlockerReasons.has(reason)) {
1127
+ 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.");
1128
+ }
1129
+ }
1130
+ }
1131
+ function validateActionableQaFinding(finding, index) {
1132
+ const prefix = `findings[${index}].`;
1133
+ requireNonEmptyStringArrayRecord(finding, "acceptance_criteria", prefix);
1134
+ requireNonEmptyStringArrayRecord(finding, "repro_steps", prefix);
1135
+ requireNonEmptyStringRecord(finding, "expected", prefix);
1136
+ requireNonEmptyStringRecord(finding, "actual", prefix);
1137
+ requireSubstantiveEvidenceRecord(finding, prefix);
1138
+ requireNonEmptyStringArrayRecord(finding, "likely_area", prefix);
1139
+ requireNonEmptyStringRecord(finding, "required_fix", prefix);
1140
+ requireNonEmptyStringRecord(finding, "required_regression", prefix);
1141
+ }
469
1142
  function validateOptionalWorkItemId(payload, expectedWorkItemId) {
470
1143
  const actual = optionalString(payload, "work_item_id") ?? optionalString(payload, "workItemId");
471
1144
  if (actual && actual !== expectedWorkItemId) {
@@ -512,6 +1185,9 @@ function parseStrictCompletionPhase(value) {
512
1185
  if (normalized === "validate" || normalized === "validation") {
513
1186
  return "validation";
514
1187
  }
1188
+ if (normalized === "qa" || normalized === "quality_assurance" || normalized === "qualityassurance") {
1189
+ return "qa";
1190
+ }
515
1191
  return null;
516
1192
  }
517
1193
  function parseCompletionRedactionSecrets(raw) {
@@ -540,6 +1216,9 @@ function phaseFromToolName(toolName) {
540
1216
  if (normalized === "forge.complete_validation" || normalized === "complete_validation") {
541
1217
  return "validation";
542
1218
  }
1219
+ if (normalized === "forge.complete_qa" || normalized === "complete_qa") {
1220
+ return "qa";
1221
+ }
543
1222
  throw new Error(`Unknown Forge completion tool: ${toolName}`);
544
1223
  }
545
1224
  function requireField(payload, key) {
@@ -637,6 +1316,109 @@ function requireSatisfiedAcceptanceCriteria(payload) {
637
1316
  }
638
1317
  }
639
1318
  }
1319
+ function qaEvidenceSource(payload) {
1320
+ const evidence = payload.evidence;
1321
+ return evidence && typeof evidence === "object" && !Array.isArray(evidence)
1322
+ ? evidence
1323
+ : {};
1324
+ }
1325
+ function qaArray(payload, key, fallback = {}) {
1326
+ const value = payload[key] ?? fallback[key];
1327
+ if (value === undefined || value === null) {
1328
+ return [];
1329
+ }
1330
+ if (!Array.isArray(value)) {
1331
+ throw new Error(`${key} must be an array.`);
1332
+ }
1333
+ return value;
1334
+ }
1335
+ function qaObjectArray(payload, key) {
1336
+ return qaArray(payload, key).map((entry, index) => {
1337
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
1338
+ throw new Error(`${key}[${index}] must be an object.`);
1339
+ }
1340
+ return entry;
1341
+ });
1342
+ }
1343
+ function qaStringArray(payload, key) {
1344
+ const value = payload[key];
1345
+ if (value === undefined || value === null) {
1346
+ return [];
1347
+ }
1348
+ if (!Array.isArray(value)) {
1349
+ throw new Error(`${key} must be an array.`);
1350
+ }
1351
+ return value.map((entry, index) => {
1352
+ if (typeof entry !== "string" || entry.trim().length === 0) {
1353
+ throw new Error(`${key}[${index}] must be a non-empty string.`);
1354
+ }
1355
+ return entry;
1356
+ });
1357
+ }
1358
+ function requireEvidenceRecord(value, label) {
1359
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1360
+ throw new Error(`${label} must be an object.`);
1361
+ }
1362
+ }
1363
+ function requireNonEmptyStringRecord(source, key, prefix = "") {
1364
+ if (!optionalString(source, key)) {
1365
+ throw new Error(`${prefix}${key} is required.`);
1366
+ }
1367
+ }
1368
+ function requireKnownStringRecord(source, key, allowed, prefix = "") {
1369
+ const value = normalizedString(optionalString(source, key));
1370
+ if (!allowed.has(value)) {
1371
+ throw new Error(`${prefix}${key} must be one of ${[...allowed].sort().join(", ")}.`);
1372
+ }
1373
+ }
1374
+ function requireNonEmptyStringArrayRecord(source, key, prefix = "") {
1375
+ const value = source[key];
1376
+ if (!Array.isArray(value) || value.length === 0) {
1377
+ throw new Error(`${prefix}${key} must include at least one value.`);
1378
+ }
1379
+ for (const [index, entry] of value.entries()) {
1380
+ if (typeof entry !== "string" || entry.trim().length === 0) {
1381
+ throw new Error(`${prefix}${key}[${index}] must be a non-empty string.`);
1382
+ }
1383
+ }
1384
+ }
1385
+ function requireSubstantiveEvidenceRecord(source, prefix = "") {
1386
+ const evidence = source.evidence;
1387
+ if (!evidence || typeof evidence !== "object" || Array.isArray(evidence)) {
1388
+ throw new Error(`${prefix}evidence must be an object.`);
1389
+ }
1390
+ if (!Object.values(evidence).some(hasSubstantiveJsonValue)) {
1391
+ throw new Error(`${prefix}evidence must include at least one concrete evidence reference or summary.`);
1392
+ }
1393
+ }
1394
+ function hasSubstantiveJsonValue(value) {
1395
+ if (typeof value === "string") {
1396
+ return value.trim().length > 0;
1397
+ }
1398
+ if (Array.isArray(value)) {
1399
+ return value.length > 0;
1400
+ }
1401
+ if (value && typeof value === "object") {
1402
+ return Object.keys(value).length > 0;
1403
+ }
1404
+ return false;
1405
+ }
1406
+ function normalizedString(value) {
1407
+ return typeof value === "string" ? value.trim().toLowerCase().replace(/-/g, "_") : "";
1408
+ }
1409
+ function defaultQaChecklist(status) {
1410
+ return [
1411
+ "Review the validated work item against acceptance criteria.",
1412
+ "Inspect implementation, self-review, and validation evidence when available.",
1413
+ status === "blocked" ? "Record the blocker reason preventing a conclusive QA verdict." : "Record concrete QA evidence and findings."
1414
+ ];
1415
+ }
1416
+ function qaArtifactRelativePath(workItemId, fileName) {
1417
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
1418
+ }
1419
+ function jsonText(value) {
1420
+ return `${JSON.stringify(value, null, 2)}\n`;
1421
+ }
640
1422
  function fallbackReport(parsed, phase, artifactPath) {
641
1423
  return `# Forge ${phase.replace(/_/g, " ")} completion
642
1424