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

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.
@@ -5,10 +5,14 @@ import { execFile, spawn } from "node:child_process";
5
5
  import readline from "node:readline";
6
6
  import { promisify } from "node:util";
7
7
  import { GitClient } from "../../shared/git/git.js";
8
+ import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
9
+ import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
8
10
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
9
- import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForPhase, prepareCompletionToolRuntime, readCompletionArtifact } from "../phase-completion.js";
11
+ import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDevelopCycle, completionPromptForPhase, completionRedactionEnv, expectedCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor } from "../phase-completion.js";
12
+ import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
10
13
  const fakeWorkerModel = "server-local-fake-worker";
11
14
  const execFileAsync = promisify(execFile);
15
+ const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
12
16
  export class RoutingProviderCliService {
13
17
  realProvider;
14
18
  deterministicProvider;
@@ -26,10 +30,10 @@ export class RoutingProviderCliService {
26
30
  ? await this.deterministicProvider.runConflictResolve(context)
27
31
  : await this.realProvider.runConflictResolve(context);
28
32
  }
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);
33
+ async runQa(context) {
34
+ return isFakeWorkerModel(context.dispatch.execution.model)
35
+ ? await this.deterministicProvider.runQa(context)
36
+ : await this.realProvider.runQa(context);
33
37
  }
34
38
  }
