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

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.
@@ -6,8 +6,9 @@ import readline from "node:readline";
6
6
  import { promisify } from "node:util";
7
7
  import { GitClient } from "../../shared/git/git.js";
8
8
  import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
9
+ import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
9
10
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
10
- import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDevelopCycle, completionPromptForPhase, completionRedactionEnv, expectedCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor } from "../phase-completion.js";
11
+ import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDebugCycle, completionPromptForDevelopCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, debugCompletionPhaseOrder, qaCompletionGateOrder } from "../phase-completion.js";
11
12
  import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
12
13
  const fakeWorkerModel = "server-local-fake-worker";
13
14
  const execFileAsync = promisify(execFile);
@@ -24,6 +25,11 @@ export class RoutingProviderCliService {
24
25
  ? await this.deterministicProvider.runImplementation(context)
25
26
  : await this.realProvider.runImplementation(context);
26
27
  }
28
+ async runArchitect(context) {
29
+ return isFakeWorkerModel(context.dispatch.execution.model)
30
+ ? await this.deterministicProvider.runArchitect(context)
31
+ : await this.realProvider.runArchitect(context);
32
+ }
27
33
  async runConflictResolve(context) {
28
34
  return isFakeWorkerModel(context.dispatch.execution.model)
29
35
  ? await this.deterministicProvider.runConflictResolve(context)
@@ -46,6 +52,7 @@ export class ProcessBackedProviderCliService {
46
52
  const { dispatch, worktree } = context;
47
53
  const phase = completionPhaseFromDispatch(dispatch);
48
54
  const developCycle = usesDevelopCycleCompletion(dispatch);
55
+ const debugCycle = usesDebugCycleCompletion(dispatch);
49
56
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
50
57
  await fs.mkdir(metadataRoot, { recursive: true });
51
58
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -59,7 +66,11 @@ export class ProcessBackedProviderCliService {
59
66
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
60
67
  const command = buildProviderCliCommand(dispatch, {
61
68
  worktreePath: worktree.worktreePath,
62
- prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
69
+ prompt: debugCycle
70
+ ? buildDebugCyclePrompt(dispatch, phase)
71
+ : developCycle
72
+ ? buildDevelopCyclePrompt(dispatch, phase)
73
+ : buildImplementationPrompt(dispatch, phase),
63
74
  completionTools
64
75
  });
65
76
  await context.emit({
@@ -71,13 +82,15 @@ export class ProcessBackedProviderCliService {
71
82
  await context.emit({
72
83
  role: "runner",
73
84
  kind: "checkpoint",
74
- content: developCycle
75
- ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
76
- : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
85
+ content: debugCycle
86
+ ? "Forge Debug completion tools configured for debug_repro -> debug_root_cause -> debug_fix -> debug_regression; provider must call each MCP completion tool before exit."
87
+ : developCycle
88
+ ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
89
+ : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
77
90
  eventType: "completion_tools_configured"
78
91
  });
79
92
  const outputState = createProviderOutputState(dispatch.execution.provider);
80
- const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, context.emit);
93
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
81
94
  let result;
82
95
  try {
83
96
  liveCompletionEvents.start();
@@ -111,7 +124,7 @@ export class ProcessBackedProviderCliService {
111
124
  });
112
125
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
113
126
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
114
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle);
127
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
115
128
  for (const artifact of completionArtifacts) {
116
129
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
117
130
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -137,7 +150,7 @@ export class ProcessBackedProviderCliService {
137
150
  });
138
151
  }
139
152
  return {
140
- summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
153
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
141
154
  spec: {
142
155
  repoPath: worktree.worktreePath,
143
156
  path: specPath,
@@ -149,11 +162,95 @@ export class ProcessBackedProviderCliService {
149
162
  artifacts: completionArtifacts
150
163
  };
151
164
  }
165
+ async runArchitect(context) {
166
+ const { dispatch, worktree } = context;
167
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
168
+ const command = buildProviderCliCommand(dispatch, {
169
+ worktreePath: worktree.worktreePath,
170
+ prompt: buildArchitectPrompt(dispatch),
171
+ completionTools
172
+ });
173
+ const commandText = formatProviderCliCommand(command);
174
+ await context.emit({
175
+ role: "runner",
176
+ kind: "checkpoint",
177
+ content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
178
+ eventType: "provider_cli_started"
179
+ });
180
+ await context.emit({
181
+ role: "runner",
182
+ kind: "checkpoint",
183
+ content: "Forge Architect completion tools configured; provider must call forge.complete_architect_plan before exit.",
184
+ eventType: "completion_tools_configured"
185
+ });
186
+ const outputState = createProviderOutputState(dispatch.execution.provider);
187
+ let result;
188
+ try {
189
+ result = await this.processRunner.run({
190
+ command: command.command,
191
+ args: command.args,
192
+ cwd: worktree.worktreePath,
193
+ env: providerRedactionEnv(dispatch)
194
+ }, {
195
+ onStdoutLine: async (line) => {
196
+ const event = outputState.consume(line);
197
+ if (event) {
198
+ await context.emit(event);
199
+ }
200
+ }
201
+ }, context.signal);
202
+ }
203
+ finally {
204
+ await cleanupCompletionTools(completionTools, context.emit);
205
+ }
206
+ if (result.exitCode !== 0) {
207
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
208
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
209
+ }
210
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
211
+ const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
212
+ if (!architectArtifact) {
213
+ throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
214
+ }
215
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
216
+ await context.emit({
217
+ role: "assistant",
218
+ kind: "message",
219
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI produced an Architect plan for ${worktree.branchName}.`,
220
+ eventType: "architect_complete"
221
+ });
222
+ const specPath = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id, "spec.md");
223
+ const specBody = await fs.readFile(specPath, "utf8").catch(() => `# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`);
224
+ return {
225
+ summary: `${dispatch.execution.provider} CLI Architect plan produced.`,
226
+ spec: {
227
+ repoPath: worktree.worktreePath,
228
+ path: specPath,
229
+ body: specBody,
230
+ producedBy: `${dispatch.execution.provider}-cli`,
231
+ status: "pending_approval"
232
+ },
233
+ artifact: architectArtifact,
234
+ artifacts: [architectArtifact]
235
+ };
236
+ }
152
237
  async runQa(context) {
153
238
  const { dispatch, worktree } = context;
239
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
240
+ await fs.mkdir(metadataRoot, { recursive: true });
241
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
242
+ if (!laneCommand) {
243
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
244
+ }
245
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem, "qa");
246
+ const specPath = path.join(metadataRoot, "spec.md");
247
+ await fs.writeFile(specPath, specBody, "utf8");
248
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
249
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
154
250
  const command = buildProviderCliCommand(dispatch, {
155
251
  worktreePath: worktree.worktreePath,
156
- prompt: buildQaPrompt(dispatch)
252
+ prompt: buildQaPrompt(dispatch, specBody),
253
+ completionTools
157
254
  });
158
255
  const commandText = formatProviderCliCommand(command);
159
256
  await context.emit({
@@ -162,20 +259,35 @@ export class ProcessBackedProviderCliService {
162
259
  content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
163
260
  eventType: "provider_cli_started"
164
261
  });
262
+ await context.emit({
263
+ role: "runner",
264
+ kind: "checkpoint",
265
+ content: "Forge QA completion tools configured; provider must call all seven QA MCP gates before exit.",
266
+ eventType: "completion_tools_configured"
267
+ });
165
268
  const outputState = createProviderOutputState(dispatch.execution.provider);
166
- const result = await this.processRunner.run({
167
- command: command.command,
168
- args: command.args,
169
- cwd: worktree.worktreePath,
170
- env: providerRedactionEnv(dispatch)
171
- }, {
172
- onStdoutLine: async (line) => {
173
- const event = outputState.consume(line);
174
- if (event) {
175
- await context.emit(event);
269
+ const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
270
+ let result;
271
+ try {
272
+ liveQaEvents.start();
273
+ result = await this.processRunner.run({
274
+ command: command.command,
275
+ args: command.args,
276
+ cwd: worktree.worktreePath,
277
+ env: providerRedactionEnv(dispatch)
278
+ }, {
279
+ onStdoutLine: async (line) => {
280
+ const event = outputState.consume(line);
281
+ if (event) {
282
+ await context.emit(event);
283
+ }
176
284
  }
177
- }
178
- }, context.signal);
285
+ }, context.signal);
286
+ }
287
+ finally {
288
+ await liveQaEvents.stop();
289
+ await cleanupCompletionTools(completionTools, context.emit);
290
+ }
179
291
  if (result.exitCode !== 0) {
180
292
  const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
181
293
  throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
@@ -187,34 +299,50 @@ export class ProcessBackedProviderCliService {
187
299
  eventType: "provider_cli_completed"
188
300
  });
189
301
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
190
- const summary = outputState.finalMessage || `${dispatch.execution.provider} CLI QA passed.`;
191
- const qaArtifact = await writeQaArtifacts({
192
- worktreePath: worktree.worktreePath,
193
- workItemId: dispatch.workItem.id,
194
- acceptanceCriteria: dispatch.workItem.acceptanceCriteria,
195
- producedBy: `${dispatch.execution.provider}-cli`,
196
- provider: dispatch.execution.provider,
197
- model: dispatch.execution.model,
198
- command: commandText,
199
- summary
200
- });
201
- await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
302
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
303
+ if (!qaArtifact) {
304
+ const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
305
+ throw new Error(verdictOnly
306
+ ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
307
+ : "Provider CLI QA completed but did not call the Forge QA completion tool.");
308
+ }
309
+ enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
310
+ if (!liveQaEvents.hasEmitted()) {
311
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
312
+ await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
313
+ }
314
+ const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
315
+ const statusSummary = status === "pass"
316
+ ? "passed"
317
+ : status === "blocked"
318
+ ? "blocked"
319
+ : "found rework";
202
320
  return {
203
- summary: `${dispatch.execution.provider} CLI QA passed.`,
321
+ summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
322
+ spec: {
323
+ repoPath: worktree.worktreePath,
324
+ path: specPath,
325
+ body: specBody,
326
+ producedBy: "forge-lane-command",
327
+ status: "approved"
328
+ },
204
329
  artifact: qaArtifact,
205
330
  artifacts: [qaArtifact]
206
331
  };
207
332
  }
208
333
  async runConflictResolve(context) {
209
334
  const { dispatch, worktree } = context;
335
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
210
336
  const command = buildProviderCliCommand(dispatch, {
211
337
  worktreePath: worktree.worktreePath,
212
- prompt: buildConflictResolvePrompt(dispatch, worktree.branchName)
338
+ prompt: addressComments
339
+ ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
340
+ : buildConflictResolvePrompt(dispatch, worktree.branchName)
213
341
  });
214
342
  await context.emit({
215
343
  role: "runner",
216
344
  kind: "checkpoint",
217
- content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
345
+ content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
218
346
  eventType: "provider_cli_started"
219
347
  });
220
348
  const outputState = createProviderOutputState(dispatch.execution.provider);
@@ -240,11 +368,15 @@ export class ProcessBackedProviderCliService {
240
368
  await context.emit({
241
369
  role: "assistant",
242
370
  kind: "message",
243
- content: outputState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
244
- eventType: "conflict_resolve_complete"
371
+ content: outputState.finalMessage || (addressComments
372
+ ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
373
+ : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
374
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
245
375
  });
246
376
  return {
247
- summary: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
377
+ summary: addressComments
378
+ ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
379
+ : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
248
380
  };
249
381
  }
250
382
  }
@@ -257,6 +389,7 @@ export class DeterministicProviderCliService {
257
389
  const { dispatch, worktree } = context;
258
390
  const phase = completionPhaseFromDispatch(dispatch);
259
391
  const developCycle = usesDevelopCycleCompletion(dispatch);
392
+ const debugCycle = usesDebugCycleCompletion(dispatch);
260
393
  const providerCommand = buildProviderCliCommand(dispatch);
261
394
  const providerCommandText = formatProviderCliCommand(providerCommand);
262
395
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -287,9 +420,11 @@ export class DeterministicProviderCliService {
287
420
  content: `Created bridge changeset at ${changesetPath}`,
288
421
  eventType: "changeset"
289
422
  });
290
- const phases = developCycle
291
- ? ["implementation", "self_review", "validation"]
292
- : [phase];
423
+ const phases = debugCycle
424
+ ? debugCompletionPhaseOrder
425
+ : developCycle
426
+ ? ["implementation", "self_review", "validation"]
427
+ : [phase];
293
428
  const completionArtifacts = [];
294
429
  for (const completionPhase of phases) {
295
430
  await writeCompletionArtifact({
@@ -298,7 +433,9 @@ export class DeterministicProviderCliService {
298
433
  phase: completionPhase,
299
434
  producedBy: "forge-bridge",
300
435
  redactionSecrets: exactRedactionSecrets(dispatch)
301
- }, expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
436
+ }, isDebugCompletionPhaseForProvider(completionPhase)
437
+ ? expectedDebugCompletionToolName(completionPhase)
438
+ : expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
302
439
  const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
303
440
  if (!completionArtifact) {
304
441
  throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
@@ -314,7 +451,7 @@ export class DeterministicProviderCliService {
314
451
  }
315
452
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
316
453
  return {
317
- summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
454
+ summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
318
455
  spec: {
319
456
  repoPath: worktree.worktreePath,
320
457
  path: specPath,
@@ -326,57 +463,130 @@ export class DeterministicProviderCliService {
326
463
  artifacts: completionArtifacts
327
464
  };
328
465
  }
329
- async runQa(context) {
466
+ async runArchitect(context) {
330
467
  const { dispatch, worktree } = context;
331
- await context.emit({
332
- role: "worker",
333
- kind: "message",
334
- content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
335
- eventType: "qa_analysis"
336
- });
337
- const summary = "All checks passed. forge-bridge QA completed.";
338
- const qaArtifact = await writeQaArtifacts({
468
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
469
+ await fs.mkdir(metadataRoot, { recursive: true });
470
+ const specBody = `---\ntitle: "${dispatch.workItem.title}"\nstatus: pending_approval\nproduced_by: forge-bridge\n---\n\n# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`;
471
+ const specPath = path.join(metadataRoot, "spec.md");
472
+ await fs.writeFile(specPath, specBody, "utf8");
473
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
474
+ await writeCompletionArtifact({
339
475
  worktreePath: worktree.worktreePath,
340
476
  workItemId: dispatch.workItem.id,
341
- acceptanceCriteria: dispatch.workItem.acceptanceCriteria,
477
+ phase: "architect",
342
478
  producedBy: "forge-bridge",
343
- provider: dispatch.execution.provider,
344
- model: dispatch.execution.model,
345
- command: "forge-bridge deterministic QA",
346
- summary
347
- });
348
- await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
479
+ redactionSecrets: exactRedactionSecrets(dispatch),
480
+ architectCycle: true
481
+ }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
482
+ const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
483
+ if (!artifact) {
484
+ throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
485
+ }
486
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
349
487
  await context.emit({
350
488
  role: "assistant",
351
489
  kind: "message",
352
- content: summary,
353
- eventType: "qa_complete"
490
+ content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
491
+ eventType: "architect_complete"
354
492
  });
493
+ return {
494
+ summary: "forge-bridge completed Architect plan (deterministic).",
495
+ spec: {
496
+ repoPath: worktree.worktreePath,
497
+ path: specPath,
498
+ body: specBody,
499
+ producedBy: "forge-bridge",
500
+ status: "pending_approval"
501
+ },
502
+ artifact,
503
+ artifacts: [artifact]
504
+ };
505
+ }
506
+ async runQa(context) {
507
+ const { dispatch, worktree } = context;
508
+ await context.emit({
509
+ role: "worker",
510
+ kind: "message",
511
+ content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
512
+ eventType: "qa_plan"
513
+ });
514
+ const qaBrowser = dispatch.qaBrowser;
515
+ const launchTarget = qaBrowser?.launchTarget ?? null;
516
+ const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
517
+ const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
518
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget)
519
+ : null;
520
+ const browserChecks = browserSidecar && launchTarget
521
+ ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
522
+ : [];
523
+ const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
524
+ const summary = missingLaunchTarget
525
+ ? "QA blocked because browser testing is required but no app launch target was provided."
526
+ : "All checks passed. forge-bridge QA completed.";
527
+ const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
528
+ for (const gate of qaCompletionGateOrder) {
529
+ await writeCompletionArtifact({
530
+ worktreePath: worktree.worktreePath,
531
+ workItemId: dispatch.workItem.id,
532
+ phase: "qa",
533
+ producedBy: "forge-bridge",
534
+ redactionSecrets: exactRedactionSecrets(dispatch),
535
+ qaCycle: true
536
+ }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
537
+ gate,
538
+ criterion,
539
+ summary,
540
+ missingLaunchTarget,
541
+ browserChecks,
542
+ sidecars
543
+ }));
544
+ await context.emit({
545
+ role: "hook",
546
+ kind: "checkpoint",
547
+ content: `qa_gate: ${gate} artifact accepted.`,
548
+ eventType: "qa_gate"
549
+ });
550
+ }
551
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
552
+ if (!qaArtifact) {
553
+ throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
554
+ }
555
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
556
+ await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
355
557
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
356
558
  return {
357
- summary: "forge-bridge QA passed.",
559
+ summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
358
560
  artifact: qaArtifact,
359
561
  artifacts: [qaArtifact]
360
562
  };
361
563
  }
362
564
  async runConflictResolve(context) {
363
565
  const { dispatch, worktree } = context;
364
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
566
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
567
+ await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
365
568
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
366
569
  await context.emit({
367
570
  role: "assistant",
368
571
  kind: "message",
369
- content: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
370
- eventType: "conflict_resolve_complete"
572
+ content: addressComments
573
+ ? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
574
+ : `Deterministic conflict resolve completed for ${worktree.branchName}.`,
575
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
371
576
  });
372
577
  return {
373
- summary: `forge-bridge resolved conflicts for ${worktree.branchName}.`
578
+ summary: addressComments
579
+ ? `forge-bridge addressed PR comments for ${worktree.branchName}.`
580
+ : `forge-bridge resolved conflicts for ${worktree.branchName}.`
374
581
  };
375
582
  }
376
583
  }
377
584
  function phaseCompleteEventType(phase) {
378
585
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
379
586
  }
587
+ function isDebugCompletionPhaseForProvider(phase) {
588
+ return debugCompletionPhaseOrder.includes(phase);
589
+ }
380
590
  function deterministicCompletionPayload(phase, dispatch, changesetBody) {
381
591
  const changesetHash = sha256(changesetBody);
382
592
  const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
@@ -399,6 +609,56 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
399
609
  next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
400
610
  };
401
611
  }
612
+ if (phase === "debug_repro") {
613
+ return {
614
+ status: "pass",
615
+ summary: "forge-bridge reproduced the bug deterministically.",
616
+ repro_steps: ["Run the deterministic fake-worker debug reproduction."],
617
+ observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
618
+ expected: "The bug scenario should be fixed before QA handoff.",
619
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
620
+ };
621
+ }
622
+ if (phase === "debug_root_cause") {
623
+ return {
624
+ status: "pass",
625
+ summary: "forge-bridge isolated a deterministic root cause.",
626
+ root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
627
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
628
+ eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
629
+ risk_area: "forge-bridge deterministic debug lane"
630
+ };
631
+ }
632
+ if (phase === "debug_fix") {
633
+ return {
634
+ status: "pass",
635
+ summary: "forge-bridge applied a deterministic debug fix.",
636
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
637
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
638
+ remaining_risks: [],
639
+ resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
640
+ qa_id: qaId,
641
+ status: "resolved",
642
+ summary: `Resolved deterministic QA finding ${qaId}.`,
643
+ evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
644
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
645
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
646
+ regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
647
+ }))
648
+ };
649
+ }
650
+ if (phase === "debug_regression") {
651
+ return {
652
+ status: "pass",
653
+ summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
654
+ commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
655
+ required_regressions: ["Original deterministic repro no longer fails."],
656
+ build_status: "not_applicable",
657
+ test_status: "pass",
658
+ repro_negative: true,
659
+ qa_ready: true
660
+ };
661
+ }
402
662
  if (phase === "self_review") {
403
663
  return {
404
664
  status: "pass",
@@ -459,6 +719,149 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
459
719
  ready_for_dev_test: true
460
720
  };
461
721
  }
722
+ function deterministicArchitectPayload(dispatch) {
723
+ const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
724
+ return {
725
+ status: "pass",
726
+ summary: "forge-bridge produced a deterministic Architect plan.",
727
+ implementation_plan: {
728
+ schema_version: 1,
729
+ plan_id: planId,
730
+ story_id: dispatch.workItem.id,
731
+ phases: [
732
+ { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
733
+ ],
734
+ tasks: [
735
+ {
736
+ id: "task-1",
737
+ title: `Implement ${dispatch.workItem.title}`,
738
+ phase: "phase-1",
739
+ summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
740
+ acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
741
+ tests: [
742
+ { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
743
+ ]
744
+ }
745
+ ],
746
+ dependencies: [],
747
+ phase_gates: [
748
+ { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
749
+ ]
750
+ },
751
+ qa_plan: {
752
+ schema_version: 1,
753
+ plan_id: planId,
754
+ final_qa: [
755
+ { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
756
+ ]
757
+ },
758
+ report_markdown: `# Architect Report\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\n\nVerdict: pass\n\nDeterministic bridge Architect plan produced for pending approval.\n`
759
+ };
760
+ }
761
+ function deterministicQaGatePayload(options) {
762
+ const blocked = options.missingLaunchTarget;
763
+ const skippedBecauseBlocked = blocked
764
+ ? {
765
+ status: "skipped",
766
+ summary: "Skipped because browser QA was blocked by missing launch target.",
767
+ reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
768
+ }
769
+ : null;
770
+ switch (options.gate) {
771
+ case "qa_plan":
772
+ return {
773
+ status: "pass",
774
+ summary: "Deterministic QA plan recorded.",
775
+ checklist: [
776
+ "Review the validated work item against acceptance criteria.",
777
+ "Run deterministic regression evidence.",
778
+ "Confirm no in-scope QA findings remain."
779
+ ],
780
+ acceptance_criteria: [options.criterion]
781
+ };
782
+ case "qa_regression":
783
+ return {
784
+ status: "pass",
785
+ summary: "Deterministic regression QA completed.",
786
+ commands: [
787
+ {
788
+ command: "forge-bridge deterministic QA",
789
+ exit_code: 0,
790
+ status: "pass",
791
+ summary: "Deterministic regression evidence completed."
792
+ }
793
+ ],
794
+ notes: "Regression gate passed in deterministic fake-worker mode."
795
+ };
796
+ case "qa_api":
797
+ return {
798
+ status: "skipped",
799
+ summary: "No API/backend surface was identified for deterministic QA.",
800
+ reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
801
+ };
802
+ case "qa_manual_web":
803
+ return blocked
804
+ ? {
805
+ status: "blocked",
806
+ summary: "Browser QA could not run because no app launch target was provided.",
807
+ blocker_reason: "missing_app_launch_target"
808
+ }
809
+ : options.browserChecks.length > 0
810
+ ? {
811
+ status: "pass",
812
+ summary: "Deterministic browser QA exercised the configured launch target.",
813
+ browser_checks: options.browserChecks,
814
+ sidecars: options.sidecars,
815
+ notes: "Browser sidecar evidence recorded."
816
+ }
817
+ : {
818
+ status: "skipped",
819
+ summary: "Manual web QA was not required for this deterministic run.",
820
+ reason: "Forge did not require browser QA and no launch target was necessary."
821
+ };
822
+ case "qa_bug_repro":
823
+ return skippedBecauseBlocked ?? {
824
+ status: "skipped",
825
+ summary: "No failed QA observation required bug reproduction.",
826
+ reason: "No defects or candidate bugs were observed."
827
+ };
828
+ case "qa_findings":
829
+ return skippedBecauseBlocked ?? {
830
+ status: "pass",
831
+ summary: "No QA findings or candidate bugs were identified.",
832
+ findings: [],
833
+ candidate_bugs: []
834
+ };
835
+ case "qa_verdict":
836
+ return {
837
+ status: blocked ? "blocked" : "pass",
838
+ summary: options.summary,
839
+ checklist: [
840
+ "Review the validated work item against acceptance criteria.",
841
+ "Run deterministic regression evidence.",
842
+ blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
843
+ ],
844
+ tested_acceptance_criteria: blocked ? [] : [options.criterion],
845
+ commands: blocked
846
+ ? []
847
+ : [
848
+ {
849
+ command: "forge-bridge deterministic QA",
850
+ exit_code: 0,
851
+ status: "pass",
852
+ summary: "Deterministic QA command completed."
853
+ }
854
+ ],
855
+ browser_checks: blocked ? [] : options.browserChecks,
856
+ sidecars: blocked ? [] : options.sidecars,
857
+ notes: options.summary,
858
+ findings: [],
859
+ candidate_bugs: [],
860
+ blocker_reason: blocked ? "missing_app_launch_target" : null,
861
+ report_markdown: `# QA report\n\n${options.summary}\n`
862
+ };
863
+ }
864
+ }
462
865
  const qaArtifactFileNames = {
463
866
  plan: "qa.plan.json",
464
867
  evidence: "qa.evidence.json",
@@ -466,73 +869,57 @@ const qaArtifactFileNames = {
466
869
  verdict: "qa.verdict.json",
467
870
  report: "qa.report.md"
468
871
  };
469
- async function writeQaArtifacts(request) {
470
- const artifactRoot = artifactRootFor(request.worktreePath, request.workItemId);
471
- await fs.mkdir(artifactRoot, { recursive: true });
472
- const criterion = request.acceptanceCriteria.trim() || "Forge QA evidence exists";
473
- const relativeEvidencePath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.evidence);
474
- const relativeFindingsPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.findings);
475
- const relativeReportPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.report);
476
- const planJson = jsonText({
477
- schema_version: 1,
478
- phase: "qa",
479
- checklist: [
480
- "Review the validated work item against acceptance criteria.",
481
- "Run relevant provider QA verification.",
482
- "Confirm no in-scope QA findings remain."
483
- ],
484
- acceptance_criteria: [criterion]
485
- });
486
- const evidenceJson = jsonText({
487
- schema_version: 1,
488
- phase: "qa",
489
- commands: [
490
- {
491
- command: request.command,
492
- exit_code: 0,
493
- status: "pass",
494
- summary: `${request.provider} QA completed successfully.`
495
- }
496
- ],
497
- browser_checks: [],
498
- notes: request.summary
499
- });
500
- const findingsJson = jsonText({
501
- schema_version: 1,
502
- phase: "qa",
503
- findings: [],
504
- candidate_bugs: []
505
- });
506
- const verdictJson = jsonText({
507
- schema_version: 1,
508
- phase: "qa",
509
- status: "pass",
510
- summary: request.summary,
511
- tested_acceptance_criteria: [criterion],
512
- finding_ids: [],
513
- candidate_bug_ids: [],
514
- blocker_reason: null,
515
- evidence_path: relativeEvidencePath,
516
- findings_path: relativeFindingsPath,
517
- report_path: relativeReportPath
518
- });
519
- const report = `# QA report\n\n${request.summary}\n\n- Provider: ${singleLine(request.provider)}\n- Model: ${singleLine(request.model)}\n- Command: ${singleLine(request.command)}\n`;
520
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.plan), planJson, "utf8");
521
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.evidence), evidenceJson, "utf8");
522
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.findings), findingsJson, "utf8");
523
- const verdictPath = path.join(artifactRoot, qaArtifactFileNames.verdict);
524
- await fs.writeFile(verdictPath, verdictJson, "utf8");
525
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.report), report, "utf8");
872
+ function hasLaunchTarget(target) {
873
+ return Boolean(target?.url?.trim()
874
+ || target?.ready_url?.trim()
875
+ || target?.command?.trim()
876
+ || (target?.routes ?? []).some((route) => route.trim().length > 0));
877
+ }
878
+ function deterministicBrowserSidecar(workItemId, target) {
879
+ const route = primaryLaunchRoute(target);
880
+ return {
881
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt"),
882
+ content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
883
+ };
884
+ }
885
+ function deterministicBrowserCheck(target, screenshotPath) {
886
+ const route = primaryLaunchRoute(target);
526
887
  return {
527
- repoPath: request.worktreePath,
528
- path: verdictPath,
529
- verdictJson,
530
- report,
531
- producedBy: request.producedBy,
888
+ route,
889
+ url: route,
532
890
  status: "pass",
533
- phase: "qa"
891
+ summary: "Deterministic browser QA exercised the configured launch target.",
892
+ actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
893
+ screenshots: [screenshotPath],
894
+ console_errors: [],
895
+ network_errors: [],
896
+ responsive_checks: ["desktop", "mobile"]
534
897
  };
535
898
  }
899
+ function primaryLaunchRoute(target) {
900
+ return target.ready_url?.trim()
901
+ || target.url?.trim()
902
+ || target.routes.find((route) => route.trim().length > 0)?.trim()
903
+ || "app launch command";
904
+ }
905
+ async function writeQaSidecarFiles(worktreePath, files) {
906
+ const sidecars = [];
907
+ for (const file of files) {
908
+ const fullPath = path.resolve(worktreePath, file.relativePath);
909
+ const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
910
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
911
+ throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
912
+ }
913
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
914
+ await fs.writeFile(fullPath, file.content, "utf8");
915
+ sidecars.push({
916
+ path: relativePath,
917
+ content_hash: sha256(file.content),
918
+ bytes: Buffer.byteLength(file.content, "utf8")
919
+ });
920
+ }
921
+ return sidecars;
922
+ }
536
923
  async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
