@loucompanion/forge-bridge 0.1.1-dev.4f31cdd58cac → 0.1.1-dev.5093acd6bece

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 } 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,15 +155,25 @@ 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)
30
166
  : await this.realProvider.runConflictResolve(context);
31
167
  }
32
- async runQa(dispatch, emit, signal) {
33
- return isFakeWorkerModel(dispatch.execution.model)
34
- ? await this.deterministicProvider.runQa(dispatch, emit, signal)
35
- : await this.realProvider.runQa(dispatch, emit, signal);
168
+ async runQa(context) {
169
+ return isFakeWorkerModel(context.dispatch.execution.model)
170
+ ? await this.deterministicProvider.runQa(context)
171
+ : await this.realProvider.runQa(context);
172
+ }
173
+ async runDraft(context) {
174
+ return isFakeWorkerModel(context.dispatch.execution.model)
175
+ ? await this.deterministicProvider.runDraft(context)
176
+ : await this.realProvider.runDraft(context);
36
177
  }
37
178
  }
38
179
  export class ProcessBackedProviderCliService {
@@ -42,10 +183,108 @@ 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 completionTools = await prepareCompletionToolRuntime({ dispatch, worktree: draftWorktree, phase: "draft" });
204
+ const command = buildProviderCliCommand(dispatch, {
205
+ worktreePath: tempDir,
206
+ prompt: buildDraftPrompt(dispatch),
207
+ completionTools,
208
+ skipGitRepoCheck: true
209
+ });
210
+ const draftArtifactSlugs = dispatch.artifacts
211
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
212
+ .map((artifact) => `${artifact.kind}:${artifact.slug}`);
213
+ await context.emit({
214
+ role: "runner",
215
+ kind: "checkpoint",
216
+ content: `Draft artifacts injected: ${draftArtifactSlugs.length}${draftArtifactSlugs.length ? ` (${draftArtifactSlugs.join(", ")})` : ""}. Project: ${dispatch.draft.projectName ?? dispatch.repo.name}. Repo: ${dispatch.draft.repoName ?? dispatch.repo.name}.`,
217
+ eventType: "draft_artifacts_injected"
218
+ });
219
+ await context.emit({
220
+ role: "runner",
221
+ kind: "checkpoint",
222
+ content: `Starting provider CLI Draft: ${formatProviderCliCommand(command)}`,
223
+ eventType: "provider_cli_started"
224
+ });
225
+ await context.emit({
226
+ role: "runner",
227
+ kind: "checkpoint",
228
+ 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.",
229
+ eventType: "completion_tools_configured"
230
+ });
231
+ const outputState = createProviderOutputState(dispatch.execution.provider);
232
+ try {
233
+ const result = await this.processRunner.run({
234
+ command: command.command,
235
+ args: command.args,
236
+ cwd: tempDir,
237
+ env: providerProcessEnv(dispatch)
238
+ }, {
239
+ onStdoutLine: async (line) => {
240
+ for (const event of outputState.consume(line)) {
241
+ await context.emit(event);
242
+ }
243
+ }
244
+ }, context.signal);
245
+ if (result.exitCode !== 0) {
246
+ throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
247
+ }
248
+ await context.emit({
249
+ role: "runner",
250
+ kind: "checkpoint",
251
+ content: `Provider CLI Draft completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
252
+ eventType: "provider_cli_completed"
253
+ });
254
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
255
+ await emitDraftGateArtifacts(context.emit, tempDir, dispatch.workItem.id);
256
+ const proposalArtifact = await readCompletionArtifact(tempDir, dispatch.workItem.id, "draft");
257
+ if (!proposalArtifact) {
258
+ throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
259
+ }
260
+ const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
261
+ const draftJson = proposal["draft_json"];
262
+ if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
263
+ throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
264
+ }
265
+ const json = JSON.stringify(draftJson);
266
+ await context.emit({
267
+ role: "assistant",
268
+ kind: "message",
269
+ content: json,
270
+ eventType: "draft_complete"
271
+ });
272
+ return {
273
+ summary: "Draft generated through Forge Draft completion cycle.",
274
+ artifact: proposalArtifact,
275
+ artifacts: [proposalArtifact]
276
+ };
277
+ }
278
+ finally {
279
+ await cleanupCompletionTools(completionTools, context.emit);
280
+ await fs.rm(tempDir, { recursive: true, force: true });
281
+ }
282
+ }
45
283
  async runImplementation(context) {
46
284
  const { dispatch, worktree } = context;
47
285
  const phase = completionPhaseFromDispatch(dispatch);
48
286
  const developCycle = usesDevelopCycleCompletion(dispatch);
287
+ const debugCycle = usesDebugCycleCompletion(dispatch);
49
288
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
50
289
  await fs.mkdir(metadataRoot, { recursive: true });
51
290
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -59,7 +298,11 @@ export class ProcessBackedProviderCliService {
59
298
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
60
299
  const command = buildProviderCliCommand(dispatch, {
61
300
  worktreePath: worktree.worktreePath,
62
- prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
301
+ prompt: debugCycle
302
+ ? buildDebugCyclePrompt(dispatch, phase)
303
+ : developCycle
304
+ ? buildDevelopCyclePrompt(dispatch, phase)
305
+ : buildImplementationPrompt(dispatch, phase),
63
306
  completionTools
64
307
  });
65
308
  await context.emit({
@@ -71,13 +314,15 @@ export class ProcessBackedProviderCliService {
71
314
  await context.emit({
72
315
  role: "runner",
73
316
  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.`,
317
+ content: debugCycle
318
+ ? "Forge Debug completion tools configured for debug_repro -> debug_root_cause -> debug_fix -> debug_regression; provider must call each MCP completion tool before exit."
319
+ : developCycle
320
+ ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
321
+ : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
77
322
  eventType: "completion_tools_configured"
78
323
  });
79
324
  const outputState = createProviderOutputState(dispatch.execution.provider);
80
- const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, context.emit);
325
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
81
326
  let result;
82
327
  try {
83
328
  liveCompletionEvents.start();
@@ -85,11 +330,10 @@ export class ProcessBackedProviderCliService {
85
330
  command: command.command,
86
331
  args: command.args,
87
332
  cwd: worktree.worktreePath,
88
- env: providerRedactionEnv(dispatch)
333
+ env: providerProcessEnv(dispatch)
89
334
  }, {
90
335
  onStdoutLine: async (line) => {
91
- const event = outputState.consume(line);
92
- if (event) {
336
+ for (const event of outputState.consume(line)) {
93
337
  await context.emit(event);
94
338
  }
95
339
  }
@@ -111,7 +355,7 @@ export class ProcessBackedProviderCliService {
111
355
  });
112
356
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
113
357
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
114
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle);
358
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
115
359
  for (const artifact of completionArtifacts) {
116
360
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
117
361
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -137,7 +381,7 @@ export class ProcessBackedProviderCliService {
137
381
  });
138
382
  }
139
383
  return {
140
- summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
384
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
141
385
  spec: {
142
386
  repoPath: worktree.worktreePath,
143
387
  path: specPath,
@@ -149,65 +393,208 @@ export class ProcessBackedProviderCliService {
149
393
  artifacts: completionArtifacts
150
394
  };
151
395
  }
152
- async runQa(dispatch, emit, signal) {
396
+ async runArchitect(context) {
397
+ const { dispatch, worktree } = context;
398
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
153
399
  const command = buildProviderCliCommand(dispatch, {
154
- prompt: buildQaPrompt(dispatch)
400
+ worktreePath: worktree.worktreePath,
401
+ prompt: buildArchitectPrompt(dispatch),
402
+ completionTools
155
403
  });
156
- await emit({
404
+ const commandText = formatProviderCliCommand(command);
405
+ await context.emit({
157
406
  role: "runner",
158
407
  kind: "checkpoint",
159
- content: `Starting provider CLI QA: ${formatProviderCliCommand(command)}`,
408
+ content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
160
409
  eventType: "provider_cli_started"
161
410
  });
411
+ await context.emit({
412
+ role: "runner",
413
+ kind: "checkpoint",
414
+ content: "Forge Architect completion tools configured; provider must call forge.complete_architect_plan before exit.",
415
+ eventType: "completion_tools_configured"
416
+ });
162
417
  const outputState = createProviderOutputState(dispatch.execution.provider);
163
- const result = await this.processRunner.run({
164
- command: command.command,
165
- args: command.args,
166
- cwd: process.cwd()
167
- }, {
168
- onStdoutLine: async (line) => {
169
- const event = outputState.consume(line);
170
- if (event) {
171
- await emit(event);
418
+ const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
419
+ let result;
420
+ try {
421
+ liveArchitectEvents.start();
422
+ result = await this.processRunner.run({
423
+ command: command.command,
424
+ args: command.args,
425
+ cwd: worktree.worktreePath,
426
+ env: providerProcessEnv(dispatch)
427
+ }, {
428
+ onStdoutLine: async (line) => {
429
+ for (const event of outputState.consume(line)) {
430
+ await context.emit(event);
431
+ }
172
432
  }
173
- }
174
- }, signal);
433
+ }, context.signal);
434
+ }
435
+ finally {
436
+ await liveArchitectEvents.stop();
437
+ await cleanupCompletionTools(completionTools, context.emit);
438
+ }
175
439
  if (result.exitCode !== 0) {
176
440
  const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
177
441
  throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
178
442
  }
179
- await emit({
443
+ await context.emit({
444
+ role: "runner",
445
+ kind: "checkpoint",
446
+ content: `Provider CLI Architect completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
447
+ eventType: "provider_cli_completed"
448
+ });
449
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
450
+ const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
451
+ if (!architectArtifact) {
452
+ throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
453
+ }
454
+ if (!liveArchitectEvents.hasEmitted()) {
455
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
456
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, architectArtifact);
457
+ }
458
+ await context.emit({
459
+ role: "assistant",
460
+ kind: "message",
461
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI produced an Architect plan for ${worktree.branchName}.`,
462
+ eventType: "architect_complete"
463
+ });
464
+ const specPath = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id, "spec.md");
465
+ const specBody = await fs.readFile(specPath, "utf8").catch(() => `# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`);
466
+ return {
467
+ summary: `${dispatch.execution.provider} CLI Architect plan produced.`,
468
+ spec: {
469
+ repoPath: worktree.worktreePath,
470
+ path: specPath,
471
+ body: specBody,
472
+ producedBy: `${dispatch.execution.provider}-cli`,
473
+ status: "pending_approval"
474
+ },
475
+ artifact: architectArtifact,
476
+ artifacts: [architectArtifact]
477
+ };
478
+ }
479
+ async runQa(context) {
480
+ const { dispatch, worktree } = context;
481
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
482
+ await fs.mkdir(metadataRoot, { recursive: true });
483
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
484
+ if (!laneCommand) {
485
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
486
+ }
487
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem, "qa");
488
+ const specPath = path.join(metadataRoot, "spec.md");
489
+ await fs.writeFile(specPath, specBody, "utf8");
490
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
491
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
492
+ const command = buildProviderCliCommand(dispatch, {
493
+ worktreePath: worktree.worktreePath,
494
+ prompt: buildQaPrompt(dispatch, specBody),
495
+ completionTools
496
+ });
497
+ const commandText = formatProviderCliCommand(command);
498
+ await context.emit({
499
+ role: "runner",
500
+ kind: "checkpoint",
501
+ content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
502
+ eventType: "provider_cli_started"
503
+ });
504
+ await context.emit({
505
+ role: "runner",
506
+ kind: "checkpoint",
507
+ content: "Forge QA completion tools configured; provider must call all seven QA MCP gates before exit.",
508
+ eventType: "completion_tools_configured"
509
+ });
510
+ const outputState = createProviderOutputState(dispatch.execution.provider);
511
+ const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
512
+ let result;
513
+ try {
514
+ liveQaEvents.start();
515
+ result = await this.processRunner.run({
516
+ command: command.command,
517
+ args: command.args,
518
+ cwd: worktree.worktreePath,
519
+ env: providerProcessEnv(dispatch)
520
+ }, {
521
+ onStdoutLine: async (line) => {
522
+ for (const event of outputState.consume(line)) {
523
+ await context.emit(event);
524
+ }
525
+ }
526
+ }, context.signal);
527
+ }
528
+ finally {
529
+ await liveQaEvents.stop();
530
+ await cleanupCompletionTools(completionTools, context.emit);
531
+ }
532
+ if (result.exitCode !== 0) {
533
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
534
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
535
+ }
536
+ await context.emit({
180
537
  role: "runner",
181
538
  kind: "checkpoint",
182
539
  content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
183
540
  eventType: "provider_cli_completed"
184
541
  });
185
- await emitProviderUsageEvent(emit, dispatch, outputState);
542
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
543
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
544
+ if (!qaArtifact) {
545
+ const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
546
+ throw new Error(verdictOnly
547
+ ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
548
+ : "Provider CLI QA completed but did not call the Forge QA completion tool.");
549
+ }
550
+ enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
551
+ if (!liveQaEvents.hasEmitted()) {
552
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
553
+ await emitQaStructuredEvents(context.emit, qaArtifact);
554
+ }
555
+ const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
556
+ const statusSummary = status === "pass"
557
+ ? "passed"
558
+ : status === "blocked"
559
+ ? "blocked"
560
+ : "found rework";
186
561
  return {
187
- summary: `${dispatch.execution.provider} CLI QA passed.`
562
+ summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
563
+ spec: {
564
+ repoPath: worktree.worktreePath,
565
+ path: specPath,
566
+ body: specBody,
567
+ producedBy: "forge-lane-command",
568
+ status: "approved"
569
+ },
570
+ artifact: qaArtifact,
571
+ artifacts: [qaArtifact]
188
572
  };
189
573
  }
190
574
  async runConflictResolve(context) {
191
575
  const { dispatch, worktree } = context;
576
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
192
577
  const command = buildProviderCliCommand(dispatch, {
193
578
  worktreePath: worktree.worktreePath,
194
- prompt: buildConflictResolvePrompt(dispatch, worktree.branchName)
579
+ prompt: addressComments
580
+ ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
581
+ : buildConflictResolvePrompt(dispatch, worktree.branchName)
195
582
  });
196
583
  await context.emit({
197
584
  role: "runner",
198
585
  kind: "checkpoint",
199
- content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
586
+ content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
200
587
  eventType: "provider_cli_started"
201
588
  });
202
589
  const outputState = createProviderOutputState(dispatch.execution.provider);
203
590
  const result = await this.processRunner.run({
204
591
  command: command.command,
205
592
  args: command.args,
206
- cwd: worktree.worktreePath
593
+ cwd: worktree.worktreePath,
594
+ env: providerProcessEnv(dispatch)
207
595
  }, {
208
596
  onStdoutLine: async (line) => {
209
- const event = outputState.consume(line);
210
- if (event) {
597
+ for (const event of outputState.consume(line)) {
211
598
  await context.emit(event);
212
599
  }
213
600
  }
@@ -222,11 +609,15 @@ export class ProcessBackedProviderCliService {
222
609
  await context.emit({
223
610
  role: "assistant",
224
611
  kind: "message",
225
- content: outputState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
226
- eventType: "conflict_resolve_complete"
612
+ content: outputState.finalMessage || (addressComments
613
+ ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
614
+ : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
615
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
227
616
  });
228
617
  return {
229
- summary: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
618
+ summary: addressComments
619
+ ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
620
+ : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
230
621
  };
231
622
  }
232
623
  }
@@ -235,10 +626,22 @@ export class DeterministicProviderCliService {
235
626
  constructor(git = new GitClient()) {
236
627
  this.git = git;
237
628
  }
629
+ async runDraft(context) {
630
+ const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
631
+ await context.emit({
632
+ role: "assistant",
633
+ kind: "message",
634
+ content,
635
+ eventType: "draft_complete"
636
+ });
637
+ await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
638
+ return { summary: "forge-bridge generated deterministic draft." };
639
+ }
238
640
  async runImplementation(context) {
239
641
  const { dispatch, worktree } = context;
240
642
  const phase = completionPhaseFromDispatch(dispatch);
241
643
  const developCycle = usesDevelopCycleCompletion(dispatch);
644
+ const debugCycle = usesDebugCycleCompletion(dispatch);
242
645
  const providerCommand = buildProviderCliCommand(dispatch);
243
646
  const providerCommandText = formatProviderCliCommand(providerCommand);
244
647
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -269,9 +672,11 @@ export class DeterministicProviderCliService {
269
672
  content: `Created bridge changeset at ${changesetPath}`,
270
673
  eventType: "changeset"
271
674
  });
272
- const phases = developCycle
273
- ? ["implementation", "self_review", "validation"]
274
- : [phase];
675
+ const phases = debugCycle
676
+ ? debugCompletionPhaseOrder
677
+ : developCycle
678
+ ? ["implementation", "self_review", "validation"]
679
+ : [phase];
275
680
  const completionArtifacts = [];
276
681
  for (const completionPhase of phases) {
277
682
  await writeCompletionArtifact({
@@ -280,7 +685,9 @@ export class DeterministicProviderCliService {
280
685
  phase: completionPhase,
281
686
  producedBy: "forge-bridge",
282
687
  redactionSecrets: exactRedactionSecrets(dispatch)
283
- }, expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
688
+ }, isDebugCompletionPhaseForProvider(completionPhase)
689
+ ? expectedDebugCompletionToolName(completionPhase)
690
+ : expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
284
691
  const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
285
692
  if (!completionArtifact) {
286
693
  throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
@@ -296,7 +703,7 @@ export class DeterministicProviderCliService {
296
703
  }
297
704
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
298
705
  return {
299
- summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
706
+ summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
300
707
  spec: {
301
708
  repoPath: worktree.worktreePath,
302
709
  path: specPath,
@@ -308,131 +715,899 @@ export class DeterministicProviderCliService {
308
715
  artifacts: completionArtifacts
309
716
  };
310
717
  }
311
- async runQa(dispatch, emit) {
312
- await emit({
313
- role: "worker",
718
+ async runArchitect(context) {
719
+ const { dispatch, worktree } = context;
720
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
721
+ await fs.mkdir(metadataRoot, { recursive: true });
722
+ 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`;
723
+ const specPath = path.join(metadataRoot, "spec.md");
724
+ await fs.writeFile(specPath, specBody, "utf8");
725
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
726
+ await writeCompletionArtifact({
727
+ worktreePath: worktree.worktreePath,
728
+ workItemId: dispatch.workItem.id,
729
+ phase: "architect",
730
+ producedBy: "forge-bridge",
731
+ redactionSecrets: exactRedactionSecrets(dispatch),
732
+ architectCycle: true
733
+ }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
734
+ const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
735
+ if (!artifact) {
736
+ throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
737
+ }
738
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
739
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
740
+ await context.emit({
741
+ role: "assistant",
314
742
  kind: "message",
315
- content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
316
- eventType: "qa_analysis"
743
+ content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
744
+ eventType: "architect_complete"
317
745
  });
318
- await emit({
319
- role: "assistant",
746
+ return {
747
+ summary: "forge-bridge completed Architect plan (deterministic).",
748
+ spec: {
749
+ repoPath: worktree.worktreePath,
750
+ path: specPath,
751
+ body: specBody,
752
+ producedBy: "forge-bridge",
753
+ status: "pending_approval"
754
+ },
755
+ artifact,
756
+ artifacts: [artifact]
757
+ };
758
+ }
759
+ async runQa(context) {
760
+ const { dispatch, worktree } = context;
761
+ await context.emit({
762
+ role: "worker",
320
763
  kind: "message",
321
- content: "All checks passed. forge-bridge QA completed.",
322
- eventType: "qa_complete"
764
+ content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
765
+ eventType: "qa_plan"
323
766
  });
324
- await emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
767
+ const qaBrowser = dispatch.qaBrowser;
768
+ const launchTarget = qaBrowser?.launchTarget ?? null;
769
+ const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
770
+ const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
771
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
772
+ : null;
773
+ const browserChecks = browserSidecar && launchTarget
774
+ ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
775
+ : [];
776
+ const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
777
+ const summary = missingLaunchTarget
778
+ ? "QA blocked because browser testing is required but no app launch target was provided."
779
+ : "All checks passed. forge-bridge QA completed.";
780
+ const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
781
+ for (const gate of qaCompletionGateOrder) {
782
+ await writeCompletionArtifact({
783
+ worktreePath: worktree.worktreePath,
784
+ workItemId: dispatch.workItem.id,
785
+ phase: "qa",
786
+ producedBy: "forge-bridge",
787
+ redactionSecrets: exactRedactionSecrets(dispatch),
788
+ qaCycle: true,
789
+ ownerType: dispatch.cycleRun.ownerType ?? undefined,
790
+ ownerId: dispatch.cycleRun.ownerId ?? undefined
791
+ }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
792
+ gate,
793
+ criterion,
794
+ summary,
795
+ missingLaunchTarget,
796
+ browserChecks,
797
+ sidecars
798
+ }));
799
+ const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
800
+ if (gateArtifact) {
801
+ await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
802
+ }
803
+ }
804
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
805
+ if (!qaArtifact) {
806
+ throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
807
+ }
808
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
809
+ await emitQaStructuredEvents(context.emit, qaArtifact);
810
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
325
811
  return {
326
- summary: "forge-bridge QA passed."
812
+ summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
813
+ artifact: qaArtifact,
814
+ artifacts: [qaArtifact]
327
815
  };
328
816
  }
329
817
  async runConflictResolve(context) {
330
818
  const { dispatch, worktree } = context;
331
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
819
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
820
+ await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
332
821
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
333
822
  await context.emit({
334
823
  role: "assistant",
335
824
  kind: "message",
336
- content: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
337
- eventType: "conflict_resolve_complete"
825
+ content: addressComments
826
+ ? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
827
+ : `Deterministic conflict resolve completed for ${worktree.branchName}.`,
828
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
338
829
  });
339
830
  return {
340
- summary: `forge-bridge resolved conflicts for ${worktree.branchName}.`
831
+ summary: addressComments
832
+ ? `forge-bridge addressed PR comments for ${worktree.branchName}.`
833
+ : `forge-bridge resolved conflicts for ${worktree.branchName}.`
834
+ };
835
+ }
836
+ }
837
+ function phaseCompleteEventType(phase) {
838
+ return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
839
+ }
840
+ function isDebugCompletionPhaseForProvider(phase) {
841
+ return debugCompletionPhaseOrder.includes(phase);
842
+ }
843
+ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
844
+ const changesetHash = sha256(changesetBody);
845
+ const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
846
+ if (phase === "implementation") {
847
+ return {
848
+ status: "pass",
849
+ summary: "forge-bridge produced a deterministic implementation changeset.",
850
+ plan: [{ step: "Create deterministic changeset", status: "done" }],
851
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
852
+ tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
853
+ docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
854
+ acceptance_criteria: [
855
+ {
856
+ criterion,
857
+ evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
858
+ status: "satisfied"
859
+ }
860
+ ],
861
+ known_gaps: [],
862
+ next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
863
+ };
864
+ }
865
+ if (phase === "debug_repro") {
866
+ return {
867
+ status: "pass",
868
+ summary: "forge-bridge reproduced the bug deterministically.",
869
+ repro_steps: ["Run the deterministic fake-worker debug reproduction."],
870
+ observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
871
+ expected: "The bug scenario should be fixed before QA handoff.",
872
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
873
+ };
874
+ }
875
+ if (phase === "debug_root_cause") {
876
+ return {
877
+ status: "pass",
878
+ summary: "forge-bridge isolated a deterministic root cause.",
879
+ root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
880
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
881
+ eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
882
+ risk_area: "forge-bridge deterministic debug lane"
883
+ };
884
+ }
885
+ if (phase === "debug_fix") {
886
+ return {
887
+ status: "pass",
888
+ summary: "forge-bridge applied a deterministic debug fix.",
889
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
890
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
891
+ remaining_risks: [],
892
+ resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
893
+ qa_id: qaId,
894
+ status: "resolved",
895
+ summary: `Resolved deterministic QA finding ${qaId}.`,
896
+ evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
897
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
898
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
899
+ regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
900
+ }))
341
901
  };
342
902
  }
903
+ if (phase === "debug_regression") {
904
+ return {
905
+ status: "pass",
906
+ summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
907
+ commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
908
+ required_regressions: ["Original deterministic repro no longer fails."],
909
+ build_status: "not_applicable",
910
+ test_status: "pass",
911
+ repro_negative: true,
912
+ qa_ready: true
913
+ };
914
+ }
915
+ if (phase === "self_review") {
916
+ return {
917
+ status: "pass",
918
+ summary: "forge-bridge fake worker completed deterministic self-review.",
919
+ reviewed_diff: true,
920
+ findings: [],
921
+ security_review: {
922
+ status: "pass",
923
+ notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
924
+ },
925
+ edge_case_review: {
926
+ status: "pass",
927
+ notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
928
+ },
929
+ design_review: {
930
+ status: "not_applicable",
931
+ screenshots: [],
932
+ notes: "No UI changes."
933
+ },
934
+ deterministic_comparison: {
935
+ status: "pass",
936
+ command_or_tool: "git diff --stat HEAD~1..HEAD",
937
+ notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
938
+ },
939
+ fixes_applied: [],
940
+ remaining_risks: []
941
+ };
942
+ }
943
+ return {
944
+ status: "pass",
945
+ summary: "forge-bridge fake worker completed deterministic validation.",
946
+ commands: [
947
+ {
948
+ command: "git status --short && git diff --check",
949
+ exit_code: 0,
950
+ status: "pass",
951
+ summary: "Deterministic validation command completed for the fake-worker changeset."
952
+ }
953
+ ],
954
+ acceptance_criteria: [
955
+ {
956
+ criterion,
957
+ evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
958
+ status: "satisfied"
959
+ }
960
+ ],
961
+ build_status: "pass",
962
+ test_status: "pass",
963
+ lint_status: "not_applicable",
964
+ design_status: "not_applicable",
965
+ drift_checks: [
966
+ {
967
+ command_or_tool: "git diff --check",
968
+ status: "pass",
969
+ summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
970
+ }
971
+ ],
972
+ ready_for_dev_test: true
973
+ };
974
+ }
975
+ function deterministicArchitectPayload(dispatch) {
976
+ const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
977
+ return {
978
+ status: "pass",
979
+ summary: "forge-bridge produced a deterministic Architect plan.",
980
+ implementation_plan: {
981
+ schema_version: 1,
982
+ plan_id: planId,
983
+ story_id: dispatch.workItem.id,
984
+ phases: [
985
+ { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
986
+ ],
987
+ tasks: [
988
+ {
989
+ id: "task-1",
990
+ title: `Implement ${dispatch.workItem.title}`,
991
+ phase: "phase-1",
992
+ summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
993
+ acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
994
+ tests: [
995
+ { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
996
+ ]
997
+ }
998
+ ],
999
+ dependencies: [],
1000
+ phase_gates: [
1001
+ { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
1002
+ ]
1003
+ },
1004
+ qa_plan: {
1005
+ schema_version: 1,
1006
+ plan_id: planId,
1007
+ final_qa: [
1008
+ { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
1009
+ ]
1010
+ },
1011
+ 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`
1012
+ };
1013
+ }
1014
+ function deterministicQaGatePayload(options) {
1015
+ const blocked = options.missingLaunchTarget;
1016
+ const skippedBecauseBlocked = blocked
1017
+ ? {
1018
+ status: "skipped",
1019
+ summary: "Skipped because browser QA was blocked by missing launch target.",
1020
+ reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
1021
+ }
1022
+ : null;
1023
+ switch (options.gate) {
1024
+ case "qa_plan":
1025
+ return {
1026
+ status: "pass",
1027
+ summary: "Deterministic QA plan recorded.",
1028
+ checklist: [
1029
+ "Review the validated work item against acceptance criteria.",
1030
+ "Run deterministic regression evidence.",
1031
+ "Confirm no in-scope QA findings remain."
1032
+ ],
1033
+ acceptance_criteria: [options.criterion]
1034
+ };
1035
+ case "qa_regression":
1036
+ return {
1037
+ status: "pass",
1038
+ summary: "Deterministic regression QA completed.",
1039
+ commands: [
1040
+ {
1041
+ command: "forge-bridge deterministic QA",
1042
+ exit_code: 0,
1043
+ status: "pass",
1044
+ summary: "Deterministic regression evidence completed."
1045
+ }
1046
+ ],
1047
+ notes: "Regression gate passed in deterministic fake-worker mode."
1048
+ };
1049
+ case "qa_api":
1050
+ return {
1051
+ status: "skipped",
1052
+ summary: "No API/backend surface was identified for deterministic QA.",
1053
+ reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
1054
+ };
1055
+ case "qa_manual_web":
1056
+ return blocked
1057
+ ? {
1058
+ status: "blocked",
1059
+ summary: "Browser QA could not run because no app launch target was provided.",
1060
+ blocker_reason: "missing_app_launch_target"
1061
+ }
1062
+ : options.browserChecks.length > 0
1063
+ ? {
1064
+ status: "pass",
1065
+ summary: "Deterministic browser QA exercised the configured launch target.",
1066
+ browser_checks: options.browserChecks,
1067
+ sidecars: options.sidecars,
1068
+ notes: "Browser sidecar evidence recorded."
1069
+ }
1070
+ : {
1071
+ status: "skipped",
1072
+ summary: "Manual web QA was not required for this deterministic run.",
1073
+ reason: "Forge did not require browser QA and no launch target was necessary."
1074
+ };
1075
+ case "qa_bug_repro":
1076
+ return skippedBecauseBlocked ?? {
1077
+ status: "skipped",
1078
+ summary: "No failed QA observation required bug reproduction.",
1079
+ reason: "No defects or candidate bugs were observed."
1080
+ };
1081
+ case "qa_findings":
1082
+ return skippedBecauseBlocked ?? {
1083
+ status: "pass",
1084
+ summary: "No QA findings or candidate bugs were identified.",
1085
+ findings: [],
1086
+ candidate_bugs: []
1087
+ };
1088
+ case "qa_verdict":
1089
+ return {
1090
+ status: blocked ? "blocked" : "pass",
1091
+ summary: options.summary,
1092
+ checklist: [
1093
+ "Review the validated work item against acceptance criteria.",
1094
+ "Run deterministic regression evidence.",
1095
+ blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
1096
+ ],
1097
+ tested_acceptance_criteria: blocked ? [] : [options.criterion],
1098
+ commands: blocked
1099
+ ? []
1100
+ : [
1101
+ {
1102
+ command: "forge-bridge deterministic QA",
1103
+ exit_code: 0,
1104
+ status: "pass",
1105
+ summary: "Deterministic QA command completed."
1106
+ }
1107
+ ],
1108
+ browser_checks: blocked ? [] : options.browserChecks,
1109
+ sidecars: blocked ? [] : options.sidecars,
1110
+ notes: options.summary,
1111
+ findings: [],
1112
+ candidate_bugs: [],
1113
+ blocker_reason: blocked ? "missing_app_launch_target" : null,
1114
+ report_markdown: `# QA report\n\n${options.summary}\n`
1115
+ };
1116
+ }
1117
+ }
1118
+ const qaArtifactFileNames = {
1119
+ plan: "qa.plan.json",
1120
+ evidence: "qa.evidence.json",
1121
+ findings: "qa.findings.json",
1122
+ verdict: "qa.verdict.json",
1123
+ report: "qa.report.md"
1124
+ };
1125
+ const qaGateArtifactFileNames = {
1126
+ qa_plan: "qa.plan.json",
1127
+ qa_regression: "qa.regression.json",
1128
+ qa_api: "qa.api.json",
1129
+ qa_manual_web: "qa.manual-web.json",
1130
+ qa_bug_repro: "qa.bug-repro.json",
1131
+ qa_findings: "qa.findings.json",
1132
+ qa_verdict: "qa.verdict.json"
1133
+ };
1134
+ function hasLaunchTarget(target) {
1135
+ return Boolean(target?.url?.trim()
1136
+ || target?.ready_url?.trim()
1137
+ || target?.command?.trim()
1138
+ || (target?.routes ?? []).some((route) => route.trim().length > 0));
1139
+ }
1140
+ function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
1141
+ const route = primaryLaunchRoute(target);
1142
+ return {
1143
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
1144
+ content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
1145
+ };
1146
+ }
1147
+ function deterministicBrowserCheck(target, screenshotPath) {
1148
+ const route = primaryLaunchRoute(target);
1149
+ return {
1150
+ route,
1151
+ url: route,
1152
+ status: "pass",
1153
+ summary: "Deterministic browser QA exercised the configured launch target.",
1154
+ actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
1155
+ screenshots: [screenshotPath],
1156
+ console_errors: [],
1157
+ network_errors: [],
1158
+ responsive_checks: ["desktop", "mobile"]
1159
+ };
1160
+ }
1161
+ function primaryLaunchRoute(target) {
1162
+ return target.ready_url?.trim()
1163
+ || target.url?.trim()
1164
+ || target.routes.find((route) => route.trim().length > 0)?.trim()
1165
+ || "app launch command";
1166
+ }
1167
+ async function writeQaSidecarFiles(worktreePath, files) {
1168
+ const sidecars = [];
1169
+ for (const file of files) {
1170
+ const fullPath = path.resolve(worktreePath, file.relativePath);
1171
+ const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
1172
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
1173
+ throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
1174
+ }
1175
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
1176
+ await fs.writeFile(fullPath, file.content, "utf8");
1177
+ sidecars.push({
1178
+ path: relativePath,
1179
+ content_hash: sha256(file.content),
1180
+ bytes: Buffer.byteLength(file.content, "utf8")
1181
+ });
1182
+ }
1183
+ return sidecars;
1184
+ }
1185
+ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
1186
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1187
+ await emit({
1188
+ role: "tool",
1189
+ kind: "tool_result",
1190
+ content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
1191
+ eventType: "qa_artifact_recorded"
1192
+ });
1193
+ await emit({
1194
+ role: "hook",
1195
+ kind: "checkpoint",
1196
+ content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
1197
+ eventType: "phase_gate"
1198
+ });
1199
+ }
1200
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1201
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1202
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
1203
+ return null;
1204
+ }
1205
+ const artifactRoot = ownerType && ownerId
1206
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1207
+ : artifactRootFor(worktreePath, workItemId);
1208
+ const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1209
+ const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1210
+ const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1211
+ await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1212
+ return {
1213
+ ...artifact,
1214
+ planJson,
1215
+ evidenceJson,
1216
+ findingsJson
1217
+ };
1218
+ }
1219
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1220
+ const artifactRoot = ownerType && ownerId
1221
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1222
+ : artifactRootFor(worktreePath, workItemId);
1223
+ for (const fileName of Object.values(qaArtifactFileNames)) {
1224
+ try {
1225
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1226
+ if (!stat.isFile()) {
1227
+ return false;
1228
+ }
1229
+ }
1230
+ catch (error) {
1231
+ if (isNodeError(error) && error.code === "ENOENT") {
1232
+ return false;
1233
+ }
1234
+ throw error;
1235
+ }
1236
+ }
1237
+ return true;
1238
+ }
1239
+ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
1240
+ const qaBrowser = dispatch.qaBrowser;
1241
+ if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
1242
+ return;
1243
+ }
1244
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1245
+ const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
1246
+ const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
1247
+ if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
1248
+ 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.");
1249
+ }
1250
+ }
1251
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1252
+ const artifactRoot = ownerType && ownerId
1253
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1254
+ : artifactRootFor(worktreePath, workItemId);
1255
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1256
+ const sidecars = arrayField(evidence, "sidecars");
1257
+ if (sidecars.length === 0) {
1258
+ return;
1259
+ }
1260
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
1261
+ for (const [index, sidecar] of sidecars.entries()) {
1262
+ const sidecarPath = stringField(sidecar, "path");
1263
+ const expectedHash = stringField(sidecar, "content_hash");
1264
+ const expectedBytes = sidecar.bytes;
1265
+ if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
1266
+ throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
1267
+ }
1268
+ if (path.isAbsolute(sidecarPath)) {
1269
+ throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
1270
+ }
1271
+ const fullPath = path.resolve(worktreePath, sidecarPath);
1272
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
1273
+ const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1274
+ const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1275
+ throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
1276
+ }
1277
+ const stat = await fs.lstat(fullPath).catch((error) => {
1278
+ if (isNodeError(error) && error.code === "ENOENT") {
1279
+ throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
1280
+ }
1281
+ throw error;
1282
+ });
1283
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1284
+ throw new Error(`QA sidecar ${index} must reference a regular file.`);
1285
+ }
1286
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
1287
+ if (stat.size !== expectedBytes) {
1288
+ throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
1289
+ }
1290
+ const actualHash = await sha256File(fullPath);
1291
+ if (actualHash !== expectedHash.trim().toLowerCase()) {
1292
+ throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
1293
+ }
1294
+ }
1295
+ }
1296
+ async function emitQaStructuredEvents(emit, artifact) {
1297
+ const artifactRoot = path.dirname(artifact.path);
1298
+ const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
1299
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1300
+ const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
1301
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1302
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1303
+ const checklist = stringArrayField(plan, "checklist");
1304
+ await emit({
1305
+ role: "worker",
1306
+ kind: "message",
1307
+ content: checklist.length > 0
1308
+ ? `QA plan: ${checklist.join("; ")}`
1309
+ : "QA plan recorded.",
1310
+ eventType: "qa_plan"
1311
+ });
1312
+ for (const browserCheck of arrayField(evidence, "browser_checks")) {
1313
+ await emit({
1314
+ role: "worker",
1315
+ kind: "checkpoint",
1316
+ content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
1317
+ eventType: "qa_browser_check"
1318
+ });
1319
+ }
1320
+ for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
1321
+ await emit({
1322
+ role: "worker",
1323
+ kind: "checkpoint",
1324
+ content: `QA finding: ${summarizeQaObject(finding)}`,
1325
+ eventType: "qa_finding"
1326
+ });
1327
+ }
1328
+ await emit({
1329
+ role: "assistant",
1330
+ kind: "message",
1331
+ content: status === "blocked"
1332
+ ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
1333
+ : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
1334
+ eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
1335
+ });
1336
+ }
1337
+ function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1338
+ return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1339
+ ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1340
+ : artifactRootFor(worktreePath, workItemId);
1341
+ }
1342
+ async function readQaGateArtifact(artifactRoot, gate) {
1343
+ const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1344
+ try {
1345
+ const stat = await fs.stat(artifactPath);
1346
+ if (!stat.isFile()) {
1347
+ return null;
1348
+ }
1349
+ }
1350
+ catch (error) {
1351
+ if (isNodeError(error) && error.code === "ENOENT") {
1352
+ return null;
1353
+ }
1354
+ throw error;
1355
+ }
1356
+ const payload = await readJsonObjectFile(artifactPath);
1357
+ return {
1358
+ gate,
1359
+ path: artifactPath,
1360
+ status: stringField(payload, "status") ?? "unknown",
1361
+ producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1362
+ contentHash: stringField(payload, "content_hash") ?? undefined
1363
+ };
1364
+ }
1365
+ function nextQaGate(gate) {
1366
+ const index = qaCompletionGateOrder.indexOf(gate);
1367
+ return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1368
+ }
1369
+ async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1370
+ const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1371
+ await emit({
1372
+ role: "hook",
1373
+ kind: artifact.status === "blocked" ? "error" : "checkpoint",
1374
+ content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1375
+ eventType: "phase_gate",
1376
+ data: JSON.stringify({
1377
+ phase: "qa",
1378
+ qa_gate: artifact.gate,
1379
+ status: artifact.status,
1380
+ artifact_relative_paths: [relativePath],
1381
+ content_hash: artifact.contentHash ?? null,
1382
+ produced_by: artifact.producedBy ?? null
1383
+ })
1384
+ });
1385
+ if (!nextGate) {
1386
+ return;
1387
+ }
1388
+ await emit({
1389
+ role: "hook",
1390
+ kind: "checkpoint",
1391
+ content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1392
+ eventType: "phase_gate",
1393
+ data: JSON.stringify({
1394
+ phase: "qa",
1395
+ from_gate: artifact.gate,
1396
+ to_gate: nextGate
1397
+ })
1398
+ });
1399
+ }
1400
+ class LiveQaArtifactEmitter {
1401
+ worktreePath;
1402
+ workItemId;
1403
+ dispatch;
1404
+ emit;
1405
+ emittedBundle = false;
1406
+ emittedGates = new Set();
1407
+ timer = null;
1408
+ pending = Promise.resolve();
1409
+ constructor(worktreePath, workItemId, dispatch, emit) {
1410
+ this.worktreePath = worktreePath;
1411
+ this.workItemId = workItemId;
1412
+ this.dispatch = dispatch;
1413
+ this.emit = emit;
1414
+ }
1415
+ start() {
1416
+ void this.pollQueued();
1417
+ this.timer = setInterval(() => {
1418
+ void this.pollQueued();
1419
+ }, 250);
1420
+ }
1421
+ async stop() {
1422
+ if (this.timer) {
1423
+ clearInterval(this.timer);
1424
+ this.timer = null;
1425
+ }
1426
+ await this.pollQueued();
1427
+ }
1428
+ hasEmitted() {
1429
+ return this.emittedBundle;
1430
+ }
1431
+ pollQueued() {
1432
+ this.pending = this.pending
1433
+ .then(() => this.poll())
1434
+ .catch(() => undefined);
1435
+ return this.pending;
1436
+ }
1437
+ async poll() {
1438
+ await this.emitAvailableGateEvents();
1439
+ if (this.emittedBundle) {
1440
+ return;
1441
+ }
1442
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
1443
+ if (!artifact) {
1444
+ return;
1445
+ }
1446
+ enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
1447
+ this.emittedBundle = true;
1448
+ await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
1449
+ await emitQaStructuredEvents(this.emit, artifact);
1450
+ }
1451
+ async emitAvailableGateEvents() {
1452
+ const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1453
+ for (const gate of qaCompletionGateOrder) {
1454
+ if (this.emittedGates.has(gate)) {
1455
+ continue;
1456
+ }
1457
+ const artifact = await readQaGateArtifact(artifactRoot, gate);
1458
+ if (!artifact) {
1459
+ return;
1460
+ }
1461
+ this.emittedGates.add(gate);
1462
+ await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
1463
+ }
1464
+ }
1465
+ }
1466
+ class LiveArchitectArtifactEmitter {
1467
+ worktreePath;
1468
+ workItemId;
1469
+ emit;
1470
+ emitted = false;
1471
+ timer = null;
1472
+ pending = Promise.resolve();
1473
+ constructor(worktreePath, workItemId, emit) {
1474
+ this.worktreePath = worktreePath;
1475
+ this.workItemId = workItemId;
1476
+ this.emit = emit;
1477
+ }
1478
+ start() {
1479
+ void this.pollQueued();
1480
+ this.timer = setInterval(() => {
1481
+ void this.pollQueued();
1482
+ }, 250);
1483
+ }
1484
+ async stop() {
1485
+ if (this.timer) {
1486
+ clearInterval(this.timer);
1487
+ this.timer = null;
1488
+ }
1489
+ await this.pollQueued();
1490
+ }
1491
+ hasEmitted() {
1492
+ return this.emitted;
1493
+ }
1494
+ pollQueued() {
1495
+ this.pending = this.pending
1496
+ .then(() => this.poll())
1497
+ .catch(() => undefined);
1498
+ return this.pending;
1499
+ }
1500
+ async poll() {
1501
+ if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
1502
+ return;
1503
+ }
1504
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
1505
+ if (!artifact) {
1506
+ return;
1507
+ }
1508
+ this.emitted = true;
1509
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1510
+ await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1511
+ }
343
1512
  }
