@loucompanion/forge-bridge 0.1.1-dev.32d4dd5874ee → 0.1.1-dev.40fbc494669b

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,15 +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, completionArtifactJsonPath, completionArtifactReportPath, completionPhaseFromDispatch, completionPromptForPhase, prepareCompletionToolRuntime, readCompletionArtifact } from "../phase-completion.js";
12
+ import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDebugCycle, completionPromptForDevelopCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, qaCompletionGateOrder } from "../phase-completion.js";
13
+ import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
11
14
  const fakeWorkerModel = "server-local-fake-worker";
12
15
  const execFileAsync = promisify(execFile);
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
+ }
13
146
  export class RoutingProviderCliService {
14
147
  realProvider;
15
148
  deterministicProvider;
@@ -22,15 +155,25 @@ export class RoutingProviderCliService {
22
155
  ? await this.deterministicProvider.runImplementation(context)
23
156
  : await this.realProvider.runImplementation(context);
24
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
+ }
25
163
  async runConflictResolve(context) {
26
164
  return isFakeWorkerModel(context.dispatch.execution.model)
27
165
  ? await this.deterministicProvider.runConflictResolve(context)
28
166
  : await this.realProvider.runConflictResolve(context);
29
167
  }
30
- async runQa(dispatch, emit, signal) {
31
- return isFakeWorkerModel(dispatch.execution.model)
32
- ? await this.deterministicProvider.runQa(dispatch, emit, signal)
33
- : 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);
34
177
  }
35
178
  }
