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

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,13 @@ 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";
8
9
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
9
- import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForPhase, prepareCompletionToolRuntime, readCompletionArtifact } from "../phase-completion.js";
10
+ import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDevelopCycle, completionPromptForPhase, completionRedactionEnv, expectedCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor } from "../phase-completion.js";
11
+ import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
10
12
  const fakeWorkerModel = "server-local-fake-worker";
11
13
  const execFileAsync = promisify(execFile);
14
+ const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
12
15
  export class RoutingProviderCliService {
13
16
  realProvider;
14
17
  deterministicProvider;
@@ -26,10 +29,10 @@ export class RoutingProviderCliService {
26
29
  ? await this.deterministicProvider.runConflictResolve(context)
27
30
  : await this.realProvider.runConflictResolve(context);
28
31
  }
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);
32
+ async runQa(context) {
33
+ return isFakeWorkerModel(context.dispatch.execution.model)
34
+ ? await this.deterministicProvider.runQa(context)
35
+ : await this.realProvider.runQa(context);
33
36
  }
34
37
  }
35
38
  export class ProcessBackedProviderCliService {
@@ -42,6 +45,7 @@ export class ProcessBackedProviderCliService {
42
45
  async runImplementation(context) {
43
46
  const { dispatch, worktree } = context;
44
47
  const phase = completionPhaseFromDispatch(dispatch);
48
+ const developCycle = usesDevelopCycleCompletion(dispatch);
45
49
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
46
50
  await fs.mkdir(metadataRoot, { recursive: true });
47
51
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -55,7 +59,7 @@ export class ProcessBackedProviderCliService {
55
59
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
56
60
  const command = buildProviderCliCommand(dispatch, {
57
61
  worktreePath: worktree.worktreePath,
58
- prompt: buildImplementationPrompt(dispatch, phase),
62
+ prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
59
63
  completionTools
60
64
  });
61
65
  await context.emit({
@@ -67,19 +71,24 @@ export class ProcessBackedProviderCliService {
67
71
  await context.emit({
68
72
  role: "runner",
69
73
  kind: "checkpoint",
70
- content: `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
74
+ content: developCycle
75
+ ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
76
+ : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
71
77
  eventType: "completion_tools_configured"
72
78
  });
73
- const codexState = new CodexJsonState();
79
+ const outputState = createProviderOutputState(dispatch.execution.provider);
80
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, context.emit);
74
81
  let result;
75
82
  try {
83
+ liveCompletionEvents.start();
76
84
  result = await this.processRunner.run({
77
85
  command: command.command,
78
86
  args: command.args,
79
- cwd: worktree.worktreePath
87
+ cwd: worktree.worktreePath,
88
+ env: providerRedactionEnv(dispatch)
80
89
  }, {
81
90
  onStdoutLine: async (line) => {
82
- const event = codexState.consume(line);
91
+ const event = outputState.consume(line);
83
92
  if (event) {
84
93
  await context.emit(event);
85
94
  }
@@ -87,6 +96,7 @@ export class ProcessBackedProviderCliService {
87
96
  }, context.signal);
88
97
  }
89
98
  finally {
99
+ await liveCompletionEvents.stop();
90
100
  await cleanupCompletionTools(completionTools, context.emit);
91
101
  }
92
102
  if (result.exitCode !== 0) {
@@ -96,20 +106,26 @@ export class ProcessBackedProviderCliService {
96
106
  await context.emit({
97
107
  role: "runner",
98
108
  kind: "checkpoint",
99
- content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${codexState.threadId ? ` thread ${codexState.threadId}` : ""}.`,
109
+ content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
100
110
  eventType: "provider_cli_completed"
101
111
  });
112
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
102
113
  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.`);
114
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle);
115
+ for (const artifact of completionArtifacts) {
116
+ if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
117
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
118
+ await emitPhaseCompletionEvent(context.emit, artifact);
119
+ await emitPhaseGateEvents(context.emit, artifact);
120
+ }
106
121
  }
107
- if (codexState.finalMessage) {
122
+ const completionArtifact = completionArtifacts[0];
123
+ if (outputState.finalMessage) {
108
124
  await context.emit({
109
125
  role: "assistant",
110
126
  kind: "message",
111
- content: codexState.finalMessage,
112
- eventType: "implementation_complete"
127
+ content: outputState.finalMessage,
128
+ eventType: "provider_final_message"
113
129
  });
114
130
  }
115
131
  else {
@@ -117,11 +133,11 @@ export class ProcessBackedProviderCliService {
117
133
  role: "assistant",
118
134
  kind: "message",
119
135
  content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
120
- eventType: "implementation_complete"
136
+ eventType: "provider_final_message"
121
137
  });
122
138
  }
123
139
  return {
124
- summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${phase}, ${committed.commitSha.slice(0, 12)}).`,
140
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
125
141
  spec: {
126
142
  repoPath: worktree.worktreePath,
127
143
  path: specPath,
@@ -129,44 +145,86 @@ export class ProcessBackedProviderCliService {
129
145
  producedBy: "forge-lane-command",
130
146
  status: "approved"
131
147
  },
132
- artifact: completionArtifact
148
+ artifact: completionArtifact,
149
+ artifacts: completionArtifacts
133
150
  };
134
151
  }
135
- async runQa(dispatch, emit, signal) {
152
+ async runQa(context) {
153
+ const { dispatch, worktree } = context;
154
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
136
155
  const command = buildProviderCliCommand(dispatch, {
137
- prompt: buildQaPrompt(dispatch)
156
+ worktreePath: worktree.worktreePath,
157
+ prompt: buildQaPrompt(dispatch),
158
+ completionTools
138
159
  });
139
- await emit({
160
+ const commandText = formatProviderCliCommand(command);
161
+ await context.emit({
140
162
  role: "runner",
141
163
  kind: "checkpoint",
142
- content: `Starting provider CLI QA: ${formatProviderCliCommand(command)}`,
164
+ content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
143
165
  eventType: "provider_cli_started"
144
166
  });
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);
167
+ await context.emit({
168
+ role: "runner",
169
+ kind: "checkpoint",
170
+ content: "Forge QA completion tool configured; provider must call forge.complete_qa before exit.",
171
+ eventType: "completion_tools_configured"
172
+ });
173
+ const outputState = createProviderOutputState(dispatch.execution.provider);
174
+ const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
175
+ let result;
176
+ try {
177
+ liveQaEvents.start();
178
+ result = await this.processRunner.run({
179
+ command: command.command,
180
+ args: command.args,
181
+ cwd: worktree.worktreePath,
182
+ env: providerRedactionEnv(dispatch)
183
+ }, {
184
+ onStdoutLine: async (line) => {
185
+ const event = outputState.consume(line);
186
+ if (event) {
187
+ await context.emit(event);
188
+ }
155
189
  }
156
- }
157
- }, signal);
190
+ }, context.signal);
191
+ }
192
+ finally {
193
+ await liveQaEvents.stop();
194
+ await cleanupCompletionTools(completionTools, context.emit);
195
+ }
158
196
  if (result.exitCode !== 0) {
159
197
  const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
160
198
  throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
161
199
  }
162
- await emit({
200
+ await context.emit({
163
201
  role: "runner",
164
202
  kind: "checkpoint",
165
- content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${codexState.threadId ? ` thread ${codexState.threadId}` : ""}.`,
203
+ content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
166
204
  eventType: "provider_cli_completed"
167
205
  });
206
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
207
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
208
+ if (!qaArtifact) {
209
+ const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
210
+ throw new Error(verdictOnly
211
+ ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
212
+ : "Provider CLI QA completed but did not call the Forge QA completion tool.");
213
+ }
214
+ if (!liveQaEvents.hasEmitted()) {
215
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
216
+ await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
217
+ }
218
+ const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
219
+ const statusSummary = status === "pass"
220
+ ? "passed"
221
+ : status === "blocked"
222
+ ? "blocked"
223
+ : "found rework";
168
224
  return {
169
- summary: `${dispatch.execution.provider} CLI QA passed.`
225
+ summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
226
+ artifact: qaArtifact,
227
+ artifacts: [qaArtifact]
170
228
  };
171
229
  }
172
230
  async runConflictResolve(context) {
@@ -181,14 +239,14 @@ export class ProcessBackedProviderCliService {
181
239
  content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
182
240
  eventType: "provider_cli_started"
183
241
  });
184
- const codexState = new CodexJsonState();
242
+ const outputState = createProviderOutputState(dispatch.execution.provider);
185
243
  const result = await this.processRunner.run({
186
244
  command: command.command,
187
245
  args: command.args,
188
246
  cwd: worktree.worktreePath
189
247
  }, {
190
248
  onStdoutLine: async (line) => {
191
- const event = codexState.consume(line);
249
+ const event = outputState.consume(line);
192
250
  if (event) {
193
251
  await context.emit(event);
194
252
  }
@@ -200,10 +258,11 @@ export class ProcessBackedProviderCliService {
200
258
  }
201
259
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
202
260
  await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
261
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
203
262
  await context.emit({
204
263
  role: "assistant",
205
264
  kind: "message",
206
- content: codexState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
265
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
207
266
  eventType: "conflict_resolve_complete"
208
267
  });
209
268
  return {
@@ -219,6 +278,7 @@ export class DeterministicProviderCliService {
219
278
  async runImplementation(context) {
220
279
  const { dispatch, worktree } = context;
221
280
  const phase = completionPhaseFromDispatch(dispatch);
281
+ const developCycle = usesDevelopCycleCompletion(dispatch);
222
282
  const providerCommand = buildProviderCliCommand(dispatch);
223
283
  const providerCommandText = formatProviderCliCommand(providerCommand);
224
284
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -249,27 +309,34 @@ export class DeterministicProviderCliService {
249
309
  content: `Created bridge changeset at ${changesetPath}`,
250
310
  eventType: "changeset"
251
311
  });
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
- });
312
+ const phases = developCycle
313
+ ? ["implementation", "self_review", "validation"]
314
+ : [phase];
315
+ const completionArtifacts = [];
316
+ for (const completionPhase of phases) {
317
+ await writeCompletionArtifact({
318
+ worktreePath: worktree.worktreePath,
319
+ workItemId: dispatch.workItem.id,
320
+ phase: completionPhase,
321
+ producedBy: "forge-bridge",
322
+ redactionSecrets: exactRedactionSecrets(dispatch)
323
+ }, expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
324
+ const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
325
+ if (!completionArtifact) {
326
+ throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
327
+ }
328
+ completionArtifacts.push(completionArtifact);
329
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
330
+ await context.emit({
331
+ role: "assistant",
332
+ kind: "message",
333
+ content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
334
+ eventType: phaseCompleteEventType(completionPhase)
335
+ });
336
+ }
337
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
271
338
  return {
272
- summary: `forge-bridge completed ${worktree.branchName}.`,
339
+ summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
273
340
  spec: {
274
341
  repoPath: worktree.worktreePath,
275
342
  path: specPath,
@@ -277,36 +344,42 @@ export class DeterministicProviderCliService {
277
344
  producedBy: "forge-lane-command",
278
345
  status: "approved"
279
346
  },
280
- artifact: {
281
- repoPath: worktree.worktreePath,
282
- path: artifactPath,
283
- verdictJson,
284
- report,
285
- producedBy: "forge-bridge",
286
- status: "pass"
287
- }
347
+ artifact: completionArtifacts[0],
348
+ artifacts: completionArtifacts
288
349
  };
289
350
  }
290
- async runQa(dispatch, emit) {
291
- await emit({
351
+ async runQa(context) {
352
+ const { dispatch, worktree } = context;
353
+ await context.emit({
292
354
  role: "worker",
293
355
  kind: "message",
294
- content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
295
- eventType: "qa_analysis"
356
+ content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
357
+ eventType: "qa_plan"
296
358
  });
297
- await emit({
298
- role: "assistant",
299
- kind: "message",
300
- content: "All checks passed. forge-bridge QA completed.",
301
- eventType: "qa_complete"
359
+ const summary = "All checks passed. forge-bridge QA completed.";
360
+ const qaArtifact = await writeQaArtifacts({
361
+ worktreePath: worktree.worktreePath,
362
+ workItemId: dispatch.workItem.id,
363
+ acceptanceCriteria: dispatch.workItem.acceptanceCriteria,
364
+ producedBy: "forge-bridge",
365
+ provider: dispatch.execution.provider,
366
+ model: dispatch.execution.model,
367
+ command: "forge-bridge deterministic QA",
368
+ summary
302
369
  });
370
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
371
+ await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
372
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
303
373
  return {
304
- summary: "forge-bridge QA passed."
374
+ summary: "forge-bridge QA passed.",
375
+ artifact: qaArtifact,
376
+ artifacts: [qaArtifact]
305
377
  };
306
378
  }
307
379
  async runConflictResolve(context) {
308
380
  const { dispatch, worktree } = context;
309
381
  await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
382
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
310
383
  await context.emit({
311
384
  role: "assistant",
312
385
  kind: "message",
@@ -318,12 +391,483 @@ export class DeterministicProviderCliService {
318
391
  };
319
392
  }
320
393
  }
394
+ function phaseCompleteEventType(phase) {
395
+ return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
396
+ }
397
+ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
398
+ const changesetHash = sha256(changesetBody);
399
+ const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
400
+ if (phase === "implementation") {
401
+ return {
402
+ status: "pass",
403
+ summary: "forge-bridge produced a deterministic implementation changeset.",
404
+ plan: [{ step: "Create deterministic changeset", status: "done" }],
405
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
406
+ tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
407
+ docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
408
+ acceptance_criteria: [
409
+ {
410
+ criterion,
411
+ evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
412
+ status: "satisfied"
413
+ }
414
+ ],
415
+ known_gaps: [],
416
+ next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
417
+ };
418
+ }
419
+ if (phase === "self_review") {
420
+ return {
421
+ status: "pass",
422
+ summary: "forge-bridge fake worker completed deterministic self-review.",
423
+ reviewed_diff: true,
424
+ findings: [],
425
+ security_review: {
426
+ status: "pass",
427
+ notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
428
+ },
429
+ edge_case_review: {
430
+ status: "pass",
431
+ notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
432
+ },
433
+ design_review: {
434
+ status: "not_applicable",
435
+ screenshots: [],
436
+ notes: "No UI changes."
437
+ },
438
+ deterministic_comparison: {
439
+ status: "pass",
440
+ command_or_tool: "git diff --stat HEAD~1..HEAD",
441
+ notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
442
+ },
443
+ fixes_applied: [],
444
+ remaining_risks: []
445
+ };
446
+ }
447
+ return {
448
+ status: "pass",
449
+ summary: "forge-bridge fake worker completed deterministic validation.",
450
+ commands: [
451
+ {
452
+ command: "git status --short && git diff --check",
453
+ exit_code: 0,
454
+ status: "pass",
455
+ summary: "Deterministic validation command completed for the fake-worker changeset."
456
+ }
457
+ ],
458
+ acceptance_criteria: [
459
+ {
460
+ criterion,
461
+ evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
462
+ status: "satisfied"
463
+ }
464
+ ],
465
+ build_status: "pass",
466
+ test_status: "pass",
467
+ lint_status: "not_applicable",
468
+ design_status: "not_applicable",
469
+ drift_checks: [
470
+ {
471
+ command_or_tool: "git diff --check",
472
+ status: "pass",
473
+ summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
474
+ }
475
+ ],
476
+ ready_for_dev_test: true
477
+ };
478
+ }
479
+ const qaArtifactFileNames = {
480
+ plan: "qa.plan.json",
481
+ evidence: "qa.evidence.json",
482
+ findings: "qa.findings.json",
483
+ verdict: "qa.verdict.json",
484
+ report: "qa.report.md"
485
+ };
486
+ async function writeQaArtifacts(request) {
487
+ const artifactRoot = artifactRootFor(request.worktreePath, request.workItemId);
488
+ await fs.mkdir(artifactRoot, { recursive: true });
489
+ const criterion = request.acceptanceCriteria.trim() || "Forge QA evidence exists";
490
+ const relativeEvidencePath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.evidence);
491
+ const relativeFindingsPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.findings);
492
+ const relativeReportPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.report);
493
+ const planJson = jsonText({
494
+ schema_version: 1,
495
+ phase: "qa",
496
+ checklist: [
497
+ "Review the validated work item against acceptance criteria.",
498
+ "Run relevant provider QA verification.",
499
+ "Confirm no in-scope QA findings remain."
500
+ ],
501
+ acceptance_criteria: [criterion]
502
+ });
503
+ const evidenceJson = jsonText({
504
+ schema_version: 1,
505
+ phase: "qa",
506
+ commands: [
507
+ {
508
+ command: request.command,
509
+ exit_code: 0,
510
+ status: "pass",
511
+ summary: `${request.provider} QA completed successfully.`
512
+ }
513
+ ],
514
+ browser_checks: [],
515
+ notes: request.summary
516
+ });
517
+ const findingsJson = jsonText({
518
+ schema_version: 1,
519
+ phase: "qa",
520
+ findings: [],
521
+ candidate_bugs: []
522
+ });
523
+ const verdictJson = jsonText({
524
+ schema_version: 1,
525
+ phase: "qa",
526
+ status: "pass",
527
+ summary: request.summary,
528
+ tested_acceptance_criteria: [criterion],
529
+ finding_ids: [],
530
+ candidate_bug_ids: [],
531
+ blocker_reason: null,
532
+ evidence_path: relativeEvidencePath,
533
+ findings_path: relativeFindingsPath,
534
+ report_path: relativeReportPath
535
+ });
536
+ 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`;
537
+ await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.plan), planJson, "utf8");
538
+ await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.evidence), evidenceJson, "utf8");
539
+ await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.findings), findingsJson, "utf8");
540
+ const verdictPath = path.join(artifactRoot, qaArtifactFileNames.verdict);
541
+ await fs.writeFile(verdictPath, verdictJson, "utf8");
542
+ await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.report), report, "utf8");
543
+ return {
544
+ repoPath: request.worktreePath,
545
+ path: verdictPath,
546
+ verdictJson,
547
+ report,
548
+ producedBy: request.producedBy,
549
+ status: "pass",
550
+ phase: "qa"
551
+ };
552
+ }
553
+ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
554
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
555
+ await emit({
556
+ role: "tool",
557
+ kind: "tool_result",
558
+ content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
559
+ eventType: "qa_artifact_recorded"
560
+ });
561
+ await emit({
562
+ role: "hook",
563
+ kind: "checkpoint",
564
+ content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
565
+ eventType: "phase_gate"
566
+ });
567
+ }
568
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
569
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
570
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
571
+ return null;
572
+ }
573
+ return artifact;
574
+ }
575
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
576
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
577
+ for (const fileName of Object.values(qaArtifactFileNames)) {
578
+ try {
579
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
580
+ if (!stat.isFile()) {
581
+ return false;
582
+ }
583
+ }
584
+ catch (error) {
585
+ if (isNodeError(error) && error.code === "ENOENT") {
586
+ return false;
587
+ }
588
+ throw error;
589
+ }
590
+ }
591
+ return true;
592
+ }
593
+ async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
594
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
595
+ const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
596
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
597
+ const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
598
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
599
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
600
+ const checklist = stringArrayField(plan, "checklist");
601
+ await emit({
602
+ role: "worker",
603
+ kind: "message",
604
+ content: checklist.length > 0
605
+ ? `QA plan: ${checklist.join("; ")}`
606
+ : "QA plan recorded.",
607
+ eventType: "qa_plan"
608
+ });
609
+ for (const browserCheck of arrayField(evidence, "browser_checks")) {
610
+ await emit({
611
+ role: "worker",
612
+ kind: "checkpoint",
613
+ content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
614
+ eventType: "qa_browser_check"
615
+ });
616
+ }
617
+ for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
618
+ await emit({
619
+ role: "worker",
620
+ kind: "checkpoint",
621
+ content: `QA finding: ${summarizeQaObject(finding)}`,
622
+ eventType: "qa_finding"
623
+ });
624
+ }
625
+ await emit({
626
+ role: "assistant",
627
+ kind: "message",
628
+ content: status === "blocked"
629
+ ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
630
+ : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
631
+ eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
632
+ });
633
+ }
634
+ class LiveQaArtifactEmitter {
635
+ worktreePath;
636
+ workItemId;
637
+ emit;
638
+ emitted = false;
639
+ timer = null;
640
+ pending = Promise.resolve();
641
+ constructor(worktreePath, workItemId, emit) {
642
+ this.worktreePath = worktreePath;
643
+ this.workItemId = workItemId;
644
+ this.emit = emit;
645
+ }
646
+ start() {
647
+ void this.pollQueued();
648
+ this.timer = setInterval(() => {
649
+ void this.pollQueued();
650
+ }, 250);
651
+ }
652
+ async stop() {
653
+ if (this.timer) {
654
+ clearInterval(this.timer);
655
+ this.timer = null;
656
+ }
657
+ await this.pollQueued();
658
+ }
659
+ hasEmitted() {
660
+ return this.emitted;
661
+ }
662
+ pollQueued() {
663
+ this.pending = this.pending
664
+ .then(() => this.poll())
665
+ .catch(() => undefined);
666
+ return this.pending;
667
+ }
668
+ async poll() {
669
+ if (this.emitted) {
670
+ return;
671
+ }
672
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
673
+ if (!artifact) {
674
+ return;
675
+ }
676
+ this.emitted = true;
677
+ await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
678
+ await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
679
+ }
680
+ }
681
+ async function readJsonObjectFile(filePath) {
682
+ const content = await fs.readFile(filePath, "utf8").catch(() => "");
683
+ return parseJsonLine(content) ?? {};
684
+ }
685
+ function arrayField(source, key) {
686
+ const value = source[key];
687
+ if (!Array.isArray(value)) {
688
+ return [];
689
+ }
690
+ return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
691
+ }
692
+ function stringArrayField(source, key) {
693
+ const value = source[key];
694
+ if (!Array.isArray(value)) {
695
+ return [];
696
+ }
697
+ return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
698
+ }
699
+ function summarizeQaObject(source) {
700
+ return clip(stringField(source, "title")
701
+ ?? stringField(source, "summary")
702
+ ?? stringField(source, "id")
703
+ ?? JSON.stringify(source), 500);
704
+ }
705
+ function qaArtifactRelativePath(workItemId, fileName) {
706
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
707
+ }
708
+ function jsonText(value) {
709
+ return `${JSON.stringify(value, null, 2)}\n`;
710
+ }
711
+ async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
712
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
713
+ await emit({
714
+ role: "tool",
715
+ kind: "tool_result",
716
+ content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
717
+ eventType: "completion_tool_artifact_recorded"
718
+ });
719
+ }
720
+ async function emitPhaseCompletionEvent(emit, artifact) {
721
+ const phase = completionPhaseFromArtifact(artifact);
722
+ await emit({
723
+ role: "assistant",
724
+ kind: "message",
725
+ content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
726
+ eventType: phaseCompleteEventType(phase)
727
+ });
728
+ }
729
+ async function emitPhaseGateEvents(emit, artifact) {
730
+ const phase = completionPhaseFromArtifact(artifact);
731
+ const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
732
+ await emit({
733
+ role: "hook",
734
+ kind: "checkpoint",
735
+ content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
736
+ eventType: "phase_gate"
737
+ });
738
+ if (status !== "pass") {
739
+ return;
740
+ }
741
+ const progression = phase === "implementation"
742
+ ? "phase_progression: implementation -> self_review"
743
+ : phase === "self_review"
744
+ ? "phase_progression: self_review -> validation"
745
+ : "phase_progression: validation -> QA ready";
746
+ await emit({
747
+ role: "hook",
748
+ kind: "checkpoint",
749
+ content: progression,
750
+ eventType: "phase_gate"
751
+ });
752
+ }
753
+ function completionPhaseFromArtifact(artifact) {
754
+ const phase = artifact.phase?.trim();
755
+ return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
756
+ ? phase
757
+ : "implementation";
758
+ }
759
+ class LiveCompletionArtifactEmitter {
760
+ worktreePath;
761
+ workItemId;
762
+ emit;
763
+ phases;
764
+ emitted = new Set();
765
+ timer = null;
766
+ pending = Promise.resolve();
767
+ constructor(worktreePath, workItemId, phase, developCycle, emit) {
768
+ this.worktreePath = worktreePath;
769
+ this.workItemId = workItemId;
770
+ this.emit = emit;
771
+ this.phases = developCycle
772
+ ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
773
+ : [phase];
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(phase) {
789
+ return this.emitted.has(phase);
790
+ }
791
+ pollQueued() {
792
+ this.pending = this.pending
793
+ .then(() => this.poll())
794
+ .catch(() => undefined);
795
+ return this.pending;
796
+ }
797
+ async poll() {
798
+ for (const phase of this.phases) {
799
+ if (this.emitted.has(phase)) {
800
+ continue;
801
+ }
802
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
803
+ if (!artifact) {
804
+ return;
805
+ }
806
+ this.emitted.add(phase);
807
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
808
+ await emitPhaseCompletionEvent(this.emit, artifact);
809
+ await emitPhaseGateEvents(this.emit, artifact);
810
+ if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
811
+ return;
812
+ }
813
+ }
814
+ }
815
+ }
816
+ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle) {
817
+ if (!developCycle) {
818
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
819
+ if (!artifact) {
820
+ throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
821
+ }
822
+ return [artifact];
823
+ }
824
+ const artifacts = [];
825
+ for (const expectedPhase of ["implementation", "self_review", "validation"]) {
826
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
827
+ if (!artifact) {
828
+ if (artifacts.length === 0) {
829
+ throw new Error("Provider CLI completed but did not call the Forge implementation completion tool.");
830
+ }
831
+ const previous = artifacts[artifacts.length - 1];
832
+ if ((previous.status ?? "").trim().toLowerCase() === "pass") {
833
+ throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
834
+ }
835
+ return artifacts;
836
+ }
837
+ artifacts.push(artifact);
838
+ if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
839
+ return artifacts;
840
+ }
841
+ }
842
+ return artifacts;
843
+ }
844
+ function providerRedactionEnv(dispatch) {
845
+ const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
846
+ return Object.keys(env).length > 0 ? env : undefined;
847
+ }
848
+ function exactRedactionSecrets(dispatch) {
849
+ return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
850
+ }
851
+ async function emitProviderUsageEvent(emit, dispatch, outputState) {
852
+ const usage = outputState.usage;
853
+ if (hasUsage(usage)) {
854
+ await emit(buildProviderUsageEvent(dispatch, usage));
855
+ }
856
+ }
857
+ function estimatedDeterministicUsage() {
858
+ return addUsage(emptyUsage("estimated"), {
859
+ inputTokens: 1000,
860
+ outputTokens: 400,
861
+ source: "estimated"
862
+ });
863
+ }
321
864
  export class StreamingProviderProcessRunner {
322
865
  async run(request, handlers = {}, signal) {
323
866
  const launch = await resolveProviderProcessLaunch(request.command, request.args);
324
867
  return await new Promise((resolve, reject) => {
325
868
  const child = spawn(launch.command, launch.args, {
326
869
  cwd: request.cwd,
870
+ env: request.env ? { ...process.env, ...request.env } : undefined,
327
871
  stdio: ["ignore", "pipe", "pipe"],
328
872
  windowsHide: true
329
873
  });
@@ -392,6 +936,10 @@ async function resolveProviderProcessLaunch(command, args) {
392
936
  if (process.platform !== "win32") {
393
937
  return { command, args };
394
938
  }
939
+ const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
940
+ if (cursorDirect) {
941
+ return cursorDirect;
942
+ }
395
943
  const resolved = await resolveWindowsCommand(command);
396
944
  return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
397
945
  }
@@ -399,10 +947,6 @@ async function resolveWindowsCommand(command) {
399
947
  if (path.isAbsolute(command)) {
400
948
  return command;
401
949
  }
402
- const cursorScript = await resolveCursorAgentPowerShellScript(command);
403
- if (cursorScript) {
404
- return cursorScript;
405
- }
406
950
  try {
407
951
  const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
408
952
  return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
@@ -411,18 +955,6 @@ async function resolveWindowsCommand(command) {
411
955
  return null;
412
956
  }
413
957
  }
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
958
  export function chooseWindowsCommandCandidate(candidates) {
427
959
  const normalized = candidates
428
960
  .map((candidate) => candidate.trim())
@@ -519,10 +1051,12 @@ export function buildProviderCliCommand(dispatch, run) {
519
1051
  return { command: "codex", args };
520
1052
  }
521
1053
  if (normalizedProvider === "cursor") {
522
- const args = ["--model", model];
1054
+ const args = ["--print", "--output-format", "stream-json", "--model", model];
1055
+ if (run?.worktreePath) {
1056
+ args.push("--workspace", run.worktreePath);
1057
+ }
523
1058
  if (run?.prompt) {
524
- args.push("--yolo");
525
- args.push(run.prompt);
1059
+ args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
526
1060
  }
527
1061
  return { command: "cursor-agent", args };
528
1062
  }
@@ -545,20 +1079,54 @@ ${completionPromptForPhase(phase)}
545
1079
 
546
1080
  Finish with a concise summary of changed files and verification after calling the completion tool.`;
547
1081
  }
1082
+ function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1083
+ return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
1084
+
1085
+ 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.
1086
+ 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.
1087
+ Use the repository's existing conventions. Run relevant tests when practical.
1088
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
1089
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
1090
+
1091
+ ${completionPromptForDevelopCycle(phase)}
1092
+
1093
+ 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.`;
1094
+ }
548
1095
  function phaseWorkInstruction(phase) {
549
1096
  if (phase === "self_review") {
550
1097
  return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
551
1098
  }
552
1099
  if (phase === "validation") {
553
- return "Run the validation commands and deterministic drift checks needed to prove the work is ready for Dev Test.";
1100
+ return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
554
1101
  }
555
1102
  return "Implement the work item and keep the change focused.";
556
1103
  }
557
1104
  function buildQaPrompt(dispatch) {
558
- return `You are Forge's QA lane running locally.
1105
+ return `You are Forge's QA lane running locally in a prepared git worktree.
1106
+
1107
+ Work item: ${dispatch.workItem.id}
1108
+ Title: ${dispatch.workItem.title}
1109
+ Description:
1110
+ ${dispatch.workItem.description || "Not provided."}
1111
+
1112
+ Acceptance criteria:
1113
+ ${dispatch.workItem.acceptanceCriteria || "Not specified."}
1114
+
1115
+ Repro steps / scenario:
1116
+ ${dispatch.workItem.reproSteps || "Not provided."}
1117
+
1118
+ System info / environment notes:
1119
+ ${dispatch.workItem.systemInfo || "Not provided."}
1120
+
1121
+ Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1122
+ QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
1123
+ Record concrete evidence. For UI/browser work, include browser_checks with URLs, actions, observed results, screenshots/traces when available, and console/network notes.
1124
+ Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
1125
+ Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
559
1126
 
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.`;
1127
+ ${completionPromptForPhase("qa")}
1128
+
1129
+ Finish with a concise summary only after forge.complete_qa accepts the QA bundle.`;
562
1130
  }
563
1131
  function buildConflictResolvePrompt(dispatch, branchName) {
564
1132
  const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
@@ -611,27 +1179,227 @@ function clip(value, maxLength) {
611
1179
  }
612
1180
  return `${value.slice(0, maxLength)}...`;
613
1181
  }
614
- class CodexJsonState {
615
- threadId = null;
1182
+ function createProviderOutputState(provider) {
1183
+ return provider.trim().toLowerCase() === "cursor"
1184
+ ? new CursorStreamJsonState()
1185
+ : new CodexJsonState();
1186
+ }
1187
+ class CursorStreamJsonState {
1188
+ sessionId = null;
616
1189
  finalMessage = null;
617
- emittedThread = false;
1190
+ emittedSession = false;
1191
+ accumulatedUsage = null;
1192
+ get sessionLabel() {
1193
+ return this.sessionId ? `session ${this.sessionId}` : null;
1194
+ }
1195
+ get usage() {
1196
+ return this.accumulatedUsage;
1197
+ }
618
1198
  consume(line) {
619
- const trimmed = line.trim();
620
- if (!trimmed.startsWith("{")) {
1199
+ const event = parseJsonLine(line);
1200
+ if (!event) {
621
1201
  return null;
622
1202
  }
623
- let parsed;
624
- try {
625
- parsed = JSON.parse(trimmed);
1203
+ const type = stringField(event, "type");
1204
+ if (type === "system" && stringField(event, "subtype") === "init") {
1205
+ this.sessionId = stringField(event, "session_id");
1206
+ if (this.sessionId && !this.emittedSession) {
1207
+ this.emittedSession = true;
1208
+ return {
1209
+ role: "runner",
1210
+ kind: "checkpoint",
1211
+ content: `Cursor session started: ${this.sessionId}.`,
1212
+ eventType: "provider_thread_started"
1213
+ };
1214
+ }
1215
+ }
1216
+ if (type === "assistant") {
1217
+ const text = assistantMessageText(event);
1218
+ if (text) {
1219
+ this.finalMessage = clip(text, 4000);
1220
+ return {
1221
+ role: "assistant",
1222
+ kind: "message",
1223
+ content: this.finalMessage,
1224
+ eventType: "provider_message"
1225
+ };
1226
+ }
626
1227
  }
627
- catch {
1228
+ if (type === "tool_call") {
1229
+ const subtype = stringField(event, "subtype");
1230
+ const toolCall = objectField(event, "tool_call");
1231
+ if (subtype === "started") {
1232
+ const summary = formatCursorToolCallStarted(toolCall);
1233
+ if (summary) {
1234
+ return {
1235
+ role: "worker",
1236
+ kind: "checkpoint",
1237
+ content: summary,
1238
+ eventType: "provider_tool_call"
1239
+ };
1240
+ }
1241
+ }
1242
+ if (subtype === "completed") {
1243
+ const completed = formatCursorToolCallCompleted(toolCall);
1244
+ if (completed) {
1245
+ return {
1246
+ role: "worker",
1247
+ kind: completed.kind,
1248
+ content: completed.content,
1249
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
1250
+ };
1251
+ }
1252
+ }
1253
+ }
1254
+ if (type === "result" && stringField(event, "subtype") === "success") {
1255
+ const result = stringField(event, "result");
1256
+ if (result) {
1257
+ this.finalMessage = clip(result, 4000);
1258
+ }
1259
+ this.accumulateUsage(event);
1260
+ }
1261
+ if (type === "error" || (type === "result" && event.is_error === true)) {
1262
+ return {
1263
+ role: "runner",
1264
+ kind: "error",
1265
+ content: clip(line.trim(), 1000),
1266
+ eventType: "provider_cli_error"
1267
+ };
1268
+ }
1269
+ return null;
1270
+ }
1271
+ accumulateUsage(event) {
1272
+ const usage = objectField(event, "usage");
1273
+ const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
1274
+ if (Object.keys(usage).length === 0 && durationMs === 0) {
1275
+ return;
1276
+ }
1277
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
1278
+ inputTokens: readUsageNumber(usage, "inputTokens"),
1279
+ outputTokens: readUsageNumber(usage, "outputTokens"),
1280
+ cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
1281
+ cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
1282
+ providerDurationMs: durationMs > 0 ? durationMs : null,
1283
+ source: "provider_reported"
1284
+ });
1285
+ }
1286
+ }
1287
+ function formatCursorToolCallStarted(toolCall) {
1288
+ const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
1289
+ const readPath = stringField(readArgs, "path");
1290
+ if (readPath) {
1291
+ return `Reading ${readPath}`;
1292
+ }
1293
+ const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
1294
+ const writePath = stringField(writeArgs, "path");
1295
+ if (writePath) {
1296
+ return `Writing ${writePath}`;
1297
+ }
1298
+ const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
1299
+ const command = stringField(shellArgs, "command");
1300
+ if (command) {
1301
+ return `Shell command started: ${clip(command, 500)}`;
1302
+ }
1303
+ const fn = objectField(toolCall, "function");
1304
+ const name = stringField(fn, "name");
1305
+ if (name) {
1306
+ return `Tool call started: ${name}`;
1307
+ }
1308
+ return null;
1309
+ }
1310
+ function formatCursorToolCallCompleted(toolCall) {
1311
+ const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
1312
+ const writePath = stringField(writeArgs, "path");
1313
+ const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
1314
+ const writtenPath = stringField(writeResult, "path") ?? writePath;
1315
+ if (writtenPath) {
1316
+ return {
1317
+ kind: "file_edit",
1318
+ content: `Wrote ${writtenPath}`
1319
+ };
1320
+ }
1321
+ const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
1322
+ const readPath = stringField(readArgs, "path");
1323
+ if (readPath) {
1324
+ const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
1325
+ const totalLines = readResult.totalLines;
1326
+ const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
1327
+ return {
1328
+ kind: "checkpoint",
1329
+ content: `Read ${readPath}${lineSummary}`
1330
+ };
1331
+ }
1332
+ const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
1333
+ const command = stringField(shellArgs, "command");
1334
+ if (command) {
1335
+ return {
1336
+ kind: "checkpoint",
1337
+ content: `Shell command completed: ${clip(command, 500)}`
1338
+ };
1339
+ }
1340
+ const fn = objectField(toolCall, "function");
1341
+ const name = stringField(fn, "name");
1342
+ if (name) {
1343
+ return {
1344
+ kind: "checkpoint",
1345
+ content: `Tool call completed: ${name}`
1346
+ };
1347
+ }
1348
+ return null;
1349
+ }
1350
+ function assistantMessageText(event) {
1351
+ const message = objectField(event, "message");
1352
+ const content = message.content;
1353
+ if (!Array.isArray(content)) {
1354
+ return null;
1355
+ }
1356
+ const parts = content
1357
+ .map((entry) => {
1358
+ if (!entry || typeof entry !== "object") {
628
1359
  return null;
629
1360
  }
630
- if (!parsed || typeof parsed !== "object") {
1361
+ const block = entry;
1362
+ return stringField(block, "text");
1363
+ })
1364
+ .filter((text) => Boolean(text));
1365
+ if (parts.length === 0) {
1366
+ return null;
1367
+ }
1368
+ return parts.join("");
1369
+ }
1370
+ function parseJsonLine(line) {
1371
+ const trimmed = line.trim();
1372
+ if (!trimmed.startsWith("{")) {
1373
+ return null;
1374
+ }
1375
+ let parsed;
1376
+ try {
1377
+ parsed = JSON.parse(trimmed);
1378
+ }
1379
+ catch {
1380
+ return null;
1381
+ }
1382
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
1383
+ ? parsed
1384
+ : null;
1385
+ }
1386
+ class CodexJsonState {
1387
+ threadId = null;
1388
+ finalMessage = null;
1389
+ emittedThread = false;
1390
+ accumulatedUsage = null;
1391
+ get sessionLabel() {
1392
+ return this.threadId ? `thread ${this.threadId}` : null;
1393
+ }
1394
+ get usage() {
1395
+ return this.accumulatedUsage;
1396
+ }
1397
+ consume(line) {
1398
+ const event = parseJsonLine(line);
1399
+ if (!event) {
631
1400
  return null;
632
1401
  }
633
- const event = parsed;
634
- const type = typeof event.type === "string" ? event.type : "";
1402
+ const type = stringField(event, "type") ?? "";
635
1403
  if (type === "thread.started") {
636
1404
  this.threadId = stringField(event, "thread_id");
637
1405
  if (this.threadId && !this.emittedThread) {
@@ -645,6 +1413,7 @@ class CodexJsonState {
645
1413
  }
646
1414
  }
647
1415
  if (type === "turn.completed") {
1416
+ this.accumulateUsage(event);
648
1417
  return {
649
1418
  role: "runner",
650
1419
  kind: "checkpoint",
@@ -656,7 +1425,7 @@ class CodexJsonState {
656
1425
  return {
657
1426
  role: "runner",
658
1427
  kind: "error",
659
- content: clip(trimmed, 1000),
1428
+ content: clip(line.trim(), 1000),
660
1429
  eventType: "provider_cli_error"
661
1430
  };
662
1431
  }
@@ -690,6 +1459,19 @@ class CodexJsonState {
690
1459
  }
691
1460
  return null;
692
1461
  }
1462
+ accumulateUsage(event) {
1463
+ const usage = objectField(event, "usage");
1464
+ if (Object.keys(usage).length === 0) {
1465
+ return;
1466
+ }
1467
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
1468
+ inputTokens: readUsageNumber(usage, "input_tokens"),
1469
+ outputTokens: readUsageNumber(usage, "output_tokens"),
1470
+ cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
1471
+ reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
1472
+ source: "provider_reported"
1473
+ });
1474
+ }
693
1475
  }
694
1476
  function objectField(source, key) {
695
1477
  const value = source[key];
@@ -701,3 +1483,6 @@ function stringField(source, key) {
701
1483
  const value = source[key];
702
1484
  return typeof value === "string" && value.trim().length > 0 ? value : null;
703
1485
  }
1486
+ function isNodeError(error) {
1487
+ return error instanceof Error && "code" in error;
1488
+ }