35
39
  export class ProcessBackedProviderCliService {
@@ -42,6 +46,7 @@ export class ProcessBackedProviderCliService {
42
46
  async runImplementation(context) {
43
47
  const { dispatch, worktree } = context;
44
48
  const phase = completionPhaseFromDispatch(dispatch);
49
+ const developCycle = usesDevelopCycleCompletion(dispatch);
45
50
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
46
51
  await fs.mkdir(metadataRoot, { recursive: true });
47
52
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -55,7 +60,7 @@ export class ProcessBackedProviderCliService {
55
60
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
56
61
  const command = buildProviderCliCommand(dispatch, {
57
62
  worktreePath: worktree.worktreePath,
58
- prompt: buildImplementationPrompt(dispatch, phase),
63
+ prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
59
64
  completionTools
60
65
  });
61
66
  await context.emit({
@@ -67,19 +72,24 @@ export class ProcessBackedProviderCliService {
67
72
  await context.emit({
68
73
  role: "runner",
69
74
  kind: "checkpoint",
70
- content: `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
75
+ content: developCycle
76
+ ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
77
+ : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
71
78
  eventType: "completion_tools_configured"
72
79
  });
73
- const codexState = new CodexJsonState();
80
+ const outputState = createProviderOutputState(dispatch.execution.provider);
81
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, context.emit);
74
82
  let result;
75
83
  try {
84
+ liveCompletionEvents.start();
76
85
  result = await this.processRunner.run({
77
86
  command: command.command,
78
87
  args: command.args,
79
- cwd: worktree.worktreePath
88
+ cwd: worktree.worktreePath,
89
+ env: providerRedactionEnv(dispatch)
80
90
  }, {
81
91
  onStdoutLine: async (line) => {
82
- const event = codexState.consume(line);
92
+ const event = outputState.consume(line);
83
93
  if (event) {
84
94
  await context.emit(event);
85
95
  }
@@ -87,6 +97,7 @@ export class ProcessBackedProviderCliService {
87
97
  }, context.signal);
88
98
  }
89
99
  finally {
100
+ await liveCompletionEvents.stop();
90
101
  await cleanupCompletionTools(completionTools, context.emit);
91
102
  }
92
103
  if (result.exitCode !== 0) {
@@ -96,20 +107,26 @@ export class ProcessBackedProviderCliService {
96
107
  await context.emit({
97
108
  role: "runner",
98
109
  kind: "checkpoint",
99
- content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${codexState.threadId ? ` thread ${codexState.threadId}` : ""}.`,
110
+ content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
100
111
  eventType: "provider_cli_completed"
101
112
  });
113
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
102
114
  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.`);
115
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle);
116
+ for (const artifact of completionArtifacts) {
117
+ if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
118
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
119
+ await emitPhaseCompletionEvent(context.emit, artifact);
120
+ await emitPhaseGateEvents(context.emit, artifact);
121
+ }
106
122
  }
107
- if (codexState.finalMessage) {
123
+ const completionArtifact = completionArtifacts[0];
124
+ if (outputState.finalMessage) {
108
125
  await context.emit({
109
126
  role: "assistant",
110
127
  kind: "message",
111
- content: codexState.finalMessage,
112
- eventType: "implementation_complete"
128
+ content: outputState.finalMessage,
129
+ eventType: "provider_final_message"
113
130
  });
114
131
  }
115
132
  else {
@@ -117,11 +134,11 @@ export class ProcessBackedProviderCliService {
117
134
  role: "assistant",
118
135
  kind: "message",
119
136
  content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
120
- eventType: "implementation_complete"
137
+ eventType: "provider_final_message"
121
138
  });
122
139
  }
123
140
  return {
124
- summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${phase}, ${committed.commitSha.slice(0, 12)}).`,
141
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
125
142
  spec: {
126
143
  repoPath: worktree.worktreePath,
127
144
  path: specPath,
@@ -129,44 +146,87 @@ export class ProcessBackedProviderCliService {
129
146
  producedBy: "forge-lane-command",
130
147
  status: "approved"
131
148
  },
132
- artifact: completionArtifact
149
+ artifact: completionArtifact,
150
+ artifacts: completionArtifacts
133
151
  };
134
152
  }
135
- async runQa(dispatch, emit, signal) {
153
+ async runQa(context) {
154
+ const { dispatch, worktree } = context;
155
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
136
156
  const command = buildProviderCliCommand(dispatch, {
137
- prompt: buildQaPrompt(dispatch)
157
+ worktreePath: worktree.worktreePath,
158
+ prompt: buildQaPrompt(dispatch),
159
+ completionTools
138
160
  });
139
- await emit({
161
+ const commandText = formatProviderCliCommand(command);
162
+ await context.emit({
140
163
  role: "runner",
141
164
  kind: "checkpoint",
142
- content: `Starting provider CLI QA: ${formatProviderCliCommand(command)}`,
165
+ content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
143
166
  eventType: "provider_cli_started"
144
167
  });
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);
168
+ await context.emit({
169
+ role: "runner",
170
+ kind: "checkpoint",
171
+ content: "Forge QA completion tool configured; provider must call forge.complete_qa before exit.",
172
+ eventType: "completion_tools_configured"
173
+ });
174
+ const outputState = createProviderOutputState(dispatch.execution.provider);
175
+ const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
176
+ let result;
177
+ try {
178
+ liveQaEvents.start();
179
+ result = await this.processRunner.run({
180
+ command: command.command,
181
+ args: command.args,
182
+ cwd: worktree.worktreePath,
183
+ env: providerRedactionEnv(dispatch)
184
+ }, {
185
+ onStdoutLine: async (line) => {
186
+ const event = outputState.consume(line);
187
+ if (event) {
188
+ await context.emit(event);
189
+ }
155
190
  }
156
- }
157
- }, signal);
191
+ }, context.signal);
192
+ }
193
+ finally {
194
+ await liveQaEvents.stop();
195
+ await cleanupCompletionTools(completionTools, context.emit);
196
+ }
158
197
  if (result.exitCode !== 0) {
159
198
  const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
160
199
  throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
161
200
  }
162
- await emit({
201
+ await context.emit({
163
202
  role: "runner",
164
203
  kind: "checkpoint",
165
- content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${codexState.threadId ? ` thread ${codexState.threadId}` : ""}.`,
204
+ content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
166
205
  eventType: "provider_cli_completed"
167
206
  });
207
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
208
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
209
+ if (!qaArtifact) {
210
+ const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
211
+ throw new Error(verdictOnly
212
+ ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
213
+ : "Provider CLI QA completed but did not call the Forge QA completion tool.");
214
+ }
215
+ enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
216
+ if (!liveQaEvents.hasEmitted()) {
217
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
218
+ await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
219
+ }
220
+ const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
221
+ const statusSummary = status === "pass"
222
+ ? "passed"
223
+ : status === "blocked"
224
+ ? "blocked"
225
+ : "found rework";
168
226
  return {
169
- summary: `${dispatch.execution.provider} CLI QA passed.`
227
+ summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
228
+ artifact: qaArtifact,
229
+ artifacts: [qaArtifact]
170
230
  };
171
231
  }
172
232
  async runConflictResolve(context) {
@@ -181,14 +241,14 @@ export class ProcessBackedProviderCliService {
181
241
  content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
182
242
  eventType: "provider_cli_started"
183
243
  });
184
- const codexState = new CodexJsonState();
244
+ const outputState = createProviderOutputState(dispatch.execution.provider);
185
245
  const result = await this.processRunner.run({
186
246
  command: command.command,
187
247
  args: command.args,
188
248
  cwd: worktree.worktreePath
189
249
  }, {
190
250
  onStdoutLine: async (line) => {
191
- const event = codexState.consume(line);
251
+ const event = outputState.consume(line);
192
252
  if (event) {
193
253
  await context.emit(event);
194
254
  }
@@ -200,10 +260,11 @@ export class ProcessBackedProviderCliService {
200
260
  }
201
261
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
202
262
  await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
263
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
203
264
  await context.emit({
204
265
  role: "assistant",
205
266
  kind: "message",
206
- content: codexState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
267
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
207
268
  eventType: "conflict_resolve_complete"
208
269
  });
209
270
  return {
@@ -219,6 +280,7 @@ export class DeterministicProviderCliService {
219
280
  async runImplementation(context) {
220
281
  const { dispatch, worktree } = context;
221
282
  const phase = completionPhaseFromDispatch(dispatch);
283
+ const developCycle = usesDevelopCycleCompletion(dispatch);
222
284
  const providerCommand = buildProviderCliCommand(dispatch);
223
285
  const providerCommandText = formatProviderCliCommand(providerCommand);
224
286
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -249,27 +311,34 @@ export class DeterministicProviderCliService {
249
311
  content: `Created bridge changeset at ${changesetPath}`,
250
312
  eventType: "changeset"
251
313
  });
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)
259
- };
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");
265
- await context.emit({
266
- role: "assistant",
267
- kind: "message",
268
- content: "Implementation complete. forge-bridge produced deterministic phase artifacts.",
269
- eventType: "implementation_complete"
270
- });
314
+ const phases = developCycle
315
+ ? ["implementation", "self_review", "validation"]
316
+ : [phase];
317
+ const completionArtifacts = [];
318
+ for (const completionPhase of phases) {
319
+ await writeCompletionArtifact({
320
+ worktreePath: worktree.worktreePath,
321
+ workItemId: dispatch.workItem.id,
322
+ phase: completionPhase,
323
+ producedBy: "forge-bridge",
324
+ redactionSecrets: exactRedactionSecrets(dispatch)
325
+ }, expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
326
+ const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
327
+ if (!completionArtifact) {
328
+ throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
329
+ }
330
+ completionArtifacts.push(completionArtifact);
331
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
332
+ await context.emit({
333
+ role: "assistant",
334
+ kind: "message",
335
+ content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
336
+ eventType: phaseCompleteEventType(completionPhase)
337
+ });
338
+ }
339
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
271
340
  return {
272
- summary: `forge-bridge completed ${worktree.branchName}.`,
341
+ summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
273
342
  spec: {
274
343
  repoPath: worktree.worktreePath,
275
344
  path: specPath,
@@ -277,36 +346,57 @@ export class DeterministicProviderCliService {
277
346
  producedBy: "forge-lane-command",
278
347
  status: "approved"
279
348
  },
280
- artifact: {
281
- repoPath: worktree.worktreePath,
282
- path: artifactPath,
283
- verdictJson,
284
- report,
285
- producedBy: "forge-bridge",
286
- status: "pass"
287
- }
349
+ artifact: completionArtifacts[0],
350
+ artifacts: completionArtifacts
288
351
  };
289
352
  }
290
- async runQa(dispatch, emit) {
291
- await emit({
353
+ async runQa(context) {
354
+ const { dispatch, worktree } = context;
355
+ await context.emit({
292
356
  role: "worker",
293
357
  kind: "message",
294
- content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
295
- eventType: "qa_analysis"
358
+ content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
359
+ eventType: "qa_plan"
296
360
  });
297
- await emit({
298
- role: "assistant",
299
- kind: "message",
300
- content: "All checks passed. forge-bridge QA completed.",
301
- eventType: "qa_complete"
361
+ const qaBrowser = dispatch.qaBrowser;
362
+ const launchTarget = qaBrowser?.launchTarget ?? null;
363
+ const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
364
+ const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
365
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget)
366
+ : null;
367
+ const browserChecks = browserSidecar && launchTarget
368
+ ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
369
+ : [];
370
+ const summary = missingLaunchTarget
371
+ ? "QA blocked because browser testing is required but no app launch target was provided."
372
+ : "All checks passed. forge-bridge QA completed.";
373
+ const qaArtifact = await writeQaArtifacts({
374
+ worktreePath: worktree.worktreePath,
375
+ workItemId: dispatch.workItem.id,
376
+ acceptanceCriteria: dispatch.workItem.acceptanceCriteria,
377
+ producedBy: "forge-bridge",
378
+ provider: dispatch.execution.provider,
379
+ model: dispatch.execution.model,
380
+ command: "forge-bridge deterministic QA",
381
+ summary,
382
+ status: missingLaunchTarget ? "blocked" : "pass",
383
+ blockerReason: missingLaunchTarget ? "missing_app_launch_target" : null,
384
+ browserChecks,
385
+ sidecarFiles: browserSidecar ? [browserSidecar] : []
302
386
  });
387
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
388
+ await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
389
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
303
390
  return {
304
- summary: "forge-bridge QA passed."
391
+ summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
392
+ artifact: qaArtifact,
393
+ artifacts: [qaArtifact]
305
394
  };
306
395
  }
307
396
  async runConflictResolve(context) {
308
397
  const { dispatch, worktree } = context;
309
398
  await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
399
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
310
400
  await context.emit({
311
401
  role: "assistant",
312
402
  kind: "message",
@@ -318,12 +408,596 @@ export class DeterministicProviderCliService {
318
408
  };
319
409
  }
320
410
  }
411
+ function phaseCompleteEventType(phase) {
412
+ return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
413
+ }
414
+ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
415
+ const changesetHash = sha256(changesetBody);
416
+ const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
417
+ if (phase === "implementation") {
418
+ return {
419
+ status: "pass",
420
+ summary: "forge-bridge produced a deterministic implementation changeset.",
421
+ plan: [{ step: "Create deterministic changeset", status: "done" }],
422
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
423
+ tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
424
+ docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
425
+ acceptance_criteria: [
426
+ {
427
+ criterion,
428
+ evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
429
+ status: "satisfied"
430
+ }
431
+ ],
432
+ known_gaps: [],
433
+ next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
434
+ };
435
+ }
436
+ if (phase === "self_review") {
437
+ return {
438
+ status: "pass",
439
+ summary: "forge-bridge fake worker completed deterministic self-review.",
440
+ reviewed_diff: true,
441
+ findings: [],
442
+ security_review: {
443
+ status: "pass",
444
+ notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
445
+ },
446
+ edge_case_review: {
447
+ status: "pass",
448
+ notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
449
+ },
450
+ design_review: {
451
+ status: "not_applicable",
452
+ screenshots: [],
453
+ notes: "No UI changes."
454
+ },
455
+ deterministic_comparison: {
456
+ status: "pass",
457
+ command_or_tool: "git diff --stat HEAD~1..HEAD",
458
+ notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
459
+ },
460
+ fixes_applied: [],
461
+ remaining_risks: []
462
+ };
463
+ }
464
+ return {
465
+ status: "pass",
466
+ summary: "forge-bridge fake worker completed deterministic validation.",
467
+ commands: [
468
+ {
469
+ command: "git status --short && git diff --check",
470
+ exit_code: 0,
471
+ status: "pass",
472
+ summary: "Deterministic validation command completed for the fake-worker changeset."
473
+ }
474
+ ],
475
+ acceptance_criteria: [
476
+ {
477
+ criterion,
478
+ evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
479
+ status: "satisfied"
480
+ }
481
+ ],
482
+ build_status: "pass",
483
+ test_status: "pass",
484
+ lint_status: "not_applicable",
485
+ design_status: "not_applicable",
486
+ drift_checks: [
487
+ {
488
+ command_or_tool: "git diff --check",
489
+ status: "pass",
490
+ summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
491
+ }
492
+ ],
493
+ ready_for_dev_test: true
494
+ };
495
+ }
496
+ const qaArtifactFileNames = {
497
+ plan: "qa.plan.json",
498
+ evidence: "qa.evidence.json",
499
+ findings: "qa.findings.json",
500
+ verdict: "qa.verdict.json",
501
+ report: "qa.report.md"
502
+ };
503
+ function hasLaunchTarget(target) {
504
+ return Boolean(target?.url?.trim()
505
+ || target?.ready_url?.trim()
506
+ || target?.command?.trim()
507
+ || (target?.routes ?? []).some((route) => route.trim().length > 0));
508
+ }
509
+ function deterministicBrowserSidecar(workItemId, target) {
510
+ const route = primaryLaunchRoute(target);
511
+ return {
512
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt"),
513
+ content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
514
+ };
515
+ }
516
+ function deterministicBrowserCheck(target, screenshotPath) {
517
+ const route = primaryLaunchRoute(target);
518
+ return {
519
+ route,
520
+ url: route,
521
+ status: "pass",
522
+ summary: "Deterministic browser QA exercised the configured launch target.",
523
+ actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
524
+ screenshots: [screenshotPath],
525
+ console_errors: [],
526
+ network_errors: [],
527
+ responsive_checks: ["desktop", "mobile"]
528
+ };
529
+ }
530
+ function primaryLaunchRoute(target) {
531
+ return target.ready_url?.trim()
532
+ || target.url?.trim()
533
+ || target.routes.find((route) => route.trim().length > 0)?.trim()
534
+ || "app launch command";
535
+ }
536
+ async function writeQaSidecarFiles(worktreePath, files) {
537
+ const sidecars = [];
538
+ for (const file of files) {
539
+ const fullPath = path.resolve(worktreePath, file.relativePath);
540
+ const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
541
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
542
+ throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
543
+ }
544
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
545
+ await fs.writeFile(fullPath, file.content, "utf8");
546
+ sidecars.push({
547
+ path: relativePath,
548
+ content_hash: sha256(file.content),
549
+ bytes: Buffer.byteLength(file.content, "utf8")
550
+ });
551
+ }
552
+ return sidecars;
553
+ }
554
+ async function writeQaArtifacts(request) {
555
+ const artifactRoot = artifactRootFor(request.worktreePath, request.workItemId);
556
+ await fs.mkdir(artifactRoot, { recursive: true });
557
+ const sidecars = await writeQaSidecarFiles(request.worktreePath, request.sidecarFiles ?? []);
558
+ const status = request.status ?? "pass";
559
+ const criterion = request.acceptanceCriteria.trim() || "Forge QA evidence exists";
560
+ const relativeEvidencePath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.evidence);
561
+ const relativeFindingsPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.findings);
562
+ const relativeReportPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.report);
563
+ const planJson = jsonText({
564
+ schema_version: 1,
565
+ phase: "qa",
566
+ checklist: [
567
+ "Review the validated work item against acceptance criteria.",
568
+ "Run relevant provider QA verification.",
569
+ "Confirm no in-scope QA findings remain."
570
+ ],
571
+ acceptance_criteria: [criterion]
572
+ });
573
+ const evidenceJson = jsonText({
574
+ schema_version: 1,
575
+ phase: "qa",
576
+ commands: status === "blocked"
577
+ ? []
578
+ : [
579
+ {
580
+ command: request.command,
581
+ exit_code: 0,
582
+ status: "pass",
583
+ summary: `${request.provider} QA completed successfully.`
584
+ }
585
+ ],
586
+ browser_checks: request.browserChecks ?? [],
587
+ sidecars,
588
+ notes: request.summary
589
+ });
590
+ const findingsJson = jsonText({
591
+ schema_version: 1,
592
+ phase: "qa",
593
+ findings: [],
594
+ candidate_bugs: []
595
+ });
596
+ const verdictJson = jsonText({
597
+ schema_version: 1,
598
+ phase: "qa",
599
+ status,
600
+ summary: request.summary,
601
+ tested_acceptance_criteria: status === "blocked" ? [] : [criterion],
602
+ finding_ids: [],
603
+ candidate_bug_ids: [],
604
+ blocker_reason: status === "blocked" ? request.blockerReason ?? "inconclusive" : null,
605
+ evidence_path: relativeEvidencePath,
606
+ findings_path: relativeFindingsPath,
607
+ report_path: relativeReportPath
608
+ });
609
+ const report = `# QA report\n\n${request.summary}\n\n- Provider: ${singleLine(request.provider)}\n- Model: ${singleLine(request.model)}\n- Command: ${singleLine(request.command)}\n`;
610
+ await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.plan), planJson, "utf8");
611
+ await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.evidence), evidenceJson, "utf8");
612
+ await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.findings), findingsJson, "utf8");
613
+ const verdictPath = path.join(artifactRoot, qaArtifactFileNames.verdict);
614
+ await fs.writeFile(verdictPath, verdictJson, "utf8");
615
+ await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.report), report, "utf8");
616
+ return {
617
+ repoPath: request.worktreePath,
618
+ path: verdictPath,
619
+ verdictJson,
620
+ report,
621
+ producedBy: request.producedBy,
622
+ status,
623
+ phase: "qa"
624
+ };
625
+ }
626
+ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
627
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
628
+ await emit({
629
+ role: "tool",
630
+ kind: "tool_result",
631
+ content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
632
+ eventType: "qa_artifact_recorded"
633
+ });
634
+ await emit({
635
+ role: "hook",
636
+ kind: "checkpoint",
637
+ content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
638
+ eventType: "phase_gate"
639
+ });
640
+ }
641
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
642
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
643
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
644
+ return null;
645
+ }
646
+ await validateQaBundleSidecarReferences(worktreePath, workItemId);
647
+ return artifact;
648
+ }
649
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
650
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
651
+ for (const fileName of Object.values(qaArtifactFileNames)) {
652
+ try {
653
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
654
+ if (!stat.isFile()) {
655
+ return false;
656
+ }
657
+ }
658
+ catch (error) {
659
+ if (isNodeError(error) && error.code === "ENOENT") {
660
+ return false;
661
+ }
662
+ throw error;
663
+ }
664
+ }
665
+ return true;
666
+ }
667
+ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
668
+ const qaBrowser = dispatch.qaBrowser;
669
+ if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
670
+ return;
671
+ }
672
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
673
+ const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
674
+ const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
675
+ if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
676
+ 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.");
677
+ }
678
+ }
679
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
680
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
681
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
682
+ const sidecars = arrayField(evidence, "sidecars");
683
+ if (sidecars.length === 0) {
684
+ return;
685
+ }
686
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
687
+ for (const [index, sidecar] of sidecars.entries()) {
688
+ const sidecarPath = stringField(sidecar, "path");
689
+ const expectedHash = stringField(sidecar, "content_hash");
690
+ const expectedBytes = sidecar.bytes;
691
+ if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
692
+ throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
693
+ }
694
+ if (path.isAbsolute(sidecarPath)) {
695
+ throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
696
+ }
697
+ const fullPath = path.resolve(worktreePath, sidecarPath);
698
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
699
+ throw new Error(`QA sidecar ${index} path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
700
+ }
701
+ const stat = await fs.lstat(fullPath).catch((error) => {
702
+ if (isNodeError(error) && error.code === "ENOENT") {
703
+ throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
704
+ }
705
+ throw error;
706
+ });
707
+ if (!stat.isFile() || stat.isSymbolicLink()) {
708
+ throw new Error(`QA sidecar ${index} must reference a regular file.`);
709
+ }
710
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
711
+ if (stat.size !== expectedBytes) {
712
+ throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
713
+ }
714
+ const actualHash = await sha256File(fullPath);
715
+ if (actualHash !== expectedHash.trim().toLowerCase()) {
716
+ throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
717
+ }
718
+ }
719
+ }
720
+ async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
721
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
722
+ const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
723
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
724
+ const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
725
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
726
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
727
+ const checklist = stringArrayField(plan, "checklist");
728
+ await emit({
729
+ role: "worker",
730
+ kind: "message",
731
+ content: checklist.length > 0
732
+ ? `QA plan: ${checklist.join("; ")}`
733
+ : "QA plan recorded.",
734
+ eventType: "qa_plan"
735
+ });
736
+ for (const browserCheck of arrayField(evidence, "browser_checks")) {
737
+ await emit({
738
+ role: "worker",
739
+ kind: "checkpoint",
740
+ content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
741
+ eventType: "qa_browser_check"
742
+ });
743
+ }
744
+ for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
745
+ await emit({
746
+ role: "worker",
747
+ kind: "checkpoint",
748
+ content: `QA finding: ${summarizeQaObject(finding)}`,
749
+ eventType: "qa_finding"
750
+ });
751
+ }
752
+ await emit({
753
+ role: "assistant",
754
+ kind: "message",
755
+ content: status === "blocked"
756
+ ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
757
+ : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
758
+ eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
759
+ });
760
+ }
761
+ class LiveQaArtifactEmitter {
762
+ worktreePath;
763
+ workItemId;
764
+ dispatch;
765
+ emit;
766
+ emitted = false;
767
+ timer = null;
768
+ pending = Promise.resolve();
769
+ constructor(worktreePath, workItemId, dispatch, emit) {
770
+ this.worktreePath = worktreePath;
771
+ this.workItemId = workItemId;
772
+ this.dispatch = dispatch;
773
+ this.emit = emit;
774
+ }
775
+ start() {
776
+ void this.pollQueued();
777
+ this.timer = setInterval(() => {
778
+ void this.pollQueued();
779
+ }, 250);
780
+ }
781
+ async stop() {
782
+ if (this.timer) {
783
+ clearInterval(this.timer);
784
+ this.timer = null;
785
+ }
786
+ await this.pollQueued();
787
+ }
788
+ hasEmitted() {
789
+ return this.emitted;
790
+ }
791
+ pollQueued() {
792
+ this.pending = this.pending
793
+ .then(() => this.poll())
794
+ .catch(() => undefined);
795
+ return this.pending;
796
+ }
797
+ async poll() {
798
+ if (this.emitted) {
799
+ return;
800
+ }
801
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
802
+ if (!artifact) {
803
+ return;
804
+ }
805
+ enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
806
+ this.emitted = true;
807
+ await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
808
+ await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
809
+ }
810
+ }
811
+ async function readJsonObjectFile(filePath) {
812
+ const content = await fs.readFile(filePath, "utf8").catch(() => "");
813
+ return parseJsonLine(content) ?? {};
814
+ }
815
+ function arrayField(source, key) {
816
+ const value = source[key];
817
+ if (!Array.isArray(value)) {
818
+ return [];
819
+ }
820
+ return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
821
+ }
822
+ function stringArrayField(source, key) {
823
+ const value = source[key];
824
+ if (!Array.isArray(value)) {
825
+ return [];
826
+ }
827
+ return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
828
+ }
829
+ function summarizeQaObject(source) {
830
+ return clip(stringField(source, "title")
831
+ ?? stringField(source, "summary")
832
+ ?? stringField(source, "id")
833
+ ?? JSON.stringify(source), 500);
834
+ }
835
+ function qaArtifactRelativePath(workItemId, fileName) {
836
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
837
+ }
838
+ function jsonText(value) {
839
+ return `${JSON.stringify(value, null, 2)}\n`;
840
+ }
841
+ async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
842
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
843
+ await emit({
844
+ role: "tool",
845
+ kind: "tool_result",
846
+ content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
847
+ eventType: "completion_tool_artifact_recorded"
848
+ });
849
+ }
850
+ async function emitPhaseCompletionEvent(emit, artifact) {
851
+ const phase = completionPhaseFromArtifact(artifact);
852
+ await emit({
853
+ role: "assistant",
854
+ kind: "message",
855
+ content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
856
+ eventType: phaseCompleteEventType(phase)
857
+ });
858
+ }
859
+ async function emitPhaseGateEvents(emit, artifact) {
860
+ const phase = completionPhaseFromArtifact(artifact);
861
+ const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
862
+ await emit({
863
+ role: "hook",
864
+ kind: "checkpoint",
865
+ content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
866
+ eventType: "phase_gate"
867
+ });
868
+ if (status !== "pass") {
869
+ return;
870
+ }
871
+ const progression = phase === "implementation"
872
+ ? "phase_progression: implementation -> self_review"
873
+ : phase === "self_review"
874
+ ? "phase_progression: self_review -> validation"
875
+ : "phase_progression: validation -> QA ready";
876
+ await emit({
877
+ role: "hook",
878
+ kind: "checkpoint",
879
+ content: progression,
880
+ eventType: "phase_gate"
881
+ });
882
+ }
883
+ function completionPhaseFromArtifact(artifact) {
884
+ const phase = artifact.phase?.trim();
885
+ return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
886
+ ? phase
887
+ : "implementation";
888
+ }
889
+ class LiveCompletionArtifactEmitter {
890
+ worktreePath;
891
+ workItemId;
892
+ emit;
893
+ phases;
894
+ emitted = new Set();
895
+ timer = null;
896
+ pending = Promise.resolve();
897
+ constructor(worktreePath, workItemId, phase, developCycle, emit) {
898
+ this.worktreePath = worktreePath;
899
+ this.workItemId = workItemId;
900
+ this.emit = emit;
901
+ this.phases = developCycle
902
+ ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
903
+ : [phase];
904
+ }
905
+ start() {
906
+ void this.pollQueued();
907
+ this.timer = setInterval(() => {
908
+ void this.pollQueued();
909
+ }, 250);
910
+ }
911
+ async stop() {
912
+ if (this.timer) {
913
+ clearInterval(this.timer);
914
+ this.timer = null;
915
+ }
916
+ await this.pollQueued();
917
+ }
918
+ hasEmitted(phase) {
919
+ return this.emitted.has(phase);
920
+ }
921
+ pollQueued() {
922
+ this.pending = this.pending
923
+ .then(() => this.poll())
924
+ .catch(() => undefined);
925
+ return this.pending;
926
+ }
927
+ async poll() {
928
+ for (const phase of this.phases) {
929
+ if (this.emitted.has(phase)) {
930
+ continue;
931
+ }
932
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
933
+ if (!artifact) {
934
+ return;
935
+ }
936
+ this.emitted.add(phase);
937
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
938
+ await emitPhaseCompletionEvent(this.emit, artifact);
939
+ await emitPhaseGateEvents(this.emit, artifact);
940
+ if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
941
+ return;
942
+ }
943
+ }
944
+ }
945
+ }
946
+ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle) {
947
+ if (!developCycle) {
948
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
949
+ if (!artifact) {
950
+ throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
951
+ }
952
+ return [artifact];
953
+ }
954
+ const artifacts = [];
955
+ for (const expectedPhase of ["implementation", "self_review", "validation"]) {
956
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
957
+ if (!artifact) {
958
+ if (artifacts.length === 0) {
959
+ throw new Error("Provider CLI completed but did not call the Forge implementation completion tool.");
960
+ }
961
+ const previous = artifacts[artifacts.length - 1];
962
+ if ((previous.status ?? "").trim().toLowerCase() === "pass") {
963
+ throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
964
+ }
965
+ return artifacts;
966
+ }
967
+ artifacts.push(artifact);
968
+ if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
969
+ return artifacts;
970
+ }
971
+ }
972
+ return artifacts;
973
+ }
974
+ function providerRedactionEnv(dispatch) {
975
+ const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
976
+ return Object.keys(env).length > 0 ? env : undefined;
977
+ }
978
+ function exactRedactionSecrets(dispatch) {
979
+ return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
980
+ }
981
+ async function emitProviderUsageEvent(emit, dispatch, outputState) {
982
+ const usage = outputState.usage;
983
+ if (hasUsage(usage)) {
984
+ await emit(buildProviderUsageEvent(dispatch, usage));
985
+ }
986
+ }
987
+ function estimatedDeterministicUsage() {
988
+ return addUsage(emptyUsage("estimated"), {
989
+ inputTokens: 1000,
990
+ outputTokens: 400,
991
+ source: "estimated"
992
+ });
993
+ }
321
994
  export class StreamingProviderProcessRunner {
322
995
  async run(request, handlers = {}, signal) {
323
996
  const launch = await resolveProviderProcessLaunch(request.command, request.args);
324
997
  return await new Promise((resolve, reject) => {
325
998
  const child = spawn(launch.command, launch.args, {
326
999
  cwd: request.cwd,
1000
+ env: request.env ? { ...process.env, ...request.env } : undefined,
327
1001
  stdio: ["ignore", "pipe", "pipe"],
328
1002
  windowsHide: true
329
1003
  });
@@ -392,6 +1066,10 @@ async function resolveProviderProcessLaunch(command, args) {
392
1066
  if (process.platform !== "win32") {
393
1067
  return { command, args };
394
1068
  }
1069
+ const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
1070
+ if (cursorDirect) {
1071
+ return cursorDirect;
1072
+ }
395
1073
  const resolved = await resolveWindowsCommand(command);
396
1074
  return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
397
1075
  }
@@ -399,10 +1077,6 @@ async function resolveWindowsCommand(command) {
399
1077
  if (path.isAbsolute(command)) {
400
1078
  return command;
401
1079
  }
402
- const cursorScript = await resolveCursorAgentPowerShellScript(command);
403
- if (cursorScript) {
404
- return cursorScript;
405
- }
406
1080
  try {
407
1081
  const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
408
1082
  return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
@@ -411,18 +1085,6 @@ async function resolveWindowsCommand(command) {
411
1085
  return null;
412
1086
  }
413
1087
  }
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
1088
  export function chooseWindowsCommandCandidate(candidates) {
427
1089
  const normalized = candidates
428
1090
  .map((candidate) => candidate.trim())
@@ -519,10 +1181,12 @@ export function buildProviderCliCommand(dispatch, run) {
519
1181
  return { command: "codex", args };
520
1182
  }
521
1183
  if (normalizedProvider === "cursor") {
522
- const args = ["--model", model];
1184
+ const args = ["--print", "--output-format", "stream-json", "--model", model];
1185
+ if (run?.worktreePath) {
1186
+ args.push("--workspace", run.worktreePath);
1187
+ }
523
1188
  if (run?.prompt) {
524
- args.push("--yolo");
525
- args.push(run.prompt);
1189
+ args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
526
1190
  }
527
1191
  return { command: "cursor-agent", args };
528
1192
  }
@@ -537,6 +1201,7 @@ function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch
537
1201
 
538
1202
  Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
539
1203
  ${phaseWorkInstruction(phase)}
1204
+ ${qaReworkImplementationInstruction(dispatch)}
540
1205
  Use the repository's existing conventions. Run relevant tests when practical.
541
1206
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
542
1207
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -545,20 +1210,94 @@ ${completionPromptForPhase(phase)}
545
1210
 
546
1211
  Finish with a concise summary of changed files and verification after calling the completion tool.`;
547
1212
  }
