@loucompanion/forge-bridge 0.1.1-dev.af36c7fa102b → 0.1.1-dev.cada6731ecc7

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