537
924
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
538
925
  await emit({
@@ -548,12 +935,203 @@ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
548
935
  eventType: "phase_gate"
549
936
  });
550
937
  }
938
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
939
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
940
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
941
+ return null;
942
+ }
943
+ await validateQaBundleSidecarReferences(worktreePath, workItemId);
944
+ return artifact;
945
+ }
946
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
947
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
948
+ for (const fileName of Object.values(qaArtifactFileNames)) {
949
+ try {
950
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
951
+ if (!stat.isFile()) {
952
+ return false;
953
+ }
954
+ }
955
+ catch (error) {
956
+ if (isNodeError(error) && error.code === "ENOENT") {
957
+ return false;
958
+ }
959
+ throw error;
960
+ }
961
+ }
962
+ return true;
963
+ }
964
+ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
965
+ const qaBrowser = dispatch.qaBrowser;
966
+ if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
967
+ return;
968
+ }
969
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
970
+ const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
971
+ const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
972
+ if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
973
+ throw new Error("QA browser testing is required but no app launch target was provided; provider must return blocked with blocker_reason missing_app_launch_target.");
974
+ }
975
+ }
976
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
977
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
978
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
979
+ const sidecars = arrayField(evidence, "sidecars");
980
+ if (sidecars.length === 0) {
981
+ return;
982
+ }
983
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
984
+ for (const [index, sidecar] of sidecars.entries()) {
985
+ const sidecarPath = stringField(sidecar, "path");
986
+ const expectedHash = stringField(sidecar, "content_hash");
987
+ const expectedBytes = sidecar.bytes;
988
+ if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
989
+ throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
990
+ }
991
+ if (path.isAbsolute(sidecarPath)) {
992
+ throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
993
+ }
994
+ const fullPath = path.resolve(worktreePath, sidecarPath);
995
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
996
+ throw new Error(`QA sidecar ${index} path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
997
+ }
998
+ const stat = await fs.lstat(fullPath).catch((error) => {
999
+ if (isNodeError(error) && error.code === "ENOENT") {
1000
+ throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
1001
+ }
1002
+ throw error;
1003
+ });
1004
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1005
+ throw new Error(`QA sidecar ${index} must reference a regular file.`);
1006
+ }
1007
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
1008
+ if (stat.size !== expectedBytes) {
1009
+ throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
1010
+ }
1011
+ const actualHash = await sha256File(fullPath);
1012
+ if (actualHash !== expectedHash.trim().toLowerCase()) {
1013
+ throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
1014
+ }
1015
+ }
1016
+ }
1017
+ async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
1018
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1019
+ const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
1020
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1021
+ const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
1022
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1023
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1024
+ const checklist = stringArrayField(plan, "checklist");
1025
+ await emit({
1026
+ role: "worker",
1027
+ kind: "message",
1028
+ content: checklist.length > 0
1029
+ ? `QA plan: ${checklist.join("; ")}`
1030
+ : "QA plan recorded.",
1031
+ eventType: "qa_plan"
1032
+ });
1033
+ for (const browserCheck of arrayField(evidence, "browser_checks")) {
1034
+ await emit({
1035
+ role: "worker",
1036
+ kind: "checkpoint",
1037
+ content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
1038
+ eventType: "qa_browser_check"
1039
+ });
1040
+ }
1041
+ for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
1042
+ await emit({
1043
+ role: "worker",
1044
+ kind: "checkpoint",
1045
+ content: `QA finding: ${summarizeQaObject(finding)}`,
1046
+ eventType: "qa_finding"
1047
+ });
1048
+ }
1049
+ await emit({
1050
+ role: "assistant",
1051
+ kind: "message",
1052
+ content: status === "blocked"
1053
+ ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
1054
+ : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
1055
+ eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
1056
+ });
1057
+ }
1058
+ class LiveQaArtifactEmitter {
1059
+ worktreePath;
1060
+ workItemId;
1061
+ dispatch;
1062
+ emit;
1063
+ emitted = false;
1064
+ timer = null;
1065
+ pending = Promise.resolve();
1066
+ constructor(worktreePath, workItemId, dispatch, emit) {
1067
+ this.worktreePath = worktreePath;
1068
+ this.workItemId = workItemId;
1069
+ this.dispatch = dispatch;
1070
+ this.emit = emit;
1071
+ }
1072
+ start() {
1073
+ void this.pollQueued();
1074
+ this.timer = setInterval(() => {
1075
+ void this.pollQueued();
1076
+ }, 250);
1077
+ }
1078
+ async stop() {
1079
+ if (this.timer) {
1080
+ clearInterval(this.timer);
1081
+ this.timer = null;
1082
+ }
1083
+ await this.pollQueued();
1084
+ }
1085
+ hasEmitted() {
1086
+ return this.emitted;
1087
+ }
1088
+ pollQueued() {
1089
+ this.pending = this.pending
1090
+ .then(() => this.poll())
1091
+ .catch(() => undefined);
1092
+ return this.pending;
1093
+ }
1094
+ async poll() {
1095
+ if (this.emitted) {
1096
+ return;
1097
+ }
1098
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
1099
+ if (!artifact) {
1100
+ return;
1101
+ }
1102
+ enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
1103
+ this.emitted = true;
1104
+ await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
1105
+ await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1106
+ }
1107
+ }
1108
+ async function readJsonObjectFile(filePath) {
1109
+ const content = await fs.readFile(filePath, "utf8").catch(() => "");
1110
+ return parseJsonLine(content) ?? {};
1111
+ }
1112
+ function arrayField(source, key) {
1113
+ const value = source[key];
1114
+ if (!Array.isArray(value)) {
1115
+ return [];
1116
+ }
1117
+ return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
1118
+ }
1119
+ function stringArrayField(source, key) {
1120
+ const value = source[key];
1121
+ if (!Array.isArray(value)) {
1122
+ return [];
1123
+ }
1124
+ return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
1125
+ }
1126
+ function summarizeQaObject(source) {
1127
+ return clip(stringField(source, "title")
1128
+ ?? stringField(source, "summary")
1129
+ ?? stringField(source, "id")
1130
+ ?? JSON.stringify(source), 500);
1131
+ }
551
1132
  function qaArtifactRelativePath(workItemId, fileName) {
552
1133
  return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
553
1134
  }
554
- function jsonText(value) {
555
- return `${JSON.stringify(value, null, 2)}\n`;
556
- }
557
1135
  async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
558
1136
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
559
1137
  await emit({
@@ -588,7 +1166,15 @@ async function emitPhaseGateEvents(emit, artifact) {
588
1166
  ? "phase_progression: implementation -> self_review"
589
1167
  : phase === "self_review"
590
1168
  ? "phase_progression: self_review -> validation"
591
- : "phase_progression: validation -> QA ready";
1169
+ : phase === "debug_repro"
1170
+ ? "phase_progression: debug_repro -> debug_root_cause"
1171
+ : phase === "debug_root_cause"
1172
+ ? "phase_progression: debug_root_cause -> debug_fix"
1173
+ : phase === "debug_fix"
1174
+ ? "phase_progression: debug_fix -> debug_regression"
1175
+ : phase === "debug_regression"
1176
+ ? "phase_progression: debug_regression -> QA ready"
1177
+ : "phase_progression: validation -> QA ready";
592
1178
  await emit({
593
1179
  role: "hook",
594
1180
  kind: "checkpoint",
@@ -598,7 +1184,8 @@ async function emitPhaseGateEvents(emit, artifact) {
598
1184
  }
599
1185
  function completionPhaseFromArtifact(artifact) {
600
1186
  const phase = artifact.phase?.trim();
601
- return phase === "self_review" || phase === "validation" || phase === "implementation"
1187
+ return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1188
+ || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
602
1189
  ? phase
603
1190
  : "implementation";
604
1191
  }
@@ -610,13 +1197,18 @@ class LiveCompletionArtifactEmitter {
610
1197
  emitted = new Set();
611
1198
  timer = null;
612
1199
  pending = Promise.resolve();
613
- constructor(worktreePath, workItemId, phase, developCycle, emit) {
1200
+ constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
614
1201
  this.worktreePath = worktreePath;
615
1202
  this.workItemId = workItemId;
616
1203
  this.emit = emit;
617
- this.phases = developCycle
618
- ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
619
- : [phase];
1204
+ if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
1205
+ this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
1206
+ }
1207
+ else {
1208
+ this.phases = developCycle
1209
+ ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1210
+ : [phase];
1211
+ }
620
1212
  }
621
1213
  start() {
622
1214
  void this.pollQueued();
@@ -659,20 +1251,23 @@ class LiveCompletionArtifactEmitter {
659
1251
  }
660
1252
  }
661
1253
  }
662
- async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle) {
663
- if (!developCycle) {
1254
+ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
1255
+ if (!developCycle && !debugCycle) {
664
1256
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
665
1257
  if (!artifact) {
666
1258
  throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
667
1259
  }
668
1260
  return [artifact];
669
1261
  }
1262
+ const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
1263
+ ? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
1264
+ : ["implementation", "self_review", "validation"];
670
1265
  const artifacts = [];
671
- for (const expectedPhase of ["implementation", "self_review", "validation"]) {
1266
+ for (const expectedPhase of expectedPhases) {
672
1267
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
673
1268
  if (!artifact) {
674
1269
  if (artifacts.length === 0) {
675
- throw new Error("Provider CLI completed but did not call the Forge implementation completion tool.");
1270
+ throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
676
1271
  }
677
1272
  const previous = artifacts[artifacts.length - 1];
678
1273
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
@@ -848,9 +1443,6 @@ function quoteWindowsCommandLineArg(value) {
848
1443
  }
849
1444
  return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
850
1445
  }
851
- async function fileExists(inputPath) {
852
- return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
853
- }
854
1446
  async function readProcessLines(stream, onLine) {
855
1447
  const reader = readline.createInterface({ input: stream });
856
1448
  try {
@@ -871,9 +1463,6 @@ function sha256(content) {
871
1463
  export function formatProviderCliCommand(command) {
872
1464
  return [command.command, ...command.args].map(singleLine).join(" ");
873
1465
  }
874
- function yamlQuotedScalar(value) {
875
- return JSON.stringify(singleLine(value));
876
- }
877
1466
  function singleLine(value) {
878
1467
  return value.replace(/\s+/g, " ").trim();
879
1468
  }
@@ -912,11 +1501,25 @@ export function buildProviderCliCommand(dispatch, run) {
912
1501
  }
913
1502
  return { command: provider, args };
914
1503
  }
1504
+ function buildArchitectPrompt(dispatch) {
1505
+ return `You are Forge's Architect lane running locally in a prepared git worktree.
1506
+
1507
+ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
1508
+
1509
+ Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
1510
+ Read injected Forge context under .forge plus the repository shape, then produce a repo-grounded implementation DAG with task tests, phase gates, final QA coverage, and a pending-approval spec.
1511
+ Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
1512
+
1513
+ ${completionPromptForPhase("architect")}
1514
+
1515
+ Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
1516
+ }
915
1517
  function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