1213
+ function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1214
+ return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
1215
+
1216
+ 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.
1217
+ 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.
1218
+ ${qaReworkImplementationInstruction(dispatch)}
1219
+ Use the repository's existing conventions. Run relevant tests when practical.
1220
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
1221
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
1222
+
1223
+ ${completionPromptForDevelopCycle(phase)}
1224
+
1225
+ 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.`;
1226
+ }
1227
+ function qaReworkImplementationInstruction(dispatch) {
1228
+ if (!dispatch.qaRework) {
1229
+ return "";
1230
+ }
1231
+ return `
1232
+ QA rework context:
1233
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1234
+ - Rework packet: ${dispatch.qaRework.packetPath}
1235
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1236
+ 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.`;
1237
+ }
1238
+ function qaReworkRetestInstruction(dispatch) {
1239
+ if (!dispatch.qaRework) {
1240
+ return "";
1241
+ }
1242
+ return `
1243
+ QA retest context:
1244
+ - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1245
+ - Rework packet: ${dispatch.qaRework.packetPath}
1246
+ - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1247
+ Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
1248
+ }
548
1249
  function phaseWorkInstruction(phase) {
549
1250
  if (phase === "self_review") {
550
1251
  return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
551
1252
  }
552
1253
  if (phase === "validation") {
553
- return "Run the validation commands and deterministic drift checks needed to prove the work is ready for Dev Test.";
1254
+ return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
554
1255
  }
555
1256
  return "Implement the work item and keep the change focused.";
556
1257
  }