36
179
  export class ProcessBackedProviderCliService {
@@ -40,9 +183,65 @@ export class ProcessBackedProviderCliService {
40
183
  this.processRunner = processRunner;
41
184
  this.git = git;
42
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 command = buildProviderCliCommand(dispatch, {
193
+ worktreePath: tempDir,
194
+ prompt: buildDraftPrompt(dispatch),
195
+ skipGitRepoCheck: true
196
+ });
197
+ await context.emit({
198
+ role: "runner",
199
+ kind: "checkpoint",
200
+ content: `Starting provider CLI Draft: ${formatProviderCliCommand(command)}`,
201
+ eventType: "provider_cli_started"
202
+ });
203
+ const outputState = createProviderOutputState(dispatch.execution.provider);
204
+ try {
205
+ const result = await this.processRunner.run({
206
+ command: command.command,
207
+ args: command.args,
208
+ cwd: tempDir,
209
+ env: providerProcessEnv(dispatch)
210
+ }, {
211
+ onStdoutLine: async (line) => {
212
+ for (const event of outputState.consume(line)) {
213
+ await context.emit(event);
214
+ }
215
+ }
216
+ }, context.signal);
217
+ if (result.exitCode !== 0) {
218
+ throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
219
+ }
220
+ const content = outputState.finalMessage ?? result.stdout.trim();
221
+ if (!content) {
222
+ throw new Error("Provider CLI completed without returning a draft.");
223
+ }
224
+ const json = extractJsonObject(content);
225
+ await context.emit({
226
+ role: "assistant",
227
+ kind: "message",
228
+ content: json,
229
+ eventType: "draft_complete"
230
+ });
231
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
232
+ return {
233
+ summary: "Draft generated through Forge Runner."
234
+ };
235
+ }
236
+ finally {
237
+ await fs.rm(tempDir, { recursive: true, force: true });
238
+ }
239
+ }
43
240
  async runImplementation(context) {
44
241
  const { dispatch, worktree } = context;
45
242
  const phase = completionPhaseFromDispatch(dispatch);
243
+ const developCycle = usesDevelopCycleCompletion(dispatch);
244
+ const debugCycle = usesDebugCycleCompletion(dispatch);
46
245
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
47
246
  await fs.mkdir(metadataRoot, { recursive: true });
48
247
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -56,7 +255,11 @@ export class ProcessBackedProviderCliService {
56
255
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
57
256
  const command = buildProviderCliCommand(dispatch, {
58
257
  worktreePath: worktree.worktreePath,
59
- prompt: buildImplementationPrompt(dispatch, phase),
258
+ prompt: debugCycle
259
+ ? buildDebugCyclePrompt(dispatch, phase)
260
+ : developCycle
261
+ ? buildDevelopCyclePrompt(dispatch, phase)
262
+ : buildImplementationPrompt(dispatch, phase),
60
263
  completionTools
61
264
  });
62
265
  await context.emit({
@@ -68,26 +271,33 @@ export class ProcessBackedProviderCliService {
68
271
  await context.emit({
69
272
  role: "runner",
70
273
  kind: "checkpoint",
71
- content: `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
274
+ content: debugCycle
275
+ ? "Forge Debug completion tools configured for debug_repro -> debug_root_cause -> debug_fix -> debug_regression; provider must call each MCP completion tool before exit."
276
+ : developCycle
277
+ ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
278
+ : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
72
279
  eventType: "completion_tools_configured"
73
280
  });
74
281
  const outputState = createProviderOutputState(dispatch.execution.provider);
282
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
75
283
  let result;
76
284
  try {
285
+ liveCompletionEvents.start();
77
286
  result = await this.processRunner.run({
78
287
  command: command.command,
79
288
  args: command.args,
80
- cwd: worktree.worktreePath
289
+ cwd: worktree.worktreePath,
290
+ env: providerProcessEnv(dispatch)
81
291
  }, {
82
292
  onStdoutLine: async (line) => {
83
- const event = outputState.consume(line);
84
- if (event) {
293
+ for (const event of outputState.consume(line)) {
85
294
  await context.emit(event);
86
295
  }
87
296
  }
88
297
  }, context.signal);
89
298
  }
90
299
  finally {
300
+ await liveCompletionEvents.stop();
91
301
  await cleanupCompletionTools(completionTools, context.emit);
92
302
  }
93
303
  if (result.exitCode !== 0) {
@@ -100,17 +310,23 @@ export class ProcessBackedProviderCliService {
100
310
  content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
101
311
  eventType: "provider_cli_completed"
102
312
  });
313
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
103
314
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
104
- const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, phase);
105
- if (!completionArtifact) {
106
- throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
315
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
316
+ for (const artifact of completionArtifacts) {
317
+ if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
318
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
319
+ await emitPhaseCompletionEvent(context.emit, artifact);
320
+ await emitPhaseGateEvents(context.emit, artifact);
321
+ }
107
322
  }
323
+ const completionArtifact = completionArtifacts[0];
108
324
  if (outputState.finalMessage) {
109
325
  await context.emit({
110
326
  role: "assistant",
111
327
  kind: "message",
112
328
  content: outputState.finalMessage,
113
- eventType: "implementation_complete"
329
+ eventType: "provider_final_message"
114
330
  });
115
331
  }
116
332
  else {
@@ -118,11 +334,11 @@ export class ProcessBackedProviderCliService {
118
334
  role: "assistant",
119
335
  kind: "message",
120
336
  content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
121
- eventType: "implementation_complete"
337
+ eventType: "provider_final_message"
122
338
  });
123
339
  }
124
340
  return {
125
- summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${phase}, ${committed.commitSha.slice(0, 12)}).`,
341
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
126
342
  spec: {
127
343
  repoPath: worktree.worktreePath,
128
344
  path: specPath,
@@ -130,67 +346,212 @@ export class ProcessBackedProviderCliService {
130
346
  producedBy: "forge-lane-command",
131
347
  status: "approved"
132
348
  },
133
- artifact: completionArtifact
349
+ artifact: completionArtifact,
350
+ artifacts: completionArtifacts
134
351
  };
135
352
  }
136
- async runQa(dispatch, emit, signal) {
353
+ async runArchitect(context) {
354
+ const { dispatch, worktree } = context;
355
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
137
356
  const command = buildProviderCliCommand(dispatch, {
138
- prompt: buildQaPrompt(dispatch)
357
+ worktreePath: worktree.worktreePath,
358
+ prompt: buildArchitectPrompt(dispatch),
359
+ completionTools
139
360
  });
140
- await emit({
361
+ const commandText = formatProviderCliCommand(command);
362
+ await context.emit({
141
363
  role: "runner",
142
364
  kind: "checkpoint",
143
- content: `Starting provider CLI QA: ${formatProviderCliCommand(command)}`,
365
+ content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
144
366
  eventType: "provider_cli_started"
145
367
  });
368
+ await context.emit({
369
+ role: "runner",
370
+ kind: "checkpoint",
371
+ content: "Forge Architect completion tools configured; provider must call forge.complete_architect_plan before exit.",
372
+ eventType: "completion_tools_configured"
373
+ });
146
374
  const outputState = createProviderOutputState(dispatch.execution.provider);
147
- const result = await this.processRunner.run({
148
- command: command.command,
149
- args: command.args,
150
- cwd: process.cwd()
151
- }, {
152
- onStdoutLine: async (line) => {
153
- const event = outputState.consume(line);
154
- if (event) {
155
- await emit(event);
375
+ const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
376
+ let result;
377
+ try {
378
+ liveArchitectEvents.start();
379
+ result = await this.processRunner.run({
380
+ command: command.command,
381
+ args: command.args,
382
+ cwd: worktree.worktreePath,
383
+ env: providerProcessEnv(dispatch)
384
+ }, {
385
+ onStdoutLine: async (line) => {
386
+ for (const event of outputState.consume(line)) {
387
+ await context.emit(event);
388
+ }
156
389
  }
157
- }
158
- }, signal);
390
+ }, context.signal);
391
+ }
392
+ finally {
393
+ await liveArchitectEvents.stop();
394
+ await cleanupCompletionTools(completionTools, context.emit);
395
+ }
159
396
  if (result.exitCode !== 0) {
160
397
  const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
161
398
  throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
162
399
  }
163
- await emit({
400
+ await context.emit({
401
+ role: "runner",
402
+ kind: "checkpoint",
403
+ content: `Provider CLI Architect completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
404
+ eventType: "provider_cli_completed"
405
+ });
406
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
407
+ const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
408
+ if (!architectArtifact) {
409
+ throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
410
+ }
411
+ if (!liveArchitectEvents.hasEmitted()) {
412
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
413
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, architectArtifact);
414
+ }
415
+ await context.emit({
416
+ role: "assistant",
417
+ kind: "message",
418
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI produced an Architect plan for ${worktree.branchName}.`,
419
+ eventType: "architect_complete"
420
+ });
421
+ const specPath = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id, "spec.md");
422
+ const specBody = await fs.readFile(specPath, "utf8").catch(() => `# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`);
423
+ return {
424
+ summary: `${dispatch.execution.provider} CLI Architect plan produced.`,
425
+ spec: {
426
+ repoPath: worktree.worktreePath,
427
+ path: specPath,
428
+ body: specBody,
429
+ producedBy: `${dispatch.execution.provider}-cli`,
430
+ status: "pending_approval"
431
+ },
432
+ artifact: architectArtifact,
433
+ artifacts: [architectArtifact]
434
+ };
435
+ }
436
+ async runQa(context) {
437
+ const { dispatch, worktree } = context;
438
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
439
+ await fs.mkdir(metadataRoot, { recursive: true });
440
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
441
+ if (!laneCommand) {
442
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
443
+ }
444
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem, "qa");
445
+ const specPath = path.join(metadataRoot, "spec.md");
446
+ await fs.writeFile(specPath, specBody, "utf8");
447
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
448
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
449
+ const command = buildProviderCliCommand(dispatch, {
450
+ worktreePath: worktree.worktreePath,
451
+ prompt: buildQaPrompt(dispatch, specBody),
452
+ completionTools
453
+ });
454
+ const commandText = formatProviderCliCommand(command);
455
+ await context.emit({
456
+ role: "runner",
457
+ kind: "checkpoint",
458
+ content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
459
+ eventType: "provider_cli_started"
460
+ });
461
+ await context.emit({
462
+ role: "runner",
463
+ kind: "checkpoint",
464
+ content: "Forge QA completion tools configured; provider must call all seven QA MCP gates before exit.",
465
+ eventType: "completion_tools_configured"
466
+ });
467
+ const outputState = createProviderOutputState(dispatch.execution.provider);
468
+ const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
469
+ let result;
470
+ try {
471
+ liveQaEvents.start();
472
+ result = await this.processRunner.run({
473
+ command: command.command,
474
+ args: command.args,
475
+ cwd: worktree.worktreePath,
476
+ env: providerProcessEnv(dispatch)
477
+ }, {
478
+ onStdoutLine: async (line) => {
479
+ for (const event of outputState.consume(line)) {
480
+ await context.emit(event);
481
+ }
482
+ }
483
+ }, context.signal);
484
+ }
485
+ finally {
486
+ await liveQaEvents.stop();
487
+ await cleanupCompletionTools(completionTools, context.emit);
488
+ }
489
+ if (result.exitCode !== 0) {
490
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
491
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
492
+ }
493
+ await context.emit({
164
494
  role: "runner",
165
495
  kind: "checkpoint",
166
496
  content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
167
497
  eventType: "provider_cli_completed"
168
498
  });
499
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
500
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
501
+ if (!qaArtifact) {
502
+ const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
503
+ throw new Error(verdictOnly
504
+ ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
505
+ : "Provider CLI QA completed but did not call the Forge QA completion tool.");
506
+ }
507
+ enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
508
+ if (!liveQaEvents.hasEmitted()) {
509
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
510
+ await emitQaStructuredEvents(context.emit, qaArtifact);
511
+ }
512
+ const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
513
+ const statusSummary = status === "pass"
514
+ ? "passed"
515
+ : status === "blocked"
516
+ ? "blocked"
517
+ : "found rework";
169
518
  return {
170
- summary: `${dispatch.execution.provider} CLI QA passed.`
519
+ summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
520
+ spec: {
521
+ repoPath: worktree.worktreePath,
522
+ path: specPath,
523
+ body: specBody,
524
+ producedBy: "forge-lane-command",
525
+ status: "approved"
526
+ },
527
+ artifact: qaArtifact,
528
+ artifacts: [qaArtifact]
171
529
  };
172
530
  }
173
531
  async runConflictResolve(context) {
174
532
  const { dispatch, worktree } = context;
533
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
175
534
  const command = buildProviderCliCommand(dispatch, {
176
535
  worktreePath: worktree.worktreePath,
177
- prompt: buildConflictResolvePrompt(dispatch, worktree.branchName)
536
+ prompt: addressComments
537
+ ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
538
+ : buildConflictResolvePrompt(dispatch, worktree.branchName)
178
539
  });
179
540
  await context.emit({
180
541
  role: "runner",
181
542
  kind: "checkpoint",
182
- content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
543
+ content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
183
544
  eventType: "provider_cli_started"
184
545
  });
185
546
  const outputState = createProviderOutputState(dispatch.execution.provider);
186
547
  const result = await this.processRunner.run({
187
548
  command: command.command,
188
549
  args: command.args,
189
- cwd: worktree.worktreePath
550
+ cwd: worktree.worktreePath,
551
+ env: providerProcessEnv(dispatch)
190
552
  }, {
191
553
  onStdoutLine: async (line) => {
192
- const event = outputState.consume(line);
193
- if (event) {
554
+ for (const event of outputState.consume(line)) {
194
555
  await context.emit(event);
195
556
  }
196
557
  }
@@ -201,14 +562,19 @@ export class ProcessBackedProviderCliService {
201
562
  }
202
563
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
203
564
  await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
565
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
204
566
  await context.emit({
205
567
  role: "assistant",
206
568
  kind: "message",
207
- content: outputState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
208
- eventType: "conflict_resolve_complete"
569
+ content: outputState.finalMessage || (addressComments
570
+ ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
571
+ : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
572
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
209
573
  });
210
574
  return {
211
- summary: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
575
+ summary: addressComments
576
+ ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
577
+ : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
212
578
  };
213
579
  }
214
580
  }
@@ -217,9 +583,22 @@ export class DeterministicProviderCliService {
217
583
  constructor(git = new GitClient()) {
218
584
  this.git = git;
219
585
  }
586
+ async runDraft(context) {
587
+ const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
588
+ await context.emit({
589
+ role: "assistant",
590
+ kind: "message",
591
+ content,
592
+ eventType: "draft_complete"
593
+ });
594
+ await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
595
+ return { summary: "forge-bridge generated deterministic draft." };
596
+ }
220
597
  async runImplementation(context) {
221
598
  const { dispatch, worktree } = context;
222
599
  const phase = completionPhaseFromDispatch(dispatch);
600
+ const developCycle = usesDevelopCycleCompletion(dispatch);
601
+ const debugCycle = usesDebugCycleCompletion(dispatch);
223
602
  const providerCommand = buildProviderCliCommand(dispatch);
224
603
  const providerCommandText = formatProviderCliCommand(providerCommand);
225
604
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -250,9 +629,179 @@ export class DeterministicProviderCliService {
250
629
  content: `Created bridge changeset at ${changesetPath}`,
251
630
  eventType: "changeset"
252
631
  });
253
- const verdict = {
254
- schema_version: 1,
255
- phase: "implementation",
632
+ const phases = debugCycle
633
+ ? debugCompletionPhaseOrder
634
+ : developCycle
635
+ ? ["implementation", "self_review", "validation"]
636
+ : [phase];
637
+ const completionArtifacts = [];
638
+ for (const completionPhase of phases) {
639
+ await writeCompletionArtifact({
640
+ worktreePath: worktree.worktreePath,
641
+ workItemId: dispatch.workItem.id,
642
+ phase: completionPhase,
643
+ producedBy: "forge-bridge",
644
+ redactionSecrets: exactRedactionSecrets(dispatch)
645
+ }, isDebugCompletionPhaseForProvider(completionPhase)
646
+ ? expectedDebugCompletionToolName(completionPhase)
647
+ : expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
648
+ const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
649
+ if (!completionArtifact) {
650
+ throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
651
+ }
652
+ completionArtifacts.push(completionArtifact);
653
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
654
+ await context.emit({
655
+ role: "assistant",
656
+ kind: "message",
657
+ content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
658
+ eventType: phaseCompleteEventType(completionPhase)
659
+ });
660
+ }
661
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
662
+ return {
663
+ summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
664
+ spec: {
665
+ repoPath: worktree.worktreePath,
666
+ path: specPath,
667
+ body: specBody,
668
+ producedBy: "forge-lane-command",
669
+ status: "approved"
670
+ },
671
+ artifact: completionArtifacts[0],
672
+ artifacts: completionArtifacts
673
+ };
674
+ }
675
+ async runArchitect(context) {
676
+ const { dispatch, worktree } = context;
677
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
678
+ await fs.mkdir(metadataRoot, { recursive: true });
679
+ 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`;
680
+ const specPath = path.join(metadataRoot, "spec.md");
681
+ await fs.writeFile(specPath, specBody, "utf8");
682
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
683
+ await writeCompletionArtifact({
684
+ worktreePath: worktree.worktreePath,
685
+ workItemId: dispatch.workItem.id,
686
+ phase: "architect",
687
+ producedBy: "forge-bridge",
688
+ redactionSecrets: exactRedactionSecrets(dispatch),
689
+ architectCycle: true
690
+ }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
691
+ const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
692
+ if (!artifact) {
693
+ throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
694
+ }
695
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
696
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
697
+ await context.emit({
698
+ role: "assistant",
699
+ kind: "message",
700
+ content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
701
+ eventType: "architect_complete"
702
+ });
703
+ return {
704
+ summary: "forge-bridge completed Architect plan (deterministic).",
705
+ spec: {
706
+ repoPath: worktree.worktreePath,
707
+ path: specPath,
708
+ body: specBody,
709
+ producedBy: "forge-bridge",
710
+ status: "pending_approval"
711
+ },
712
+ artifact,
713
+ artifacts: [artifact]
714
+ };
715
+ }
716
+ async runQa(context) {
717
+ const { dispatch, worktree } = context;
718
+ await context.emit({
719
+ role: "worker",
720
+ kind: "message",
721
+ content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
722
+ eventType: "qa_plan"
723
+ });
724
+ const qaBrowser = dispatch.qaBrowser;
725
+ const launchTarget = qaBrowser?.launchTarget ?? null;
726
+ const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
727
+ const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
728
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
729
+ : null;
730
+ const browserChecks = browserSidecar && launchTarget
731
+ ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
732
+ : [];
733
+ const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
734
+ const summary = missingLaunchTarget
735
+ ? "QA blocked because browser testing is required but no app launch target was provided."
736
+ : "All checks passed. forge-bridge QA completed.";
737
+ const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
738
+ for (const gate of qaCompletionGateOrder) {
739
+ await writeCompletionArtifact({
740
+ worktreePath: worktree.worktreePath,
741
+ workItemId: dispatch.workItem.id,
742
+ phase: "qa",
743
+ producedBy: "forge-bridge",
744
+ redactionSecrets: exactRedactionSecrets(dispatch),
745
+ qaCycle: true,
746
+ ownerType: dispatch.cycleRun.ownerType ?? undefined,
747
+ ownerId: dispatch.cycleRun.ownerId ?? undefined
748
+ }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
749
+ gate,
750
+ criterion,
751
+ summary,
752
+ missingLaunchTarget,
753
+ browserChecks,
754
+ sidecars
755
+ }));
756
+ const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
757
+ if (gateArtifact) {
758
+ await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
759
+ }
760
+ }
761
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
762
+ if (!qaArtifact) {
763
+ throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
764
+ }
765
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
766
+ await emitQaStructuredEvents(context.emit, qaArtifact);
767
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
768
+ return {
769
+ summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
770
+ artifact: qaArtifact,
771
+ artifacts: [qaArtifact]
772
+ };
773
+ }
774
+ async runConflictResolve(context) {
775
+ const { dispatch, worktree } = context;
776
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
777
+ await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
778
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
779
+ await context.emit({
780
+ role: "assistant",
781
+ kind: "message",
782
+ content: addressComments
783
+ ? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
784
+ : `Deterministic conflict resolve completed for ${worktree.branchName}.`,
785
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
786
+ });
787
+ return {
788
+ summary: addressComments
789
+ ? `forge-bridge addressed PR comments for ${worktree.branchName}.`
790
+ : `forge-bridge resolved conflicts for ${worktree.branchName}.`
791
+ };
792
+ }
793
+ }
794
+ function phaseCompleteEventType(phase) {
795
+ return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
796
+ }
797
+ function isDebugCompletionPhaseForProvider(phase) {
798
+ return debugCompletionPhaseOrder.includes(phase);
799
+ }
800
+ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
801
+ const changesetHash = sha256(changesetBody);
802
+ const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
803
+ if (phase === "implementation") {
804
+ return {
256
805
  status: "pass",
257
806
  summary: "forge-bridge produced a deterministic implementation changeset.",
258
807
  plan: [{ step: "Create deterministic changeset", status: "done" }],
@@ -261,85 +810,945 @@ export class DeterministicProviderCliService {
261
810
  docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
262
811
  acceptance_criteria: [
263
812
  {
264
- criterion: dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists",
265
- evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${sha256(changesetBody)}.`,
813
+ criterion,
814
+ evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
266
815
  status: "satisfied"
267
816
  }
268
817
  ],
269
818
  known_gaps: [],
270
- next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation.",
271
- produced_by: "forge-bridge",
272
- content_hash: sha256(changesetBody)
819
+ next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
273
820
  };
274
- const verdictJson = JSON.stringify(verdict);
275
- const report = `# Implementation report\n\nforge-bridge prepared \`${worktree.branchName}\` and created \`${changesetPath}\`.\n`;
276
- const artifactPath = completionArtifactJsonPath(worktree.worktreePath, dispatch.workItem.id, "implementation");
277
- const reportPath = completionArtifactReportPath(worktree.worktreePath, dispatch.workItem.id, "implementation");
278
- await fs.writeFile(artifactPath, verdictJson + "\n", "utf8");
279
- await fs.writeFile(reportPath, report, "utf8");
280
- await context.emit({
281
- role: "assistant",
282
- kind: "message",
283
- content: "Implementation complete. forge-bridge produced deterministic phase artifacts.",
284
- eventType: "implementation_complete"
285
- });
821
+ }
822
+ if (phase === "debug_repro") {
286
823
  return {
287
- summary: `forge-bridge completed ${worktree.branchName}.`,
288
- spec: {
289
- repoPath: worktree.worktreePath,
290
- path: specPath,
291
- body: specBody,
292
- producedBy: "forge-lane-command",
293
- status: "approved"
824
+ status: "pass",
825
+ summary: "forge-bridge reproduced the bug deterministically.",
826
+ repro_steps: ["Run the deterministic fake-worker debug reproduction."],
827
+ observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
828
+ expected: "The bug scenario should be fixed before QA handoff.",
829
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
830
+ };
831
+ }
832
+ if (phase === "debug_root_cause") {
833
+ return {
834
+ status: "pass",
835
+ summary: "forge-bridge isolated a deterministic root cause.",
836
+ root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
837
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
838
+ eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
839
+ risk_area: "forge-bridge deterministic debug lane"
840
+ };
841
+ }
842
+ if (phase === "debug_fix") {
843
+ return {
844
+ status: "pass",
845
+ summary: "forge-bridge applied a deterministic debug fix.",
846
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
847
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
848
+ remaining_risks: [],
849
+ resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
850
+ qa_id: qaId,
851
+ status: "resolved",
852
+ summary: `Resolved deterministic QA finding ${qaId}.`,
853
+ evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
854
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
855
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
856
+ regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
857
+ }))
858
+ };
859
+ }
860
+ if (phase === "debug_regression") {
861
+ return {
862
+ status: "pass",
863
+ summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
864
+ commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
865
+ required_regressions: ["Original deterministic repro no longer fails."],
866
+ build_status: "not_applicable",
867
+ test_status: "pass",
868
+ repro_negative: true,
869
+ qa_ready: true
870
+ };
871
+ }
872
+ if (phase === "self_review") {
873
+ return {
874
+ status: "pass",
875
+ summary: "forge-bridge fake worker completed deterministic self-review.",
876
+ reviewed_diff: true,
877
+ findings: [],
878
+ security_review: {
879
+ status: "pass",
880
+ notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
294
881
  },
295
- artifact: {
296
- repoPath: worktree.worktreePath,
297
- path: artifactPath,
298
- verdictJson,
299
- report,
300
- producedBy: "forge-bridge",
882
+ edge_case_review: {
301
883
  status: "pass",
302
- phase: "implementation"
884
+ notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
885
+ },
886
+ design_review: {
887
+ status: "not_applicable",
888
+ screenshots: [],
889
+ notes: "No UI changes."
890
+ },
891
+ deterministic_comparison: {
892
+ status: "pass",
893
+ command_or_tool: "git diff --stat HEAD~1..HEAD",
894
+ notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
895
+ },
896
+ fixes_applied: [],
897
+ remaining_risks: []
898
+ };
899
+ }
900
+ return {
901
+ status: "pass",
902
+ summary: "forge-bridge fake worker completed deterministic validation.",
903
+ commands: [
904
+ {
905
+ command: "git status --short && git diff --check",
906
+ exit_code: 0,
907
+ status: "pass",
908
+ summary: "Deterministic validation command completed for the fake-worker changeset."
909
+ }
910
+ ],
911
+ acceptance_criteria: [
912
+ {
913
+ criterion,
914
+ evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
915
+ status: "satisfied"
916
+ }
917
+ ],
918
+ build_status: "pass",
919
+ test_status: "pass",
920
+ lint_status: "not_applicable",
921
+ design_status: "not_applicable",
922
+ drift_checks: [
923
+ {
924
+ command_or_tool: "git diff --check",
925
+ status: "pass",
926
+ summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
927
+ }
928
+ ],
929
+ ready_for_dev_test: true
930
+ };
931
+ }
932
+ function deterministicArchitectPayload(dispatch) {
933
+ const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
934
+ return {
935
+ status: "pass",
936
+ summary: "forge-bridge produced a deterministic Architect plan.",
937
+ implementation_plan: {
938
+ schema_version: 1,
939
+ plan_id: planId,
940
+ story_id: dispatch.workItem.id,
941
+ phases: [
942
+ { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
943
+ ],
944
+ tasks: [
945
+ {
946
+ id: "task-1",
947
+ title: `Implement ${dispatch.workItem.title}`,
948
+ phase: "phase-1",
949
+ summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
950
+ acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
951
+ tests: [
952
+ { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
953
+ ]
954
+ }
955
+ ],
956
+ dependencies: [],
957
+ phase_gates: [
958
+ { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
959
+ ]
960
+ },
961
+ qa_plan: {
962
+ schema_version: 1,
963
+ plan_id: planId,
964
+ final_qa: [
965
+ { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
966
+ ]
967
+ },
968
+ 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`
969
+ };
970
+ }
971
+ function deterministicQaGatePayload(options) {
972
+ const blocked = options.missingLaunchTarget;
973
+ const skippedBecauseBlocked = blocked
974
+ ? {
975
+ status: "skipped",
976
+ summary: "Skipped because browser QA was blocked by missing launch target.",
977
+ reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
978
+ }
979
+ : null;
980
+ switch (options.gate) {
981
+ case "qa_plan":
982
+ return {
983
+ status: "pass",
984
+ summary: "Deterministic QA plan recorded.",
985
+ checklist: [
986
+ "Review the validated work item against acceptance criteria.",
987
+ "Run deterministic regression evidence.",
988
+ "Confirm no in-scope QA findings remain."
989
+ ],
990
+ acceptance_criteria: [options.criterion]
991
+ };
992
+ case "qa_regression":
993
+ return {
994
+ status: "pass",
995
+ summary: "Deterministic regression QA completed.",
996
+ commands: [
997
+ {
998
+ command: "forge-bridge deterministic QA",
999
+ exit_code: 0,
1000
+ status: "pass",
1001
+ summary: "Deterministic regression evidence completed."
1002
+ }
1003
+ ],
1004
+ notes: "Regression gate passed in deterministic fake-worker mode."
1005
+ };
1006
+ case "qa_api":
1007
+ return {
1008
+ status: "skipped",
1009
+ summary: "No API/backend surface was identified for deterministic QA.",
1010
+ reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
1011
+ };
1012
+ case "qa_manual_web":
1013
+ return blocked
1014
+ ? {
1015
+ status: "blocked",
1016
+ summary: "Browser QA could not run because no app launch target was provided.",
1017
+ blocker_reason: "missing_app_launch_target"
1018
+ }
1019
+ : options.browserChecks.length > 0
1020
+ ? {
1021
+ status: "pass",
1022
+ summary: "Deterministic browser QA exercised the configured launch target.",
1023
+ browser_checks: options.browserChecks,
1024
+ sidecars: options.sidecars,
1025
+ notes: "Browser sidecar evidence recorded."
1026
+ }
1027
+ : {
1028
+ status: "skipped",
1029
+ summary: "Manual web QA was not required for this deterministic run.",
1030
+ reason: "Forge did not require browser QA and no launch target was necessary."
1031
+ };
1032
+ case "qa_bug_repro":
1033
+ return skippedBecauseBlocked ?? {
1034
+ status: "skipped",
1035
+ summary: "No failed QA observation required bug reproduction.",
1036
+ reason: "No defects or candidate bugs were observed."
1037
+ };
1038
+ case "qa_findings":
1039
+ return skippedBecauseBlocked ?? {
1040
+ status: "pass",
1041
+ summary: "No QA findings or candidate bugs were identified.",
1042
+ findings: [],
1043
+ candidate_bugs: []
1044
+ };
1045
+ case "qa_verdict":
1046
+ return {
1047
+ status: blocked ? "blocked" : "pass",
1048
+ summary: options.summary,
1049
+ checklist: [
1050
+ "Review the validated work item against acceptance criteria.",
1051
+ "Run deterministic regression evidence.",
1052
+ blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
1053
+ ],
1054
+ tested_acceptance_criteria: blocked ? [] : [options.criterion],
1055
+ commands: blocked
1056
+ ? []
1057
+ : [
1058
+ {
1059
+ command: "forge-bridge deterministic QA",
1060
+ exit_code: 0,
1061
+ status: "pass",
1062
+ summary: "Deterministic QA command completed."
1063
+ }
1064
+ ],
1065
+ browser_checks: blocked ? [] : options.browserChecks,
1066
+ sidecars: blocked ? [] : options.sidecars,
1067
+ notes: options.summary,
1068
+ findings: [],
1069
+ candidate_bugs: [],
1070
+ blocker_reason: blocked ? "missing_app_launch_target" : null,
1071
+ report_markdown: `# QA report\n\n${options.summary}\n`
1072
+ };
1073
+ }
1074
+ }
1075
+ const qaArtifactFileNames = {
1076
+ plan: "qa.plan.json",
1077
+ evidence: "qa.evidence.json",
1078
+ findings: "qa.findings.json",
1079
+ verdict: "qa.verdict.json",
1080
+ report: "qa.report.md"
1081
+ };
1082
+ const qaGateArtifactFileNames = {
1083
+ qa_plan: "qa.plan.json",
1084
+ qa_regression: "qa.regression.json",
1085
+ qa_api: "qa.api.json",
1086
+ qa_manual_web: "qa.manual-web.json",
1087
+ qa_bug_repro: "qa.bug-repro.json",
1088
+ qa_findings: "qa.findings.json",
1089
+ qa_verdict: "qa.verdict.json"
1090
+ };
1091
+ function hasLaunchTarget(target) {
1092
+ return Boolean(target?.url?.trim()
1093
+ || target?.ready_url?.trim()
1094
+ || target?.command?.trim()
1095
+ || (target?.routes ?? []).some((route) => route.trim().length > 0));
1096
+ }
1097
+ function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
1098
+ const route = primaryLaunchRoute(target);
1099
+ return {
1100
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
1101
+ content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
1102
+ };
1103
+ }
1104
+ function deterministicBrowserCheck(target, screenshotPath) {
1105
+ const route = primaryLaunchRoute(target);
1106
+ return {
1107
+ route,
1108
+ url: route,
1109
+ status: "pass",
1110
+ summary: "Deterministic browser QA exercised the configured launch target.",
1111
+ actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
1112
+ screenshots: [screenshotPath],
1113
+ console_errors: [],
1114
+ network_errors: [],
1115
+ responsive_checks: ["desktop", "mobile"]
1116
+ };
1117
+ }
1118
+ function primaryLaunchRoute(target) {
1119
+ return target.ready_url?.trim()
1120
+ || target.url?.trim()
1121
+ || target.routes.find((route) => route.trim().length > 0)?.trim()
1122
+ || "app launch command";
1123
+ }
1124
+ async function writeQaSidecarFiles(worktreePath, files) {
1125
+ const sidecars = [];
1126
+ for (const file of files) {
1127
+ const fullPath = path.resolve(worktreePath, file.relativePath);
1128
+ const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
1129
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
1130
+ throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
1131
+ }
1132
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
1133
+ await fs.writeFile(fullPath, file.content, "utf8");
1134
+ sidecars.push({
1135
+ path: relativePath,
1136
+ content_hash: sha256(file.content),
1137
+ bytes: Buffer.byteLength(file.content, "utf8")
1138
+ });
1139
+ }
1140
+ return sidecars;
1141
+ }
1142
+ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
1143
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1144
+ await emit({
1145
+ role: "tool",
1146
+ kind: "tool_result",
1147
+ content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
1148
+ eventType: "qa_artifact_recorded"
1149
+ });
1150
+ await emit({
1151
+ role: "hook",
1152
+ kind: "checkpoint",
1153
+ content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
1154
+ eventType: "phase_gate"
1155
+ });
1156
+ }
1157
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1158
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1159
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
1160
+ return null;
1161
+ }
1162
+ const artifactRoot = ownerType && ownerId
1163
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1164
+ : artifactRootFor(worktreePath, workItemId);
1165
+ const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1166
+ const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1167
+ const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1168
+ await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1169
+ return {
1170
+ ...artifact,
1171
+ planJson,
1172
+ evidenceJson,
1173
+ findingsJson
1174
+ };
1175
+ }
1176
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1177
+ const artifactRoot = ownerType && ownerId
1178
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1179
+ : artifactRootFor(worktreePath, workItemId);
1180
+ for (const fileName of Object.values(qaArtifactFileNames)) {
1181
+ try {
1182
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1183
+ if (!stat.isFile()) {
1184
+ return false;
1185
+ }
1186
+ }
1187
+ catch (error) {
1188
+ if (isNodeError(error) && error.code === "ENOENT") {
1189
+ return false;
1190
+ }
1191
+ throw error;
1192
+ }
1193
+ }
1194
+ return true;
1195
+ }
1196
+ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
1197
+ const qaBrowser = dispatch.qaBrowser;
1198
+ if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
1199
+ return;
1200
+ }
1201
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1202
+ const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
1203
+ const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
1204
+ if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
1205
+ 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.");
1206
+ }
1207
+ }
1208
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1209
+ const artifactRoot = ownerType && ownerId
1210
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1211
+ : artifactRootFor(worktreePath, workItemId);
1212
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1213
+ const sidecars = arrayField(evidence, "sidecars");
1214
+ if (sidecars.length === 0) {
1215
+ return;
1216
+ }
1217
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
1218
+ for (const [index, sidecar] of sidecars.entries()) {
1219
+ const sidecarPath = stringField(sidecar, "path");
1220
+ const expectedHash = stringField(sidecar, "content_hash");
1221
+ const expectedBytes = sidecar.bytes;
1222
+ if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
1223
+ throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
1224
+ }
1225
+ if (path.isAbsolute(sidecarPath)) {
1226
+ throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
1227
+ }
1228
+ const fullPath = path.resolve(worktreePath, sidecarPath);
1229
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
1230
+ const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1231
+ const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1232
+ throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
1233
+ }
1234
+ const stat = await fs.lstat(fullPath).catch((error) => {
1235
+ if (isNodeError(error) && error.code === "ENOENT") {
1236
+ throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
303
1237
  }
304
- };
1238
+ throw error;
1239
+ });
1240
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1241
+ throw new Error(`QA sidecar ${index} must reference a regular file.`);
1242
+ }
1243
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
1244
+ if (stat.size !== expectedBytes) {
1245
+ throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
1246
+ }
1247
+ const actualHash = await sha256File(fullPath);
1248
+ if (actualHash !== expectedHash.trim().toLowerCase()) {
1249
+ throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
1250
+ }
305
1251
  }
306
- async runQa(dispatch, emit) {
1252
+ }
1253
+ async function emitQaStructuredEvents(emit, artifact) {
1254
+ const artifactRoot = path.dirname(artifact.path);
1255
+ const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
1256
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1257
+ const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
1258
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1259
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1260
+ const checklist = stringArrayField(plan, "checklist");
1261
+ await emit({
1262
+ role: "worker",
1263
+ kind: "message",
1264
+ content: checklist.length > 0
1265
+ ? `QA plan: ${checklist.join("; ")}`
1266
+ : "QA plan recorded.",
1267
+ eventType: "qa_plan"
1268
+ });
1269
+ for (const browserCheck of arrayField(evidence, "browser_checks")) {
307
1270
  await emit({
308
1271
  role: "worker",
309
- kind: "message",
310
- content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
311
- eventType: "qa_analysis"
1272
+ kind: "checkpoint",
1273
+ content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
1274
+ eventType: "qa_browser_check"
312
1275
  });
1276
+ }
1277
+ for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
313
1278
  await emit({
314
- role: "assistant",
315
- kind: "message",
316
- content: "All checks passed. forge-bridge QA completed.",
317
- eventType: "qa_complete"
1279
+ role: "worker",
1280
+ kind: "checkpoint",
1281
+ content: `QA finding: ${summarizeQaObject(finding)}`,
1282
+ eventType: "qa_finding"
318
1283
  });
319
- return {
320
- summary: "forge-bridge QA passed."
321
- };
322
1284
  }
323
- async runConflictResolve(context) {
324
- const { dispatch, worktree } = context;
325
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
326
- await context.emit({
327
- role: "assistant",
328
- kind: "message",
329
- content: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
330
- eventType: "conflict_resolve_complete"
331
- });
332
- return {
333
- summary: `forge-bridge resolved conflicts for ${worktree.branchName}.`
334
- };
1285
+ await emit({
1286
+ role: "assistant",
1287
+ kind: "message",
1288
+ content: status === "blocked"
1289
+ ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
1290
+ : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
1291
+ eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
1292
+ });
1293
+ }
1294
+ function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1295
+ return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1296
+ ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1297
+ : artifactRootFor(worktreePath, workItemId);
1298
+ }
1299
+ async function readQaGateArtifact(artifactRoot, gate) {
1300
+ const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1301
+ try {
1302
+ const stat = await fs.stat(artifactPath);
1303
+ if (!stat.isFile()) {
1304
+ return null;
1305
+ }
1306
+ }
1307
+ catch (error) {
1308
+ if (isNodeError(error) && error.code === "ENOENT") {
1309
+ return null;
1310
+ }
1311
+ throw error;
1312
+ }
1313
+ const payload = await readJsonObjectFile(artifactPath);
1314
+ return {
1315
+ gate,
1316
+ path: artifactPath,
1317
+ status: stringField(payload, "status") ?? "unknown",
1318
+ producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1319
+ contentHash: stringField(payload, "content_hash") ?? undefined
1320
+ };
1321
+ }
1322
+ function nextQaGate(gate) {
1323
+ const index = qaCompletionGateOrder.indexOf(gate);
1324
+ return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1325
+ }
1326
+ async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1327
+ const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1328
+ await emit({
1329
+ role: "hook",
1330
+ kind: artifact.status === "blocked" ? "error" : "checkpoint",
1331
+ content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1332
+ eventType: "phase_gate",
1333
+ data: JSON.stringify({
1334
+ phase: "qa",
1335
+ qa_gate: artifact.gate,
1336
+ status: artifact.status,
1337
+ artifact_relative_paths: [relativePath],
1338
+ content_hash: artifact.contentHash ?? null,
1339
+ produced_by: artifact.producedBy ?? null
1340
+ })
1341
+ });
1342
+ if (!nextGate) {
1343
+ return;
1344
+ }
1345
+ await emit({
1346
+ role: "hook",
1347
+ kind: "checkpoint",
1348
+ content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1349
+ eventType: "phase_gate",
1350
+ data: JSON.stringify({
1351
+ phase: "qa",
1352
+ from_gate: artifact.gate,
1353
+ to_gate: nextGate
1354
+ })
1355
+ });
1356
+ }
1357
+ class LiveQaArtifactEmitter {
1358
+ worktreePath;
1359
+ workItemId;
1360
+ dispatch;
1361
+ emit;
1362
+ emittedBundle = false;
1363
+ emittedGates = new Set();
1364
+ timer = null;
1365
+ pending = Promise.resolve();
1366
+ constructor(worktreePath, workItemId, dispatch, emit) {
1367
+ this.worktreePath = worktreePath;
1368
+ this.workItemId = workItemId;
1369
+ this.dispatch = dispatch;
1370
+ this.emit = emit;
1371
+ }
1372
+ start() {
1373
+ void this.pollQueued();
1374
+ this.timer = setInterval(() => {
1375
+ void this.pollQueued();
1376
+ }, 250);
1377
+ }
1378
+ async stop() {
1379
+ if (this.timer) {
1380
+ clearInterval(this.timer);
1381
+ this.timer = null;
1382
+ }
1383
+ await this.pollQueued();
1384
+ }
1385
+ hasEmitted() {
1386
+ return this.emittedBundle;
1387
+ }
1388
+ pollQueued() {
1389
+ this.pending = this.pending
1390
+ .then(() => this.poll())
1391
+ .catch(() => undefined);
1392
+ return this.pending;
1393
+ }
1394
+ async poll() {
1395
+ await this.emitAvailableGateEvents();
1396
+ if (this.emittedBundle) {
1397
+ return;
1398
+ }
1399
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
1400
+ if (!artifact) {
1401
+ return;
1402
+ }
1403
+ enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
1404
+ this.emittedBundle = true;
1405
+ await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
1406
+ await emitQaStructuredEvents(this.emit, artifact);
1407
+ }
1408
+ async emitAvailableGateEvents() {
1409
+ const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1410
+ for (const gate of qaCompletionGateOrder) {
1411
+ if (this.emittedGates.has(gate)) {
1412
+ continue;
1413
+ }
1414
+ const artifact = await readQaGateArtifact(artifactRoot, gate);
1415
+ if (!artifact) {
1416
+ return;
1417
+ }
1418
+ this.emittedGates.add(gate);
1419
+ await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
1420
+ }
1421
+ }
1422
+ }
1423
+ class LiveArchitectArtifactEmitter {
1424
+ worktreePath;
1425
+ workItemId;
1426
+ emit;
1427
+ emitted = false;
1428
+ timer = null;
1429
+ pending = Promise.resolve();
1430
+ constructor(worktreePath, workItemId, emit) {
1431
+ this.worktreePath = worktreePath;
1432
+ this.workItemId = workItemId;
1433
+ this.emit = emit;
1434
+ }
1435
+ start() {
1436
+ void this.pollQueued();
1437
+ this.timer = setInterval(() => {
1438
+ void this.pollQueued();
1439
+ }, 250);
1440
+ }
1441
+ async stop() {
1442
+ if (this.timer) {
1443
+ clearInterval(this.timer);
1444
+ this.timer = null;
1445
+ }
1446
+ await this.pollQueued();
1447
+ }
1448
+ hasEmitted() {
1449
+ return this.emitted;
1450
+ }
1451
+ pollQueued() {
1452
+ this.pending = this.pending
1453
+ .then(() => this.poll())
1454
+ .catch(() => undefined);
1455
+ return this.pending;
1456
+ }
1457
+ async poll() {
1458
+ if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
1459
+ return;
1460
+ }
1461
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
1462
+ if (!artifact) {
1463
+ return;
1464
+ }
1465
+ this.emitted = true;
1466
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1467
+ await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
335
1468
  }