916
1518
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
917
1519
 
918
1520
  Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
919
1521
  ${phaseWorkInstruction(phase)}
1522
+ ${qaReworkImplementationInstruction(dispatch)}
920
1523
  Use the repository's existing conventions. Run relevant tests when practical.
921
1524
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
922
1525
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -930,6 +1533,7 @@ function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(d
930
1533
 
931
1534
  Read .forge/work-items/${dispatch.workItem.id}/spec.md, implement the work item, self-review the diff, then validate it in this same provider session.
932
1535
  Start in the ${phase.replace(/_/g, " ")} phase. Do not stop after implementation if it passes; continue through self-review and validation using the next instruction returned by each completion tool.
1536
+ ${qaReworkImplementationInstruction(dispatch)}
933
1537
  Use the repository's existing conventions. Run relevant tests when practical.
934
1538
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
935
1539
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -938,6 +1542,53 @@ ${completionPromptForDevelopCycle(phase)}
938
1542
 
939
1543
  Finish with a concise summary of changed files and verification after the validation completion tool has accepted the work, or after the current phase tool records a non-pass blocker.`;
940
1544
  }
1545
+ function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1546
+ return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
1547
+
1548
+ Read .forge/work-items/${dispatch.workItem.id}/spec.md, reproduce or characterize the bug, isolate root cause, apply the smallest safe fix, then prove the regression in this same provider session.
1549
+ Start in the ${phase.replace(/_/g, " ")} gate. Do not stop after a passing Debug gate; continue through the next Debug MCP instruction returned by the tool server until debug_regression is accepted or the current gate records a non-pass blocker.
1550
+ ${debugQaReworkInstruction(dispatch)}
1551
+ Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
1552
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
1553
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
1554
+
1555
+ ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
1556
+
1557
+ Finish with a concise summary of changed files and verification after the debug_regression completion tool has accepted the work, or after the current Debug gate tool records a non-pass blocker.`;
1558
+ }
1559
+ function qaReworkImplementationInstruction(dispatch) {
1560
+ if (!dispatch.qaRework) {
1561
+ return "";
1562
+ }
1563
+ return `
1564
+ QA rework context:
1565
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1566
+ - Rework packet: ${dispatch.qaRework.packetPath}
1567
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1568
+ Read the packet JSON and fix or explicitly dispute each listed finding. The implementation completion artifact must include resolved_findings entries for every required QA ID with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.`;
1569
+ }
1570
+ function debugQaReworkInstruction(dispatch) {
1571
+ if (!dispatch.qaRework) {
1572
+ return "";
1573
+ }
1574
+ return `
1575
+ QA rework context for Debug:
1576
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1577
+ - Rework packet: ${dispatch.qaRework.packetPath}
1578
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1579
+ Read the packet JSON, reproduce or characterize each listed finding, fix or explicitly dispute it, and include resolved_findings entries for every required QA ID in forge.complete_debug_fix with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.`;
1580
+ }
1581
+ function qaReworkRetestInstruction(dispatch) {
1582
+ if (!dispatch.qaRework) {
1583
+ return "";
1584
+ }
1585
+ return `
1586
+ QA retest context:
1587
+ - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1588
+ - Rework packet: ${dispatch.qaRework.packetPath}
1589
+ - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1590
+ Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
1591
+ }
941
1592
  function phaseWorkInstruction(phase) {
942
1593
  if (phase === "self_review") {
943
1594
  return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
@@ -947,11 +1598,56 @@ function phaseWorkInstruction(phase) {
947
1598
  }
948
1599
  return "Implement the work item and keep the change focused.";
949
1600
  }
950
- function buildQaPrompt(dispatch) {
951
- return `You are Forge's QA lane running locally.
1601
+ function qaBrowserInstruction(dispatch) {
1602
+ const qaBrowser = dispatch.qaBrowser;
1603
+ if (!qaBrowser) {
1604
+ return "Browser/app launch context: not provided by Forge.";
1605
+ }
1606
+ const launchTarget = qaBrowser.launchTarget;
1607
+ if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
1608
+ return `Browser/app launch context:\n- UI/browser QA is required for this item.\n- No app launch target was provided.\n- Return blocked with blocker_reason: missing_app_launch_target instead of pretending browser testing occurred.\n- Artifact sidecars path when available: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
1609
+ }
1610
+ if (!launchTarget) {
1611
+ return `Browser/app launch context:\n- UI/browser QA is not required by Forge heuristics for this item.\n- If you determine browser testing is needed, return blocked with blocker_reason: missing_app_launch_target unless you can safely identify a launch target from the repo.\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
1612
+ }
1613
+ const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
1614
+ return `Browser/app launch context:\n- Browser QA required: ${qaBrowser.required ? "yes" : "no, unless the diff/AC requires it"}\n- URL: ${launchTarget.url || "not specified"}\n- Ready URL: ${launchTarget.ready_url || "not specified"}\n- Launch command: ${launchTarget.command || "not specified"}\n- Working directory: ${launchTarget.working_directory || "repo root"}\n- Routes to cover: ${routes}\n- Notes: ${launchTarget.notes || "none"}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
1615
+ }
1616
+ function buildQaPrompt(dispatch, laneSpec) {
1617
+ return `You are Forge's QA lane running locally in a prepared git worktree.
1618
+
1619
+ First read and follow the injected QA lane command at .forge/work-items/${dispatch.workItem.id}/spec.md. It defines the required gated QA skill workflow for this run.
1620
+
1621
+ Injected QA lane command and work item spec:
1622
+ ${laneSpec}
1623
+
1624
+ ---
1625
+
1626
+ Work item: ${dispatch.workItem.id}
1627
+ Title: ${dispatch.workItem.title}
1628
+ Description:
1629
+ ${dispatch.workItem.description || "Not provided."}
1630
+
1631
+ Acceptance criteria:
1632
+ ${dispatch.workItem.acceptanceCriteria || "Not specified."}
952
1633
 
953
- Review the implementation for work item ${dispatch.workItem.id}: ${dispatch.workItem.title}
954
- Run relevant verification when practical and finish with a concise QA verdict.`;
1634
+ Repro steps / scenario:
1635
+ ${dispatch.workItem.reproSteps || "Not provided."}
1636
+
1637
+ System info / environment notes:
1638
+ ${dispatch.workItem.systemInfo || "Not provided."}
1639
+
1640
+ Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1641
+ ${qaBrowserInstruction(dispatch)}
1642
+ ${qaReworkRetestInstruction(dispatch)}
1643
+ QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
1644
+ Record concrete evidence. For UI/browser work, include browser_checks with URLs/routes, actions, observed results, screenshots/traces when available, console errors, failed network requests, and responsive checks. Store browser sidecars under .forge/work-items/${dispatch.workItem.id}/artifacts/qa/.
1645
+ Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
1646
+ Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
1647
+
1648
+ ${completionPromptForQaCycle()}
1649
+
1650
+ Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
955
1651
  }
956
1652
  function buildConflictResolvePrompt(dispatch, branchName) {
957
1653
  const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
@@ -966,6 +1662,33 @@ Keep the original work item intent intact:
966
1662
 
967
1663
  Finish with a concise summary of the conflicts resolved and verification performed.`;
968
1664
  }
