@loucompanion/forge-bridge 0.1.1-dev.2bc1e7f19b3a → 0.1.1-dev.2d1a116ca78d

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