344
- function phaseCompleteEventType(phase) {
345
- return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
1513
+ async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1514
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1515
+ for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1516
+ try {
1517
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1518
+ if (!stat.isFile()) {
1519
+ return false;
1520
+ }
1521
+ }
1522
+ catch (error) {
1523
+ if (isNodeError(error) && error.code === "ENOENT") {
1524
+ return false;
1525
+ }
1526
+ throw error;
1527
+ }
1528
+ }
1529
+ return true;
346
1530
  }
347
- function deterministicCompletionPayload(phase, dispatch, changesetBody) {
348
- const changesetHash = sha256(changesetBody);
349
- const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
350
- if (phase === "implementation") {
351
- return {
352
- status: "pass",
353
- summary: "forge-bridge produced a deterministic implementation changeset.",
354
- plan: [{ step: "Create deterministic changeset", status: "done" }],
355
- changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
356
- tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
357
- docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
358
- acceptance_criteria: [
359
- {
360
- criterion,
361
- evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
362
- status: "satisfied"
363
- }
364
- ],
365
- known_gaps: [],
366
- next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
367
- };
1531
+ async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1532
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1533
+ const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1534
+ const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1535
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1536
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1537
+ const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1538
+ await emit({
1539
+ role: "worker",
1540
+ kind: "checkpoint",
1541
+ content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1542
+ eventType: "architect_plan"
1543
+ });
1544
+ await emit({
1545
+ role: "worker",
1546
+ kind: "checkpoint",
1547
+ content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1548
+ eventType: "architect_qa_seed"
1549
+ });
1550
+ await emit({
1551
+ role: "hook",
1552
+ kind: status === "pass" ? "checkpoint" : "error",
1553
+ content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1554
+ eventType: "architect_mcp_complete"
1555
+ });
1556
+ }
1557
+ async function readJsonObjectFile(filePath) {
1558
+ const content = await fs.readFile(filePath, "utf8").catch(() => "");
1559
+ return parseJsonLine(content) ?? {};
1560
+ }
1561
+ function arrayField(source, key) {
1562
+ const value = source[key];
1563
+ if (!Array.isArray(value)) {
1564
+ return [];
368
1565
  }
369
- if (phase === "self_review") {
370
- return {
371
- status: "pass",
372
- summary: "forge-bridge fake worker completed deterministic self-review.",
373
- reviewed_diff: true,
374
- findings: [],
375
- security_review: {
376
- status: "pass",
377
- notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
378
- },
379
- edge_case_review: {
380
- status: "pass",
381
- notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
382
- },
383
- design_review: {
384
- status: "not_applicable",
385
- screenshots: [],
386
- notes: "No UI changes."
387
- },
388
- deterministic_comparison: {
389
- status: "pass",
390
- command_or_tool: "git diff --stat HEAD~1..HEAD",
391
- notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
392
- },
393
- fixes_applied: [],
394
- remaining_risks: []
395
- };
1566
+ return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
1567
+ }
1568
+ function stringArrayField(source, key) {
1569
+ const value = source[key];
1570
+ if (!Array.isArray(value)) {
1571
+ return [];
396
1572
  }
397
- return {
398
- status: "pass",
399
- summary: "forge-bridge fake worker completed deterministic validation.",
400
- commands: [
401
- {
402
- command: "git status --short && git diff --check",
403
- exit_code: 0,
404
- status: "pass",
405
- summary: "Deterministic validation command completed for the fake-worker changeset."
406
- }
407
- ],
408
- acceptance_criteria: [
409
- {
410
- criterion,
411
- evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
412
- status: "satisfied"
413
- }
414
- ],
415
- build_status: "pass",
416
- test_status: "pass",
417
- lint_status: "not_applicable",
418
- design_status: "not_applicable",
419
- drift_checks: [
420
- {
421
- command_or_tool: "git diff --check",
422
- status: "pass",
423
- summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
424
- }
425
- ],
426
- ready_for_dev_test: true
427
- };
1573
+ return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
1574
+ }
1575
+ function summarizeQaObject(source) {
1576
+ return clip(stringField(source, "title")
1577
+ ?? stringField(source, "summary")
1578
+ ?? stringField(source, "id")
1579
+ ?? JSON.stringify(source), 500);
1580
+ }
1581
+ function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1582
+ if (ownerType && ownerId) {
1583
+ const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1584
+ return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1585
+ }
1586
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
428
1587
  }
429
1588
  async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
430
1589
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1590
+ await emit({
1591
+ role: "tool",
1592
+ kind: "checkpoint",
1593
+ content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1594
+ eventType: "completion_tool_validation_passed",
1595
+ data: JSON.stringify({
1596
+ phase: artifact.phase ?? "unknown",
1597
+ status: artifact.status,
1598
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1599
+ })
1600
+ });
431
1601
  await emit({
432
1602
  role: "tool",
433
1603
  kind: "tool_result",
434
1604
  content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
435
- eventType: "completion_tool_artifact_recorded"
1605
+ eventType: "completion_tool_artifact_recorded",
1606
+ data: JSON.stringify({
1607
+ phase: artifact.phase ?? "unknown",
1608
+ status: artifact.status,
1609
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1610
+ })
436
1611
  });
437
1612
  }
