@loucompanion/forge-bridge 0.1.1-dev.caea7216568f → 0.1.1-dev.d71662695396

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.
@@ -1,17 +1,148 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { execFile, spawn } from "node:child_process";
5
6
  import readline from "node:readline";
6
7
  import { promisify } from "node:util";
7
8
  import { GitClient } from "../../shared/git/git.js";
8
9
  import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
10
+ import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
9
11
  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";
12
+ import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDebugCycle, completionPromptForDevelopCycle, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, qaCompletionGateOrder } from "../phase-completion.js";
11
13
  import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
12
14
  const fakeWorkerModel = "server-local-fake-worker";
13
15
  const execFileAsync = promisify(execFile);
14
16
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
17
+ const allowedProviderParentEnvNames = [
18
+ "PATH",
19
+ "HOME",
20
+ "USERPROFILE",
21
+ "TMPDIR",
22
+ "TEMP",
23
+ "TMP",
24
+ "LANG"
25
+ ];
26
+ const windowsAllowedProviderParentEnvNames = [
27
+ "SystemRoot",
28
+ "SystemDrive",
29
+ "ComSpec",
30
+ "PATHEXT",
31
+ "APPDATA",
32
+ "LOCALAPPDATA",
33
+ "USERNAME",
34
+ "USERDOMAIN",
35
+ "HOMEDRIVE",
36
+ "HOMEPATH",
37
+ "ProgramData",
38
+ "ProgramFiles",
39
+ "ProgramFiles(x86)",
40
+ "ProgramW6432",
41
+ "DOTNET_ROOT",
42
+ "DOTNET_ROOT(x86)",
43
+ "DOTNET_CLI_HOME",
44
+ "NUGET_PACKAGES",
45
+ "NUGET_HTTP_CACHE_PATH"
46
+ ];
47
+ export function buildProviderChildEnvironment(requestEnv, options = {}) {
48
+ const parentEnv = options.parentEnv ?? process.env;
49
+ const platform = options.platform ?? process.platform;
50
+ const env = {};
51
+ for (const [key, value] of Object.entries(parentEnv)) {
52
+ if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
53
+ env[key] = value;
54
+ }
55
+ }
56
+ if (requestEnv) {
57
+ for (const [key, value] of Object.entries(requestEnv)) {
58
+ const trimmedKey = key.trim();
59
+ if (trimmedKey.length > 0) {
60
+ env[trimmedKey] = value;
61
+ }
62
+ }
63
+ }
64
+ if (platform === "win32") {
65
+ normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
66
+ }
67
+ return env;
68
+ }
69
+ function isAllowedProviderParentEnv(key, platform = process.platform) {
70
+ return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
71
+ || key.toUpperCase().startsWith("LC_")
72
+ || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
73
+ }
74
+ function isAllowedProviderParentEnvName(key, allowedNames) {
75
+ return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
76
+ }
77
+ function normalizeWindowsDotNetEnvironment(env, parentEnv, homeDir) {
78
+ const systemRoot = readEnvironmentValue(env, "SystemRoot") ?? readEnvironmentValue(parentEnv, "SystemRoot") ?? "C:\\Windows";
79
+ const systemDrive = path.win32.parse(systemRoot).root.replace(/\\$/, "") || "C:";
80
+ setEnvironmentValueIfMissing(env, "SystemRoot", systemRoot);
81
+ setEnvironmentValueIfMissing(env, "SystemDrive", readEnvironmentValue(parentEnv, "SystemDrive") ?? systemDrive);
82
+ setEnvironmentValueIfMissing(env, "ComSpec", readEnvironmentValue(parentEnv, "ComSpec") ?? path.win32.join(systemRoot, "System32", "cmd.exe"));
83
+ setEnvironmentValueIfMissing(env, "PATHEXT", readEnvironmentValue(parentEnv, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL");
84
+ const userProfile = resolveWindowsUserProfile(env, parentEnv, homeDir);
85
+ if (userProfile) {
86
+ setEnvironmentValueIfMissing(env, "USERPROFILE", userProfile);
87
+ setEnvironmentValueIfMissing(env, "HOME", userProfile);
88
+ setEnvironmentValueIfMissing(env, "DOTNET_CLI_HOME", userProfile);
89
+ setEnvironmentValueIfMissing(env, "NUGET_PACKAGES", path.win32.join(userProfile, ".nuget", "packages"));
90
+ const parsed = path.win32.parse(userProfile);
91
+ if (parsed.root) {
92
+ setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
93
+ setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
94
+ }
95
+ }
96
+ const appData = readEnvironmentValue(env, "APPDATA")
97
+ ?? readEnvironmentValue(parentEnv, "APPDATA")
98
+ ?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
99
+ const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
100
+ ?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
101
+ ?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
102
+ if (appData) {
103
+ setEnvironmentValueIfMissing(env, "APPDATA", appData);
104
+ }
105
+ if (localAppData) {
106
+ setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
107
+ setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
108
+ }
109
+ setEnvironmentValueIfMissing(env, "DOTNET_NOLOGO", "1");
110
+ setEnvironmentValueIfMissing(env, "DOTNET_CLI_TELEMETRY_OPTOUT", "1");
111
+ setEnvironmentValueIfMissing(env, "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
112
+ setEnvironmentValueIfMissing(env, "NUGET_XMLDOC_MODE", "skip");
113
+ }
114
+ function resolveWindowsUserProfile(env, parentEnv, homeDir) {
115
+ const existing = readEnvironmentValue(env, "USERPROFILE") ?? readEnvironmentValue(parentEnv, "USERPROFILE");
116
+ if (existing) {
117
+ return existing;
118
+ }
119
+ const home = readEnvironmentValue(env, "HOME") ?? readEnvironmentValue(parentEnv, "HOME");
120
+ if (home && path.win32.isAbsolute(home)) {
121
+ return home;
122
+ }
123
+ const homeDrive = readEnvironmentValue(env, "HOMEDRIVE") ?? readEnvironmentValue(parentEnv, "HOMEDRIVE");
124
+ const homePath = readEnvironmentValue(env, "HOMEPATH") ?? readEnvironmentValue(parentEnv, "HOMEPATH");
125
+ if (homeDrive && homePath) {
126
+ return `${homeDrive}${homePath}`;
127
+ }
128
+ if (homeDir && path.win32.isAbsolute(homeDir)) {
129
+ return homeDir;
130
+ }
131
+ const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
132
+ const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
133
+ return username ? path.win32.join(systemDrive, "Users", username) : undefined;
134
+ }
135
+ function readEnvironmentValue(env, name) {
136
+ const entry = Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase());
137
+ const value = entry?.[1];
138
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
139
+ }
140
+ function setEnvironmentValueIfMissing(env, name, value) {
141
+ if (readEnvironmentValue(env, name)) {
142
+ return;
143
+ }
144
+ env[name] = value;
145
+ }
15
146
  export class RoutingProviderCliService {
16
147
  realProvider;
17
148
  deterministicProvider;
@@ -24,6 +155,11 @@ export class RoutingProviderCliService {
24
155
  ? await this.deterministicProvider.runImplementation(context)
25
156
  : await this.realProvider.runImplementation(context);
26
157
  }
158
+ async runArchitect(context) {
159
+ return isFakeWorkerModel(context.dispatch.execution.model)
160
+ ? await this.deterministicProvider.runArchitect(context)
161
+ : await this.realProvider.runArchitect(context);
162
+ }
27
163
  async runConflictResolve(context) {
28
164
  return isFakeWorkerModel(context.dispatch.execution.model)
29
165
  ? await this.deterministicProvider.runConflictResolve(context)
@@ -34,6 +170,11 @@ export class RoutingProviderCliService {
34
170
  ? await this.deterministicProvider.runQa(context)
35
171
  : await this.realProvider.runQa(context);
36
172
  }
173
+ async runDraft(context) {
174
+ return isFakeWorkerModel(context.dispatch.execution.model)
175
+ ? await this.deterministicProvider.runDraft(context)
176
+ : await this.realProvider.runDraft(context);
177
+ }
37
178
  }
38
179
  export class ProcessBackedProviderCliService {
39
180
  processRunner;
@@ -42,10 +183,158 @@ export class ProcessBackedProviderCliService {
42
183
  this.processRunner = processRunner;
43
184
  this.git = git;
44
185
  }
186
+ async runDraft(context) {
187
+ const { dispatch } = context;
188
+ if (!dispatch.draft) {
189
+ throw new Error("Draft dispatch context is missing.");
190
+ }
191
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "forge-bridge-draft-"));
192
+ const draftWorktree = {
193
+ repoPath: tempDir,
194
+ worktreePath: tempDir,
195
+ branchName: "draft",
196
+ baseBranch: dispatch.cycleRun.baseBranch || dispatch.repo.defaultBranch || "draft",
197
+ cleanupWorktrees: true
198
+ };
199
+ const metadataRoot = path.join(tempDir, ".forge", "work-items", dispatch.workItem.id);
200
+ await fs.mkdir(metadataRoot, { recursive: true });
201
+ await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(dispatch.draft, null, 2) + "\n", "utf8");
202
+ await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
203
+ const isDecomposePrompt = isDecomposeDraftKind(dispatch.draft.kind);
204
+ const completionTools = isDecomposePrompt
205
+ ? null
206
+ : await prepareCompletionToolRuntime({ dispatch, worktree: draftWorktree, phase: "draft" });
207
+ const command = buildProviderCliCommand(dispatch, {
208
+ worktreePath: tempDir,
209
+ prompt: buildDraftPrompt(dispatch),
210
+ completionTools: completionTools ?? undefined,
211
+ skipGitRepoCheck: true
212
+ });
213
+ const draftArtifactSlugs = dispatch.artifacts
214
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
215
+ .map((artifact) => `${artifact.kind}:${artifact.slug}`);
216
+ await context.emit({
217
+ role: "runner",
218
+ kind: "checkpoint",
219
+ content: `${isDecomposePrompt ? "Structured prompt" : "Draft"} artifacts injected: ${draftArtifactSlugs.length}${draftArtifactSlugs.length ? ` (${draftArtifactSlugs.join(", ")})` : ""}. Project: ${dispatch.draft.projectName ?? dispatch.repo.name}. Repo: ${dispatch.draft.repoName ?? dispatch.repo.name}.`,
220
+ eventType: isDecomposePrompt ? "structured_prompt_artifacts_injected" : "draft_artifacts_injected"
221
+ });
222
+ await context.emit({
223
+ role: "runner",
224
+ kind: "checkpoint",
225
+ content: `Starting provider CLI ${isDecomposePrompt ? "structured prompt" : "Draft"}: ${formatProviderCliCommand(command)}`,
226
+ eventType: "provider_cli_started"
227
+ });
228
+ if (completionTools) {
229
+ await context.emit({
230
+ role: "runner",
231
+ kind: "checkpoint",
232
+ content: "Forge Draft completion tools configured for draft_intent -> draft_repo_context -> draft_graph_context -> draft_product_scope -> draft_work_order_plan -> draft_critic -> draft_proposal; provider must call each MCP completion tool before exit.",
233
+ eventType: "completion_tools_configured"
234
+ });
235
+ }
236
+ const outputState = createProviderOutputState(dispatch.execution.provider);
237
+ try {
238
+ const providerCancellation = new AbortController();
239
+ const abortProvider = () => providerCancellation.abort();
240
+ if (context.signal?.aborted) {
241
+ abortProvider();
242
+ }
243
+ else {
244
+ context.signal?.addEventListener("abort", abortProvider, { once: true });
245
+ }
246
+ const runPromise = this.processRunner.run({
247
+ command: command.command,
248
+ args: command.args,
249
+ cwd: tempDir,
250
+ env: providerProcessEnv(dispatch)
251
+ }, {
252
+ onStdoutLine: async (line) => {
253
+ for (const event of outputState.consume(line)) {
254
+ await context.emit(event);
255
+ }
256
+ }
257
+ }, providerCancellation.signal);
258
+ let result;
259
+ let earlyProposalArtifact = null;
260
+ if (completionTools && !isDecomposePrompt) {
261
+ const terminal = await Promise.race([
262
+ runPromise.then(value => ({ kind: "process", value })),
263
+ waitForDraftProposalArtifact(tempDir, dispatch.workItem.id, context.signal).then(value => ({ kind: "artifact", value }))
264
+ ]);
265
+ if (terminal.kind === "artifact") {
266
+ earlyProposalArtifact = terminal.value;
267
+ providerCancellation.abort();
268
+ result = await runPromise.catch(() => ({ exitCode: 0, stdout: "", stderr: "" }));
269
+ }
270
+ else {
271
+ result = terminal.value;
272
+ }
273
+ }
274
+ else {
275
+ result = await runPromise;
276
+ }
277
+ context.signal?.removeEventListener("abort", abortProvider);
278
+ if (result.exitCode !== 0 && !earlyProposalArtifact) {
279
+ throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
280
+ }
281
+ await context.emit({
282
+ role: "runner",
283
+ kind: "checkpoint",
284
+ content: `Provider CLI ${isDecomposePrompt ? "structured prompt" : "Draft"} completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
285
+ eventType: "provider_cli_completed"
286
+ });
287
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
288
+ if (isDecomposePrompt) {
289
+ const structuredJson = parseJsonLine(outputState.finalMessage ?? "");
290
+ if (!structuredJson || typeof structuredJson !== "object" || Array.isArray(structuredJson)) {
291
+ throw new Error("Provider CLI structured prompt completed but did not return a JSON object.");
292
+ }
293
+ await context.emit({
294
+ role: "assistant",
295
+ kind: "message",
296
+ content: JSON.stringify(structuredJson),
297
+ eventType: "draft_complete"
298
+ });
299
+ return {
300
+ summary: "Structured prompt generated JSON through provider CLI."
301
+ };
302
+ }
303
+ await emitDraftGateArtifacts(context.emit, tempDir, dispatch.workItem.id);
304
+ const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(tempDir, dispatch.workItem.id, "draft");
305
+ if (!proposalArtifact) {
306
+ throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
307
+ }
308
+ const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
309
+ const draftJson = proposal["draft_json"];
310
+ if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
311
+ throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
312
+ }
313
+ const json = JSON.stringify(draftJson);
314
+ await context.emit({
315
+ role: "assistant",
316
+ kind: "message",
317
+ content: json,
318
+ eventType: "draft_complete"
319
+ });
320
+ return {
321
+ summary: "Draft generated through Forge Draft completion cycle.",
322
+ artifact: proposalArtifact,
323
+ artifacts: [proposalArtifact]
324
+ };
325
+ }
326
+ finally {
327
+ if (completionTools) {
328
+ await cleanupCompletionTools(completionTools, context.emit);
329
+ }
330
+ await fs.rm(tempDir, { recursive: true, force: true });
331
+ }
332
+ }
45
333
  async runImplementation(context) {
46
334
  const { dispatch, worktree } = context;
47
335
  const phase = completionPhaseFromDispatch(dispatch);
48
336
  const developCycle = usesDevelopCycleCompletion(dispatch);
337
+ const debugCycle = usesDebugCycleCompletion(dispatch);
49
338
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
50
339
  await fs.mkdir(metadataRoot, { recursive: true });
51
340
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -59,7 +348,11 @@ export class ProcessBackedProviderCliService {
59
348
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
60
349
  const command = buildProviderCliCommand(dispatch, {
61
350
  worktreePath: worktree.worktreePath,
62
- prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
351
+ prompt: debugCycle
352
+ ? buildDebugCyclePrompt(dispatch, phase)
353
+ : developCycle
354
+ ? buildDevelopCyclePrompt(dispatch, phase)
355
+ : buildImplementationPrompt(dispatch, phase),
63
356
  completionTools
64
357
  });
65
358
  await context.emit({
@@ -71,13 +364,15 @@ export class ProcessBackedProviderCliService {
71
364
  await context.emit({
72
365
  role: "runner",
73
366
  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.`,
367
+ content: debugCycle
368
+ ? "Forge Debug completion tools configured for debug_repro -> debug_root_cause -> debug_fix -> debug_regression; provider must call each MCP completion tool before exit."
369
+ : developCycle
370
+ ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
371
+ : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
77
372
  eventType: "completion_tools_configured"
78
373
  });
79
374
  const outputState = createProviderOutputState(dispatch.execution.provider);
80
- const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, context.emit);
375
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
81
376
  let result;
82
377
  try {
83
378
  liveCompletionEvents.start();
@@ -85,11 +380,10 @@ export class ProcessBackedProviderCliService {
85
380
  command: command.command,
86
381
  args: command.args,
87
382
  cwd: worktree.worktreePath,
88
- env: providerRedactionEnv(dispatch)
383
+ env: providerProcessEnv(dispatch)
89
384
  }, {
90
385
  onStdoutLine: async (line) => {
91
- const event = outputState.consume(line);
92
- if (event) {
386
+ for (const event of outputState.consume(line)) {
93
387
  await context.emit(event);
94
388
  }
95
389
  }
@@ -111,7 +405,7 @@ export class ProcessBackedProviderCliService {
111
405
  });
112
406
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
113
407
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
114
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle);
408
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
115
409
  for (const artifact of completionArtifacts) {
116
410
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
117
411
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -137,7 +431,7 @@ export class ProcessBackedProviderCliService {
137
431
  });
138
432
  }
139
433
  return {
140
- summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
434
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
141
435
  spec: {
142
436
  repoPath: worktree.worktreePath,
143
437
  path: specPath,
@@ -149,12 +443,105 @@ export class ProcessBackedProviderCliService {
149
443
  artifacts: completionArtifacts
150
444
  };
151
445
  }
446
+ async runArchitect(context) {
447
+ const { dispatch, worktree } = context;
448
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
449
+ const command = buildProviderCliCommand(dispatch, {
450
+ worktreePath: worktree.worktreePath,
451
+ prompt: buildArchitectPrompt(dispatch),
452
+ completionTools
453
+ });
454
+ const commandText = formatProviderCliCommand(command);
455
+ await context.emit({
456
+ role: "runner",
457
+ kind: "checkpoint",
458
+ content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
459
+ eventType: "provider_cli_started"
460
+ });
461
+ await context.emit({
462
+ role: "runner",
463
+ kind: "checkpoint",
464
+ content: "Forge Architect completion tools configured; provider must call forge.complete_architect_plan before exit.",
465
+ eventType: "completion_tools_configured"
466
+ });
467
+ const outputState = createProviderOutputState(dispatch.execution.provider);
468
+ const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
469
+ let result;
470
+ try {
471
+ liveArchitectEvents.start();
472
+ result = await this.processRunner.run({
473
+ command: command.command,
474
+ args: command.args,
475
+ cwd: worktree.worktreePath,
476
+ env: providerProcessEnv(dispatch)
477
+ }, {
478
+ onStdoutLine: async (line) => {
479
+ for (const event of outputState.consume(line)) {
480
+ await context.emit(event);
481
+ }
482
+ }
483
+ }, context.signal);
484
+ }
485
+ finally {
486
+ await liveArchitectEvents.stop();
487
+ await cleanupCompletionTools(completionTools, context.emit);
488
+ }
489
+ if (result.exitCode !== 0) {
490
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
491
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
492
+ }
493
+ await context.emit({
494
+ role: "runner",
495
+ kind: "checkpoint",
496
+ content: `Provider CLI Architect completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
497
+ eventType: "provider_cli_completed"
498
+ });
499
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
500
+ const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
501
+ if (!architectArtifact) {
502
+ throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
503
+ }
504
+ if (!liveArchitectEvents.hasEmitted()) {
505
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
506
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, architectArtifact);
507
+ }
508
+ await context.emit({
509
+ role: "assistant",
510
+ kind: "message",
511
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI produced an Architect plan for ${worktree.branchName}.`,
512
+ eventType: "architect_complete"
513
+ });
514
+ const specPath = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id, "spec.md");
515
+ const specBody = await fs.readFile(specPath, "utf8").catch(() => `# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`);
516
+ return {
517
+ summary: `${dispatch.execution.provider} CLI Architect plan produced.`,
518
+ spec: {
519
+ repoPath: worktree.worktreePath,
520
+ path: specPath,
521
+ body: specBody,
522
+ producedBy: `${dispatch.execution.provider}-cli`,
523
+ status: "pending_approval"
524
+ },
525
+ artifact: architectArtifact,
526
+ artifacts: [architectArtifact]
527
+ };
528
+ }
152
529
  async runQa(context) {
153
530
  const { dispatch, worktree } = context;
531
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
532
+ await fs.mkdir(metadataRoot, { recursive: true });
533
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
534
+ if (!laneCommand) {
535
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
536
+ }
537
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem, "qa");
538
+ const specPath = path.join(metadataRoot, "spec.md");
539
+ await fs.writeFile(specPath, specBody, "utf8");
540
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
154
541
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
155
542
  const command = buildProviderCliCommand(dispatch, {
156
543
  worktreePath: worktree.worktreePath,
157
- prompt: buildQaPrompt(dispatch),
544
+ prompt: buildQaPrompt(dispatch, specBody),
158
545
  completionTools
159
546
  });
160
547
  const commandText = formatProviderCliCommand(command);
@@ -167,11 +554,11 @@ export class ProcessBackedProviderCliService {
167
554
  await context.emit({
168
555
  role: "runner",
169
556
  kind: "checkpoint",
170
- content: "Forge QA completion tool configured; provider must call forge.complete_qa before exit.",
557
+ content: "Forge QA completion tools configured; provider must call all seven QA MCP gates before exit.",
171
558
  eventType: "completion_tools_configured"
172
559
  });
173
560
  const outputState = createProviderOutputState(dispatch.execution.provider);
174
- const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
561
+ const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
175
562
  let result;
176
563
  try {
177
564
  liveQaEvents.start();
@@ -179,11 +566,10 @@ export class ProcessBackedProviderCliService {
179
566
  command: command.command,
180
567
  args: command.args,
181
568
  cwd: worktree.worktreePath,
182
- env: providerRedactionEnv(dispatch)
569
+ env: providerProcessEnv(dispatch)
183
570
  }, {
184
571
  onStdoutLine: async (line) => {
185
- const event = outputState.consume(line);
186
- if (event) {
572
+ for (const event of outputState.consume(line)) {
187
573
  await context.emit(event);
188
574
  }
189
575
  }
@@ -204,16 +590,17 @@ export class ProcessBackedProviderCliService {
204
590
  eventType: "provider_cli_completed"
205
591
  });
206
592
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
207
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
593
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
208
594
  if (!qaArtifact) {
209
595
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
210
596
  throw new Error(verdictOnly
211
597
  ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
212
598
  : "Provider CLI QA completed but did not call the Forge QA completion tool.");
213
599
  }
600
+ enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
214
601
  if (!liveQaEvents.hasEmitted()) {
215
602
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
216
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
603
+ await emitQaStructuredEvents(context.emit, qaArtifact);
217
604
  }
218
605
  const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
219
606
  const statusSummary = status === "pass"
@@ -223,31 +610,41 @@ export class ProcessBackedProviderCliService {
223
610
  : "found rework";
224
611
  return {
225
612
  summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
613
+ spec: {
614
+ repoPath: worktree.worktreePath,
615
+ path: specPath,
616
+ body: specBody,
617
+ producedBy: "forge-lane-command",
618
+ status: "approved"
619
+ },
226
620
  artifact: qaArtifact,
227
621
  artifacts: [qaArtifact]
228
622
  };
229
623
  }
230
624
  async runConflictResolve(context) {
231
625
  const { dispatch, worktree } = context;
626
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
232
627
  const command = buildProviderCliCommand(dispatch, {
233
628
  worktreePath: worktree.worktreePath,
234
- prompt: buildConflictResolvePrompt(dispatch, worktree.branchName)
629
+ prompt: addressComments
630
+ ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
631
+ : buildConflictResolvePrompt(dispatch, worktree.branchName)
235
632
  });
236
633
  await context.emit({
237
634
  role: "runner",
238
635
  kind: "checkpoint",
239
- content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
636
+ content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
240
637
  eventType: "provider_cli_started"
241
638
  });
242
639
  const outputState = createProviderOutputState(dispatch.execution.provider);
243
640
  const result = await this.processRunner.run({
244
641
  command: command.command,
245
642
  args: command.args,
246
- cwd: worktree.worktreePath
643
+ cwd: worktree.worktreePath,
644
+ env: providerProcessEnv(dispatch)
247
645
  }, {
248
646
  onStdoutLine: async (line) => {
249
- const event = outputState.consume(line);
250
- if (event) {
647
+ for (const event of outputState.consume(line)) {
251
648
  await context.emit(event);
252
649
  }
253
650
  }
@@ -262,11 +659,15 @@ export class ProcessBackedProviderCliService {
262
659
  await context.emit({
263
660
  role: "assistant",
264
661
  kind: "message",
265
- content: outputState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
266
- eventType: "conflict_resolve_complete"
662
+ content: outputState.finalMessage || (addressComments
663
+ ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
664
+ : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
665
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
267
666
  });
268
667
  return {
269
- summary: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
668
+ summary: addressComments
669
+ ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
670
+ : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
270
671
  };
271
672
  }
272
673
  }
@@ -275,10 +676,22 @@ export class DeterministicProviderCliService {
275
676
  constructor(git = new GitClient()) {
276
677
  this.git = git;
277
678
  }
679
+ async runDraft(context) {
680
+ const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
681
+ await context.emit({
682
+ role: "assistant",
683
+ kind: "message",
684
+ content,
685
+ eventType: "draft_complete"
686
+ });
687
+ await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
688
+ return { summary: "forge-bridge generated deterministic draft." };
689
+ }
278
690
  async runImplementation(context) {
279
691
  const { dispatch, worktree } = context;
280
692
  const phase = completionPhaseFromDispatch(dispatch);
281
693
  const developCycle = usesDevelopCycleCompletion(dispatch);
694
+ const debugCycle = usesDebugCycleCompletion(dispatch);
282
695
  const providerCommand = buildProviderCliCommand(dispatch);
283
696
  const providerCommandText = formatProviderCliCommand(providerCommand);
284
697
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -309,9 +722,11 @@ export class DeterministicProviderCliService {
309
722
  content: `Created bridge changeset at ${changesetPath}`,
310
723
  eventType: "changeset"
311
724
  });
312
- const phases = developCycle
313
- ? ["implementation", "self_review", "validation"]
314
- : [phase];
725
+ const phases = debugCycle
726
+ ? debugCompletionPhaseOrder
727
+ : developCycle
728
+ ? ["implementation", "self_review", "validation"]
729
+ : [phase];
315
730
  const completionArtifacts = [];
316
731
  for (const completionPhase of phases) {
317
732
  await writeCompletionArtifact({
@@ -320,7 +735,9 @@ export class DeterministicProviderCliService {
320
735
  phase: completionPhase,
321
736
  producedBy: "forge-bridge",
322
737
  redactionSecrets: exactRedactionSecrets(dispatch)
323
- }, expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
738
+ }, isDebugCompletionPhaseForProvider(completionPhase)
739
+ ? expectedDebugCompletionToolName(completionPhase)
740
+ : expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
324
741
  const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
325
742
  if (!completionArtifact) {
326
743
  throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
@@ -336,7 +753,7 @@ export class DeterministicProviderCliService {
336
753
  }
337
754
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
338
755
  return {
339
- summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
756
+ summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
340
757
  spec: {
341
758
  repoPath: worktree.worktreePath,
342
759
  path: specPath,
@@ -348,6 +765,47 @@ export class DeterministicProviderCliService {
348
765
  artifacts: completionArtifacts
349
766
  };
350
767
  }
768
+ async runArchitect(context) {
769
+ const { dispatch, worktree } = context;
770
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
771
+ await fs.mkdir(metadataRoot, { recursive: true });
772
+ 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`;
773
+ const specPath = path.join(metadataRoot, "spec.md");
774
+ await fs.writeFile(specPath, specBody, "utf8");
775
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
776
+ await writeCompletionArtifact({
777
+ worktreePath: worktree.worktreePath,
778
+ workItemId: dispatch.workItem.id,
779
+ phase: "architect",
780
+ producedBy: "forge-bridge",
781
+ redactionSecrets: exactRedactionSecrets(dispatch),
782
+ architectCycle: true
783
+ }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
784
+ const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
785
+ if (!artifact) {
786
+ throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
787
+ }
788
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
789
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
790
+ await context.emit({
791
+ role: "assistant",
792
+ kind: "message",
793
+ content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
794
+ eventType: "architect_complete"
795
+ });
796
+ return {
797
+ summary: "forge-bridge completed Architect plan (deterministic).",
798
+ spec: {
799
+ repoPath: worktree.worktreePath,
800
+ path: specPath,
801
+ body: specBody,
802
+ producedBy: "forge-bridge",
803
+ status: "pending_approval"
804
+ },
805
+ artifact,
806
+ artifacts: [artifact]
807
+ };
808
+ }
351
809
  async runQa(context) {
352
810
  const { dispatch, worktree } = context;
353
811
  await context.emit({
@@ -356,44 +814,82 @@ export class DeterministicProviderCliService {
356
814
  content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
357
815
  eventType: "qa_plan"
358
816
  });
359
- const summary = "All checks passed. forge-bridge QA completed.";
360
- const qaArtifact = await writeQaArtifacts({
361
- worktreePath: worktree.worktreePath,
362
- workItemId: dispatch.workItem.id,
363
- acceptanceCriteria: dispatch.workItem.acceptanceCriteria,
364
- producedBy: "forge-bridge",
365
- provider: dispatch.execution.provider,
366
- model: dispatch.execution.model,
367
- command: "forge-bridge deterministic QA",
368
- summary
369
- });
817
+ const qaBrowser = dispatch.qaBrowser;
818
+ const launchTarget = qaBrowser?.launchTarget ?? null;
819
+ const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
820
+ const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
821
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
822
+ : null;
823
+ const browserChecks = browserSidecar && launchTarget
824
+ ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
825
+ : [];
826
+ const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
827
+ const summary = missingLaunchTarget
828
+ ? "QA blocked because browser testing is required but no app launch target was provided."
829
+ : "All checks passed. forge-bridge QA completed.";
830
+ const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
831
+ for (const gate of qaCompletionGateOrder) {
832
+ await writeCompletionArtifact({
833
+ worktreePath: worktree.worktreePath,
834
+ workItemId: dispatch.workItem.id,
835
+ phase: "qa",
836
+ producedBy: "forge-bridge",
837
+ redactionSecrets: exactRedactionSecrets(dispatch),
838
+ qaCycle: true,
839
+ ownerType: dispatch.cycleRun.ownerType ?? undefined,
840
+ ownerId: dispatch.cycleRun.ownerId ?? undefined
841
+ }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
842
+ gate,
843
+ criterion,
844
+ summary,
845
+ missingLaunchTarget,
846
+ browserChecks,
847
+ sidecars
848
+ }));
849
+ const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
850
+ if (gateArtifact) {
851
+ await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
852
+ }
853
+ }
854
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
855
+ if (!qaArtifact) {
856
+ throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
857
+ }
370
858
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
371
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
859
+ await emitQaStructuredEvents(context.emit, qaArtifact);
372
860
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
373
861
  return {
374
- summary: "forge-bridge QA passed.",
862
+ summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
375
863
  artifact: qaArtifact,
376
864
  artifacts: [qaArtifact]
377
865
  };
378
866
  }
379
867
  async runConflictResolve(context) {
380
868
  const { dispatch, worktree } = context;
381
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
869
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
870
+ await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
382
871
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
383
872
  await context.emit({
384
873
  role: "assistant",
385
874
  kind: "message",
386
- content: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
387
- eventType: "conflict_resolve_complete"
875
+ content: addressComments
876
+ ? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
877
+ : `Deterministic conflict resolve completed for ${worktree.branchName}.`,
878
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
388
879
  });
389
880
  return {
390
- summary: `forge-bridge resolved conflicts for ${worktree.branchName}.`
881
+ summary: addressComments
882
+ ? `forge-bridge addressed PR comments for ${worktree.branchName}.`
883
+ : `forge-bridge resolved conflicts for ${worktree.branchName}.`
391
884
  };
392
885
  }
393
886
  }
394
887
  function phaseCompleteEventType(phase) {
395
888
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
396
889
  }
890
+ function isDebugCompletionPhaseForProvider(phase) {
891
+ return debugCompletionPhaseOrder.includes(phase);
892
+ }
397
893
  function deterministicCompletionPayload(phase, dispatch, changesetBody) {
398
894
  const changesetHash = sha256(changesetBody);
399
895
  const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
@@ -416,6 +912,56 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
416
912
  next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
417
913
  };
418
914
  }
915
+ if (phase === "debug_repro") {
916
+ return {
917
+ status: "pass",
918
+ summary: "forge-bridge reproduced the bug deterministically.",
919
+ repro_steps: ["Run the deterministic fake-worker debug reproduction."],
920
+ observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
921
+ expected: "The bug scenario should be fixed before QA handoff.",
922
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
923
+ };
924
+ }
925
+ if (phase === "debug_root_cause") {
926
+ return {
927
+ status: "pass",
928
+ summary: "forge-bridge isolated a deterministic root cause.",
929
+ root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
930
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
931
+ eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
932
+ risk_area: "forge-bridge deterministic debug lane"
933
+ };
934
+ }
935
+ if (phase === "debug_fix") {
936
+ return {
937
+ status: "pass",
938
+ summary: "forge-bridge applied a deterministic debug fix.",
939
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
940
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
941
+ remaining_risks: [],
942
+ resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
943
+ qa_id: qaId,
944
+ status: "resolved",
945
+ summary: `Resolved deterministic QA finding ${qaId}.`,
946
+ evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
947
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
948
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
949
+ regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
950
+ }))
951
+ };
952
+ }
953
+ if (phase === "debug_regression") {
954
+ return {
955
+ status: "pass",
956
+ summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
957
+ commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
958
+ required_regressions: ["Original deterministic repro no longer fails."],
959
+ build_status: "not_applicable",
960
+ test_status: "pass",
961
+ repro_negative: true,
962
+ qa_ready: true
963
+ };
964
+ }
419
965
  if (phase === "self_review") {
420
966
  return {
421
967
  status: "pass",
@@ -476,6 +1022,149 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
476
1022
  ready_for_dev_test: true
477
1023
  };
478
1024
  }
1025
+ function deterministicArchitectPayload(dispatch) {
1026
+ const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
1027
+ return {
1028
+ status: "pass",
1029
+ summary: "forge-bridge produced a deterministic Architect plan.",
1030
+ implementation_plan: {
1031
+ schema_version: 1,
1032
+ plan_id: planId,
1033
+ story_id: dispatch.workItem.id,
1034
+ phases: [
1035
+ { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
1036
+ ],
1037
+ tasks: [
1038
+ {
1039
+ id: "task-1",
1040
+ title: `Implement ${dispatch.workItem.title}`,
1041
+ phase: "phase-1",
1042
+ summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
1043
+ acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
1044
+ tests: [
1045
+ { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
1046
+ ]
1047
+ }
1048
+ ],
1049
+ dependencies: [],
1050
+ phase_gates: [
1051
+ { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
1052
+ ]
1053
+ },
1054
+ qa_plan: {
1055
+ schema_version: 1,
1056
+ plan_id: planId,
1057
+ final_qa: [
1058
+ { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
1059
+ ]
1060
+ },
1061
+ 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`
1062
+ };
1063
+ }
1064
+ function deterministicQaGatePayload(options) {
1065
+ const blocked = options.missingLaunchTarget;
1066
+ const skippedBecauseBlocked = blocked
1067
+ ? {
1068
+ status: "skipped",
1069
+ summary: "Skipped because browser QA was blocked by missing launch target.",
1070
+ reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
1071
+ }
1072
+ : null;
1073
+ switch (options.gate) {
1074
+ case "qa_plan":
1075
+ return {
1076
+ status: "pass",
1077
+ summary: "Deterministic QA plan recorded.",
1078
+ checklist: [
1079
+ "Review the validated work item against acceptance criteria.",
1080
+ "Run deterministic regression evidence.",
1081
+ "Confirm no in-scope QA findings remain."
1082
+ ],
1083
+ acceptance_criteria: [options.criterion]
1084
+ };
1085
+ case "qa_regression":
1086
+ return {
1087
+ status: "pass",
1088
+ summary: "Deterministic regression QA completed.",
1089
+ commands: [
1090
+ {
1091
+ command: "forge-bridge deterministic QA",
1092
+ exit_code: 0,
1093
+ status: "pass",
1094
+ summary: "Deterministic regression evidence completed."
1095
+ }
1096
+ ],
1097
+ notes: "Regression gate passed in deterministic fake-worker mode."
1098
+ };
1099
+ case "qa_api":
1100
+ return {
1101
+ status: "skipped",
1102
+ summary: "No API/backend surface was identified for deterministic QA.",
1103
+ reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
1104
+ };
1105
+ case "qa_manual_web":
1106
+ return blocked
1107
+ ? {
1108
+ status: "blocked",
1109
+ summary: "Browser QA could not run because no app launch target was provided.",
1110
+ blocker_reason: "missing_app_launch_target"
1111
+ }
1112
+ : options.browserChecks.length > 0
1113
+ ? {
1114
+ status: "pass",
1115
+ summary: "Deterministic browser QA exercised the configured launch target.",
1116
+ browser_checks: options.browserChecks,
1117
+ sidecars: options.sidecars,
1118
+ notes: "Browser sidecar evidence recorded."
1119
+ }
1120
+ : {
1121
+ status: "skipped",
1122
+ summary: "Manual web QA was not required for this deterministic run.",
1123
+ reason: "Forge did not require browser QA and no launch target was necessary."
1124
+ };
1125
+ case "qa_bug_repro":
1126
+ return skippedBecauseBlocked ?? {
1127
+ status: "skipped",
1128
+ summary: "No failed QA observation required bug reproduction.",
1129
+ reason: "No defects or candidate bugs were observed."
1130
+ };
1131
+ case "qa_findings":
1132
+ return skippedBecauseBlocked ?? {
1133
+ status: "pass",
1134
+ summary: "No QA findings or candidate bugs were identified.",
1135
+ findings: [],
1136
+ candidate_bugs: []
1137
+ };
1138
+ case "qa_verdict":
1139
+ return {
1140
+ status: blocked ? "blocked" : "pass",
1141
+ summary: options.summary,
1142
+ checklist: [
1143
+ "Review the validated work item against acceptance criteria.",
1144
+ "Run deterministic regression evidence.",
1145
+ blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
1146
+ ],
1147
+ tested_acceptance_criteria: blocked ? [] : [options.criterion],
1148
+ commands: blocked
1149
+ ? []
1150
+ : [
1151
+ {
1152
+ command: "forge-bridge deterministic QA",
1153
+ exit_code: 0,
1154
+ status: "pass",
1155
+ summary: "Deterministic QA command completed."
1156
+ }
1157
+ ],
1158
+ browser_checks: blocked ? [] : options.browserChecks,
1159
+ sidecars: blocked ? [] : options.sidecars,
1160
+ notes: options.summary,
1161
+ findings: [],
1162
+ candidate_bugs: [],
1163
+ blocker_reason: blocked ? "missing_app_launch_target" : null,
1164
+ report_markdown: `# QA report\n\n${options.summary}\n`
1165
+ };
1166
+ }
1167
+ }
479
1168
  const qaArtifactFileNames = {
480
1169
  plan: "qa.plan.json",
481
1170
  evidence: "qa.evidence.json",
@@ -483,73 +1172,66 @@ const qaArtifactFileNames = {
483
1172
  verdict: "qa.verdict.json",
484
1173
  report: "qa.report.md"
485
1174
  };
486
- async function writeQaArtifacts(request) {
487
- const artifactRoot = artifactRootFor(request.worktreePath, request.workItemId);
488
- await fs.mkdir(artifactRoot, { recursive: true });
489
- const criterion = request.acceptanceCriteria.trim() || "Forge QA evidence exists";
490
- const relativeEvidencePath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.evidence);
491
- const relativeFindingsPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.findings);
492
- const relativeReportPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.report);
493
- const planJson = jsonText({
494
- schema_version: 1,
495
- phase: "qa",
496
- checklist: [
497
- "Review the validated work item against acceptance criteria.",
498
- "Run relevant provider QA verification.",
499
- "Confirm no in-scope QA findings remain."
500
- ],
501
- acceptance_criteria: [criterion]
502
- });
503
- const evidenceJson = jsonText({
504
- schema_version: 1,
505
- phase: "qa",
506
- commands: [
507
- {
508
- command: request.command,
509
- exit_code: 0,
510
- status: "pass",
511
- summary: `${request.provider} QA completed successfully.`
512
- }
513
- ],
514
- browser_checks: [],
515
- notes: request.summary
516
- });
517
- const findingsJson = jsonText({
518
- schema_version: 1,
519
- phase: "qa",
520
- findings: [],
521
- candidate_bugs: []
522
- });
523
- const verdictJson = jsonText({
524
- schema_version: 1,
525
- phase: "qa",
526
- status: "pass",
527
- summary: request.summary,
528
- tested_acceptance_criteria: [criterion],
529
- finding_ids: [],
530
- candidate_bug_ids: [],
531
- blocker_reason: null,
532
- evidence_path: relativeEvidencePath,
533
- findings_path: relativeFindingsPath,
534
- report_path: relativeReportPath
535
- });
536
- 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`;
537
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.plan), planJson, "utf8");
538
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.evidence), evidenceJson, "utf8");
539
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.findings), findingsJson, "utf8");
540
- const verdictPath = path.join(artifactRoot, qaArtifactFileNames.verdict);
541
- await fs.writeFile(verdictPath, verdictJson, "utf8");
542
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.report), report, "utf8");
1175
+ const qaGateArtifactFileNames = {
1176
+ qa_plan: "qa.plan.json",
1177
+ qa_regression: "qa.regression.json",
1178
+ qa_api: "qa.api.json",
1179
+ qa_manual_web: "qa.manual-web.json",
1180
+ qa_bug_repro: "qa.bug-repro.json",
1181
+ qa_findings: "qa.findings.json",
1182
+ qa_verdict: "qa.verdict.json"
1183
+ };
1184
+ function hasLaunchTarget(target) {
1185
+ return Boolean(target?.url?.trim()
1186
+ || target?.ready_url?.trim()
1187
+ || target?.command?.trim()
1188
+ || (target?.routes ?? []).some((route) => route.trim().length > 0));
1189
+ }
1190
+ function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
1191
+ const route = primaryLaunchRoute(target);
543
1192
  return {
544
- repoPath: request.worktreePath,
545
- path: verdictPath,
546
- verdictJson,
547
- report,
548
- producedBy: request.producedBy,
1193
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
1194
+ content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
1195
+ };
1196
+ }
1197
+ function deterministicBrowserCheck(target, screenshotPath) {
1198
+ const route = primaryLaunchRoute(target);
1199
+ return {
1200
+ route,
1201
+ url: route,
549
1202
  status: "pass",
550
- phase: "qa"
1203
+ summary: "Deterministic browser QA exercised the configured launch target.",
1204
+ actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
1205
+ screenshots: [screenshotPath],
1206
+ console_errors: [],
1207
+ network_errors: [],
1208
+ responsive_checks: ["desktop", "mobile"]
551
1209
  };
552
1210
  }
1211
+ function primaryLaunchRoute(target) {
1212
+ return target.ready_url?.trim()
1213
+ || target.url?.trim()
1214
+ || target.routes.find((route) => route.trim().length > 0)?.trim()
1215
+ || "app launch command";
1216
+ }
1217
+ async function writeQaSidecarFiles(worktreePath, files) {
1218
+ const sidecars = [];
1219
+ for (const file of files) {
1220
+ const fullPath = path.resolve(worktreePath, file.relativePath);
1221
+ const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
1222
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
1223
+ throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
1224
+ }
1225
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
1226
+ await fs.writeFile(fullPath, file.content, "utf8");
1227
+ sidecars.push({
1228
+ path: relativePath,
1229
+ content_hash: sha256(file.content),
1230
+ bytes: Buffer.byteLength(file.content, "utf8")
1231
+ });
1232
+ }
1233
+ return sidecars;
1234
+ }
553
1235
  async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
554
1236
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
555
1237
  await emit({
@@ -565,73 +1247,273 @@ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
565
1247
  eventType: "phase_gate"
566
1248
  });
567
1249
  }
568
- async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
569
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
570
- if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
1250
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1251
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1252
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
571
1253
  return null;
572
1254
  }
573
- return artifact;
574
- }
575
- async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
576
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
577
- for (const fileName of Object.values(qaArtifactFileNames)) {
578
- try {
579
- const stat = await fs.stat(path.join(artifactRoot, fileName));
580
- if (!stat.isFile()) {
581
- return false;
1255
+ const artifactRoot = ownerType && ownerId
1256
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1257
+ : artifactRootFor(worktreePath, workItemId);
1258
+ const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1259
+ const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1260
+ const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1261
+ await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1262
+ return {
1263
+ ...artifact,
1264
+ planJson,
1265
+ evidenceJson,
1266
+ findingsJson
1267
+ };
1268
+ }
1269
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1270
+ const artifactRoot = ownerType && ownerId
1271
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1272
+ : artifactRootFor(worktreePath, workItemId);
1273
+ for (const fileName of Object.values(qaArtifactFileNames)) {
1274
+ try {
1275
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1276
+ if (!stat.isFile()) {
1277
+ return false;
1278
+ }
1279
+ }
1280
+ catch (error) {
1281
+ if (isNodeError(error) && error.code === "ENOENT") {
1282
+ return false;
1283
+ }
1284
+ throw error;
1285
+ }
1286
+ }
1287
+ return true;
1288
+ }
1289
+ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
1290
+ const qaBrowser = dispatch.qaBrowser;
1291
+ if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
1292
+ return;
1293
+ }
1294
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1295
+ const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
1296
+ const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
1297
+ if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
1298
+ 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.");
1299
+ }
1300
+ }
1301
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1302
+ const artifactRoot = ownerType && ownerId
1303
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1304
+ : artifactRootFor(worktreePath, workItemId);
1305
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1306
+ const sidecars = arrayField(evidence, "sidecars");
1307
+ if (sidecars.length === 0) {
1308
+ return;
1309
+ }
1310
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
1311
+ for (const [index, sidecar] of sidecars.entries()) {
1312
+ const sidecarPath = stringField(sidecar, "path");
1313
+ const expectedHash = stringField(sidecar, "content_hash");
1314
+ const expectedBytes = sidecar.bytes;
1315
+ if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
1316
+ throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
1317
+ }
1318
+ if (path.isAbsolute(sidecarPath)) {
1319
+ throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
1320
+ }
1321
+ const fullPath = path.resolve(worktreePath, sidecarPath);
1322
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
1323
+ const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1324
+ const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1325
+ throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
1326
+ }
1327
+ const stat = await fs.lstat(fullPath).catch((error) => {
1328
+ if (isNodeError(error) && error.code === "ENOENT") {
1329
+ throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
1330
+ }
1331
+ throw error;
1332
+ });
1333
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1334
+ throw new Error(`QA sidecar ${index} must reference a regular file.`);
1335
+ }
1336
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
1337
+ if (stat.size !== expectedBytes) {
1338
+ throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
1339
+ }
1340
+ const actualHash = await sha256File(fullPath);
1341
+ if (actualHash !== expectedHash.trim().toLowerCase()) {
1342
+ throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
1343
+ }
1344
+ }
1345
+ }
1346
+ async function emitQaStructuredEvents(emit, artifact) {
1347
+ const artifactRoot = path.dirname(artifact.path);
1348
+ const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
1349
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1350
+ const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
1351
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1352
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1353
+ const checklist = stringArrayField(plan, "checklist");
1354
+ await emit({
1355
+ role: "worker",
1356
+ kind: "message",
1357
+ content: checklist.length > 0
1358
+ ? `QA plan: ${checklist.join("; ")}`
1359
+ : "QA plan recorded.",
1360
+ eventType: "qa_plan"
1361
+ });
1362
+ for (const browserCheck of arrayField(evidence, "browser_checks")) {
1363
+ await emit({
1364
+ role: "worker",
1365
+ kind: "checkpoint",
1366
+ content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
1367
+ eventType: "qa_browser_check"
1368
+ });
1369
+ }
1370
+ for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
1371
+ await emit({
1372
+ role: "worker",
1373
+ kind: "checkpoint",
1374
+ content: `QA finding: ${summarizeQaObject(finding)}`,
1375
+ eventType: "qa_finding"
1376
+ });
1377
+ }
1378
+ await emit({
1379
+ role: "assistant",
1380
+ kind: "message",
1381
+ content: status === "blocked"
1382
+ ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
1383
+ : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
1384
+ eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
1385
+ });
1386
+ }
1387
+ function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1388
+ return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1389
+ ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1390
+ : artifactRootFor(worktreePath, workItemId);
1391
+ }
1392
+ async function readQaGateArtifact(artifactRoot, gate) {
1393
+ const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1394
+ try {
1395
+ const stat = await fs.stat(artifactPath);
1396
+ if (!stat.isFile()) {
1397
+ return null;
1398
+ }
1399
+ }
1400
+ catch (error) {
1401
+ if (isNodeError(error) && error.code === "ENOENT") {
1402
+ return null;
1403
+ }
1404
+ throw error;
1405
+ }
1406
+ const payload = await readJsonObjectFile(artifactPath);
1407
+ return {
1408
+ gate,
1409
+ path: artifactPath,
1410
+ status: stringField(payload, "status") ?? "unknown",
1411
+ producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1412
+ contentHash: stringField(payload, "content_hash") ?? undefined
1413
+ };
1414
+ }
1415
+ function nextQaGate(gate) {
1416
+ const index = qaCompletionGateOrder.indexOf(gate);
1417
+ return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1418
+ }
1419
+ async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1420
+ const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1421
+ await emit({
1422
+ role: "hook",
1423
+ kind: artifact.status === "blocked" ? "error" : "checkpoint",
1424
+ content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1425
+ eventType: "phase_gate",
1426
+ data: JSON.stringify({
1427
+ phase: "qa",
1428
+ qa_gate: artifact.gate,
1429
+ status: artifact.status,
1430
+ artifact_relative_paths: [relativePath],
1431
+ content_hash: artifact.contentHash ?? null,
1432
+ produced_by: artifact.producedBy ?? null
1433
+ })
1434
+ });
1435
+ if (!nextGate) {
1436
+ return;
1437
+ }
1438
+ await emit({
1439
+ role: "hook",
1440
+ kind: "checkpoint",
1441
+ content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1442
+ eventType: "phase_gate",
1443
+ data: JSON.stringify({
1444
+ phase: "qa",
1445
+ from_gate: artifact.gate,
1446
+ to_gate: nextGate
1447
+ })
1448
+ });
1449
+ }
1450
+ class LiveQaArtifactEmitter {
1451
+ worktreePath;
1452
+ workItemId;
1453
+ dispatch;
1454
+ emit;
1455
+ emittedBundle = false;
1456
+ emittedGates = new Set();
1457
+ timer = null;
1458
+ pending = Promise.resolve();
1459
+ constructor(worktreePath, workItemId, dispatch, emit) {
1460
+ this.worktreePath = worktreePath;
1461
+ this.workItemId = workItemId;
1462
+ this.dispatch = dispatch;
1463
+ this.emit = emit;
1464
+ }
1465
+ start() {
1466
+ void this.pollQueued();
1467
+ this.timer = setInterval(() => {
1468
+ void this.pollQueued();
1469
+ }, 250);
1470
+ }
1471
+ async stop() {
1472
+ if (this.timer) {
1473
+ clearInterval(this.timer);
1474
+ this.timer = null;
1475
+ }
1476
+ await this.pollQueued();
1477
+ }
1478
+ hasEmitted() {
1479
+ return this.emittedBundle;
1480
+ }
1481
+ pollQueued() {
1482
+ this.pending = this.pending
1483
+ .then(() => this.poll())
1484
+ .catch(() => undefined);
1485
+ return this.pending;
1486
+ }
1487
+ async poll() {
1488
+ await this.emitAvailableGateEvents();
1489
+ if (this.emittedBundle) {
1490
+ return;
1491
+ }
1492
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
1493
+ if (!artifact) {
1494
+ return;
1495
+ }
1496
+ enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
1497
+ this.emittedBundle = true;
1498
+ await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
1499
+ await emitQaStructuredEvents(this.emit, artifact);
1500
+ }
1501
+ async emitAvailableGateEvents() {
1502
+ const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1503
+ for (const gate of qaCompletionGateOrder) {
1504
+ if (this.emittedGates.has(gate)) {
1505
+ continue;
582
1506
  }
583
- }
584
- catch (error) {
585
- if (isNodeError(error) && error.code === "ENOENT") {
586
- return false;
1507
+ const artifact = await readQaGateArtifact(artifactRoot, gate);
1508
+ if (!artifact) {
1509
+ return;
587
1510
  }
588
- throw error;
1511
+ this.emittedGates.add(gate);
1512
+ await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
589
1513
  }
590
1514
  }
591
- return true;
592
- }
593
- async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
594
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
595
- const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
596
- const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
597
- const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
598
- const verdict = parseJsonLine(artifact.verdictJson) ?? {};
599
- const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
600
- const checklist = stringArrayField(plan, "checklist");
601
- await emit({
602
- role: "worker",
603
- kind: "message",
604
- content: checklist.length > 0
605
- ? `QA plan: ${checklist.join("; ")}`
606
- : "QA plan recorded.",
607
- eventType: "qa_plan"
608
- });
609
- for (const browserCheck of arrayField(evidence, "browser_checks")) {
610
- await emit({
611
- role: "worker",
612
- kind: "checkpoint",
613
- content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
614
- eventType: "qa_browser_check"
615
- });
616
- }
617
- for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
618
- await emit({
619
- role: "worker",
620
- kind: "checkpoint",
621
- content: `QA finding: ${summarizeQaObject(finding)}`,
622
- eventType: "qa_finding"
623
- });
624
- }
625
- await emit({
626
- role: "assistant",
627
- kind: "message",
628
- content: status === "blocked"
629
- ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
630
- : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
631
- eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
632
- });
633
1515
  }
634
- class LiveQaArtifactEmitter {
1516
+ class LiveArchitectArtifactEmitter {
635
1517
  worktreePath;
636
1518
  workItemId;
637
1519
  emit;
@@ -666,17 +1548,61 @@ class LiveQaArtifactEmitter {
666
1548
  return this.pending;
667
1549
  }
668
1550
  async poll() {
669
- if (this.emitted) {
1551
+ if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
670
1552
  return;
671
1553
  }
672
- const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
1554
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
673
1555
  if (!artifact) {
674
1556
  return;
675
1557
  }
676
1558
  this.emitted = true;
677
- await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
678
- await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1559
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1560
+ await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1561
+ }
1562
+ }
1563
+ async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1564
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1565
+ for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1566
+ try {
1567
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1568
+ if (!stat.isFile()) {
1569
+ return false;
1570
+ }
1571
+ }
1572
+ catch (error) {
1573
+ if (isNodeError(error) && error.code === "ENOENT") {
1574
+ return false;
1575
+ }
1576
+ throw error;
1577
+ }
679
1578
  }
1579
+ return true;
1580
+ }
1581
+ async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1582
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1583
+ const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1584
+ const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1585
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1586
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1587
+ const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1588
+ await emit({
1589
+ role: "worker",
1590
+ kind: "checkpoint",
1591
+ content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1592
+ eventType: "architect_plan"
1593
+ });
1594
+ await emit({
1595
+ role: "worker",
1596
+ kind: "checkpoint",
1597
+ content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1598
+ eventType: "architect_qa_seed"
1599
+ });
1600
+ await emit({
1601
+ role: "hook",
1602
+ kind: status === "pass" ? "checkpoint" : "error",
1603
+ content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1604
+ eventType: "architect_mcp_complete"
1605
+ });
680
1606
  }
681
1607
  async function readJsonObjectFile(filePath) {
682
1608
  const content = await fs.readFile(filePath, "utf8").catch(() => "");
@@ -702,19 +1628,36 @@ function summarizeQaObject(source) {
702
1628
  ?? stringField(source, "id")
703
1629
  ?? JSON.stringify(source), 500);
704
1630
  }
705
- function qaArtifactRelativePath(workItemId, fileName) {
1631
+ function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1632
+ if (ownerType && ownerId) {
1633
+ const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1634
+ return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1635
+ }
706
1636
  return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
707
1637
  }
708
- function jsonText(value) {
709
- return `${JSON.stringify(value, null, 2)}\n`;
710
- }
711
1638
  async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
712
1639
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1640
+ await emit({
1641
+ role: "tool",
1642
+ kind: "checkpoint",
1643
+ content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1644
+ eventType: "completion_tool_validation_passed",
1645
+ data: JSON.stringify({
1646
+ phase: artifact.phase ?? "unknown",
1647
+ status: artifact.status,
1648
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1649
+ })
1650
+ });
713
1651
  await emit({
714
1652
  role: "tool",
715
1653
  kind: "tool_result",
716
1654
  content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
717
- eventType: "completion_tool_artifact_recorded"
1655
+ eventType: "completion_tool_artifact_recorded",
1656
+ data: JSON.stringify({
1657
+ phase: artifact.phase ?? "unknown",
1658
+ status: artifact.status,
1659
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1660
+ })
718
1661
  });
719
1662
  }
720
1663
  async function emitPhaseCompletionEvent(emit, artifact) {
@@ -742,7 +1685,15 @@ async function emitPhaseGateEvents(emit, artifact) {
742
1685
  ? "phase_progression: implementation -> self_review"
743
1686
  : phase === "self_review"
744
1687
  ? "phase_progression: self_review -> validation"
745
- : "phase_progression: validation -> QA ready";
1688
+ : phase === "debug_repro"
1689
+ ? "phase_progression: debug_repro -> debug_root_cause"
1690
+ : phase === "debug_root_cause"
1691
+ ? "phase_progression: debug_root_cause -> debug_fix"
1692
+ : phase === "debug_fix"
1693
+ ? "phase_progression: debug_fix -> debug_regression"
1694
+ : phase === "debug_regression"
1695
+ ? "phase_progression: debug_regression -> QA ready"
1696
+ : "phase_progression: validation -> QA ready";
746
1697
  await emit({
747
1698
  role: "hook",
748
1699
  kind: "checkpoint",
@@ -753,6 +1704,7 @@ async function emitPhaseGateEvents(emit, artifact) {
753
1704
  function completionPhaseFromArtifact(artifact) {
754
1705
  const phase = artifact.phase?.trim();
755
1706
  return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1707
+ || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
756
1708
  ? phase
757
1709
  : "implementation";
758
1710
  }
@@ -764,13 +1716,18 @@ class LiveCompletionArtifactEmitter {
764
1716
  emitted = new Set();
765
1717
  timer = null;
766
1718
  pending = Promise.resolve();
767
- constructor(worktreePath, workItemId, phase, developCycle, emit) {
1719
+ constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
768
1720
  this.worktreePath = worktreePath;
769
1721
  this.workItemId = workItemId;
770
1722
  this.emit = emit;
771
- this.phases = developCycle
772
- ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
773
- : [phase];
1723
+ if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
1724
+ this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
1725
+ }
1726
+ else {
1727
+ this.phases = developCycle
1728
+ ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1729
+ : [phase];
1730
+ }
774
1731
  }
775
1732
  start() {
776
1733
  void this.pollQueued();
@@ -813,20 +1770,23 @@ class LiveCompletionArtifactEmitter {
813
1770
  }
814
1771
  }
815
1772
  }
816
- async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle) {
817
- if (!developCycle) {
1773
+ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
1774
+ if (!developCycle && !debugCycle) {
818
1775
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
819
1776
  if (!artifact) {
820
1777
  throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
821
1778
  }
822
1779
  return [artifact];
823
1780
  }
1781
+ const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
1782
+ ? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
1783
+ : ["implementation", "self_review", "validation"];
824
1784
  const artifacts = [];
825
- for (const expectedPhase of ["implementation", "self_review", "validation"]) {
1785
+ for (const expectedPhase of expectedPhases) {
826
1786
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
827
1787
  if (!artifact) {
828
1788
  if (artifacts.length === 0) {
829
- throw new Error("Provider CLI completed but did not call the Forge implementation completion tool.");
1789
+ throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
830
1790
  }
831
1791
  const previous = artifacts[artifacts.length - 1];
832
1792
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
@@ -841,10 +1801,24 @@ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, de
841
1801
  }
842
1802
  return artifacts;
843
1803
  }
844
- function providerRedactionEnv(dispatch) {
845
- const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
1804
+ function providerProcessEnv(dispatch) {
1805
+ const env = {
1806
+ ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1807
+ ...providerCredentialEnv(dispatch)
1808
+ };
846
1809
  return Object.keys(env).length > 0 ? env : undefined;
847
1810
  }
1811
+ function providerCredentialEnv(dispatch) {
1812
+ const secret = dispatch.apiKeySecretGrant?.secret;
1813
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1814
+ return {};
1815
+ }
1816
+ const provider = dispatch.execution.provider.trim().toLowerCase();
1817
+ if (provider === "codex" || provider === "openai") {
1818
+ return { OPENAI_API_KEY: secret };
1819
+ }
1820
+ return {};
1821
+ }
848
1822
  function exactRedactionSecrets(dispatch) {
849
1823
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
850
1824
  }
@@ -867,7 +1841,7 @@ export class StreamingProviderProcessRunner {
867
1841
  return await new Promise((resolve, reject) => {
868
1842
  const child = spawn(launch.command, launch.args, {
869
1843
  cwd: request.cwd,
870
- env: request.env ? { ...process.env, ...request.env } : undefined,
1844
+ env: buildProviderChildEnvironment(request.env),
871
1845
  stdio: ["ignore", "pipe", "pipe"],
872
1846
  windowsHide: true
873
1847
  });
@@ -1002,9 +1976,6 @@ function quoteWindowsCommandLineArg(value) {
1002
1976
  }
1003
1977
  return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
1004
1978
  }
1005
- async function fileExists(inputPath) {
1006
- return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
1007
- }
1008
1979
  async function readProcessLines(stream, onLine) {
1009
1980
  const reader = readline.createInterface({ input: stream });
1010
1981
  try {
@@ -1022,12 +1993,159 @@ function isFakeWorkerModel(model) {
1022
1993
  function sha256(content) {
1023
1994
  return crypto.createHash("sha256").update(content).digest("hex");
1024
1995
  }
1996
+ function buildDraftSpec(dispatch) {
1997
+ return `# Draft Generation Context
1998
+
1999
+ Project: ${dispatch.draft?.projectName ?? dispatch.repo.name}
2000
+ Repository: ${dispatch.draft?.repoName ?? dispatch.repo.name}
2001
+ Draft kind: ${dispatch.draft?.kind ?? "draft"}
2002
+
2003
+ ## User Prompt
2004
+
2005
+ ${dispatch.draft?.userPrompt ?? ""}
2006
+ `;
2007
+ }
2008
+ async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
2009
+ const draftArtifactFiles = {
2010
+ draft_intent: "draft.intent.json",
2011
+ draft_repo_context: "draft.repo-context.json",
2012
+ draft_graph_context: "draft.graph-context.json",
2013
+ draft_product_scope: "draft.product-scope.json",
2014
+ draft_work_order_plan: "draft.work-order-plan.json",
2015
+ draft_critic: "draft.critic.json",
2016
+ draft_proposal: "draft.proposal.json"
2017
+ };
2018
+ for (const gate of draftCompletionGateOrder) {
2019
+ const actualPath = path.join(worktreePath, ".forge", "work-items", workItemId, "artifacts", draftArtifactFiles[gate]);
2020
+ if (!await fileExists(actualPath)) {
2021
+ continue;
2022
+ }
2023
+ const relativePath = path.relative(worktreePath, actualPath).split(path.sep).join("/");
2024
+ await emit({
2025
+ role: "tool",
2026
+ kind: "tool_result",
2027
+ content: `Forge Draft completion tool recorded ${gate} artifact ${relativePath}.`,
2028
+ eventType: "completion_tool_artifact_recorded",
2029
+ data: JSON.stringify({ phase: "draft", draft_gate: gate, artifact_relative_paths: [relativePath] })
2030
+ });
2031
+ await emit({
2032
+ role: "hook",
2033
+ kind: "checkpoint",
2034
+ content: `phase_gate: ${gate} artifact accepted with status pass.`,
2035
+ eventType: "phase_gate"
2036
+ });
2037
+ const next = draftCompletionGateOrder[draftCompletionGateOrder.indexOf(gate) + 1];
2038
+ if (next) {
2039
+ await emit({
2040
+ role: "hook",
2041
+ kind: "checkpoint",
2042
+ content: `phase_progression: ${gate} -> ${next}`,
2043
+ eventType: "phase_gate"
2044
+ });
2045
+ }
2046
+ }
2047
+ }
2048
+ async function fileExists(filePath) {
2049
+ try {
2050
+ await fs.access(filePath);
2051
+ return true;
2052
+ }
2053
+ catch {
2054
+ return false;
2055
+ }
2056
+ }
2057
+ function buildDraftPrompt(dispatch) {
2058
+ const draft = dispatch.draft;
2059
+ if (!draft) {
2060
+ throw new Error("Draft prompt is missing.");
2061
+ }
2062
+ const draftArtifacts = dispatch.artifacts
2063
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
2064
+ .map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
2065
+ .join("\n\n");
2066
+ const artifactSection = draftArtifacts
2067
+ ? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
2068
+ : "";
2069
+ const projectSection = [
2070
+ draft.projectName ? `Project: ${draft.projectName}` : null,
2071
+ draft.repoName ? `Repository: ${draft.repoName}` : null
2072
+ ].filter(Boolean).join("\n");
2073
+ const scopedProjectSection = projectSection ? `\n\n# Selected project context\n\n${projectSection}` : "";
2074
+ return `${draft.systemPrompt}${scopedProjectSection}${artifactSection}
2075
+
2076
+ Draft kind: ${draft.kind}
2077
+
2078
+ ${draft.userPrompt}
2079
+
2080
+ ${completionPromptForDraftCycle("draft_intent")}
2081
+
2082
+ Use the injected command/skills/hooks as lane instructions. You must call each Forge Draft MCP completion tool in order. Do not claim the Draft is complete until forge.complete_draft_proposal accepts the final draft_json.
2083
+
2084
+ Do not modify source files.`;
2085
+ }
2086
+ function extractJsonObject(content) {
2087
+ let trimmed = content.trim();
2088
+ if (trimmed.startsWith("```")) {
2089
+ const firstNewline = trimmed.indexOf("\n");
2090
+ const lastFence = trimmed.lastIndexOf("```");
2091
+ if (firstNewline >= 0 && lastFence > firstNewline) {
2092
+ trimmed = trimmed.slice(firstNewline + 1, lastFence).trim();
2093
+ }
2094
+ }
2095
+ const start = trimmed.indexOf("{");
2096
+ const end = trimmed.lastIndexOf("}");
2097
+ return start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed;
2098
+ }
2099
+ function summarizeStderr(stderr) {
2100
+ const trimmed = stderr.trim();
2101
+ return trimmed ? `: ${clip(trimmed, 1000)}` : "";
2102
+ }
2103
+ async function waitForDraftProposalArtifact(worktreePath, workItemId, signal) {
2104
+ while (!signal?.aborted) {
2105
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "draft");
2106
+ if (artifact) {
2107
+ return artifact;
2108
+ }
2109
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2110
+ }
2111
+ throw new Error("Draft proposal artifact wait was cancelled.");
2112
+ }
2113
+ function isDecomposeDraftKind(kind) {
2114
+ return kind === "work_order_decomposition" || kind === "feature_decomposition";
2115
+ }
2116
+ function deterministicDraftPayload(dispatch) {
2117
+ const kind = dispatch.draft?.kind ?? "work_item";
2118
+ if (kind === "work_order") {
2119
+ return {
2120
+ title: "Deterministic runner Work Order draft",
2121
+ summary: "Forge Runner generated this deterministic Work Order draft.",
2122
+ objective: "Validate runner-backed Draft generation.",
2123
+ planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
2124
+ decompositionContext: "Use this deterministic fixture only in bridge tests.",
2125
+ assumptions: ["Forge Runner dispatch is available."],
2126
+ warnings: []
2127
+ };
2128
+ }
2129
+ if (kind === "story") {
2130
+ return {
2131
+ title: "Deterministic runner Story draft",
2132
+ description: "Forge Runner generated this deterministic Story draft.",
2133
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
2134
+ points: 3
2135
+ };
2136
+ }
2137
+ return {
2138
+ title: "Deterministic runner Work Item draft",
2139
+ description: "Forge Runner generated this deterministic Work Item draft.",
2140
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
2141
+ reproSteps: "Run Draft with a Forge Runner provider selected.",
2142
+ systemInfo: "forge-bridge deterministic provider",
2143
+ points: 1
2144
+ };
2145
+ }
1025
2146
  export function formatProviderCliCommand(command) {
1026
2147
  return [command.command, ...command.args].map(singleLine).join(" ");
1027
2148
  }
1028
- function yamlQuotedScalar(value) {
1029
- return JSON.stringify(singleLine(value));
1030
- }
1031
2149
  function singleLine(value) {
1032
2150
  return value.replace(/\s+/g, " ").trim();
1033
2151
  }
@@ -1036,16 +2154,19 @@ export function buildProviderCliCommand(dispatch, run) {
1036
2154
  const normalizedProvider = provider.toLowerCase();
1037
2155
  const model = dispatch.execution.model.trim();
1038
2156
  if (normalizedProvider === "codex") {
1039
- const args = ["exec"];
2157
+ const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
1040
2158
  if (run?.completionTools) {
1041
2159
  args.push(...codexMcpConfigArgs(run.completionTools));
1042
2160
  }
1043
2161
  args.push("--model", model);
1044
2162
  if (run) {
1045
- args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
2163
+ args.push("--json");
1046
2164
  if (run.worktreePath) {
1047
2165
  args.push("--cd", run.worktreePath);
1048
2166
  }
2167
+ if (run.skipGitRepoCheck) {
2168
+ args.push("--skip-git-repo-check");
2169
+ }
1049
2170
  args.push(run.prompt ?? "");
1050
2171
  }
1051
2172
  return { command: "codex", args };
@@ -1066,11 +2187,41 @@ export function buildProviderCliCommand(dispatch, run) {
1066
2187
  }
1067
2188
  return { command: provider, args };
1068
2189
  }
2190
+ export function codexSandboxModeForPlatform(platform = process.platform) {
2191
+ return platform === "win32" ? "danger-full-access" : "workspace-write";
2192
+ }
2193
+ function buildArchitectPrompt(dispatch) {
2194
+ return `You are Forge's Architect lane running locally in a prepared git worktree.
2195
+
2196
+ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
2197
+
2198
+ Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
2199
+ 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.
2200
+ Implementation DAG tasks are Develop child tasks only: include focused repo/product implementation changes. Do not create child Develop tasks for parent-story QA, sign-off, materialized child inventory, child-count evidence, parent plan artifact checks, or final integrated acceptance proof; put those checks in qa_plan.final_qa.
2201
+ ${architectRevisionInstruction(dispatch)}
2202
+ Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
2203
+
2204
+ ${completionPromptForPhase("architect")}
2205
+
2206
+ Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
2207
+ }
2208
+ function architectRevisionInstruction(dispatch) {
2209
+ if (!dispatch.architectRevision) {
2210
+ return "";
2211
+ }
2212
+ return `
2213
+ Architect revision context:
2214
+ - Previous plan id: ${dispatch.architectRevision.priorPlanId}
2215
+ - Previous content hash: ${dispatch.architectRevision.priorContentHash}
2216
+ - Reviewer feedback: ${dispatch.architectRevision.feedback}
2217
+ Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
2218
+ }
1069
2219
  function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1070
2220
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
1071
2221
 
1072
2222
  Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
1073
2223
  ${phaseWorkInstruction(phase)}
2224
+ ${qaReworkImplementationInstruction(dispatch)}
1074
2225
  Use the repository's existing conventions. Run relevant tests when practical.
1075
2226
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
1076
2227
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -1084,6 +2235,7 @@ function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(d
1084
2235
 
1085
2236
  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.
1086
2237
  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.
2238
+ ${qaReworkImplementationInstruction(dispatch)}
1087
2239
  Use the repository's existing conventions. Run relevant tests when practical.
1088
2240
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
1089
2241
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -1092,6 +2244,55 @@ ${completionPromptForDevelopCycle(phase)}
1092
2244
 
1093
2245
  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.`;
1094
2246
  }
2247
+ function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2248
+ return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
2249
+
2250
+ 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.
2251
+ 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.
2252
+ ${debugQaReworkInstruction(dispatch)}
2253
+ Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
2254
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
2255
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
2256
+
2257
+ ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
2258
+
2259
+ 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.`;
2260
+ }
2261
+ function qaReworkImplementationInstruction(dispatch) {
2262
+ if (!dispatch.qaRework) {
2263
+ return "";
2264
+ }
2265
+ return `
2266
+ QA rework context:
2267
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2268
+ - Rework packet: ${dispatch.qaRework.packetPath}
2269
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2270
+ 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.
2271
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2272
+ }
2273
+ function debugQaReworkInstruction(dispatch) {
2274
+ if (!dispatch.qaRework) {
2275
+ return "";
2276
+ }
2277
+ return `
2278
+ QA rework context for Debug:
2279
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2280
+ - Rework packet: ${dispatch.qaRework.packetPath}
2281
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2282
+ 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.
2283
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2284
+ }
2285
+ function qaReworkRetestInstruction(dispatch) {
2286
+ if (!dispatch.qaRework) {
2287
+ return "";
2288
+ }
2289
+ return `
2290
+ QA retest context:
2291
+ - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2292
+ - Rework packet: ${dispatch.qaRework.packetPath}
2293
+ - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2294
+ Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
2295
+ }
1095
2296
  function phaseWorkInstruction(phase) {
1096
2297
  if (phase === "self_review") {
1097
2298
  return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
@@ -1101,9 +2302,64 @@ function phaseWorkInstruction(phase) {
1101
2302
  }
1102
2303
  return "Implement the work item and keep the change focused.";
1103
2304
  }
1104
- function buildQaPrompt(dispatch) {
2305
+ function qaBrowserInstruction(dispatch) {
2306
+ const qaBrowser = dispatch.qaBrowser;
2307
+ if (!qaBrowser) {
2308
+ return "Browser/app launch context: not provided by Forge.";
2309
+ }
2310
+ const launchTarget = qaBrowser.launchTarget;
2311
+ if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
2312
+ 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`}`;
2313
+ }
2314
+ if (!launchTarget) {
2315
+ 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`}`;
2316
+ }
2317
+ const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
2318
+ 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`}`;
2319
+ }
2320
+ function storyQaInstruction(dispatch) {
2321
+ const storyQa = dispatch.storyQa;
2322
+ if (!storyQa) {
2323
+ return "";
2324
+ }
2325
+ const childLines = storyQa.childTasks.map((child) => {
2326
+ const dependencies = child.dependencyWorkItemIds.length > 0
2327
+ ? child.dependencyWorkItemIds.join(", ")
2328
+ : "none";
2329
+ const validation = child.validationArtifact
2330
+ ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2331
+ : "missing";
2332
+ const childQa = child.qaArtifact
2333
+ ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2334
+ : "not present";
2335
+ return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2336
+ }).join("\n");
2337
+ const finalQa = storyQa.finalQaChecks.length > 0
2338
+ ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2339
+ : "- No final QA checks were provided in qa.plan.final_qa.";
2340
+ return `Story QA integration context:
2341
+ - Story work item: ${storyQa.storyWorkItemId}
2342
+ - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2343
+ - Story worktree: ${storyQa.worktreeKey}
2344
+ - Branch: ${storyQa.branch}
2345
+ - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2346
+ - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2347
+ Materialized child tasks and evidence:
2348
+ ${childLines || "- No child tasks were provided."}
2349
+ Architect final QA checks:
2350
+ ${finalQa}
2351
+ This is parent Story QA: inspect the integrated Story result, all current-plan child specs/evidence, and the final worktree state. Do not treat the final child task as separately signed off.`;
2352
+ }
2353
+ function buildQaPrompt(dispatch, laneSpec) {
1105
2354
  return `You are Forge's QA lane running locally in a prepared git worktree.
1106
2355
 
2356
+ 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.
2357
+
2358
+ Injected QA lane command and work item spec:
2359
+ ${laneSpec}
2360
+
2361
+ ---
2362
+
1107
2363
  Work item: ${dispatch.workItem.id}
1108
2364
  Title: ${dispatch.workItem.title}
1109
2365
  Description:
@@ -1118,15 +2374,18 @@ ${dispatch.workItem.reproSteps || "Not provided."}
1118
2374
  System info / environment notes:
1119
2375
  ${dispatch.workItem.systemInfo || "Not provided."}
1120
2376
 
2377
+ ${storyQaInstruction(dispatch)}
1121
2378
  Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
2379
+ ${qaBrowserInstruction(dispatch)}
2380
+ ${qaReworkRetestInstruction(dispatch)}
1122
2381
  QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
1123
- Record concrete evidence. For UI/browser work, include browser_checks with URLs, actions, observed results, screenshots/traces when available, and console/network notes.
2382
+ 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/.
1124
2383
  Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
1125
2384
  Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
1126
2385
 
1127
- ${completionPromptForPhase("qa")}
2386
+ ${completionPromptForQaCycle()}
1128
2387
 
1129
- Finish with a concise summary only after forge.complete_qa accepts the QA bundle.`;
2388
+ Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
1130
2389
  }
1131
2390
  function buildConflictResolvePrompt(dispatch, branchName) {
1132
2391
  const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
@@ -1141,6 +2400,34 @@ Keep the original work item intent intact:
1141
2400
 
1142
2401
  Finish with a concise summary of the conflicts resolved and verification performed.`;
1143
2402
  }
2403
+ function buildPullRequestCommentsPrompt(dispatch, branchName) {
2404
+ const pr = dispatch.pullRequest;
2405
+ const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
2406
+ const prLocator = pr
2407
+ ? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
2408
+ : "the open pull request for this work item";
2409
+ return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
2410
+
2411
+ The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
2412
+ PR context:
2413
+ - Provider: ${pr?.provider || "not provided"}
2414
+ - Source branch: ${pr?.sourceBranch || branchName}
2415
+ - Target branch: ${targetBranch}
2416
+ - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
2417
+
2418
+ 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.
2419
+ After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
2420
+ If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
2421
+ Keep the original work item intent intact:
2422
+ - Work item: ${dispatch.workItem.id}
2423
+ - Title: ${dispatch.workItem.title}
2424
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
2425
+
2426
+ Finish with a concise summary of comments addressed and verification performed.`;
2427
+ }
2428
+ function isPullRequestCommentsDispatch(dispatch) {
2429
+ return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
2430
+ }
1144
2431
  async function cleanupCompletionTools(completionTools, emit) {
1145
2432
  try {
1146
2433
  await completionTools.cleanup();
@@ -1198,31 +2485,31 @@ class CursorStreamJsonState {
1198
2485
  consume(line) {
1199
2486
  const event = parseJsonLine(line);
1200
2487
  if (!event) {
1201
- return null;
2488
+ return [];
1202
2489
  }
1203
2490
  const type = stringField(event, "type");
1204
2491
  if (type === "system" && stringField(event, "subtype") === "init") {
1205
2492
  this.sessionId = stringField(event, "session_id");
1206
2493
  if (this.sessionId && !this.emittedSession) {
1207
2494
  this.emittedSession = true;
1208
- return {
1209
- role: "runner",
1210
- kind: "checkpoint",
1211
- content: `Cursor session started: ${this.sessionId}.`,
1212
- eventType: "provider_thread_started"
1213
- };
2495
+ return [{
2496
+ role: "runner",
2497
+ kind: "checkpoint",
2498
+ content: `Cursor session started: ${this.sessionId}.`,
2499
+ eventType: "provider_thread_started"
2500
+ }];
1214
2501
  }
1215
2502
  }
1216
2503
  if (type === "assistant") {
1217
2504
  const text = assistantMessageText(event);
1218
2505
  if (text) {
1219
- this.finalMessage = clip(text, 4000);
1220
- return {
1221
- role: "assistant",
1222
- kind: "message",
1223
- content: this.finalMessage,
1224
- eventType: "provider_message"
1225
- };
2506
+ this.finalMessage = text;
2507
+ return [{
2508
+ role: "assistant",
2509
+ kind: "message",
2510
+ content: clip(text, 4000),
2511
+ eventType: "provider_message"
2512
+ }];
1226
2513
  }
1227
2514
  }
1228
2515
  if (type === "tool_call") {
@@ -1231,42 +2518,42 @@ class CursorStreamJsonState {
1231
2518
  if (subtype === "started") {
1232
2519
  const summary = formatCursorToolCallStarted(toolCall);
1233
2520
  if (summary) {
1234
- return {
1235
- role: "worker",
1236
- kind: "checkpoint",
1237
- content: summary,
1238
- eventType: "provider_tool_call"
1239
- };
2521
+ return [{
2522
+ role: "worker",
2523
+ kind: "checkpoint",
2524
+ content: summary,
2525
+ eventType: "provider_tool_call"
2526
+ }];
1240
2527
  }
1241
2528
  }
1242
2529
  if (subtype === "completed") {
1243
2530
  const completed = formatCursorToolCallCompleted(toolCall);
1244
2531
  if (completed) {
1245
- return {
1246
- role: "worker",
1247
- kind: completed.kind,
1248
- content: completed.content,
1249
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
1250
- };
2532
+ return [{
2533
+ role: "worker",
2534
+ kind: completed.kind,
2535
+ content: completed.content,
2536
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2537
+ }];
1251
2538
  }
1252
2539
  }
1253
2540
  }
1254
2541
  if (type === "result" && stringField(event, "subtype") === "success") {
1255
2542
  const result = stringField(event, "result");
1256
2543
  if (result) {
1257
- this.finalMessage = clip(result, 4000);
2544
+ this.finalMessage = result;
1258
2545
  }
1259
2546
  this.accumulateUsage(event);
1260
2547
  }
1261
2548
  if (type === "error" || (type === "result" && event.is_error === true)) {
1262
- return {
1263
- role: "runner",
1264
- kind: "error",
1265
- content: clip(line.trim(), 1000),
1266
- eventType: "provider_cli_error"
1267
- };
2549
+ return [{
2550
+ role: "runner",
2551
+ kind: "error",
2552
+ content: clip(line.trim(), 1000),
2553
+ eventType: "provider_cli_error"
2554
+ }];
1268
2555
  }
1269
- return null;
2556
+ return [];
1270
2557
  }
1271
2558
  accumulateUsage(event) {
1272
2559
  const usage = objectField(event, "usage");
@@ -1397,37 +2684,37 @@ class CodexJsonState {
1397
2684
  consume(line) {
1398
2685
  const event = parseJsonLine(line);
1399
2686
  if (!event) {
1400
- return null;
2687
+ return [];
1401
2688
  }
1402
2689
  const type = stringField(event, "type") ?? "";
1403
2690
  if (type === "thread.started") {
1404
2691
  this.threadId = stringField(event, "thread_id");
1405
2692
  if (this.threadId && !this.emittedThread) {
1406
2693
  this.emittedThread = true;
1407
- return {
1408
- role: "runner",
1409
- kind: "checkpoint",
1410
- content: `Codex thread started: ${this.threadId}.`,
1411
- eventType: "provider_thread_started"
1412
- };
2694
+ return [{
2695
+ role: "runner",
2696
+ kind: "checkpoint",
2697
+ content: `Codex thread started: ${this.threadId}.`,
2698
+ eventType: "provider_thread_started"
2699
+ }];
1413
2700
  }
1414
2701
  }
1415
2702
  if (type === "turn.completed") {
1416
2703
  this.accumulateUsage(event);
1417
- return {
1418
- role: "runner",
1419
- kind: "checkpoint",
1420
- content: "Codex turn completed.",
1421
- eventType: "provider_turn_completed"
1422
- };
2704
+ return [{
2705
+ role: "runner",
2706
+ kind: "checkpoint",
2707
+ content: "Codex turn completed.",
2708
+ eventType: "provider_turn_completed"
2709
+ }];
1423
2710
  }
1424
2711
  if (type === "turn.failed" || type === "error") {
1425
- return {
1426
- role: "runner",
1427
- kind: "error",
1428
- content: clip(line.trim(), 1000),
1429
- eventType: "provider_cli_error"
1430
- };
2712
+ return [{
2713
+ role: "runner",
2714
+ kind: "error",
2715
+ content: clip(line.trim(), 1000),
2716
+ eventType: "provider_cli_error"
2717
+ }];
1431
2718
  }
1432
2719
  if (type === "item.completed" || type === "item.updated") {
1433
2720
  const item = objectField(event, "item");
@@ -1435,29 +2722,33 @@ class CodexJsonState {
1435
2722
  if (itemType === "agent_message") {
1436
2723
  const text = stringField(item, "text");
1437
2724
  if (text) {
1438
- this.finalMessage = clip(text, 4000);
1439
- return {
1440
- role: "assistant",
1441
- kind: "message",
1442
- content: this.finalMessage,
1443
- eventType: "provider_message"
1444
- };
2725
+ this.finalMessage = text;
2726
+ return [{
2727
+ role: "assistant",
2728
+ kind: "message",
2729
+ content: clip(text, 4000),
2730
+ eventType: "provider_message"
2731
+ }];
1445
2732
  }
1446
2733
  }
1447
2734
  if (itemType === "command_execution") {
1448
2735
  const command = stringField(item, "command");
1449
2736
  const status = stringField(item, "status");
1450
2737
  if (command) {
1451
- return {
1452
- role: "worker",
1453
- kind: "checkpoint",
1454
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
1455
- eventType: "provider_command"
1456
- };
2738
+ return [{
2739
+ role: "worker",
2740
+ kind: "checkpoint",
2741
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2742
+ eventType: "provider_command"
2743
+ }];
1457
2744
  }
1458
2745
  }
1459
2746
  }
1460
- return null;
2747
+ const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2748
+ if (mcpEvents.length > 0) {
2749
+ return mcpEvents;
2750
+ }
2751
+ return [];
1461
2752
  }
1462
2753
  accumulateUsage(event) {
1463
2754
  const usage = objectField(event, "usage");
@@ -1473,6 +2764,113 @@ class CodexJsonState {
1473
2764
  });
1474
2765
  }
1475
2766
  }
2767
+ function formatCodexMcpToolCallEvents(type, event) {
2768
+ if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2769
+ return [];
2770
+ }
2771
+ const item = objectField(event, "item");
2772
+ const itemType = stringField(item, "type") ?? "";
2773
+ const serverName = mcpServerName(item);
2774
+ const toolName = mcpToolName(item);
2775
+ const isMcpItem = itemType.toLowerCase().includes("mcp")
2776
+ || Boolean(serverName)
2777
+ || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2778
+ if (!isMcpItem || !toolName) {
2779
+ return [];
2780
+ }
2781
+ const status = normalizedString(stringField(item, "status")
2782
+ ?? stringField(event, "status")
2783
+ ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2784
+ const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2785
+ const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2786
+ const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2787
+ const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2788
+ const label = `${serverName ?? "unknown"}.${toolName}`;
2789
+ if (failed) {
2790
+ const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2791
+ const events = [{
2792
+ role: "tool",
2793
+ kind: "error",
2794
+ content: `MCP tool call failed: ${label} - ${summary}`,
2795
+ eventType: "provider_mcp_call_failed",
2796
+ data
2797
+ }];
2798
+ if (isForgeCompletionTool(toolName)) {
2799
+ events.push({
2800
+ role: "tool",
2801
+ kind: "error",
2802
+ content: `Forge completion tool validation failed: ${label} - ${summary}`,
2803
+ eventType: "completion_tool_validation_failed",
2804
+ data
2805
+ });
2806
+ }
2807
+ return events;
2808
+ }
2809
+ if (completed) {
2810
+ return [{
2811
+ role: "tool",
2812
+ kind: "checkpoint",
2813
+ content: `MCP tool call completed: ${label}.`,
2814
+ eventType: "provider_mcp_call_completed",
2815
+ data
2816
+ }];
2817
+ }
2818
+ if (started) {
2819
+ return [{
2820
+ role: "tool",
2821
+ kind: "checkpoint",
2822
+ content: `MCP tool call started: ${label}.`,
2823
+ eventType: "provider_mcp_call_started",
2824
+ data
2825
+ }];
2826
+ }
2827
+ return [];
2828
+ }
2829
+ function mcpServerName(item) {
2830
+ return stringField(item, "server")
2831
+ ?? stringField(item, "server_name")
2832
+ ?? stringField(item, "mcp_server")
2833
+ ?? stringField(objectField(item, "mcp"), "server")
2834
+ ?? stringField(objectField(item, "mcp"), "server_name");
2835
+ }
2836
+ function mcpToolName(item) {
2837
+ return stringField(item, "tool")
2838
+ ?? stringField(item, "tool_name")
2839
+ ?? stringField(item, "name")
2840
+ ?? stringField(objectField(item, "function"), "name")
2841
+ ?? stringField(objectField(item, "mcp"), "tool")
2842
+ ?? stringField(objectField(item, "mcp"), "tool_name");
2843
+ }
2844
+ function mcpErrorSummary(item) {
2845
+ const direct = stringField(item, "error")
2846
+ ?? stringField(item, "error_message")
2847
+ ?? stringField(item, "message");
2848
+ if (direct) {
2849
+ return clip(direct, 600);
2850
+ }
2851
+ const error = objectField(item, "error");
2852
+ return stringField(error, "message")
2853
+ ?? stringField(error, "summary")
2854
+ ?? stringField(objectField(item, "result"), "error")
2855
+ ?? null;
2856
+ }
2857
+ function safeProviderMcpData(item, serverName, toolName, status) {
2858
+ const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2859
+ return JSON.stringify(stripUndefined({
2860
+ server_name: serverName,
2861
+ tool_name: toolName,
2862
+ status,
2863
+ elapsed_ms: elapsedMs,
2864
+ error_summary: mcpErrorSummary(item)
2865
+ }));
2866
+ }
2867
+ function isForgeCompletionTool(toolName) {
2868
+ const normalized = toolName.trim().toLowerCase();
2869
+ return normalized.startsWith("forge.complete_")
2870
+ || normalized.startsWith("complete_")
2871
+ || normalized.includes("forge.complete_")
2872
+ || normalized.includes("complete_architect_plan");
2873
+ }
1476
2874
  function objectField(source, key) {
1477
2875
  const value = source[key];
1478
2876
  return value && typeof value === "object" && !Array.isArray(value)
@@ -1483,6 +2881,16 @@ function stringField(source, key) {
1483
2881
  const value = source[key];
1484
2882
  return typeof value === "string" && value.trim().length > 0 ? value : null;
1485
2883
  }
2884
+ function numericField(source, key) {
2885
+ const value = source[key];
2886
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2887
+ }
2888
+ function stripUndefined(value) {
2889
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2890
+ }
2891
+ function normalizedString(value) {
2892
+ return value.trim().toLowerCase().replace(/-/g, "_");
2893
+ }
1486
2894
  function isNodeError(error) {
1487
2895
  return error instanceof Error && "code" in error;
1488
2896
  }