@loucompanion/forge-bridge 0.1.1-dev.32d4dd5874ee → 0.1.1-dev.440026b50fad

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