336
1469
  }
1470
+ async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1471
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1472
+ for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1473
+ try {
1474
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1475
+ if (!stat.isFile()) {
1476
+ return false;
1477
+ }
1478
+ }
1479
+ catch (error) {
1480
+ if (isNodeError(error) && error.code === "ENOENT") {
1481
+ return false;
1482
+ }
1483
+ throw error;
1484
+ }
1485
+ }
1486
+ return true;
1487
+ }
1488
+ async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1489
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1490
+ const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1491
+ const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1492
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1493
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1494
+ const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1495
+ await emit({
1496
+ role: "worker",
1497
+ kind: "checkpoint",
1498
+ content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1499
+ eventType: "architect_plan"
1500
+ });
1501
+ await emit({
1502
+ role: "worker",
1503
+ kind: "checkpoint",
1504
+ content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1505
+ eventType: "architect_qa_seed"
1506
+ });
1507
+ await emit({
1508
+ role: "hook",
1509
+ kind: status === "pass" ? "checkpoint" : "error",
1510
+ content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1511
+ eventType: "architect_mcp_complete"
1512
+ });
1513
+ }
1514
+ async function readJsonObjectFile(filePath) {
1515
+ const content = await fs.readFile(filePath, "utf8").catch(() => "");
1516
+ return parseJsonLine(content) ?? {};
1517
+ }
1518
+ function arrayField(source, key) {
1519
+ const value = source[key];
1520
+ if (!Array.isArray(value)) {
1521
+ return [];
1522
+ }
1523
+ return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
1524
+ }
1525
+ function stringArrayField(source, key) {
1526
+ const value = source[key];
1527
+ if (!Array.isArray(value)) {
1528
+ return [];
1529
+ }
1530
+ return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
1531
+ }
1532
+ function summarizeQaObject(source) {
1533
+ return clip(stringField(source, "title")
1534
+ ?? stringField(source, "summary")
1535
+ ?? stringField(source, "id")
1536
+ ?? JSON.stringify(source), 500);
1537
+ }
1538
+ function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1539
+ if (ownerType && ownerId) {
1540
+ const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1541
+ return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1542
+ }
1543
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
1544
+ }
1545
+ async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
1546
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1547
+ await emit({
1548
+ role: "tool",
1549
+ kind: "checkpoint",
1550
+ content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1551
+ eventType: "completion_tool_validation_passed",
1552
+ data: JSON.stringify({
1553
+ phase: artifact.phase ?? "unknown",
1554
+ status: artifact.status,
1555
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1556
+ })
1557
+ });
1558
+ await emit({
1559
+ role: "tool",
1560
+ kind: "tool_result",
1561
+ content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
1562
+ eventType: "completion_tool_artifact_recorded",
1563
+ data: JSON.stringify({
1564
+ phase: artifact.phase ?? "unknown",
1565
+ status: artifact.status,
1566
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1567
+ })
1568
+ });
1569
+ }
1570
+ async function emitPhaseCompletionEvent(emit, artifact) {
1571
+ const phase = completionPhaseFromArtifact(artifact);
1572
+ await emit({
1573
+ role: "assistant",
1574
+ kind: "message",
1575
+ content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
1576
+ eventType: phaseCompleteEventType(phase)
1577
+ });
1578
+ }
1579
+ async function emitPhaseGateEvents(emit, artifact) {
1580
+ const phase = completionPhaseFromArtifact(artifact);
1581
+ const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
1582
+ await emit({
1583
+ role: "hook",
1584
+ kind: "checkpoint",
1585
+ content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
1586
+ eventType: "phase_gate"
1587
+ });
1588
+ if (status !== "pass") {
1589
+ return;
1590
+ }
1591
+ const progression = phase === "implementation"
1592
+ ? "phase_progression: implementation -> self_review"
1593
+ : phase === "self_review"
1594
+ ? "phase_progression: self_review -> validation"
1595
+ : phase === "debug_repro"
1596
+ ? "phase_progression: debug_repro -> debug_root_cause"
1597
+ : phase === "debug_root_cause"
1598
+ ? "phase_progression: debug_root_cause -> debug_fix"
1599
+ : phase === "debug_fix"
1600
+ ? "phase_progression: debug_fix -> debug_regression"
1601
+ : phase === "debug_regression"
1602
+ ? "phase_progression: debug_regression -> QA ready"
1603
+ : "phase_progression: validation -> QA ready";
1604
+ await emit({
1605
+ role: "hook",
1606
+ kind: "checkpoint",
1607
+ content: progression,
1608
+ eventType: "phase_gate"
1609
+ });
1610
+ }
1611
+ function completionPhaseFromArtifact(artifact) {
1612
+ const phase = artifact.phase?.trim();
1613
+ return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1614
+ || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1615
+ ? phase
1616
+ : "implementation";
1617
+ }
1618
+ class LiveCompletionArtifactEmitter {
1619
+ worktreePath;
1620
+ workItemId;
1621
+ emit;
1622
+ phases;
1623
+ emitted = new Set();
1624
+ timer = null;
1625
+ pending = Promise.resolve();
1626
+ constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
1627
+ this.worktreePath = worktreePath;
1628
+ this.workItemId = workItemId;
1629
+ this.emit = emit;
1630
+ if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
1631
+ this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
1632
+ }
1633
+ else {
1634
+ this.phases = developCycle
1635
+ ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1636
+ : [phase];
1637
+ }
1638
+ }
1639
+ start() {
1640
+ void this.pollQueued();
1641
+ this.timer = setInterval(() => {
1642
+ void this.pollQueued();
1643
+ }, 250);
1644
+ }
1645
+ async stop() {
1646
+ if (this.timer) {
1647
+ clearInterval(this.timer);
1648
+ this.timer = null;
1649
+ }
1650
+ await this.pollQueued();
1651
+ }
1652
+ hasEmitted(phase) {
1653
+ return this.emitted.has(phase);
1654
+ }
1655
+ pollQueued() {
1656
+ this.pending = this.pending
1657
+ .then(() => this.poll())
1658
+ .catch(() => undefined);
1659
+ return this.pending;
1660
+ }
1661
+ async poll() {
1662
+ for (const phase of this.phases) {
1663
+ if (this.emitted.has(phase)) {
1664
+ continue;
1665
+ }
1666
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
1667
+ if (!artifact) {
1668
+ return;
1669
+ }
1670
+ this.emitted.add(phase);
1671
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1672
+ await emitPhaseCompletionEvent(this.emit, artifact);
1673
+ await emitPhaseGateEvents(this.emit, artifact);
1674
+ if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
1675
+ return;
1676
+ }
1677
+ }
1678
+ }
1679
+ }
1680
+ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
1681
+ if (!developCycle && !debugCycle) {
1682
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
1683
+ if (!artifact) {
1684
+ throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
1685
+ }
1686
+ return [artifact];
1687
+ }
1688
+ const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
1689
+ ? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
1690
+ : ["implementation", "self_review", "validation"];
1691
+ const artifacts = [];
1692
+ for (const expectedPhase of expectedPhases) {
1693
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
1694
+ if (!artifact) {
1695
+ if (artifacts.length === 0) {
1696
+ throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
1697
+ }
1698
+ const previous = artifacts[artifacts.length - 1];
1699
+ if ((previous.status ?? "").trim().toLowerCase() === "pass") {
1700
+ throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
1701
+ }
1702
+ return artifacts;
1703
+ }
1704
+ artifacts.push(artifact);
1705
+ if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
1706
+ return artifacts;
1707
+ }
1708
+ }
1709
+ return artifacts;
1710
+ }
1711
+ function providerProcessEnv(dispatch) {
1712
+ const env = {
1713
+ ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1714
+ ...providerCredentialEnv(dispatch)
1715
+ };
1716
+ return Object.keys(env).length > 0 ? env : undefined;
1717
+ }
1718
+ function providerCredentialEnv(dispatch) {
1719
+ const secret = dispatch.apiKeySecretGrant?.secret;
1720
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1721
+ return {};
1722
+ }
1723
+ const provider = dispatch.execution.provider.trim().toLowerCase();
1724
+ if (provider === "codex" || provider === "openai") {
1725
+ return { OPENAI_API_KEY: secret };
1726
+ }
1727
+ return {};
1728
+ }
1729
+ function exactRedactionSecrets(dispatch) {
1730
+ return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
1731
+ }
1732
+ async function emitProviderUsageEvent(emit, dispatch, outputState) {
1733
+ const usage = outputState.usage;
1734
+ if (hasUsage(usage)) {
1735
+ await emit(buildProviderUsageEvent(dispatch, usage));
1736
+ }
1737
+ }
1738
+ function estimatedDeterministicUsage() {
1739
+ return addUsage(emptyUsage("estimated"), {
1740
+ inputTokens: 1000,
1741
+ outputTokens: 400,
1742
+ source: "estimated"
1743
+ });
1744
+ }
337
1745
  export class StreamingProviderProcessRunner {
338
1746
  async run(request, handlers = {}, signal) {
339
1747
  const launch = await resolveProviderProcessLaunch(request.command, request.args);
340
1748
  return await new Promise((resolve, reject) => {
341
1749
  const child = spawn(launch.command, launch.args, {
342
1750
  cwd: request.cwd,
1751
+ env: buildProviderChildEnvironment(request.env),
343
1752
  stdio: ["ignore", "pipe", "pipe"],
344
1753
  windowsHide: true
345
1754
  });
@@ -474,9 +1883,6 @@ function quoteWindowsCommandLineArg(value) {
474
1883
  }
475
1884
  return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
476
1885
  }
477
- async function fileExists(inputPath) {
478
- return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
479
- }
480
1886
  async function readProcessLines(stream, onLine) {
481
1887
  const reader = readline.createInterface({ input: stream });
482
1888
  try {
@@ -494,12 +1900,76 @@ function isFakeWorkerModel(model) {
494
1900
  function sha256(content) {
495
1901
  return crypto.createHash("sha256").update(content).digest("hex");
496
1902
  }
1903
+ function buildDraftPrompt(dispatch) {
1904
+ const draft = dispatch.draft;
1905
+ if (!draft) {
1906
+ throw new Error("Draft prompt is missing.");
1907
+ }
1908
+ const draftArtifacts = dispatch.artifacts
1909
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
1910
+ .map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
1911
+ .join("\n\n");
1912
+ const artifactSection = draftArtifacts
1913
+ ? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
1914
+ : "";
1915
+ return `${draft.systemPrompt}${artifactSection}
1916
+
1917
+ Draft kind: ${draft.kind}
1918
+
1919
+ ${draft.userPrompt}
1920
+
1921
+ Return ONLY the requested JSON object. Do not wrap it in markdown and do not modify files.`;
1922
+ }
1923
+ function extractJsonObject(content) {
1924
+ let trimmed = content.trim();
1925
+ if (trimmed.startsWith("```")) {
1926
+ const firstNewline = trimmed.indexOf("\n");
1927
+ const lastFence = trimmed.lastIndexOf("```");
1928
+ if (firstNewline >= 0 && lastFence > firstNewline) {
1929
+ trimmed = trimmed.slice(firstNewline + 1, lastFence).trim();
1930
+ }
1931
+ }
1932
+ const start = trimmed.indexOf("{");
1933
+ const end = trimmed.lastIndexOf("}");
1934
+ return start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed;
1935
+ }
1936
+ function summarizeStderr(stderr) {
1937
+ const trimmed = stderr.trim();
1938
+ return trimmed ? `: ${clip(trimmed, 1000)}` : "";
1939
+ }
1940
+ function deterministicDraftPayload(dispatch) {
1941
+ const kind = dispatch.draft?.kind ?? "work_item";
1942
+ if (kind === "work_order") {
1943
+ return {
1944
+ title: "Deterministic runner Work Order draft",
1945
+ summary: "Forge Runner generated this deterministic Work Order draft.",
1946
+ objective: "Validate runner-backed Draft generation.",
1947
+ planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
1948
+ decompositionContext: "Use this deterministic fixture only in bridge tests.",
1949
+ assumptions: ["Forge Runner dispatch is available."],
1950
+ warnings: []
1951
+ };
1952
+ }
1953
+ if (kind === "story") {
1954
+ return {
1955
+ title: "Deterministic runner Story draft",
1956
+ description: "Forge Runner generated this deterministic Story draft.",
1957
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
1958
+ points: 3
1959
+ };
1960
+ }
1961
+ return {
1962
+ title: "Deterministic runner Work Item draft",
1963
+ description: "Forge Runner generated this deterministic Work Item draft.",
1964
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
1965
+ reproSteps: "Run Draft with a Forge Runner provider selected.",
1966
+ systemInfo: "forge-bridge deterministic provider",
1967
+ points: 1
1968
+ };
1969
+ }
497
1970
  export function formatProviderCliCommand(command) {
498
1971
  return [command.command, ...command.args].map(singleLine).join(" ");
499
1972
  }
500
- function yamlQuotedScalar(value) {
501
- return JSON.stringify(singleLine(value));
502
- }
503
1973
  function singleLine(value) {
504
1974
  return value.replace(/\s+/g, " ").trim();
505
1975
  }
@@ -508,16 +1978,19 @@ export function buildProviderCliCommand(dispatch, run) {
508
1978
  const normalizedProvider = provider.toLowerCase();
509
1979
  const model = dispatch.execution.model.trim();
510
1980
  if (normalizedProvider === "codex") {
511
- const args = ["exec"];
1981
+ const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
512
1982
  if (run?.completionTools) {
513
1983
  args.push(...codexMcpConfigArgs(run.completionTools));
514
1984
  }
515
1985
  args.push("--model", model);
516
1986
  if (run) {
517
- args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
1987
+ args.push("--json");
518
1988
  if (run.worktreePath) {
519
1989
  args.push("--cd", run.worktreePath);
520
1990
  }
1991
+ if (run.skipGitRepoCheck) {
1992
+ args.push("--skip-git-repo-check");
1993
+ }
521
1994
  args.push(run.prompt ?? "");
522
1995
  }
523
1996
  return { command: "codex", args };
@@ -538,11 +2011,41 @@ export function buildProviderCliCommand(dispatch, run) {
538
2011
  }
539
2012
  return { command: provider, args };
540
2013
  }
2014
+ export function codexSandboxModeForPlatform(platform = process.platform) {
2015
+ return platform === "win32" ? "danger-full-access" : "workspace-write";
2016
+ }
2017
+ function buildArchitectPrompt(dispatch) {
2018
+ return `You are Forge's Architect lane running locally in a prepared git worktree.
2019
+
2020
+ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
2021
+
2022
+ Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
2023
+ 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.
2024
+ 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.
2025
+ ${architectRevisionInstruction(dispatch)}
2026
+ Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
2027
+
2028
+ ${completionPromptForPhase("architect")}
2029
+
2030
+ Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
2031
+ }
2032
+ function architectRevisionInstruction(dispatch) {
2033
+ if (!dispatch.architectRevision) {
2034
+ return "";
2035
+ }
2036
+ return `
2037
+ Architect revision context:
2038
+ - Previous plan id: ${dispatch.architectRevision.priorPlanId}
2039
+ - Previous content hash: ${dispatch.architectRevision.priorContentHash}
2040
+ - Reviewer feedback: ${dispatch.architectRevision.feedback}
2041
+ Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
2042
+ }
541
2043
  function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
542
2044
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
543
2045
 
544
2046
  Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
545
2047
  ${phaseWorkInstruction(phase)}
2048
+ ${qaReworkImplementationInstruction(dispatch)}
546
2049
  Use the repository's existing conventions. Run relevant tests when practical.
547
2050
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
548
2051
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -551,20 +2054,162 @@ ${completionPromptForPhase(phase)}
551
2054
 
552
2055
  Finish with a concise summary of changed files and verification after calling the completion tool.`;
553
2056
  }
2057
+ function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2058
+ return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
2059
+
2060
+ 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.
2061
+ 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.
2062
+ ${qaReworkImplementationInstruction(dispatch)}
2063
+ Use the repository's existing conventions. Run relevant tests when practical.
2064
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
2065
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
2066
+
2067
+ ${completionPromptForDevelopCycle(phase)}
2068
+
2069
+ 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.`;
2070
+ }
2071
+ function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2072
+ return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
2073
+
2074
+ 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.
2075
+ 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.
2076
+ ${debugQaReworkInstruction(dispatch)}
2077
+ Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
2078
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
2079
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
2080
+
2081
+ ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
2082
+
2083
+ 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.`;
2084
+ }
2085
+ function qaReworkImplementationInstruction(dispatch) {
2086
+ if (!dispatch.qaRework) {
2087
+ return "";
2088
+ }
2089
+ return `
2090
+ QA rework context:
2091
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2092
+ - Rework packet: ${dispatch.qaRework.packetPath}
2093
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2094
+ 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.
2095
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2096
+ }
2097
+ function debugQaReworkInstruction(dispatch) {
2098
+ if (!dispatch.qaRework) {
2099
+ return "";
2100
+ }
2101
+ return `
2102
+ QA rework context for Debug:
2103
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2104
+ - Rework packet: ${dispatch.qaRework.packetPath}
2105
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2106
+ 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.
2107
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2108
+ }
2109
+ function qaReworkRetestInstruction(dispatch) {
2110
+ if (!dispatch.qaRework) {
2111
+ return "";
2112
+ }
2113
+ return `
2114
+ QA retest context:
2115
+ - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2116
+ - Rework packet: ${dispatch.qaRework.packetPath}
2117
+ - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2118
+ Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
2119
+ }
554
2120
  function phaseWorkInstruction(phase) {
555
2121
  if (phase === "self_review") {
556
2122
  return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
557
2123
  }
558
2124
  if (phase === "validation") {
559
- return "Run the validation commands and deterministic drift checks needed to prove the work is ready for Dev Test.";
2125
+ return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
560
2126
  }
561
2127
  return "Implement the work item and keep the change focused.";
562
2128
  }
563
- function buildQaPrompt(dispatch) {
564
- return `You are Forge's QA lane running locally.
2129
+ function qaBrowserInstruction(dispatch) {
2130
+ const qaBrowser = dispatch.qaBrowser;
2131
+ if (!qaBrowser) {
2132
+ return "Browser/app launch context: not provided by Forge.";
2133
+ }
2134
+ const launchTarget = qaBrowser.launchTarget;
2135
+ if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
2136
+ 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`}`;
2137
+ }
2138
+ if (!launchTarget) {
2139
+ 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`}`;
2140
+ }
2141
+ const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
2142
+ 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`}`;
2143
+ }
2144
+ function storyQaInstruction(dispatch) {
2145
+ const storyQa = dispatch.storyQa;
2146
+ if (!storyQa) {
2147
+ return "";
2148
+ }
2149
+ const childLines = storyQa.childTasks.map((child) => {
2150
+ const dependencies = child.dependencyWorkItemIds.length > 0
2151
+ ? child.dependencyWorkItemIds.join(", ")
2152
+ : "none";
2153
+ const validation = child.validationArtifact
2154
+ ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2155
+ : "missing";
2156
+ const childQa = child.qaArtifact
2157
+ ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2158
+ : "not present";
2159
+ return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2160
+ }).join("\n");
2161
+ const finalQa = storyQa.finalQaChecks.length > 0
2162
+ ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2163
+ : "- No final QA checks were provided in qa.plan.final_qa.";
2164
+ return `Story QA integration context:
2165
+ - Story work item: ${storyQa.storyWorkItemId}
2166
+ - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2167
+ - Story worktree: ${storyQa.worktreeKey}
2168
+ - Branch: ${storyQa.branch}
2169
+ - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2170
+ - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2171
+ Materialized child tasks and evidence:
2172
+ ${childLines || "- No child tasks were provided."}
2173
+ Architect final QA checks:
2174
+ ${finalQa}
2175
+ 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.`;
2176
+ }
2177
+ function buildQaPrompt(dispatch, laneSpec) {
2178
+ return `You are Forge's QA lane running locally in a prepared git worktree.
2179
+
2180
+ 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.
2181
+
2182
+ Injected QA lane command and work item spec:
2183
+ ${laneSpec}
2184
+
2185
+ ---
2186
+
2187
+ Work item: ${dispatch.workItem.id}
2188
+ Title: ${dispatch.workItem.title}
2189
+ Description:
2190
+ ${dispatch.workItem.description || "Not provided."}
2191
+
2192
+ Acceptance criteria:
2193
+ ${dispatch.workItem.acceptanceCriteria || "Not specified."}
2194
+
2195
+ Repro steps / scenario:
2196
+ ${dispatch.workItem.reproSteps || "Not provided."}
2197
+
2198
+ System info / environment notes:
2199
+ ${dispatch.workItem.systemInfo || "Not provided."}
565
2200
 
566
- Review the implementation for work item ${dispatch.workItem.id}: ${dispatch.workItem.title}
567
- Run relevant verification when practical and finish with a concise QA verdict.`;
2201
+ ${storyQaInstruction(dispatch)}
2202
+ Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
2203
+ ${qaBrowserInstruction(dispatch)}
2204
+ ${qaReworkRetestInstruction(dispatch)}
2205
+ QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
2206
+ 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/.
2207
+ Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
2208
+ Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
2209
+
2210
+ ${completionPromptForQaCycle()}
2211
+
2212
+ Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
568
2213
  }
569
2214
  function buildConflictResolvePrompt(dispatch, branchName) {
570
2215
  const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
@@ -579,6 +2224,34 @@ Keep the original work item intent intact:
579
2224
 
580
2225
  Finish with a concise summary of the conflicts resolved and verification performed.`;
581
2226
  }
2227
+ function buildPullRequestCommentsPrompt(dispatch, branchName) {
2228
+ const pr = dispatch.pullRequest;
2229
+ const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
2230
+ const prLocator = pr
2231
+ ? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
2232
+ : "the open pull request for this work item";
2233
+ return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
2234
+
2235
+ The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
2236
+ PR context:
2237
+ - Provider: ${pr?.provider || "not provided"}
2238
+ - Source branch: ${pr?.sourceBranch || branchName}
2239
+ - Target branch: ${targetBranch}
2240
+ - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
2241
+
2242
+ 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.
2243
+ After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
2244
+ If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
2245
+ Keep the original work item intent intact:
2246
+ - Work item: ${dispatch.workItem.id}
2247
+ - Title: ${dispatch.workItem.title}
2248
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
2249
+
2250
+ Finish with a concise summary of comments addressed and verification performed.`;
2251
+ }
2252
+ function isPullRequestCommentsDispatch(dispatch) {
2253
+ return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
2254
+ }
582
2255
  async function cleanupCompletionTools(completionTools, emit) {
583
2256
  try {
584
2257
  await completionTools.cleanup();
@@ -626,37 +2299,41 @@ class CursorStreamJsonState {
626
2299
  sessionId = null;
627
2300
  finalMessage = null;
628
2301
  emittedSession = false;
2302
+ accumulatedUsage = null;
629
2303
  get sessionLabel() {
630
2304
  return this.sessionId ? `session ${this.sessionId}` : null;
631
2305
  }
2306
+ get usage() {
2307
+ return this.accumulatedUsage;
2308
+ }
632
2309
  consume(line) {
633
2310
  const event = parseJsonLine(line);
634
2311
  if (!event) {
635
- return null;
2312
+ return [];
636
2313
  }
637
2314
  const type = stringField(event, "type");
638
2315
  if (type === "system" && stringField(event, "subtype") === "init") {
639
2316
  this.sessionId = stringField(event, "session_id");
640
2317
  if (this.sessionId && !this.emittedSession) {
641
2318
  this.emittedSession = true;
642
- return {
643
- role: "runner",
644
- kind: "checkpoint",
645
- content: `Cursor session started: ${this.sessionId}.`,
646
- eventType: "provider_thread_started"
647
- };
2319
+ return [{
2320
+ role: "runner",
2321
+ kind: "checkpoint",
2322
+ content: `Cursor session started: ${this.sessionId}.`,
2323
+ eventType: "provider_thread_started"
2324
+ }];
648
2325
  }
649
2326
  }
650
2327
  if (type === "assistant") {
651
2328
  const text = assistantMessageText(event);
652
2329
  if (text) {
653
2330
  this.finalMessage = clip(text, 4000);
654
- return {
655
- role: "assistant",
656
- kind: "message",
657
- content: this.finalMessage,
658
- eventType: "provider_message"
659
- };
2331
+ return [{
2332
+ role: "assistant",
2333
+ kind: "message",
2334
+ content: this.finalMessage,
2335
+ eventType: "provider_message"
2336
+ }];
660
2337
  }
661
2338
  }
662
2339
  if (type === "tool_call") {
@@ -665,23 +2342,23 @@ class CursorStreamJsonState {
665
2342
  if (subtype === "started") {
666
2343
  const summary = formatCursorToolCallStarted(toolCall);
667
2344
  if (summary) {
668
- return {
669
- role: "worker",
670
- kind: "checkpoint",
671
- content: summary,
672
- eventType: "provider_tool_call"
673
- };
2345
+ return [{
2346
+ role: "worker",
2347
+ kind: "checkpoint",
2348
+ content: summary,
2349
+ eventType: "provider_tool_call"
2350
+ }];
674
2351
  }
675
2352
  }
676
2353
  if (subtype === "completed") {
677
2354
  const completed = formatCursorToolCallCompleted(toolCall);
678
2355
  if (completed) {
679
- return {
680
- role: "worker",
681
- kind: completed.kind,
682
- content: completed.content,
683
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
684
- };
2356
+ return [{
2357
+ role: "worker",
2358
+ kind: completed.kind,
2359
+ content: completed.content,
2360
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2361
+ }];
685
2362
  }
686
2363
  }
687
2364
  }
@@ -690,16 +2367,32 @@ class CursorStreamJsonState {
690
2367
  if (result) {
691
2368
  this.finalMessage = clip(result, 4000);
692
2369
  }
2370
+ this.accumulateUsage(event);
693
2371
  }
694
2372
  if (type === "error" || (type === "result" && event.is_error === true)) {
695
- return {
696
- role: "runner",
697
- kind: "error",
698
- content: clip(line.trim(), 1000),
699
- eventType: "provider_cli_error"
700
- };
2373
+ return [{
2374
+ role: "runner",
2375
+ kind: "error",
2376
+ content: clip(line.trim(), 1000),
2377
+ eventType: "provider_cli_error"
2378
+ }];
701
2379
  }
702
- return null;
2380
+ return [];
2381
+ }
2382
+ accumulateUsage(event) {
2383
+ const usage = objectField(event, "usage");
2384
+ const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
2385
+ if (Object.keys(usage).length === 0 && durationMs === 0) {
2386
+ return;
2387
+ }
2388
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
2389
+ inputTokens: readUsageNumber(usage, "inputTokens"),
2390
+ outputTokens: readUsageNumber(usage, "outputTokens"),
2391
+ cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
2392
+ cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
2393
+ providerDurationMs: durationMs > 0 ? durationMs : null,
2394
+ source: "provider_reported"
2395
+ });
703
2396
  }
704
2397
  }
705
2398
  function formatCursorToolCallStarted(toolCall) {
@@ -805,42 +2498,47 @@ class CodexJsonState {
805
2498
  threadId = null;
806
2499
  finalMessage = null;
807
2500
  emittedThread = false;
2501
+ accumulatedUsage = null;
808
2502
  get sessionLabel() {
809
2503
  return this.threadId ? `thread ${this.threadId}` : null;
810
2504
  }
2505
+ get usage() {
2506
+ return this.accumulatedUsage;
2507
+ }
811
2508
  consume(line) {
812
2509
  const event = parseJsonLine(line);
813
2510
  if (!event) {
814
- return null;
2511
+ return [];
815
2512
  }
816
2513
  const type = stringField(event, "type") ?? "";
817
2514
  if (type === "thread.started") {
818
2515
  this.threadId = stringField(event, "thread_id");
819
2516
  if (this.threadId && !this.emittedThread) {
820
2517
  this.emittedThread = true;
821
- return {
822
- role: "runner",
823
- kind: "checkpoint",
824
- content: `Codex thread started: ${this.threadId}.`,
825
- eventType: "provider_thread_started"
826
- };
2518
+ return [{
2519
+ role: "runner",
2520
+ kind: "checkpoint",
2521
+ content: `Codex thread started: ${this.threadId}.`,
2522
+ eventType: "provider_thread_started"
2523
+ }];
827
2524
  }
828
2525
  }
829
2526
  if (type === "turn.completed") {
830
- return {
831
- role: "runner",
832
- kind: "checkpoint",
833
- content: "Codex turn completed.",
834
- eventType: "provider_turn_completed"
835
- };
2527
+ this.accumulateUsage(event);
2528
+ return [{
2529
+ role: "runner",
2530
+ kind: "checkpoint",
2531
+ content: "Codex turn completed.",
2532
+ eventType: "provider_turn_completed"
2533
+ }];
836
2534
  }
837
2535
  if (type === "turn.failed" || type === "error") {
838
- return {
839
- role: "runner",
840
- kind: "error",
841
- content: clip(line.trim(), 1000),
842
- eventType: "provider_cli_error"
843
- };
2536
+ return [{
2537
+ role: "runner",
2538
+ kind: "error",
2539
+ content: clip(line.trim(), 1000),
2540
+ eventType: "provider_cli_error"
2541
+ }];
844
2542
  }
845
2543
  if (type === "item.completed" || type === "item.updated") {
846
2544
  const item = objectField(event, "item");
@@ -849,29 +2547,153 @@ class CodexJsonState {
849
2547
  const text = stringField(item, "text");
850
2548
  if (text) {
851
2549
  this.finalMessage = clip(text, 4000);
852
- return {
853
- role: "assistant",
854
- kind: "message",
855
- content: this.finalMessage,
856
- eventType: "provider_message"
857
- };
2550
+ return [{
2551
+ role: "assistant",
2552
+ kind: "message",
2553
+ content: this.finalMessage,
2554
+ eventType: "provider_message"
2555
+ }];
858
2556
  }
859
2557
  }
860
2558
  if (itemType === "command_execution") {
861
2559
  const command = stringField(item, "command");
862
2560
  const status = stringField(item, "status");
863
2561
  if (command) {
864
- return {
865
- role: "worker",
866
- kind: "checkpoint",
867
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
868
- eventType: "provider_command"
869
- };
2562
+ return [{
2563
+ role: "worker",
2564
+ kind: "checkpoint",
2565
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2566
+ eventType: "provider_command"
2567
+ }];
870
2568
  }
871
2569
  }
872
2570
  }
873
- return null;
2571
+ const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2572
+ if (mcpEvents.length > 0) {
2573
+ return mcpEvents;
2574
+ }
2575
+ return [];
2576
+ }
2577
+ accumulateUsage(event) {
2578
+ const usage = objectField(event, "usage");
2579
+ if (Object.keys(usage).length === 0) {
2580
+ return;
2581
+ }
2582
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
2583
+ inputTokens: readUsageNumber(usage, "input_tokens"),
2584
+ outputTokens: readUsageNumber(usage, "output_tokens"),
2585
+ cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
2586
+ reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
2587
+ source: "provider_reported"
2588
+ });
2589
+ }
2590
+ }
2591
+ function formatCodexMcpToolCallEvents(type, event) {
2592
+ if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2593
+ return [];
2594
+ }
2595
+ const item = objectField(event, "item");
2596
+ const itemType = stringField(item, "type") ?? "";
2597
+ const serverName = mcpServerName(item);
2598
+ const toolName = mcpToolName(item);
2599
+ const isMcpItem = itemType.toLowerCase().includes("mcp")
2600
+ || Boolean(serverName)
2601
+ || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2602
+ if (!isMcpItem || !toolName) {
2603
+ return [];
2604
+ }
2605
+ const status = normalizedString(stringField(item, "status")
2606
+ ?? stringField(event, "status")
2607
+ ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2608
+ const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2609
+ const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2610
+ const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2611
+ const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2612
+ const label = `${serverName ?? "unknown"}.${toolName}`;
2613
+ if (failed) {
2614
+ const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2615
+ const events = [{
2616
+ role: "tool",
2617
+ kind: "error",
2618
+ content: `MCP tool call failed: ${label} - ${summary}`,
2619
+ eventType: "provider_mcp_call_failed",
2620
+ data
2621
+ }];
2622
+ if (isForgeCompletionTool(toolName)) {
2623
+ events.push({
2624
+ role: "tool",
2625
+ kind: "error",
2626
+ content: `Forge completion tool validation failed: ${label} - ${summary}`,
2627
+ eventType: "completion_tool_validation_failed",
2628
+ data
2629
+ });
2630
+ }
2631
+ return events;
2632
+ }
2633
+ if (completed) {
2634
+ return [{
2635
+ role: "tool",
2636
+ kind: "checkpoint",
2637
+ content: `MCP tool call completed: ${label}.`,
2638
+ eventType: "provider_mcp_call_completed",
2639
+ data
2640
+ }];
2641
+ }
2642
+ if (started) {
2643
+ return [{
2644
+ role: "tool",
2645
+ kind: "checkpoint",
2646
+ content: `MCP tool call started: ${label}.`,
2647
+ eventType: "provider_mcp_call_started",
2648
+ data
2649
+ }];
2650
+ }
2651
+ return [];
2652
+ }
2653
+ function mcpServerName(item) {
2654
+ return stringField(item, "server")
2655
+ ?? stringField(item, "server_name")
2656
+ ?? stringField(item, "mcp_server")
2657
+ ?? stringField(objectField(item, "mcp"), "server")
2658
+ ?? stringField(objectField(item, "mcp"), "server_name");
2659
+ }
2660
+ function mcpToolName(item) {
2661
+ return stringField(item, "tool")
2662
+ ?? stringField(item, "tool_name")
2663
+ ?? stringField(item, "name")
2664
+ ?? stringField(objectField(item, "function"), "name")
2665
+ ?? stringField(objectField(item, "mcp"), "tool")
2666
+ ?? stringField(objectField(item, "mcp"), "tool_name");
2667
+ }
2668
+ function mcpErrorSummary(item) {
2669
+ const direct = stringField(item, "error")
2670
+ ?? stringField(item, "error_message")
2671
+ ?? stringField(item, "message");
2672
+ if (direct) {
2673
+ return clip(direct, 600);
874
2674
  }
2675
+ const error = objectField(item, "error");
2676
+ return stringField(error, "message")
2677
+ ?? stringField(error, "summary")
2678
+ ?? stringField(objectField(item, "result"), "error")
2679
+ ?? null;
2680
+ }
2681
+ function safeProviderMcpData(item, serverName, toolName, status) {
2682
+ const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2683
+ return JSON.stringify(stripUndefined({
2684
+ server_name: serverName,
2685
+ tool_name: toolName,
2686
+ status,
2687
+ elapsed_ms: elapsedMs,
2688
+ error_summary: mcpErrorSummary(item)
2689
+ }));
2690
+ }
2691
+ function isForgeCompletionTool(toolName) {
2692
+ const normalized = toolName.trim().toLowerCase();
2693
+ return normalized.startsWith("forge.complete_")
2694
+ || normalized.startsWith("complete_")
2695
+ || normalized.includes("forge.complete_")
2696
+ || normalized.includes("complete_architect_plan");
875
2697
  }
876
2698
  function objectField(source, key) {
877
2699
  const value = source[key];
@@ -883,3 +2705,16 @@ function stringField(source, key) {
883
2705
  const value = source[key];
884
2706
  return typeof value === "string" && value.trim().length > 0 ? value : null;
885
2707
  }
2708
+ function numericField(source, key) {
2709
+ const value = source[key];
2710
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2711
+ }
2712
+ function stripUndefined(value) {
2713
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2714
+ }
2715
+ function normalizedString(value) {
2716
+ return value.trim().toLowerCase().replace(/-/g, "_");
2717
+ }
2718
+ function isNodeError(error) {
2719
+ return error instanceof Error && "code" in error;
2720
+ }