438
1613
  async function emitPhaseCompletionEvent(emit, artifact) {
@@ -460,7 +1635,15 @@ async function emitPhaseGateEvents(emit, artifact) {
460
1635
  ? "phase_progression: implementation -> self_review"
461
1636
  : phase === "self_review"
462
1637
  ? "phase_progression: self_review -> validation"
463
- : "phase_progression: validation -> Dev Test ready";
1638
+ : phase === "debug_repro"
1639
+ ? "phase_progression: debug_repro -> debug_root_cause"
1640
+ : phase === "debug_root_cause"
1641
+ ? "phase_progression: debug_root_cause -> debug_fix"
1642
+ : phase === "debug_fix"
1643
+ ? "phase_progression: debug_fix -> debug_regression"
1644
+ : phase === "debug_regression"
1645
+ ? "phase_progression: debug_regression -> QA ready"
1646
+ : "phase_progression: validation -> QA ready";
464
1647
  await emit({
465
1648
  role: "hook",
466
1649
  kind: "checkpoint",
@@ -470,7 +1653,8 @@ async function emitPhaseGateEvents(emit, artifact) {
470
1653
  }
471
1654
  function completionPhaseFromArtifact(artifact) {
472
1655
  const phase = artifact.phase?.trim();
473
- return phase === "self_review" || phase === "validation" || phase === "implementation"
1656
+ return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1657
+ || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
474
1658
  ? phase
475
1659
  : "implementation";
476
1660
  }
@@ -482,13 +1666,18 @@ class LiveCompletionArtifactEmitter {
482
1666
  emitted = new Set();
483
1667
  timer = null;
484
1668
  pending = Promise.resolve();
485
- constructor(worktreePath, workItemId, phase, developCycle, emit) {
1669
+ constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
486
1670
  this.worktreePath = worktreePath;
487
1671
  this.workItemId = workItemId;
488
1672
  this.emit = emit;
489
- this.phases = developCycle
490
- ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
491
- : [phase];
1673
+ if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
1674
+ this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
1675
+ }
1676
+ else {
1677
+ this.phases = developCycle
1678
+ ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1679
+ : [phase];
1680
+ }
492
1681
  }
493
1682
  start() {
494
1683
  void this.pollQueued();
@@ -531,20 +1720,23 @@ class LiveCompletionArtifactEmitter {
531
1720
  }
532
1721
  }
533
1722
  }
534
- async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle) {
535
- if (!developCycle) {
1723
+ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
1724
+ if (!developCycle && !debugCycle) {
536
1725
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
537
1726
  if (!artifact) {
538
1727
  throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
539
1728
  }
540
1729
  return [artifact];
541
1730
  }
1731
+ const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
1732
+ ? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
1733
+ : ["implementation", "self_review", "validation"];
542
1734
  const artifacts = [];
543
- for (const expectedPhase of ["implementation", "self_review", "validation"]) {
1735
+ for (const expectedPhase of expectedPhases) {
544
1736
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
545
1737
  if (!artifact) {
546
1738
  if (artifacts.length === 0) {
547
- throw new Error("Provider CLI completed but did not call the Forge implementation completion tool.");
1739
+ throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
548
1740
  }
549
1741
  const previous = artifacts[artifacts.length - 1];
550
1742
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
@@ -559,10 +1751,24 @@ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, de
559
1751
  }
560
1752
  return artifacts;
561
1753
  }
562
- function providerRedactionEnv(dispatch) {
563
- const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
1754
+ function providerProcessEnv(dispatch) {
1755
+ const env = {
1756
+ ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1757
+ ...providerCredentialEnv(dispatch)
1758
+ };
564
1759
  return Object.keys(env).length > 0 ? env : undefined;
565
1760
  }
1761
+ function providerCredentialEnv(dispatch) {
1762
+ const secret = dispatch.apiKeySecretGrant?.secret;
1763
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1764
+ return {};
1765
+ }
1766
+ const provider = dispatch.execution.provider.trim().toLowerCase();
1767
+ if (provider === "codex" || provider === "openai") {
1768
+ return { OPENAI_API_KEY: secret };
1769
+ }
1770
+ return {};
1771
+ }
566
1772
  function exactRedactionSecrets(dispatch) {
567
1773
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
568
1774
  }
@@ -585,7 +1791,7 @@ export class StreamingProviderProcessRunner {
585
1791
  return await new Promise((resolve, reject) => {
586
1792
  const child = spawn(launch.command, launch.args, {
587
1793
  cwd: request.cwd,
588
- env: request.env ? { ...process.env, ...request.env } : undefined,
1794
+ env: buildProviderChildEnvironment(request.env),
589
1795
  stdio: ["ignore", "pipe", "pipe"],
590
1796
  windowsHide: true
591
1797
  });
@@ -720,9 +1926,6 @@ function quoteWindowsCommandLineArg(value) {
720
1926
  }
721
1927
  return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
722
1928
  }
723
- async function fileExists(inputPath) {
724
- return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
725
- }
726
1929
  async function readProcessLines(stream, onLine) {
727
1930
  const reader = readline.createInterface({ input: stream });
728
1931
  try {
@@ -740,12 +1943,146 @@ function isFakeWorkerModel(model) {
740
1943
  function sha256(content) {
741
1944
  return crypto.createHash("sha256").update(content).digest("hex");
742
1945
  }
1946
+ function buildDraftSpec(dispatch) {
1947
+ return `# Draft Generation Context
1948
+
1949
+ Project: ${dispatch.draft?.projectName ?? dispatch.repo.name}
1950
+ Repository: ${dispatch.draft?.repoName ?? dispatch.repo.name}
1951
+ Draft kind: ${dispatch.draft?.kind ?? "draft"}
1952
+
1953
+ ## User Prompt
1954
+
1955
+ ${dispatch.draft?.userPrompt ?? ""}
1956
+ `;
1957
+ }
1958
+ async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
1959
+ const draftArtifactFiles = {
1960
+ draft_intent: "draft.intent.json",
1961
+ draft_repo_context: "draft.repo-context.json",
1962
+ draft_graph_context: "draft.graph-context.json",
1963
+ draft_product_scope: "draft.product-scope.json",
1964
+ draft_work_order_plan: "draft.work-order-plan.json",
1965
+ draft_critic: "draft.critic.json",
1966
+ draft_proposal: "draft.proposal.json"
1967
+ };
1968
+ for (const gate of draftCompletionGateOrder) {
1969
+ const actualPath = path.join(worktreePath, ".forge", "work-items", workItemId, "artifacts", draftArtifactFiles[gate]);
1970
+ if (!await fileExists(actualPath)) {
1971
+ continue;
1972
+ }
1973
+ const relativePath = path.relative(worktreePath, actualPath).split(path.sep).join("/");
1974
+ await emit({
1975
+ role: "tool",
1976
+ kind: "tool_result",
1977
+ content: `Forge Draft completion tool recorded ${gate} artifact ${relativePath}.`,
1978
+ eventType: "completion_tool_artifact_recorded",
1979
+ data: JSON.stringify({ phase: "draft", draft_gate: gate, artifact_relative_paths: [relativePath] })
1980
+ });
1981
+ await emit({
1982
+ role: "hook",
1983
+ kind: "checkpoint",
1984
+ content: `phase_gate: ${gate} artifact accepted with status pass.`,
1985
+ eventType: "phase_gate"
1986
+ });
1987
+ const next = draftCompletionGateOrder[draftCompletionGateOrder.indexOf(gate) + 1];
1988
+ if (next) {
1989
+ await emit({
1990
+ role: "hook",
1991
+ kind: "checkpoint",
1992
+ content: `phase_progression: ${gate} -> ${next}`,
1993
+ eventType: "phase_gate"
1994
+ });
1995
+ }
1996
+ }
1997
+ }
1998
+ async function fileExists(filePath) {
1999
+ try {
2000
+ await fs.access(filePath);
2001
+ return true;
2002
+ }
2003
+ catch {
2004
+ return false;
2005
+ }
2006
+ }
2007
+ function buildDraftPrompt(dispatch) {
2008
+ const draft = dispatch.draft;
2009
+ if (!draft) {
2010
+ throw new Error("Draft prompt is missing.");
2011
+ }
2012
+ const draftArtifacts = dispatch.artifacts
2013
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
2014
+ .map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
2015
+ .join("\n\n");
2016
+ const artifactSection = draftArtifacts
2017
+ ? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
2018
+ : "";
2019
+ const projectSection = [
2020
+ draft.projectName ? `Project: ${draft.projectName}` : null,
2021
+ draft.repoName ? `Repository: ${draft.repoName}` : null
2022
+ ].filter(Boolean).join("\n");
2023
+ const scopedProjectSection = projectSection ? `\n\n# Selected project context\n\n${projectSection}` : "";
2024
+ return `${draft.systemPrompt}${scopedProjectSection}${artifactSection}
2025
+
2026
+ Draft kind: ${draft.kind}
2027
+
2028
+ ${draft.userPrompt}
2029
+
2030
+ ${completionPromptForDraftCycle("draft_intent")}
2031
+
2032
+ 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.
2033
+
2034
+ Do not modify source files.`;
2035
+ }
2036
+ function extractJsonObject(content) {
2037
+ let trimmed = content.trim();
2038
+ if (trimmed.startsWith("```")) {
2039
+ const firstNewline = trimmed.indexOf("\n");
2040
+ const lastFence = trimmed.lastIndexOf("```");
2041
+ if (firstNewline >= 0 && lastFence > firstNewline) {
2042
+ trimmed = trimmed.slice(firstNewline + 1, lastFence).trim();
2043
+ }
2044
+ }
2045
+ const start = trimmed.indexOf("{");
2046
+ const end = trimmed.lastIndexOf("}");
2047
+ return start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed;
2048
+ }
2049
+ function summarizeStderr(stderr) {
2050
+ const trimmed = stderr.trim();
2051
+ return trimmed ? `: ${clip(trimmed, 1000)}` : "";
2052
+ }
2053
+ function deterministicDraftPayload(dispatch) {
2054
+ const kind = dispatch.draft?.kind ?? "work_item";
2055
+ if (kind === "work_order") {
2056
+ return {
2057
+ title: "Deterministic runner Work Order draft",
2058
+ summary: "Forge Runner generated this deterministic Work Order draft.",
2059
+ objective: "Validate runner-backed Draft generation.",
2060
+ planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
2061
+ decompositionContext: "Use this deterministic fixture only in bridge tests.",
2062
+ assumptions: ["Forge Runner dispatch is available."],
2063
+ warnings: []
2064
+ };
2065
+ }
2066
+ if (kind === "story") {
2067
+ return {
2068
+ title: "Deterministic runner Story draft",
2069
+ description: "Forge Runner generated this deterministic Story draft.",
2070
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
2071
+ points: 3
2072
+ };
2073
+ }
2074
+ return {
2075
+ title: "Deterministic runner Work Item draft",
2076
+ description: "Forge Runner generated this deterministic Work Item draft.",
2077
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
2078
+ reproSteps: "Run Draft with a Forge Runner provider selected.",
2079
+ systemInfo: "forge-bridge deterministic provider",
2080
+ points: 1
2081
+ };
2082
+ }
743
2083
  export function formatProviderCliCommand(command) {
744
2084
  return [command.command, ...command.args].map(singleLine).join(" ");
745
2085
  }
746
- function yamlQuotedScalar(value) {
747
- return JSON.stringify(singleLine(value));
748
- }
749
2086
  function singleLine(value) {
750
2087
  return value.replace(/\s+/g, " ").trim();
751
2088
  }
@@ -754,16 +2091,19 @@ export function buildProviderCliCommand(dispatch, run) {
754
2091
  const normalizedProvider = provider.toLowerCase();
755
2092
  const model = dispatch.execution.model.trim();
756
2093
  if (normalizedProvider === "codex") {
757
- const args = ["exec"];
2094
+ const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
758
2095
  if (run?.completionTools) {
759
2096
  args.push(...codexMcpConfigArgs(run.completionTools));
760
2097
  }
761
2098
  args.push("--model", model);
762
2099
  if (run) {
763
- args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
2100
+ args.push("--json");
764
2101
  if (run.worktreePath) {
765
2102
  args.push("--cd", run.worktreePath);
766
2103
  }
2104
+ if (run.skipGitRepoCheck) {
2105
+ args.push("--skip-git-repo-check");
2106
+ }
767
2107
  args.push(run.prompt ?? "");
768
2108
  }
769
2109
  return { command: "codex", args };
@@ -784,11 +2124,41 @@ export function buildProviderCliCommand(dispatch, run) {
784
2124
  }
785
2125
  return { command: provider, args };
786
2126
  }
2127
+ export function codexSandboxModeForPlatform(platform = process.platform) {
2128
+ return platform === "win32" ? "danger-full-access" : "workspace-write";
2129
+ }
2130
+ function buildArchitectPrompt(dispatch) {
2131
+ return `You are Forge's Architect lane running locally in a prepared git worktree.
2132
+
2133
+ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
2134
+
2135
+ Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
2136
+ 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.
2137
+ 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.
2138
+ ${architectRevisionInstruction(dispatch)}
2139
+ Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
2140
+
2141
+ ${completionPromptForPhase("architect")}
2142
+
2143
+ Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
2144
+ }
2145
+ function architectRevisionInstruction(dispatch) {
2146
+ if (!dispatch.architectRevision) {
2147
+ return "";
2148
+ }
2149
+ return `
2150
+ Architect revision context:
2151
+ - Previous plan id: ${dispatch.architectRevision.priorPlanId}
2152
+ - Previous content hash: ${dispatch.architectRevision.priorContentHash}
2153
+ - Reviewer feedback: ${dispatch.architectRevision.feedback}
2154
+ Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
2155
+ }
787
2156
  function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
788
2157
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
789
2158
 
790
2159
  Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
791
2160
  ${phaseWorkInstruction(phase)}
2161
+ ${qaReworkImplementationInstruction(dispatch)}
792
2162
  Use the repository's existing conventions. Run relevant tests when practical.
793
2163
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
794
2164
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -802,6 +2172,7 @@ function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(d
802
2172
 
803
2173
  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.
804
2174
  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.
2175
+ ${qaReworkImplementationInstruction(dispatch)}
805
2176
  Use the repository's existing conventions. Run relevant tests when practical.
806
2177
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
807
2178
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -810,20 +2181,148 @@ ${completionPromptForDevelopCycle(phase)}
810
2181
 
811
2182
  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.`;
812
2183
  }
2184
+ function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2185
+ return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
2186
+
2187
+ 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.
2188
+ 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.
2189
+ ${debugQaReworkInstruction(dispatch)}
2190
+ Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
2191
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
2192
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
2193
+
2194
+ ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
2195
+
2196
+ 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.`;
2197
+ }
2198
+ function qaReworkImplementationInstruction(dispatch) {
2199
+ if (!dispatch.qaRework) {
2200
+ return "";
2201
+ }
2202
+ return `
2203
+ QA rework context:
2204
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2205
+ - Rework packet: ${dispatch.qaRework.packetPath}
2206
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2207
+ 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.
2208
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2209
+ }
2210
+ function debugQaReworkInstruction(dispatch) {
2211
+ if (!dispatch.qaRework) {
2212
+ return "";
2213
+ }
2214
+ return `
2215
+ QA rework context for Debug:
2216
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2217
+ - Rework packet: ${dispatch.qaRework.packetPath}
2218
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2219
+ 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.
2220
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2221
+ }
2222
+ function qaReworkRetestInstruction(dispatch) {
2223
+ if (!dispatch.qaRework) {
2224
+ return "";
2225
+ }
2226
+ return `
2227
+ QA retest context:
2228
+ - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2229
+ - Rework packet: ${dispatch.qaRework.packetPath}
2230
+ - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2231
+ Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
2232
+ }
813
2233
  function phaseWorkInstruction(phase) {
814
2234
  if (phase === "self_review") {
815
2235
  return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
816
2236
  }
817
2237
  if (phase === "validation") {
818
- return "Run the validation commands and deterministic drift checks needed to prove the work is ready for Dev Test.";
2238
+ return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
819
2239
  }
820
2240
  return "Implement the work item and keep the change focused.";
821
2241
  }
822
- function buildQaPrompt(dispatch) {
823
- return `You are Forge's QA lane running locally.
2242
+ function qaBrowserInstruction(dispatch) {
2243
+ const qaBrowser = dispatch.qaBrowser;
2244
+ if (!qaBrowser) {
2245
+ return "Browser/app launch context: not provided by Forge.";
2246
+ }
2247
+ const launchTarget = qaBrowser.launchTarget;
2248
+ if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
2249
+ 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`}`;
2250
+ }
2251
+ if (!launchTarget) {
2252
+ 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`}`;
2253
+ }
2254
+ const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
2255
+ 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`}`;
2256
+ }
2257
+ function storyQaInstruction(dispatch) {
2258
+ const storyQa = dispatch.storyQa;
2259
+ if (!storyQa) {
2260
+ return "";
2261
+ }
2262
+ const childLines = storyQa.childTasks.map((child) => {
2263
+ const dependencies = child.dependencyWorkItemIds.length > 0
2264
+ ? child.dependencyWorkItemIds.join(", ")
2265
+ : "none";
2266
+ const validation = child.validationArtifact
2267
+ ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2268
+ : "missing";
2269
+ const childQa = child.qaArtifact
2270
+ ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2271
+ : "not present";
2272
+ return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2273
+ }).join("\n");
2274
+ const finalQa = storyQa.finalQaChecks.length > 0
2275
+ ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2276
+ : "- No final QA checks were provided in qa.plan.final_qa.";
2277
+ return `Story QA integration context:
2278
+ - Story work item: ${storyQa.storyWorkItemId}
2279
+ - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2280
+ - Story worktree: ${storyQa.worktreeKey}
2281
+ - Branch: ${storyQa.branch}
2282
+ - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2283
+ - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2284
+ Materialized child tasks and evidence:
2285
+ ${childLines || "- No child tasks were provided."}
2286
+ Architect final QA checks:
2287
+ ${finalQa}
2288
+ 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.`;
2289
+ }
2290
+ function buildQaPrompt(dispatch, laneSpec) {
2291
+ return `You are Forge's QA lane running locally in a prepared git worktree.
2292
+
2293
+ 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.
2294
+
2295
+ Injected QA lane command and work item spec:
2296
+ ${laneSpec}
2297
+
2298
+ ---
2299
+
2300
+ Work item: ${dispatch.workItem.id}
2301
+ Title: ${dispatch.workItem.title}
2302
+ Description:
2303
+ ${dispatch.workItem.description || "Not provided."}
2304
+
2305
+ Acceptance criteria:
2306
+ ${dispatch.workItem.acceptanceCriteria || "Not specified."}
2307
+
2308
+ Repro steps / scenario:
2309
+ ${dispatch.workItem.reproSteps || "Not provided."}
824
2310
 
825
- Review the implementation for work item ${dispatch.workItem.id}: ${dispatch.workItem.title}
826
- Run relevant verification when practical and finish with a concise QA verdict.`;
2311
+ System info / environment notes:
2312
+ ${dispatch.workItem.systemInfo || "Not provided."}
2313
+
2314
+ ${storyQaInstruction(dispatch)}
2315
+ Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
2316
+ ${qaBrowserInstruction(dispatch)}
2317
+ ${qaReworkRetestInstruction(dispatch)}
2318
+ QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
2319
+ 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/.
2320
+ Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
2321
+ Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
2322
+
2323
+ ${completionPromptForQaCycle()}
2324
+
2325
+ Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
827
2326
  }
828
2327
  function buildConflictResolvePrompt(dispatch, branchName) {
829
2328
  const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
@@ -838,6 +2337,34 @@ Keep the original work item intent intact:
838
2337
 
839
2338
  Finish with a concise summary of the conflicts resolved and verification performed.`;
840
2339
  }
2340
+ function buildPullRequestCommentsPrompt(dispatch, branchName) {
2341
+ const pr = dispatch.pullRequest;
2342
+ const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
2343
+ const prLocator = pr
2344
+ ? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
2345
+ : "the open pull request for this work item";
2346
+ return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
2347
+
2348
+ The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
2349
+ PR context:
2350
+ - Provider: ${pr?.provider || "not provided"}
2351
+ - Source branch: ${pr?.sourceBranch || branchName}
2352
+ - Target branch: ${targetBranch}
2353
+ - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
2354
+
2355
+ 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.
2356
+ After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
2357
+ If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
2358
+ Keep the original work item intent intact:
2359
+ - Work item: ${dispatch.workItem.id}
2360
+ - Title: ${dispatch.workItem.title}
2361
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
2362
+
2363
+ Finish with a concise summary of comments addressed and verification performed.`;
2364
+ }
2365
+ function isPullRequestCommentsDispatch(dispatch) {
2366
+ return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
2367
+ }
841
2368
  async function cleanupCompletionTools(completionTools, emit) {
842
2369
  try {
843
2370
  await completionTools.cleanup();
@@ -895,31 +2422,31 @@ class CursorStreamJsonState {
895
2422
  consume(line) {
896
2423
  const event = parseJsonLine(line);
897
2424
  if (!event) {
898
- return null;
2425
+ return [];
899
2426
  }
900
2427
  const type = stringField(event, "type");
901
2428
  if (type === "system" && stringField(event, "subtype") === "init") {
902
2429
  this.sessionId = stringField(event, "session_id");
903
2430
  if (this.sessionId && !this.emittedSession) {
904
2431
  this.emittedSession = true;
905
- return {
906
- role: "runner",
907
- kind: "checkpoint",
908
- content: `Cursor session started: ${this.sessionId}.`,
909
- eventType: "provider_thread_started"
910
- };
2432
+ return [{
2433
+ role: "runner",
2434
+ kind: "checkpoint",
2435
+ content: `Cursor session started: ${this.sessionId}.`,
2436
+ eventType: "provider_thread_started"
2437
+ }];
911
2438
  }
912
2439
  }
913
2440
  if (type === "assistant") {
914
2441
  const text = assistantMessageText(event);
915
2442
  if (text) {
916
2443
  this.finalMessage = clip(text, 4000);
917
- return {
918
- role: "assistant",
919
- kind: "message",
920
- content: this.finalMessage,
921
- eventType: "provider_message"
922
- };
2444
+ return [{
2445
+ role: "assistant",
2446
+ kind: "message",
2447
+ content: this.finalMessage,
2448
+ eventType: "provider_message"
2449
+ }];
923
2450
  }
924
2451
  }
925
2452
  if (type === "tool_call") {
@@ -928,23 +2455,23 @@ class CursorStreamJsonState {
928
2455
  if (subtype === "started") {
929
2456
  const summary = formatCursorToolCallStarted(toolCall);
930
2457
  if (summary) {
931
- return {
932
- role: "worker",
933
- kind: "checkpoint",
934
- content: summary,
935
- eventType: "provider_tool_call"
936
- };
2458
+ return [{
2459
+ role: "worker",
2460
+ kind: "checkpoint",
2461
+ content: summary,
2462
+ eventType: "provider_tool_call"
2463
+ }];
937
2464
  }
938
2465
  }
939
2466
  if (subtype === "completed") {
940
2467
  const completed = formatCursorToolCallCompleted(toolCall);
941
2468
  if (completed) {
942
- return {
943
- role: "worker",
944
- kind: completed.kind,
945
- content: completed.content,
946
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
947
- };
2469
+ return [{
2470
+ role: "worker",
2471
+ kind: completed.kind,
2472
+ content: completed.content,
2473
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2474
+ }];
948
2475
  }
949
2476
  }
950
2477
  }
@@ -956,14 +2483,14 @@ class CursorStreamJsonState {
956
2483
  this.accumulateUsage(event);
957
2484
  }
958
2485
  if (type === "error" || (type === "result" && event.is_error === true)) {
959
- return {
960
- role: "runner",
961
- kind: "error",
962
- content: clip(line.trim(), 1000),
963
- eventType: "provider_cli_error"
964
- };
2486
+ return [{
2487
+ role: "runner",
2488
+ kind: "error",
2489
+ content: clip(line.trim(), 1000),
2490
+ eventType: "provider_cli_error"
2491
+ }];
965
2492
  }
966
- return null;
2493
+ return [];
967
2494
  }
968
2495
  accumulateUsage(event) {
969
2496
  const usage = objectField(event, "usage");
@@ -1094,37 +2621,37 @@ class CodexJsonState {
1094
2621
  consume(line) {
1095
2622
  const event = parseJsonLine(line);
1096
2623
  if (!event) {
1097
- return null;
2624
+ return [];
1098
2625
  }
1099
2626
  const type = stringField(event, "type") ?? "";
1100
2627
  if (type === "thread.started") {
1101
2628
  this.threadId = stringField(event, "thread_id");
1102
2629
  if (this.threadId && !this.emittedThread) {
1103
2630
  this.emittedThread = true;
1104
- return {
1105
- role: "runner",
1106
- kind: "checkpoint",
1107
- content: `Codex thread started: ${this.threadId}.`,
1108
- eventType: "provider_thread_started"
1109
- };
2631
+ return [{
2632
+ role: "runner",
2633
+ kind: "checkpoint",
2634
+ content: `Codex thread started: ${this.threadId}.`,
2635
+ eventType: "provider_thread_started"
2636
+ }];
1110
2637
  }
1111
2638
  }
1112
2639
  if (type === "turn.completed") {
1113
2640
  this.accumulateUsage(event);
1114
- return {
1115
- role: "runner",
1116
- kind: "checkpoint",
1117
- content: "Codex turn completed.",
1118
- eventType: "provider_turn_completed"
1119
- };
2641
+ return [{
2642
+ role: "runner",
2643
+ kind: "checkpoint",
2644
+ content: "Codex turn completed.",
2645
+ eventType: "provider_turn_completed"
2646
+ }];
1120
2647
  }
1121
2648
  if (type === "turn.failed" || type === "error") {
1122
- return {
1123
- role: "runner",
1124
- kind: "error",
1125
- content: clip(line.trim(), 1000),
1126
- eventType: "provider_cli_error"
1127
- };
2649
+ return [{
2650
+ role: "runner",
2651
+ kind: "error",
2652
+ content: clip(line.trim(), 1000),
2653
+ eventType: "provider_cli_error"
2654
+ }];
1128
2655
  }
1129
2656
  if (type === "item.completed" || type === "item.updated") {
1130
2657
  const item = objectField(event, "item");
@@ -1133,28 +2660,32 @@ class CodexJsonState {
1133
2660
  const text = stringField(item, "text");
1134
2661
  if (text) {
1135
2662
  this.finalMessage = clip(text, 4000);
1136
- return {
1137
- role: "assistant",
1138
- kind: "message",
1139
- content: this.finalMessage,
1140
- eventType: "provider_message"
1141
- };
2663
+ return [{
2664
+ role: "assistant",
2665
+ kind: "message",
2666
+ content: this.finalMessage,
2667
+ eventType: "provider_message"
2668
+ }];
1142
2669
  }
1143
2670
  }
1144
2671
  if (itemType === "command_execution") {
1145
2672
  const command = stringField(item, "command");
1146
2673
  const status = stringField(item, "status");
1147
2674
  if (command) {
1148
- return {
1149
- role: "worker",
1150
- kind: "checkpoint",
1151
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
1152
- eventType: "provider_command"
1153
- };
2675
+ return [{
2676
+ role: "worker",
2677
+ kind: "checkpoint",
2678
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2679
+ eventType: "provider_command"
2680
+ }];
1154
2681
  }
1155
2682
  }
1156
2683
  }
1157
- return null;
2684
+ const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2685
+ if (mcpEvents.length > 0) {
2686
+ return mcpEvents;
2687
+ }
2688
+ return [];
1158
2689
  }
1159
2690
  accumulateUsage(event) {
1160
2691
  const usage = objectField(event, "usage");
@@ -1170,6 +2701,113 @@ class CodexJsonState {
1170
2701
  });
1171
2702
  }
1172
2703
  }
2704
+ function formatCodexMcpToolCallEvents(type, event) {
2705
+ if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2706
+ return [];
2707
+ }
2708
+ const item = objectField(event, "item");
2709
+ const itemType = stringField(item, "type") ?? "";
2710
+ const serverName = mcpServerName(item);
2711
+ const toolName = mcpToolName(item);
2712
+ const isMcpItem = itemType.toLowerCase().includes("mcp")
2713
+ || Boolean(serverName)
2714
+ || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2715
+ if (!isMcpItem || !toolName) {
2716
+ return [];
2717
+ }
2718
+ const status = normalizedString(stringField(item, "status")
2719
+ ?? stringField(event, "status")
2720
+ ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2721
+ const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2722
+ const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2723
+ const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2724
+ const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2725
+ const label = `${serverName ?? "unknown"}.${toolName}`;
2726
+ if (failed) {
2727
+ const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2728
+ const events = [{
2729
+ role: "tool",
2730
+ kind: "error",
2731
+ content: `MCP tool call failed: ${label} - ${summary}`,
2732
+ eventType: "provider_mcp_call_failed",
2733
+ data
2734
+ }];
2735
+ if (isForgeCompletionTool(toolName)) {
2736
+ events.push({
2737
+ role: "tool",
2738
+ kind: "error",
2739
+ content: `Forge completion tool validation failed: ${label} - ${summary}`,
2740
+ eventType: "completion_tool_validation_failed",
2741
+ data
2742
+ });
2743
+ }
2744
+ return events;
2745
+ }
2746
+ if (completed) {
2747
+ return [{
2748
+ role: "tool",
2749
+ kind: "checkpoint",
2750
+ content: `MCP tool call completed: ${label}.`,
2751
+ eventType: "provider_mcp_call_completed",
2752
+ data
2753
+ }];
2754
+ }
2755
+ if (started) {
2756
+ return [{
2757
+ role: "tool",
2758
+ kind: "checkpoint",
2759
+ content: `MCP tool call started: ${label}.`,
2760
+ eventType: "provider_mcp_call_started",
2761
+ data
2762
+ }];
2763
+ }
2764
+ return [];
2765
+ }
2766
+ function mcpServerName(item) {
2767
+ return stringField(item, "server")
2768
+ ?? stringField(item, "server_name")
2769
+ ?? stringField(item, "mcp_server")
2770
+ ?? stringField(objectField(item, "mcp"), "server")
2771
+ ?? stringField(objectField(item, "mcp"), "server_name");
2772
+ }
2773
+ function mcpToolName(item) {
2774
+ return stringField(item, "tool")
2775
+ ?? stringField(item, "tool_name")
2776
+ ?? stringField(item, "name")
2777
+ ?? stringField(objectField(item, "function"), "name")
2778
+ ?? stringField(objectField(item, "mcp"), "tool")
2779
+ ?? stringField(objectField(item, "mcp"), "tool_name");
2780
+ }
2781
+ function mcpErrorSummary(item) {
2782
+ const direct = stringField(item, "error")
2783
+ ?? stringField(item, "error_message")
2784
+ ?? stringField(item, "message");
2785
+ if (direct) {
2786
+ return clip(direct, 600);
2787
+ }
2788
+ const error = objectField(item, "error");
2789
+ return stringField(error, "message")
2790
+ ?? stringField(error, "summary")
2791
+ ?? stringField(objectField(item, "result"), "error")
2792
+ ?? null;
2793
+ }
2794
+ function safeProviderMcpData(item, serverName, toolName, status) {
2795
+ const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2796
+ return JSON.stringify(stripUndefined({
2797
+ server_name: serverName,
2798
+ tool_name: toolName,
2799
+ status,
2800
+ elapsed_ms: elapsedMs,
2801
+ error_summary: mcpErrorSummary(item)
2802
+ }));
2803
+ }
2804
+ function isForgeCompletionTool(toolName) {
2805
+ const normalized = toolName.trim().toLowerCase();
2806
+ return normalized.startsWith("forge.complete_")
2807
+ || normalized.startsWith("complete_")
2808
+ || normalized.includes("forge.complete_")
2809
+ || normalized.includes("complete_architect_plan");
2810
+ }
1173
2811
  function objectField(source, key) {
1174
2812
  const value = source[key];
1175
2813
  return value && typeof value === "object" && !Array.isArray(value)
@@ -1180,3 +2818,16 @@ function stringField(source, key) {
1180
2818
  const value = source[key];
1181
2819
  return typeof value === "string" && value.trim().length > 0 ? value : null;
1182
2820
  }
2821
+ function numericField(source, key) {
2822
+ const value = source[key];
2823
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2824
+ }
2825
+ function stripUndefined(value) {
2826
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2827
+ }
2828
+ function normalizedString(value) {
2829
+ return value.trim().toLowerCase().replace(/-/g, "_");
2830
+ }
2831
+ function isNodeError(error) {
2832
+ return error instanceof Error && "code" in error;
2833
+ }