@loucompanion/forge-bridge 0.1.1-dev.615630fb4618 → 0.1.1-dev.65ea6889412c

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.
@@ -7,9 +7,11 @@ import { promisify } from "node:util";
7
7
  import { GitClient } from "../../shared/git/git.js";
8
8
  import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
9
9
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
10
- import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForPhase, completionRedactionEnv, expectedCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, writeCompletionArtifact } 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";
11
12
  const fakeWorkerModel = "server-local-fake-worker";
12
13
  const execFileAsync = promisify(execFile);
14
+ const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
13
15
  export class RoutingProviderCliService {
14
16
  realProvider;
15
17
  deterministicProvider;
@@ -27,10 +29,10 @@ export class RoutingProviderCliService {
27
29
  ? await this.deterministicProvider.runConflictResolve(context)
28
30
  : await this.realProvider.runConflictResolve(context);
29
31
  }
30
- async runQa(dispatch, emit, signal) {
31
- return isFakeWorkerModel(dispatch.execution.model)
32
- ? await this.deterministicProvider.runQa(dispatch, emit, signal)
33
- : await this.realProvider.runQa(dispatch, emit, signal);
32
+ async runQa(context) {
33
+ return isFakeWorkerModel(context.dispatch.execution.model)
34
+ ? await this.deterministicProvider.runQa(context)
35
+ : await this.realProvider.runQa(context);
34
36
  }
35
37
  }
36
38
  export class ProcessBackedProviderCliService {
@@ -43,6 +45,7 @@ export class ProcessBackedProviderCliService {
43
45
  async runImplementation(context) {
44
46
  const { dispatch, worktree } = context;
45
47
  const phase = completionPhaseFromDispatch(dispatch);
48
+ const developCycle = usesDevelopCycleCompletion(dispatch);
46
49
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
47
50
  await fs.mkdir(metadataRoot, { recursive: true });
48
51
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -56,7 +59,7 @@ export class ProcessBackedProviderCliService {
56
59
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
57
60
  const command = buildProviderCliCommand(dispatch, {
58
61
  worktreePath: worktree.worktreePath,
59
- prompt: buildImplementationPrompt(dispatch, phase),
62
+ prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
60
63
  completionTools
61
64
  });
62
65
  await context.emit({
@@ -68,12 +71,16 @@ export class ProcessBackedProviderCliService {
68
71
  await context.emit({
69
72
  role: "runner",
70
73
  kind: "checkpoint",
71
- 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.`,
72
77
  eventType: "completion_tools_configured"
73
78
  });
74
79
  const outputState = createProviderOutputState(dispatch.execution.provider);
80
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, context.emit);
75
81
  let result;
76
82
  try {
83
+ liveCompletionEvents.start();
77
84
  result = await this.processRunner.run({
78
85
  command: command.command,
79
86
  args: command.args,
@@ -89,6 +96,7 @@ export class ProcessBackedProviderCliService {
89
96
  }, context.signal);
90
97
  }
91
98
  finally {
99
+ await liveCompletionEvents.stop();
92
100
  await cleanupCompletionTools(completionTools, context.emit);
93
101
  }
94
102
  if (result.exitCode !== 0) {
@@ -101,18 +109,23 @@ export class ProcessBackedProviderCliService {
101
109
  content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
102
110
  eventType: "provider_cli_completed"
103
111
  });
112
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
104
113
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
105
- const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, phase);
106
- if (!completionArtifact) {
107
- 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
+ }
108
121
  }
109
- await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
122
+ const completionArtifact = completionArtifacts[0];
110
123
  if (outputState.finalMessage) {
111
124
  await context.emit({
112
125
  role: "assistant",
113
126
  kind: "message",
114
127
  content: outputState.finalMessage,
115
- eventType: phaseCompleteEventType(phase)
128
+ eventType: "provider_final_message"
116
129
  });
117
130
  }
118
131
  else {
@@ -120,11 +133,11 @@ export class ProcessBackedProviderCliService {
120
133
  role: "assistant",
121
134
  kind: "message",
122
135
  content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
123
- eventType: phaseCompleteEventType(phase)
136
+ eventType: "provider_final_message"
124
137
  });
125
138
  }
126
139
  return {
127
- 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)}).`,
128
141
  spec: {
129
142
  repoPath: worktree.worktreePath,
130
143
  path: specPath,
@@ -132,44 +145,86 @@ export class ProcessBackedProviderCliService {
132
145
  producedBy: "forge-lane-command",
133
146
  status: "approved"
134
147
  },
135
- artifact: completionArtifact
148
+ artifact: completionArtifact,
149
+ artifacts: completionArtifacts
136
150
  };
137
151
  }
138
- async runQa(dispatch, emit, signal) {
152
+ async runQa(context) {
153
+ const { dispatch, worktree } = context;
154
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
139
155
  const command = buildProviderCliCommand(dispatch, {
140
- prompt: buildQaPrompt(dispatch)
156
+ worktreePath: worktree.worktreePath,
157
+ prompt: buildQaPrompt(dispatch),
158
+ completionTools
141
159
  });
142
- await emit({
160
+ const commandText = formatProviderCliCommand(command);
161
+ await context.emit({
143
162
  role: "runner",
144
163
  kind: "checkpoint",
145
- content: `Starting provider CLI QA: ${formatProviderCliCommand(command)}`,
164
+ content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
146
165
  eventType: "provider_cli_started"
147
166
  });
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
+ });
148
173
  const outputState = createProviderOutputState(dispatch.execution.provider);
149
- const result = await this.processRunner.run({
150
- command: command.command,
151
- args: command.args,
152
- cwd: process.cwd()
153
- }, {
154
- onStdoutLine: async (line) => {
155
- const event = outputState.consume(line);
156
- if (event) {
157
- await emit(event);
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
+ }
158
189
  }
159
- }
160
- }, signal);
190
+ }, context.signal);
191
+ }
192
+ finally {
193
+ await liveQaEvents.stop();
194
+ await cleanupCompletionTools(completionTools, context.emit);
195
+ }
161
196
  if (result.exitCode !== 0) {
162
197
  const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
163
198
  throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
164
199
  }
165
- await emit({
200
+ await context.emit({
166
201
  role: "runner",
167
202
  kind: "checkpoint",
168
203
  content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
169
204
  eventType: "provider_cli_completed"
170
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";
171
224
  return {
172
- summary: `${dispatch.execution.provider} CLI QA passed.`
225
+ summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
226
+ artifact: qaArtifact,
227
+ artifacts: [qaArtifact]
173
228
  };
174
229
  }
175
230
  async runConflictResolve(context) {
@@ -203,6 +258,7 @@ export class ProcessBackedProviderCliService {
203
258
  }
204
259
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
205
260
  await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
261
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
206
262
  await context.emit({
207
263
  role: "assistant",
208
264
  kind: "message",
@@ -222,6 +278,7 @@ export class DeterministicProviderCliService {
222
278
  async runImplementation(context) {
223
279
  const { dispatch, worktree } = context;
224
280
  const phase = completionPhaseFromDispatch(dispatch);
281
+ const developCycle = usesDevelopCycleCompletion(dispatch);
225
282
  const providerCommand = buildProviderCliCommand(dispatch);
226
283
  const providerCommandText = formatProviderCliCommand(providerCommand);
227
284
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -252,26 +309,34 @@ export class DeterministicProviderCliService {
252
309
  content: `Created bridge changeset at ${changesetPath}`,
253
310
  eventType: "changeset"
254
311
  });
255
- await writeCompletionArtifact({
256
- worktreePath: worktree.worktreePath,
257
- workItemId: dispatch.workItem.id,
258
- phase,
259
- producedBy: "forge-bridge",
260
- redactionSecrets: exactRedactionSecrets(dispatch)
261
- }, expectedCompletionToolName(phase), deterministicCompletionPayload(phase, dispatch, changesetBody));
262
- const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, phase);
263
- if (!completionArtifact) {
264
- throw new Error(`Deterministic provider did not produce the Forge ${phase} completion artifact.`);
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
+ });
265
336
  }
266
- await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
267
- await context.emit({
268
- role: "assistant",
269
- kind: "message",
270
- content: `${phase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
271
- eventType: phaseCompleteEventType(phase)
272
- });
337
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
273
338
  return {
274
- summary: `forge-bridge completed ${worktree.branchName} (${phase}).`,
339
+ summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
275
340
  spec: {
276
341
  repoPath: worktree.worktreePath,
277
342
  path: specPath,
@@ -279,29 +344,42 @@ export class DeterministicProviderCliService {
279
344
  producedBy: "forge-lane-command",
280
345
  status: "approved"
281
346
  },
282
- artifact: completionArtifact
347
+ artifact: completionArtifacts[0],
348
+ artifacts: completionArtifacts
283
349
  };
284
350
  }
285
- async runQa(dispatch, emit) {
286
- await emit({
351
+ async runQa(context) {
352
+ const { dispatch, worktree } = context;
353
+ await context.emit({
287
354
  role: "worker",
288
355
  kind: "message",
289
- content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
290
- eventType: "qa_analysis"
356
+ content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
357
+ eventType: "qa_plan"
291
358
  });
292
- await emit({
293
- role: "assistant",
294
- kind: "message",
295
- content: "All checks passed. forge-bridge QA completed.",
296
- 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
297
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()));
298
373
  return {
299
- summary: "forge-bridge QA passed."
374
+ summary: "forge-bridge QA passed.",
375
+ artifact: qaArtifact,
376
+ artifacts: [qaArtifact]
300
377
  };
301
378
  }
302
379
  async runConflictResolve(context) {
303
380
  const { dispatch, worktree } = context;
304
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()));
305
383
  await context.emit({
306
384
  role: "assistant",
307
385
  kind: "message",
@@ -398,6 +476,238 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
398
476
  ready_for_dev_test: true
399
477
  };
400
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
+ }
401
711
  async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
402
712
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
403
713
  await emit({
@@ -407,6 +717,130 @@ async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
407
717
  eventType: "completion_tool_artifact_recorded"
408
718
  });
409
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
+ }
410
844
  function providerRedactionEnv(dispatch) {
411
845
  const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
412
846
  return Object.keys(env).length > 0 ? env : undefined;
@@ -414,6 +848,19 @@ function providerRedactionEnv(dispatch) {
414
848
  function exactRedactionSecrets(dispatch) {
415
849
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
416
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
+ }
417
864
  export class StreamingProviderProcessRunner {
418
865
  async run(request, handlers = {}, signal) {
419
866
  const launch = await resolveProviderProcessLaunch(request.command, request.args);
@@ -624,6 +1071,7 @@ function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch
624
1071
 
625
1072
  Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
626
1073
  ${phaseWorkInstruction(phase)}
1074
+ ${qaReworkImplementationInstruction(dispatch)}
627
1075
  Use the repository's existing conventions. Run relevant tests when practical.
628
1076
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
629
1077
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -632,20 +1080,78 @@ ${completionPromptForPhase(phase)}
632
1080
 
633
1081
  Finish with a concise summary of changed files and verification after calling the completion tool.`;
634
1082
  }
1083
+ function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1084
+ return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
1085
+
1086
+ 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.
1087
+ 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.
1088
+ ${qaReworkImplementationInstruction(dispatch)}
1089
+ Use the repository's existing conventions. Run relevant tests when practical.
1090
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
1091
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
1092
+
1093
+ ${completionPromptForDevelopCycle(phase)}
1094
+
1095
+ 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.`;
1096
+ }
1097
+ function qaReworkImplementationInstruction(dispatch) {
1098
+ if (!dispatch.qaRework) {
1099
+ return "";
1100
+ }
1101
+ return `
1102
+ QA rework context:
1103
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1104
+ - Rework packet: ${dispatch.qaRework.packetPath}
1105
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1106
+ 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.`;
1107
+ }
1108
+ function qaReworkRetestInstruction(dispatch) {
1109
+ if (!dispatch.qaRework) {
1110
+ return "";
1111
+ }
1112
+ return `
1113
+ QA retest context:
1114
+ - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1115
+ - Rework packet: ${dispatch.qaRework.packetPath}
1116
+ - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1117
+ Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
1118
+ }
635
1119
  function phaseWorkInstruction(phase) {
636
1120
  if (phase === "self_review") {
637
1121
  return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
638
1122
  }
639
1123
  if (phase === "validation") {
640
- return "Run the validation commands and deterministic drift checks needed to prove the work is ready for Dev Test.";
1124
+ return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
641
1125
  }
642
1126
  return "Implement the work item and keep the change focused.";
643
1127
  }
644
1128
  function buildQaPrompt(dispatch) {
645
- return `You are Forge's QA lane running locally.
1129
+ return `You are Forge's QA lane running locally in a prepared git worktree.
1130
+
1131
+ Work item: ${dispatch.workItem.id}
1132
+ Title: ${dispatch.workItem.title}
1133
+ Description:
1134
+ ${dispatch.workItem.description || "Not provided."}
1135
+
1136
+ Acceptance criteria:
1137
+ ${dispatch.workItem.acceptanceCriteria || "Not specified."}
1138
+
1139
+ Repro steps / scenario:
1140
+ ${dispatch.workItem.reproSteps || "Not provided."}
646
1141
 
647
- Review the implementation for work item ${dispatch.workItem.id}: ${dispatch.workItem.title}
648
- Run relevant verification when practical and finish with a concise QA verdict.`;
1142
+ System info / environment notes:
1143
+ ${dispatch.workItem.systemInfo || "Not provided."}
1144
+
1145
+ Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1146
+ ${qaReworkRetestInstruction(dispatch)}
1147
+ QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
1148
+ Record concrete evidence. For UI/browser work, include browser_checks with URLs, actions, observed results, screenshots/traces when available, and console/network notes.
1149
+ Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
1150
+ Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
1151
+
1152
+ ${completionPromptForPhase("qa")}
1153
+
1154
+ Finish with a concise summary only after forge.complete_qa accepts the QA bundle.`;
649
1155
  }
650
1156
  function buildConflictResolvePrompt(dispatch, branchName) {
651
1157
  const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
@@ -707,9 +1213,13 @@ class CursorStreamJsonState {
707
1213
  sessionId = null;
708
1214
  finalMessage = null;
709
1215
  emittedSession = false;
1216
+ accumulatedUsage = null;
710
1217
  get sessionLabel() {
711
1218
  return this.sessionId ? `session ${this.sessionId}` : null;
712
1219
  }
1220
+ get usage() {
1221
+ return this.accumulatedUsage;
1222
+ }
713
1223
  consume(line) {
714
1224
  const event = parseJsonLine(line);
715
1225
  if (!event) {
@@ -771,6 +1281,7 @@ class CursorStreamJsonState {
771
1281
  if (result) {
772
1282
  this.finalMessage = clip(result, 4000);
773
1283
  }
1284
+ this.accumulateUsage(event);
774
1285
  }
775
1286
  if (type === "error" || (type === "result" && event.is_error === true)) {
776
1287
  return {
@@ -782,6 +1293,21 @@ class CursorStreamJsonState {
782
1293
  }
783
1294
  return null;
784
1295
  }
1296
+ accumulateUsage(event) {
1297
+ const usage = objectField(event, "usage");
1298
+ const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
1299
+ if (Object.keys(usage).length === 0 && durationMs === 0) {
1300
+ return;
1301
+ }
1302
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
1303
+ inputTokens: readUsageNumber(usage, "inputTokens"),
1304
+ outputTokens: readUsageNumber(usage, "outputTokens"),
1305
+ cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
1306
+ cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
1307
+ providerDurationMs: durationMs > 0 ? durationMs : null,
1308
+ source: "provider_reported"
1309
+ });
1310
+ }
785
1311
  }
786
1312
  function formatCursorToolCallStarted(toolCall) {
787
1313
  const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
@@ -886,9 +1412,13 @@ class CodexJsonState {
886
1412
  threadId = null;
887
1413
  finalMessage = null;
888
1414
  emittedThread = false;
1415
+ accumulatedUsage = null;
889
1416
  get sessionLabel() {
890
1417
  return this.threadId ? `thread ${this.threadId}` : null;
891
1418
  }
1419
+ get usage() {
1420
+ return this.accumulatedUsage;
1421
+ }
892
1422
  consume(line) {
893
1423
  const event = parseJsonLine(line);
894
1424
  if (!event) {
@@ -908,6 +1438,7 @@ class CodexJsonState {
908
1438
  }
909
1439
  }
910
1440
  if (type === "turn.completed") {
1441
+ this.accumulateUsage(event);
911
1442
  return {
912
1443
  role: "runner",
913
1444
  kind: "checkpoint",
@@ -953,6 +1484,19 @@ class CodexJsonState {
953
1484
  }
954
1485
  return null;
955
1486
  }
1487
+ accumulateUsage(event) {
1488
+ const usage = objectField(event, "usage");
1489
+ if (Object.keys(usage).length === 0) {
1490
+ return;
1491
+ }
1492
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
1493
+ inputTokens: readUsageNumber(usage, "input_tokens"),
1494
+ outputTokens: readUsageNumber(usage, "output_tokens"),
1495
+ cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
1496
+ reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
1497
+ source: "provider_reported"
1498
+ });
1499
+ }
956
1500
  }
957
1501
  function objectField(source, key) {
958
1502
  const value = source[key];
@@ -964,3 +1508,6 @@ function stringField(source, key) {
964
1508
  const value = source[key];
965
1509
  return typeof value === "string" && value.trim().length > 0 ? value : null;
966
1510
  }
1511
+ function isNodeError(error) {
1512
+ return error instanceof Error && "code" in error;
1513
+ }