1258
+ function qaBrowserInstruction(dispatch) {
1259
+ const qaBrowser = dispatch.qaBrowser;
1260
+ if (!qaBrowser) {
1261
+ return "Browser/app launch context: not provided by Forge.";
1262
+ }
1263
+ const launchTarget = qaBrowser.launchTarget;
1264
+ if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
1265
+ 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`}`;
1266
+ }
1267
+ if (!launchTarget) {
1268
+ 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`}`;
1269
+ }
1270
+ const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
1271
+ 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`}`;
1272
+ }
557
1273
  function buildQaPrompt(dispatch) {
558
- return `You are Forge's QA lane running locally.
1274
+ return `You are Forge's QA lane running locally in a prepared git worktree.
1275
+
1276
+ Work item: ${dispatch.workItem.id}
1277
+ Title: ${dispatch.workItem.title}
1278
+ Description:
1279
+ ${dispatch.workItem.description || "Not provided."}
1280
+
1281
+ Acceptance criteria:
1282
+ ${dispatch.workItem.acceptanceCriteria || "Not specified."}
1283
+
1284
+ Repro steps / scenario:
1285
+ ${dispatch.workItem.reproSteps || "Not provided."}
1286
+
1287
+ System info / environment notes:
1288
+ ${dispatch.workItem.systemInfo || "Not provided."}
559
1289
 
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.`;
1290
+ Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1291
+ ${qaBrowserInstruction(dispatch)}
1292
+ ${qaReworkRetestInstruction(dispatch)}
1293
+ QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
1294
+ 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/.
1295
+ Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
1296
+ Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
1297
+
1298
+ ${completionPromptForPhase("qa")}
1299
+
1300
+ Finish with a concise summary only after forge.complete_qa accepts the QA bundle.`;
562
1301
  }