1665
+ function buildPullRequestCommentsPrompt(dispatch, branchName) {
1666
+ const pr = dispatch.pullRequest;
1667
+ const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
1668
+ const prLocator = pr
1669
+ ? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
1670
+ : "the open pull request for this work item";
1671
+ return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
1672
+
1673
+ The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
1674
+ PR context:
1675
+ - Provider: ${pr?.provider || "not provided"}
1676
+ - Source branch: ${pr?.sourceBranch || branchName}
1677
+ - Target branch: ${targetBranch}
1678
+ - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
1679
+
1680
+ Use the PR URL, local git metadata, and available GitHub tooling/auth to inspect unresolved review threads. Make focused code or test changes that answer the feedback, commit the changes, and push ${branchName} to origin.
1681
+ If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
1682
+ Keep the original work item intent intact:
1683
+ - Work item: ${dispatch.workItem.id}
1684
+ - Title: ${dispatch.workItem.title}
1685
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
1686
+
1687
+ Finish with a concise summary of comments addressed and verification performed.`;
1688
+ }
1689
+ function isPullRequestCommentsDispatch(dispatch) {
1690
+ return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
1691
+ }
969
1692
  async function cleanupCompletionTools(completionTools, emit) {
970
1693
  try {
971
1694
  await completionTools.cleanup();
@@ -1308,3 +2031,9 @@ function stringField(source, key) {
1308
2031
  const value = source[key];
1309
2032
  return typeof value === "string" && value.trim().length > 0 ? value : null;
1310
2033
  }
2034
+ function normalizedString(value) {
2035
+ return value.trim().toLowerCase().replace(/-/g, "_");
2036
+ }
2037
+ function isNodeError(error) {
2038
+ return error instanceof Error && "code" in error;
2039
+ }