563
1302
  function buildConflictResolvePrompt(dispatch, branchName) {
564
1303
  const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
@@ -611,27 +1350,227 @@ function clip(value, maxLength) {
611
1350
  }
612
1351
  return `${value.slice(0, maxLength)}...`;
613
1352
  }
614
- class CodexJsonState {
615
- threadId = null;
1353
+ function createProviderOutputState(provider) {
1354
+ return provider.trim().toLowerCase() === "cursor"
1355
+ ? new CursorStreamJsonState()
1356
+ : new CodexJsonState();
1357
+ }
1358
+ class CursorStreamJsonState {
1359
+ sessionId = null;
616
1360
  finalMessage = null;
617
- emittedThread = false;
1361
+ emittedSession = false;
1362
+ accumulatedUsage = null;
1363
+ get sessionLabel() {
1364
+ return this.sessionId ? `session ${this.sessionId}` : null;
1365
+ }
1366
+ get usage() {
1367
+ return this.accumulatedUsage;
1368
+ }
618
1369
  consume(line) {
619
- const trimmed = line.trim();
620
- if (!trimmed.startsWith("{")) {
1370
+ const event = parseJsonLine(line);
1371
+ if (!event) {
621
1372
  return null;
622
1373
  }
623
- let parsed;
624
- try {
625
- parsed = JSON.parse(trimmed);
1374
+ const type = stringField(event, "type");
1375
+ if (type === "system" && stringField(event, "subtype") === "init") {
1376
+ this.sessionId = stringField(event, "session_id");
1377
+ if (this.sessionId && !this.emittedSession) {
1378
+ this.emittedSession = true;
1379
+ return {
1380
+ role: "runner",
1381
+ kind: "checkpoint",
1382
+ content: `Cursor session started: ${this.sessionId}.`,
1383
+ eventType: "provider_thread_started"
1384
+ };
1385
+ }
1386
+ }
1387
+ if (type === "assistant") {
1388
+ const text = assistantMessageText(event);
1389
+ if (text) {
1390
+ this.finalMessage = clip(text, 4000);
1391
+ return {
1392
+ role: "assistant",
1393
+ kind: "message",
1394
+ content: this.finalMessage,
1395
+ eventType: "provider_message"
1396
+ };
1397
+ }
626
1398
  }
627
- catch {
1399
+ if (type === "tool_call") {
1400
+ const subtype = stringField(event, "subtype");
1401
+ const toolCall = objectField(event, "tool_call");
1402
+ if (subtype === "started") {
1403
+ const summary = formatCursorToolCallStarted(toolCall);
1404
+ if (summary) {
1405
+ return {
1406
+ role: "worker",
1407
+ kind: "checkpoint",
1408
+ content: summary,
1409
+ eventType: "provider_tool_call"
1410
+ };
1411
+ }
1412
+ }
1413
+ if (subtype === "completed") {
1414
+ const completed = formatCursorToolCallCompleted(toolCall);
1415
+ if (completed) {
1416
+ return {
1417
+ role: "worker",
1418
+ kind: completed.kind,
1419
+ content: completed.content,
1420
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
1421
+ };
1422
+ }
1423
+ }
1424
+ }
1425
+ if (type === "result" && stringField(event, "subtype") === "success") {
1426
+ const result = stringField(event, "result");
1427
+ if (result) {
1428
+ this.finalMessage = clip(result, 4000);
1429
+ }
1430
+ this.accumulateUsage(event);
1431
+ }
1432
+ if (type === "error" || (type === "result" && event.is_error === true)) {
1433
+ return {
1434
+ role: "runner",
1435
+ kind: "error",
1436
+ content: clip(line.trim(), 1000),
1437
+ eventType: "provider_cli_error"
1438
+ };
1439
+ }
1440
+ return null;
1441
+ }
1442
+ accumulateUsage(event) {
1443
+ const usage = objectField(event, "usage");
1444
+ const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
1445
+ if (Object.keys(usage).length === 0 && durationMs === 0) {
1446
+ return;
1447
+ }
1448
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
1449
+ inputTokens: readUsageNumber(usage, "inputTokens"),
1450
+ outputTokens: readUsageNumber(usage, "outputTokens"),
1451
+ cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
1452
+ cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
1453
+ providerDurationMs: durationMs > 0 ? durationMs : null,
1454
+ source: "provider_reported"
1455
+ });
1456
+ }
1457
+ }
1458
+ function formatCursorToolCallStarted(toolCall) {
1459
+ const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
1460
+ const readPath = stringField(readArgs, "path");
1461
+ if (readPath) {
1462
+ return `Reading ${readPath}`;
1463
+ }
1464
+ const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
1465
+ const writePath = stringField(writeArgs, "path");
1466
+ if (writePath) {
1467
+ return `Writing ${writePath}`;
1468
+ }
1469
+ const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
1470
+ const command = stringField(shellArgs, "command");
1471
+ if (command) {
1472
+ return `Shell command started: ${clip(command, 500)}`;
1473
+ }
1474
+ const fn = objectField(toolCall, "function");
1475
+ const name = stringField(fn, "name");
1476
+ if (name) {
1477
+ return `Tool call started: ${name}`;
1478
+ }
1479
+ return null;
1480
+ }
1481
+ function formatCursorToolCallCompleted(toolCall) {
1482
+ const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
1483
+ const writePath = stringField(writeArgs, "path");
1484
+ const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
1485
+ const writtenPath = stringField(writeResult, "path") ?? writePath;
1486
+ if (writtenPath) {
1487
+ return {
1488
+ kind: "file_edit",
1489
+ content: `Wrote ${writtenPath}`
1490
+ };
1491
+ }
1492
+ const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
1493
+ const readPath = stringField(readArgs, "path");
1494
+ if (readPath) {
1495
+ const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
1496
+ const totalLines = readResult.totalLines;
1497
+ const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
1498
+ return {
1499
+ kind: "checkpoint",
1500
+ content: `Read ${readPath}${lineSummary}`
1501
+ };
1502
+ }
1503
+ const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
1504
+ const command = stringField(shellArgs, "command");
1505
+ if (command) {
1506
+ return {
1507
+ kind: "checkpoint",
1508
+ content: `Shell command completed: ${clip(command, 500)}`
1509
+ };
1510
+ }
1511
+ const fn = objectField(toolCall, "function");
1512
+ const name = stringField(fn, "name");
1513
+ if (name) {
1514
+ return {
1515
+ kind: "checkpoint",
1516
+ content: `Tool call completed: ${name}`
1517
+ };
1518
+ }
1519
+ return null;
1520
+ }
1521
+ function assistantMessageText(event) {
1522
+ const message = objectField(event, "message");
1523
+ const content = message.content;
1524
+ if (!Array.isArray(content)) {
1525
+ return null;
1526
+ }
1527
+ const parts = content
1528
+ .map((entry) => {
1529
+ if (!entry || typeof entry !== "object") {
628
1530
  return null;
629
1531
  }
630
- if (!parsed || typeof parsed !== "object") {
1532
+ const block = entry;
1533
+ return stringField(block, "text");
1534
+ })
1535
+ .filter((text) => Boolean(text));
1536
+ if (parts.length === 0) {
1537
+ return null;
1538
+ }
1539
+ return parts.join("");
1540
+ }
1541
+ function parseJsonLine(line) {
1542
+ const trimmed = line.trim();
1543
+ if (!trimmed.startsWith("{")) {
1544
+ return null;
1545
+ }
1546
+ let parsed;
1547
+ try {
1548
+ parsed = JSON.parse(trimmed);
1549
+ }
1550
+ catch {
1551
+ return null;
1552
+ }
1553
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
1554
+ ? parsed
1555
+ : null;
1556
+ }
1557
+ class CodexJsonState {
1558
+ threadId = null;
1559
+ finalMessage = null;
1560
+ emittedThread = false;
1561
+ accumulatedUsage = null;
1562
+ get sessionLabel() {
1563
+ return this.threadId ? `thread ${this.threadId}` : null;
1564
+ }
1565
+ get usage() {
1566
+ return this.accumulatedUsage;
1567
+ }
1568
+ consume(line) {
1569
+ const event = parseJsonLine(line);
1570
+ if (!event) {
631
1571
  return null;
632
1572
  }
633
- const event = parsed;
634
- const type = typeof event.type === "string" ? event.type : "";
1573
+ const type = stringField(event, "type") ?? "";
635
1574
  if (type === "thread.started") {
636
1575
  this.threadId = stringField(event, "thread_id");
637
1576
  if (this.threadId && !this.emittedThread) {
@@ -645,6 +1584,7 @@ class CodexJsonState {
645
1584
  }
646
1585
  }
647
1586
  if (type === "turn.completed") {
1587
+ this.accumulateUsage(event);
648
1588
  return {
649
1589
  role: "runner",
650
1590
  kind: "checkpoint",
@@ -656,7 +1596,7 @@ class CodexJsonState {
656
1596
  return {
657
1597
  role: "runner",
658
1598
  kind: "error",
659
- content: clip(trimmed, 1000),
1599
+ content: clip(line.trim(), 1000),
660
1600
  eventType: "provider_cli_error"
661
1601
  };
662
1602
  }
@@ -690,6 +1630,19 @@ class CodexJsonState {
690
1630
  }
691
1631
  return null;
692
1632
  }
1633
+ accumulateUsage(event) {
1634
+ const usage = objectField(event, "usage");
1635
+ if (Object.keys(usage).length === 0) {
1636
+ return;
1637
+ }
1638
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
1639
+ inputTokens: readUsageNumber(usage, "input_tokens"),
1640
+ outputTokens: readUsageNumber(usage, "output_tokens"),
1641
+ cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
1642
+ reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
1643
+ source: "provider_reported"
1644
+ });
1645
+ }
693
1646
  }
694
1647
  function objectField(source, key) {
695
1648
  const value = source[key];
@@ -701,3 +1654,9 @@ function stringField(source, key) {
701
1654
  const value = source[key];
702
1655
  return typeof value === "string" && value.trim().length > 0 ? value : null;
703
1656
  }
1657
+ function normalizedString(value) {
1658
+ return value.trim().toLowerCase().replace(/-/g, "_");
1659
+ }
1660
+ function isNodeError(error) {
1661
+ return error instanceof Error && "code" in error;
1662
+ }