@loucompanion/forge-bridge 0.1.1-dev.7d43998c4521 → 0.1.1-dev.895607f4402a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +1 -0
  2. package/dist/bridge/bridge.service.js +84 -12
  3. package/dist/bridge/bridge.types.d.ts +16 -0
  4. package/dist/cli/cli.service.d.ts +27 -2
  5. package/dist/cli/cli.service.js +406 -16
  6. package/dist/cli/local-config.d.ts +4 -1
  7. package/dist/cli/local-config.js +60 -8
  8. package/dist/session/index.d.ts +2 -0
  9. package/dist/session/index.js +1 -0
  10. package/dist/session/internals.d.ts +5 -3
  11. package/dist/session/internals.js +2 -1
  12. package/dist/session/phase-completion.d.ts +111 -0
  13. package/dist/session/phase-completion.js +2350 -0
  14. package/dist/session/provider-cli/index.d.ts +2 -2
  15. package/dist/session/provider-cli/index.js +1 -1
  16. package/dist/session/provider-cli/provider-cli.base.d.ts +2 -2
  17. package/dist/session/provider-cli/provider-cli.service.d.ts +48 -3
  18. package/dist/session/provider-cli/provider-cli.service.js +1807 -48
  19. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  20. package/dist/session/provider-cli/provider-usage.d.ts +25 -0
  21. package/dist/session/provider-cli/provider-usage.js +64 -0
  22. package/dist/session/qa-sidecar-validation.d.ts +3 -0
  23. package/dist/session/qa-sidecar-validation.js +44 -0
  24. package/dist/session/session.service.js +57 -12
  25. package/dist/session/session.types.d.ts +66 -0
  26. package/dist/session/session.types.js +165 -2
  27. package/dist/shared/cursor-agent/cursor-agent.launch.d.ts +9 -0
  28. package/dist/shared/cursor-agent/cursor-agent.launch.js +66 -0
  29. package/dist/version.d.ts +1 -1
  30. package/dist/version.js +1 -1
  31. package/dist/worktree/artifact-injector.d.ts +12 -0
  32. package/dist/worktree/artifact-injector.js +133 -0
  33. package/dist/worktree/dependency-warmer.d.ts +32 -0
  34. package/dist/worktree/dependency-warmer.js +297 -0
  35. package/dist/worktree/index.d.ts +2 -0
  36. package/dist/worktree/index.js +1 -0
  37. package/dist/worktree/worktree.service.d.ts +4 -0
  38. package/dist/worktree/worktree.service.js +175 -11
  39. package/dist/worktree/worktree.types.d.ts +7 -1
  40. package/package.json +8 -3
@@ -1,7 +1,308 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { execFile, spawn } from "node:child_process";
5
+ import readline from "node:readline";
6
+ import { promisify } from "node:util";
4
7
  import { GitClient } from "../../shared/git/git.js";
8
+ import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
9
+ import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
10
+ import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
11
+ import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDebugCycle, completionPromptForDevelopCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, debugCompletionPhaseOrder, qaCompletionGateOrder } from "../phase-completion.js";
12
+ import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
13
+ const fakeWorkerModel = "server-local-fake-worker";
14
+ const execFileAsync = promisify(execFile);
15
+ const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
16
+ export class RoutingProviderCliService {
17
+ realProvider;
18
+ deterministicProvider;
19
+ constructor(realProvider = new ProcessBackedProviderCliService(), deterministicProvider = new DeterministicProviderCliService()) {
20
+ this.realProvider = realProvider;
21
+ this.deterministicProvider = deterministicProvider;
22
+ }
23
+ async runImplementation(context) {
24
+ return isFakeWorkerModel(context.dispatch.execution.model)
25
+ ? await this.deterministicProvider.runImplementation(context)
26
+ : await this.realProvider.runImplementation(context);
27
+ }
28
+ async runConflictResolve(context) {
29
+ return isFakeWorkerModel(context.dispatch.execution.model)
30
+ ? await this.deterministicProvider.runConflictResolve(context)
31
+ : await this.realProvider.runConflictResolve(context);
32
+ }
33
+ async runQa(context) {
34
+ return isFakeWorkerModel(context.dispatch.execution.model)
35
+ ? await this.deterministicProvider.runQa(context)
36
+ : await this.realProvider.runQa(context);
37
+ }
38
+ }
39
+ export class ProcessBackedProviderCliService {
40
+ processRunner;
41
+ git;
42
+ constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient()) {
43
+ this.processRunner = processRunner;
44
+ this.git = git;
45
+ }
46
+ async runImplementation(context) {
47
+ const { dispatch, worktree } = context;
48
+ const phase = completionPhaseFromDispatch(dispatch);
49
+ const developCycle = usesDevelopCycleCompletion(dispatch);
50
+ const debugCycle = usesDebugCycleCompletion(dispatch);
51
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
52
+ await fs.mkdir(metadataRoot, { recursive: true });
53
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
54
+ if (!laneCommand) {
55
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
56
+ }
57
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem, phase);
58
+ const specPath = path.join(metadataRoot, "spec.md");
59
+ await fs.writeFile(specPath, specBody, "utf8");
60
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
61
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
62
+ const command = buildProviderCliCommand(dispatch, {
63
+ worktreePath: worktree.worktreePath,
64
+ prompt: debugCycle
65
+ ? buildDebugCyclePrompt(dispatch, phase)
66
+ : developCycle
67
+ ? buildDevelopCyclePrompt(dispatch, phase)
68
+ : buildImplementationPrompt(dispatch, phase),
69
+ completionTools
70
+ });
71
+ await context.emit({
72
+ role: "runner",
73
+ kind: "checkpoint",
74
+ content: `Starting provider CLI: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
75
+ eventType: "provider_cli_started"
76
+ });
77
+ await context.emit({
78
+ role: "runner",
79
+ kind: "checkpoint",
80
+ content: debugCycle
81
+ ? "Forge Debug completion tools configured for debug_repro -> debug_root_cause -> debug_fix -> debug_regression; provider must call each MCP completion tool before exit."
82
+ : developCycle
83
+ ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
84
+ : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
85
+ eventType: "completion_tools_configured"
86
+ });
87
+ const outputState = createProviderOutputState(dispatch.execution.provider);
88
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
89
+ let result;
90
+ try {
91
+ liveCompletionEvents.start();
92
+ result = await this.processRunner.run({
93
+ command: command.command,
94
+ args: command.args,
95
+ cwd: worktree.worktreePath,
96
+ env: providerRedactionEnv(dispatch)
97
+ }, {
98
+ onStdoutLine: async (line) => {
99
+ const event = outputState.consume(line);
100
+ if (event) {
101
+ await context.emit(event);
102
+ }
103
+ }
104
+ }, context.signal);
105
+ }
106
+ finally {
107
+ await liveCompletionEvents.stop();
108
+ await cleanupCompletionTools(completionTools, context.emit);
109
+ }
110
+ if (result.exitCode !== 0) {
111
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
112
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
113
+ }
114
+ await context.emit({
115
+ role: "runner",
116
+ kind: "checkpoint",
117
+ content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
118
+ eventType: "provider_cli_completed"
119
+ });
120
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
121
+ const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
122
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
123
+ for (const artifact of completionArtifacts) {
124
+ if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
125
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
126
+ await emitPhaseCompletionEvent(context.emit, artifact);
127
+ await emitPhaseGateEvents(context.emit, artifact);
128
+ }
129
+ }
130
+ const completionArtifact = completionArtifacts[0];
131
+ if (outputState.finalMessage) {
132
+ await context.emit({
133
+ role: "assistant",
134
+ kind: "message",
135
+ content: outputState.finalMessage,
136
+ eventType: "provider_final_message"
137
+ });
138
+ }
139
+ else {
140
+ await context.emit({
141
+ role: "assistant",
142
+ kind: "message",
143
+ content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
144
+ eventType: "provider_final_message"
145
+ });
146
+ }
147
+ return {
148
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
149
+ spec: {
150
+ repoPath: worktree.worktreePath,
151
+ path: specPath,
152
+ body: specBody,
153
+ producedBy: "forge-lane-command",
154
+ status: "approved"
155
+ },
156
+ artifact: completionArtifact,
157
+ artifacts: completionArtifacts
158
+ };
159
+ }
160
+ async runQa(context) {
161
+ const { dispatch, worktree } = context;
162
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
163
+ await fs.mkdir(metadataRoot, { recursive: true });
164
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
165
+ if (!laneCommand) {
166
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
167
+ }
168
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem, "qa");
169
+ const specPath = path.join(metadataRoot, "spec.md");
170
+ await fs.writeFile(specPath, specBody, "utf8");
171
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
172
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
173
+ const command = buildProviderCliCommand(dispatch, {
174
+ worktreePath: worktree.worktreePath,
175
+ prompt: buildQaPrompt(dispatch, specBody),
176
+ completionTools
177
+ });
178
+ const commandText = formatProviderCliCommand(command);
179
+ await context.emit({
180
+ role: "runner",
181
+ kind: "checkpoint",
182
+ content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
183
+ eventType: "provider_cli_started"
184
+ });
185
+ await context.emit({
186
+ role: "runner",
187
+ kind: "checkpoint",
188
+ content: "Forge QA completion tools configured; provider must call all seven QA MCP gates before exit.",
189
+ eventType: "completion_tools_configured"
190
+ });
191
+ const outputState = createProviderOutputState(dispatch.execution.provider);
192
+ const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
193
+ let result;
194
+ try {
195
+ liveQaEvents.start();
196
+ result = await this.processRunner.run({
197
+ command: command.command,
198
+ args: command.args,
199
+ cwd: worktree.worktreePath,
200
+ env: providerRedactionEnv(dispatch)
201
+ }, {
202
+ onStdoutLine: async (line) => {
203
+ const event = outputState.consume(line);
204
+ if (event) {
205
+ await context.emit(event);
206
+ }
207
+ }
208
+ }, context.signal);
209
+ }
210
+ finally {
211
+ await liveQaEvents.stop();
212
+ await cleanupCompletionTools(completionTools, context.emit);
213
+ }
214
+ if (result.exitCode !== 0) {
215
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
216
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
217
+ }
218
+ await context.emit({
219
+ role: "runner",
220
+ kind: "checkpoint",
221
+ content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
222
+ eventType: "provider_cli_completed"
223
+ });
224
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
225
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
226
+ if (!qaArtifact) {
227
+ const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
228
+ throw new Error(verdictOnly
229
+ ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
230
+ : "Provider CLI QA completed but did not call the Forge QA completion tool.");
231
+ }
232
+ enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
233
+ if (!liveQaEvents.hasEmitted()) {
234
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
235
+ await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
236
+ }
237
+ const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
238
+ const statusSummary = status === "pass"
239
+ ? "passed"
240
+ : status === "blocked"
241
+ ? "blocked"
242
+ : "found rework";
243
+ return {
244
+ summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
245
+ spec: {
246
+ repoPath: worktree.worktreePath,
247
+ path: specPath,
248
+ body: specBody,
249
+ producedBy: "forge-lane-command",
250
+ status: "approved"
251
+ },
252
+ artifact: qaArtifact,
253
+ artifacts: [qaArtifact]
254
+ };
255
+ }
256
+ async runConflictResolve(context) {
257
+ const { dispatch, worktree } = context;
258
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
259
+ const command = buildProviderCliCommand(dispatch, {
260
+ worktreePath: worktree.worktreePath,
261
+ prompt: addressComments
262
+ ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
263
+ : buildConflictResolvePrompt(dispatch, worktree.branchName)
264
+ });
265
+ await context.emit({
266
+ role: "runner",
267
+ kind: "checkpoint",
268
+ content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
269
+ eventType: "provider_cli_started"
270
+ });
271
+ const outputState = createProviderOutputState(dispatch.execution.provider);
272
+ const result = await this.processRunner.run({
273
+ command: command.command,
274
+ args: command.args,
275
+ cwd: worktree.worktreePath
276
+ }, {
277
+ onStdoutLine: async (line) => {
278
+ const event = outputState.consume(line);
279
+ if (event) {
280
+ await context.emit(event);
281
+ }
282
+ }
283
+ }, context.signal);
284
+ if (result.exitCode !== 0) {
285
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
286
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
287
+ }
288
+ const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
289
+ await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
290
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
291
+ await context.emit({
292
+ role: "assistant",
293
+ kind: "message",
294
+ content: outputState.finalMessage || (addressComments
295
+ ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
296
+ : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
297
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
298
+ });
299
+ return {
300
+ summary: addressComments
301
+ ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
302
+ : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
303
+ };
304
+ }
305
+ }
5
306
  export class DeterministicProviderCliService {
6
307
  git;
7
308
  constructor(git = new GitClient()) {
@@ -9,15 +310,28 @@ export class DeterministicProviderCliService {
9
310
  }
10
311
  async runImplementation(context) {
11
312
  const { dispatch, worktree } = context;
313
+ const phase = completionPhaseFromDispatch(dispatch);
314
+ const developCycle = usesDevelopCycleCompletion(dispatch);
315
+ const debugCycle = usesDebugCycleCompletion(dispatch);
12
316
  const providerCommand = buildProviderCliCommand(dispatch);
13
317
  const providerCommandText = formatProviderCliCommand(providerCommand);
14
- const metadataRoot = path.join(worktree.repoPath, ".forge", "work-items", dispatch.workItem.id);
318
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
15
319
  const artifactRoot = path.join(metadataRoot, "artifacts");
16
320
  await fs.mkdir(artifactRoot, { recursive: true });
17
- const specBody = `---\nwork_item_id: ${dispatch.workItem.id}\nstatus: approved\nlane: ${dispatch.execution.lane}\nprovider: ${yamlQuotedScalar(dispatch.execution.provider)}\nmodel: ${yamlQuotedScalar(dispatch.execution.model)}\nprovider_command: ${yamlQuotedScalar(providerCommandText)}\n---\n\n# Forge bridge implementation spec\n\nImplement **${dispatch.workItem.title}**.\n\nAcceptance:\n- prepare a task-scoped git worktree\n- emit newline JSON runner events\n- produce Forge phase artifacts\n`;
321
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
322
+ if (!laneCommand) {
323
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
324
+ }
325
+ const specBody = `${buildSpecBody(laneCommand, dispatch.workItem, phase)}
326
+ ## Execution
327
+
328
+ - Provider: ${singleLine(dispatch.execution.provider)}
329
+ - Model: ${singleLine(dispatch.execution.model)}
330
+ - Command: ${providerCommandText}
331
+ `;
18
332
  const specPath = path.join(metadataRoot, "spec.md");
19
333
  await fs.writeFile(specPath, specBody, "utf8");
20
- await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-bridge" }) + "\n", "utf8");
334
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
21
335
  const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
22
336
  const changesetBody = `# Forge Phase 5 bridge changeset\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\nBranch: ${worktree.branchName}\nProvider: ${singleLine(dispatch.execution.provider)}\nModel: ${singleLine(dispatch.execution.model)}\nCommand: ${providerCommandText}\n\nThis deterministic file is written by forge-bridge run-once through the shared session/worktree service path.\n`;
23
337
  await fs.writeFile(changesetPath, changesetBody, "utf8");
@@ -29,61 +343,963 @@ export class DeterministicProviderCliService {
29
343
  content: `Created bridge changeset at ${changesetPath}`,
30
344
  eventType: "changeset"
31
345
  });
32
- const verdict = {
33
- schema_version: 1,
34
- status: "pass",
35
- checks: [{ name: "forge_bridge_run_once", status: "pass" }],
36
- metrics: { files_changed: 1 },
37
- produced_by: "forge-bridge",
38
- content_hash: sha256(changesetBody)
39
- };
40
- const verdictJson = JSON.stringify(verdict);
41
- const report = `# Implementation report\n\nforge-bridge prepared \`${worktree.branchName}\` and created \`${changesetPath}\`.\n`;
42
- const artifactPath = path.join(artifactRoot, "implementation.verdict.json");
43
- await fs.writeFile(artifactPath, verdictJson + "\n", "utf8");
44
- await fs.writeFile(path.join(artifactRoot, "implementation.report.md"), report, "utf8");
45
- await context.emit({
46
- role: "assistant",
47
- kind: "message",
48
- content: "Implementation complete. forge-bridge produced deterministic phase artifacts.",
49
- eventType: "implementation_complete"
50
- });
346
+ const phases = debugCycle
347
+ ? debugCompletionPhaseOrder
348
+ : developCycle
349
+ ? ["implementation", "self_review", "validation"]
350
+ : [phase];
351
+ const completionArtifacts = [];
352
+ for (const completionPhase of phases) {
353
+ await writeCompletionArtifact({
354
+ worktreePath: worktree.worktreePath,
355
+ workItemId: dispatch.workItem.id,
356
+ phase: completionPhase,
357
+ producedBy: "forge-bridge",
358
+ redactionSecrets: exactRedactionSecrets(dispatch)
359
+ }, isDebugCompletionPhaseForProvider(completionPhase)
360
+ ? expectedDebugCompletionToolName(completionPhase)
361
+ : expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
362
+ const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
363
+ if (!completionArtifact) {
364
+ throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
365
+ }
366
+ completionArtifacts.push(completionArtifact);
367
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
368
+ await context.emit({
369
+ role: "assistant",
370
+ kind: "message",
371
+ content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
372
+ eventType: phaseCompleteEventType(completionPhase)
373
+ });
374
+ }
375
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
51
376
  return {
52
- summary: `forge-bridge completed ${worktree.branchName}.`,
377
+ summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
53
378
  spec: {
54
- repoPath: worktree.repoPath,
379
+ repoPath: worktree.worktreePath,
55
380
  path: specPath,
56
381
  body: specBody,
57
- producedBy: "forge-bridge",
382
+ producedBy: "forge-lane-command",
58
383
  status: "approved"
59
384
  },
60
- artifact: {
61
- repoPath: worktree.repoPath,
62
- path: artifactPath,
63
- verdictJson,
64
- report,
65
- producedBy: "forge-bridge",
66
- status: "pass"
67
- }
385
+ artifact: completionArtifacts[0],
386
+ artifacts: completionArtifacts
68
387
  };
69
388
  }
70
- async runQa(dispatch, emit) {
71
- await emit({
389
+ async runQa(context) {
390
+ const { dispatch, worktree } = context;
391
+ await context.emit({
72
392
  role: "worker",
73
393
  kind: "message",
74
- content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
75
- eventType: "qa_analysis"
394
+ content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
395
+ eventType: "qa_plan"
76
396
  });
77
- await emit({
397
+ const qaBrowser = dispatch.qaBrowser;
398
+ const launchTarget = qaBrowser?.launchTarget ?? null;
399
+ const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
400
+ const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
401
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget)
402
+ : null;
403
+ const browserChecks = browserSidecar && launchTarget
404
+ ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
405
+ : [];
406
+ const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
407
+ const summary = missingLaunchTarget
408
+ ? "QA blocked because browser testing is required but no app launch target was provided."
409
+ : "All checks passed. forge-bridge QA completed.";
410
+ const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
411
+ for (const gate of qaCompletionGateOrder) {
412
+ await writeCompletionArtifact({
413
+ worktreePath: worktree.worktreePath,
414
+ workItemId: dispatch.workItem.id,
415
+ phase: "qa",
416
+ producedBy: "forge-bridge",
417
+ redactionSecrets: exactRedactionSecrets(dispatch),
418
+ qaCycle: true
419
+ }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
420
+ gate,
421
+ criterion,
422
+ summary,
423
+ missingLaunchTarget,
424
+ browserChecks,
425
+ sidecars
426
+ }));
427
+ await context.emit({
428
+ role: "hook",
429
+ kind: "checkpoint",
430
+ content: `qa_gate: ${gate} artifact accepted.`,
431
+ eventType: "qa_gate"
432
+ });
433
+ }
434
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
435
+ if (!qaArtifact) {
436
+ throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
437
+ }
438
+ await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
439
+ await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
440
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
441
+ return {
442
+ summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
443
+ artifact: qaArtifact,
444
+ artifacts: [qaArtifact]
445
+ };
446
+ }
447
+ async runConflictResolve(context) {
448
+ const { dispatch, worktree } = context;
449
+ const addressComments = isPullRequestCommentsDispatch(dispatch);
450
+ await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
451
+ await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
452
+ await context.emit({
78
453
  role: "assistant",
79
454
  kind: "message",
80
- content: "All checks passed. forge-bridge QA completed.",
81
- eventType: "qa_complete"
455
+ content: addressComments
456
+ ? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
457
+ : `Deterministic conflict resolve completed for ${worktree.branchName}.`,
458
+ eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
459
+ });
460
+ return {
461
+ summary: addressComments
462
+ ? `forge-bridge addressed PR comments for ${worktree.branchName}.`
463
+ : `forge-bridge resolved conflicts for ${worktree.branchName}.`
464
+ };
465
+ }
466
+ }
467
+ function phaseCompleteEventType(phase) {
468
+ return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
469
+ }
470
+ function isDebugCompletionPhaseForProvider(phase) {
471
+ return debugCompletionPhaseOrder.includes(phase);
472
+ }
473
+ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
474
+ const changesetHash = sha256(changesetBody);
475
+ const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
476
+ if (phase === "implementation") {
477
+ return {
478
+ status: "pass",
479
+ summary: "forge-bridge produced a deterministic implementation changeset.",
480
+ plan: [{ step: "Create deterministic changeset", status: "done" }],
481
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
482
+ tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
483
+ docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
484
+ acceptance_criteria: [
485
+ {
486
+ criterion,
487
+ evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
488
+ status: "satisfied"
489
+ }
490
+ ],
491
+ known_gaps: [],
492
+ next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
493
+ };
494
+ }
495
+ if (phase === "debug_repro") {
496
+ return {
497
+ status: "pass",
498
+ summary: "forge-bridge reproduced the bug deterministically.",
499
+ repro_steps: ["Run the deterministic fake-worker debug reproduction."],
500
+ observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
501
+ expected: "The bug scenario should be fixed before QA handoff.",
502
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
503
+ };
504
+ }
505
+ if (phase === "debug_root_cause") {
506
+ return {
507
+ status: "pass",
508
+ summary: "forge-bridge isolated a deterministic root cause.",
509
+ root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
510
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
511
+ eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
512
+ risk_area: "forge-bridge deterministic debug lane"
513
+ };
514
+ }
515
+ if (phase === "debug_fix") {
516
+ return {
517
+ status: "pass",
518
+ summary: "forge-bridge applied a deterministic debug fix.",
519
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
520
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
521
+ remaining_risks: [],
522
+ resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
523
+ qa_id: qaId,
524
+ status: "resolved",
525
+ summary: `Resolved deterministic QA finding ${qaId}.`,
526
+ evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
527
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
528
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
529
+ regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
530
+ }))
531
+ };
532
+ }
533
+ if (phase === "debug_regression") {
534
+ return {
535
+ status: "pass",
536
+ summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
537
+ commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
538
+ required_regressions: ["Original deterministic repro no longer fails."],
539
+ build_status: "not_applicable",
540
+ test_status: "pass",
541
+ repro_negative: true,
542
+ qa_ready: true
543
+ };
544
+ }
545
+ if (phase === "self_review") {
546
+ return {
547
+ status: "pass",
548
+ summary: "forge-bridge fake worker completed deterministic self-review.",
549
+ reviewed_diff: true,
550
+ findings: [],
551
+ security_review: {
552
+ status: "pass",
553
+ notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
554
+ },
555
+ edge_case_review: {
556
+ status: "pass",
557
+ notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
558
+ },
559
+ design_review: {
560
+ status: "not_applicable",
561
+ screenshots: [],
562
+ notes: "No UI changes."
563
+ },
564
+ deterministic_comparison: {
565
+ status: "pass",
566
+ command_or_tool: "git diff --stat HEAD~1..HEAD",
567
+ notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
568
+ },
569
+ fixes_applied: [],
570
+ remaining_risks: []
571
+ };
572
+ }
573
+ return {
574
+ status: "pass",
575
+ summary: "forge-bridge fake worker completed deterministic validation.",
576
+ commands: [
577
+ {
578
+ command: "git status --short && git diff --check",
579
+ exit_code: 0,
580
+ status: "pass",
581
+ summary: "Deterministic validation command completed for the fake-worker changeset."
582
+ }
583
+ ],
584
+ acceptance_criteria: [
585
+ {
586
+ criterion,
587
+ evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
588
+ status: "satisfied"
589
+ }
590
+ ],
591
+ build_status: "pass",
592
+ test_status: "pass",
593
+ lint_status: "not_applicable",
594
+ design_status: "not_applicable",
595
+ drift_checks: [
596
+ {
597
+ command_or_tool: "git diff --check",
598
+ status: "pass",
599
+ summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
600
+ }
601
+ ],
602
+ ready_for_dev_test: true
603
+ };
604
+ }
605
+ function deterministicQaGatePayload(options) {
606
+ const blocked = options.missingLaunchTarget;
607
+ const skippedBecauseBlocked = blocked
608
+ ? {
609
+ status: "skipped",
610
+ summary: "Skipped because browser QA was blocked by missing launch target.",
611
+ reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
612
+ }
613
+ : null;
614
+ switch (options.gate) {
615
+ case "qa_plan":
616
+ return {
617
+ status: "pass",
618
+ summary: "Deterministic QA plan recorded.",
619
+ checklist: [
620
+ "Review the validated work item against acceptance criteria.",
621
+ "Run deterministic regression evidence.",
622
+ "Confirm no in-scope QA findings remain."
623
+ ],
624
+ acceptance_criteria: [options.criterion]
625
+ };
626
+ case "qa_regression":
627
+ return {
628
+ status: "pass",
629
+ summary: "Deterministic regression QA completed.",
630
+ commands: [
631
+ {
632
+ command: "forge-bridge deterministic QA",
633
+ exit_code: 0,
634
+ status: "pass",
635
+ summary: "Deterministic regression evidence completed."
636
+ }
637
+ ],
638
+ notes: "Regression gate passed in deterministic fake-worker mode."
639
+ };
640
+ case "qa_api":
641
+ return {
642
+ status: "skipped",
643
+ summary: "No API/backend surface was identified for deterministic QA.",
644
+ reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
645
+ };
646
+ case "qa_manual_web":
647
+ return blocked
648
+ ? {
649
+ status: "blocked",
650
+ summary: "Browser QA could not run because no app launch target was provided.",
651
+ blocker_reason: "missing_app_launch_target"
652
+ }
653
+ : options.browserChecks.length > 0
654
+ ? {
655
+ status: "pass",
656
+ summary: "Deterministic browser QA exercised the configured launch target.",
657
+ browser_checks: options.browserChecks,
658
+ sidecars: options.sidecars,
659
+ notes: "Browser sidecar evidence recorded."
660
+ }
661
+ : {
662
+ status: "skipped",
663
+ summary: "Manual web QA was not required for this deterministic run.",
664
+ reason: "Forge did not require browser QA and no launch target was necessary."
665
+ };
666
+ case "qa_bug_repro":
667
+ return skippedBecauseBlocked ?? {
668
+ status: "skipped",
669
+ summary: "No failed QA observation required bug reproduction.",
670
+ reason: "No defects or candidate bugs were observed."
671
+ };
672
+ case "qa_findings":
673
+ return skippedBecauseBlocked ?? {
674
+ status: "pass",
675
+ summary: "No QA findings or candidate bugs were identified.",
676
+ findings: [],
677
+ candidate_bugs: []
678
+ };
679
+ case "qa_verdict":
680
+ return {
681
+ status: blocked ? "blocked" : "pass",
682
+ summary: options.summary,
683
+ checklist: [
684
+ "Review the validated work item against acceptance criteria.",
685
+ "Run deterministic regression evidence.",
686
+ blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
687
+ ],
688
+ tested_acceptance_criteria: blocked ? [] : [options.criterion],
689
+ commands: blocked
690
+ ? []
691
+ : [
692
+ {
693
+ command: "forge-bridge deterministic QA",
694
+ exit_code: 0,
695
+ status: "pass",
696
+ summary: "Deterministic QA command completed."
697
+ }
698
+ ],
699
+ browser_checks: blocked ? [] : options.browserChecks,
700
+ sidecars: blocked ? [] : options.sidecars,
701
+ notes: options.summary,
702
+ findings: [],
703
+ candidate_bugs: [],
704
+ blocker_reason: blocked ? "missing_app_launch_target" : null,
705
+ report_markdown: `# QA report\n\n${options.summary}\n`
706
+ };
707
+ }
708
+ }
709
+ const qaArtifactFileNames = {
710
+ plan: "qa.plan.json",
711
+ evidence: "qa.evidence.json",
712
+ findings: "qa.findings.json",
713
+ verdict: "qa.verdict.json",
714
+ report: "qa.report.md"
715
+ };
716
+ function hasLaunchTarget(target) {
717
+ return Boolean(target?.url?.trim()
718
+ || target?.ready_url?.trim()
719
+ || target?.command?.trim()
720
+ || (target?.routes ?? []).some((route) => route.trim().length > 0));
721
+ }
722
+ function deterministicBrowserSidecar(workItemId, target) {
723
+ const route = primaryLaunchRoute(target);
724
+ return {
725
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt"),
726
+ content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
727
+ };
728
+ }
729
+ function deterministicBrowserCheck(target, screenshotPath) {
730
+ const route = primaryLaunchRoute(target);
731
+ return {
732
+ route,
733
+ url: route,
734
+ status: "pass",
735
+ summary: "Deterministic browser QA exercised the configured launch target.",
736
+ actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
737
+ screenshots: [screenshotPath],
738
+ console_errors: [],
739
+ network_errors: [],
740
+ responsive_checks: ["desktop", "mobile"]
741
+ };
742
+ }
743
+ function primaryLaunchRoute(target) {
744
+ return target.ready_url?.trim()
745
+ || target.url?.trim()
746
+ || target.routes.find((route) => route.trim().length > 0)?.trim()
747
+ || "app launch command";
748
+ }
749
+ async function writeQaSidecarFiles(worktreePath, files) {
750
+ const sidecars = [];
751
+ for (const file of files) {
752
+ const fullPath = path.resolve(worktreePath, file.relativePath);
753
+ const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
754
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
755
+ throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
756
+ }
757
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
758
+ await fs.writeFile(fullPath, file.content, "utf8");
759
+ sidecars.push({
760
+ path: relativePath,
761
+ content_hash: sha256(file.content),
762
+ bytes: Buffer.byteLength(file.content, "utf8")
763
+ });
764
+ }
765
+ return sidecars;
766
+ }
767
+ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
768
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
769
+ await emit({
770
+ role: "tool",
771
+ kind: "tool_result",
772
+ content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
773
+ eventType: "qa_artifact_recorded"
774
+ });
775
+ await emit({
776
+ role: "hook",
777
+ kind: "checkpoint",
778
+ content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
779
+ eventType: "phase_gate"
780
+ });
781
+ }
782
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
783
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
784
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
785
+ return null;
786
+ }
787
+ await validateQaBundleSidecarReferences(worktreePath, workItemId);
788
+ return artifact;
789
+ }
790
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
791
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
792
+ for (const fileName of Object.values(qaArtifactFileNames)) {
793
+ try {
794
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
795
+ if (!stat.isFile()) {
796
+ return false;
797
+ }
798
+ }
799
+ catch (error) {
800
+ if (isNodeError(error) && error.code === "ENOENT") {
801
+ return false;
802
+ }
803
+ throw error;
804
+ }
805
+ }
806
+ return true;
807
+ }
808
+ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
809
+ const qaBrowser = dispatch.qaBrowser;
810
+ if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
811
+ return;
812
+ }
813
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
814
+ const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
815
+ const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
816
+ if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
817
+ throw new Error("QA browser testing is required but no app launch target was provided; provider must return blocked with blocker_reason missing_app_launch_target.");
818
+ }
819
+ }
820
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
821
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
822
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
823
+ const sidecars = arrayField(evidence, "sidecars");
824
+ if (sidecars.length === 0) {
825
+ return;
826
+ }
827
+ const qaSidecarRoot = path.resolve(artifactRoot, "qa");
828
+ for (const [index, sidecar] of sidecars.entries()) {
829
+ const sidecarPath = stringField(sidecar, "path");
830
+ const expectedHash = stringField(sidecar, "content_hash");
831
+ const expectedBytes = sidecar.bytes;
832
+ if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
833
+ throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
834
+ }
835
+ if (path.isAbsolute(sidecarPath)) {
836
+ throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
837
+ }
838
+ const fullPath = path.resolve(worktreePath, sidecarPath);
839
+ if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
840
+ throw new Error(`QA sidecar ${index} path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
841
+ }
842
+ const stat = await fs.lstat(fullPath).catch((error) => {
843
+ if (isNodeError(error) && error.code === "ENOENT") {
844
+ throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
845
+ }
846
+ throw error;
847
+ });
848
+ if (!stat.isFile() || stat.isSymbolicLink()) {
849
+ throw new Error(`QA sidecar ${index} must reference a regular file.`);
850
+ }
851
+ await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
852
+ if (stat.size !== expectedBytes) {
853
+ throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
854
+ }
855
+ const actualHash = await sha256File(fullPath);
856
+ if (actualHash !== expectedHash.trim().toLowerCase()) {
857
+ throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
858
+ }
859
+ }
860
+ }
861
+ async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
862
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
863
+ const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
864
+ const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
865
+ const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
866
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
867
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
868
+ const checklist = stringArrayField(plan, "checklist");
869
+ await emit({
870
+ role: "worker",
871
+ kind: "message",
872
+ content: checklist.length > 0
873
+ ? `QA plan: ${checklist.join("; ")}`
874
+ : "QA plan recorded.",
875
+ eventType: "qa_plan"
876
+ });
877
+ for (const browserCheck of arrayField(evidence, "browser_checks")) {
878
+ await emit({
879
+ role: "worker",
880
+ kind: "checkpoint",
881
+ content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
882
+ eventType: "qa_browser_check"
883
+ });
884
+ }
885
+ for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
886
+ await emit({
887
+ role: "worker",
888
+ kind: "checkpoint",
889
+ content: `QA finding: ${summarizeQaObject(finding)}`,
890
+ eventType: "qa_finding"
891
+ });
892
+ }
893
+ await emit({
894
+ role: "assistant",
895
+ kind: "message",
896
+ content: status === "blocked"
897
+ ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
898
+ : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
899
+ eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
900
+ });
901
+ }
902
+ class LiveQaArtifactEmitter {
903
+ worktreePath;
904
+ workItemId;
905
+ dispatch;
906
+ emit;
907
+ emitted = false;
908
+ timer = null;
909
+ pending = Promise.resolve();
910
+ constructor(worktreePath, workItemId, dispatch, emit) {
911
+ this.worktreePath = worktreePath;
912
+ this.workItemId = workItemId;
913
+ this.dispatch = dispatch;
914
+ this.emit = emit;
915
+ }
916
+ start() {
917
+ void this.pollQueued();
918
+ this.timer = setInterval(() => {
919
+ void this.pollQueued();
920
+ }, 250);
921
+ }
922
+ async stop() {
923
+ if (this.timer) {
924
+ clearInterval(this.timer);
925
+ this.timer = null;
926
+ }
927
+ await this.pollQueued();
928
+ }
929
+ hasEmitted() {
930
+ return this.emitted;
931
+ }
932
+ pollQueued() {
933
+ this.pending = this.pending
934
+ .then(() => this.poll())
935
+ .catch(() => undefined);
936
+ return this.pending;
937
+ }
938
+ async poll() {
939
+ if (this.emitted) {
940
+ return;
941
+ }
942
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
943
+ if (!artifact) {
944
+ return;
945
+ }
946
+ enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
947
+ this.emitted = true;
948
+ await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
949
+ await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
950
+ }
951
+ }
952
+ async function readJsonObjectFile(filePath) {
953
+ const content = await fs.readFile(filePath, "utf8").catch(() => "");
954
+ return parseJsonLine(content) ?? {};
955
+ }
956
+ function arrayField(source, key) {
957
+ const value = source[key];
958
+ if (!Array.isArray(value)) {
959
+ return [];
960
+ }
961
+ return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
962
+ }
963
+ function stringArrayField(source, key) {
964
+ const value = source[key];
965
+ if (!Array.isArray(value)) {
966
+ return [];
967
+ }
968
+ return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
969
+ }
970
+ function summarizeQaObject(source) {
971
+ return clip(stringField(source, "title")
972
+ ?? stringField(source, "summary")
973
+ ?? stringField(source, "id")
974
+ ?? JSON.stringify(source), 500);
975
+ }
976
+ function qaArtifactRelativePath(workItemId, fileName) {
977
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
978
+ }
979
+ async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
980
+ const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
981
+ await emit({
982
+ role: "tool",
983
+ kind: "tool_result",
984
+ content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
985
+ eventType: "completion_tool_artifact_recorded"
986
+ });
987
+ }
988
+ async function emitPhaseCompletionEvent(emit, artifact) {
989
+ const phase = completionPhaseFromArtifact(artifact);
990
+ await emit({
991
+ role: "assistant",
992
+ kind: "message",
993
+ content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
994
+ eventType: phaseCompleteEventType(phase)
995
+ });
996
+ }
997
+ async function emitPhaseGateEvents(emit, artifact) {
998
+ const phase = completionPhaseFromArtifact(artifact);
999
+ const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
1000
+ await emit({
1001
+ role: "hook",
1002
+ kind: "checkpoint",
1003
+ content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
1004
+ eventType: "phase_gate"
1005
+ });
1006
+ if (status !== "pass") {
1007
+ return;
1008
+ }
1009
+ const progression = phase === "implementation"
1010
+ ? "phase_progression: implementation -> self_review"
1011
+ : phase === "self_review"
1012
+ ? "phase_progression: self_review -> validation"
1013
+ : phase === "debug_repro"
1014
+ ? "phase_progression: debug_repro -> debug_root_cause"
1015
+ : phase === "debug_root_cause"
1016
+ ? "phase_progression: debug_root_cause -> debug_fix"
1017
+ : phase === "debug_fix"
1018
+ ? "phase_progression: debug_fix -> debug_regression"
1019
+ : phase === "debug_regression"
1020
+ ? "phase_progression: debug_regression -> QA ready"
1021
+ : "phase_progression: validation -> QA ready";
1022
+ await emit({
1023
+ role: "hook",
1024
+ kind: "checkpoint",
1025
+ content: progression,
1026
+ eventType: "phase_gate"
1027
+ });
1028
+ }
1029
+ function completionPhaseFromArtifact(artifact) {
1030
+ const phase = artifact.phase?.trim();
1031
+ return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1032
+ || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1033
+ ? phase
1034
+ : "implementation";
1035
+ }
1036
+ class LiveCompletionArtifactEmitter {
1037
+ worktreePath;
1038
+ workItemId;
1039
+ emit;
1040
+ phases;
1041
+ emitted = new Set();
1042
+ timer = null;
1043
+ pending = Promise.resolve();
1044
+ constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
1045
+ this.worktreePath = worktreePath;
1046
+ this.workItemId = workItemId;
1047
+ this.emit = emit;
1048
+ if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
1049
+ this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
1050
+ }
1051
+ else {
1052
+ this.phases = developCycle
1053
+ ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1054
+ : [phase];
1055
+ }
1056
+ }
1057
+ start() {
1058
+ void this.pollQueued();
1059
+ this.timer = setInterval(() => {
1060
+ void this.pollQueued();
1061
+ }, 250);
1062
+ }
1063
+ async stop() {
1064
+ if (this.timer) {
1065
+ clearInterval(this.timer);
1066
+ this.timer = null;
1067
+ }
1068
+ await this.pollQueued();
1069
+ }
1070
+ hasEmitted(phase) {
1071
+ return this.emitted.has(phase);
1072
+ }
1073
+ pollQueued() {
1074
+ this.pending = this.pending
1075
+ .then(() => this.poll())
1076
+ .catch(() => undefined);
1077
+ return this.pending;
1078
+ }
1079
+ async poll() {
1080
+ for (const phase of this.phases) {
1081
+ if (this.emitted.has(phase)) {
1082
+ continue;
1083
+ }
1084
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
1085
+ if (!artifact) {
1086
+ return;
1087
+ }
1088
+ this.emitted.add(phase);
1089
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1090
+ await emitPhaseCompletionEvent(this.emit, artifact);
1091
+ await emitPhaseGateEvents(this.emit, artifact);
1092
+ if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
1093
+ return;
1094
+ }
1095
+ }
1096
+ }
1097
+ }
1098
+ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
1099
+ if (!developCycle && !debugCycle) {
1100
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
1101
+ if (!artifact) {
1102
+ throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
1103
+ }
1104
+ return [artifact];
1105
+ }
1106
+ const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
1107
+ ? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
1108
+ : ["implementation", "self_review", "validation"];
1109
+ const artifacts = [];
1110
+ for (const expectedPhase of expectedPhases) {
1111
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
1112
+ if (!artifact) {
1113
+ if (artifacts.length === 0) {
1114
+ throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
1115
+ }
1116
+ const previous = artifacts[artifacts.length - 1];
1117
+ if ((previous.status ?? "").trim().toLowerCase() === "pass") {
1118
+ throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
1119
+ }
1120
+ return artifacts;
1121
+ }
1122
+ artifacts.push(artifact);
1123
+ if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
1124
+ return artifacts;
1125
+ }
1126
+ }
1127
+ return artifacts;
1128
+ }
1129
+ function providerRedactionEnv(dispatch) {
1130
+ const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
1131
+ return Object.keys(env).length > 0 ? env : undefined;
1132
+ }
1133
+ function exactRedactionSecrets(dispatch) {
1134
+ return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
1135
+ }
1136
+ async function emitProviderUsageEvent(emit, dispatch, outputState) {
1137
+ const usage = outputState.usage;
1138
+ if (hasUsage(usage)) {
1139
+ await emit(buildProviderUsageEvent(dispatch, usage));
1140
+ }
1141
+ }
1142
+ function estimatedDeterministicUsage() {
1143
+ return addUsage(emptyUsage("estimated"), {
1144
+ inputTokens: 1000,
1145
+ outputTokens: 400,
1146
+ source: "estimated"
1147
+ });
1148
+ }
1149
+ export class StreamingProviderProcessRunner {
1150
+ async run(request, handlers = {}, signal) {
1151
+ const launch = await resolveProviderProcessLaunch(request.command, request.args);
1152
+ return await new Promise((resolve, reject) => {
1153
+ const child = spawn(launch.command, launch.args, {
1154
+ cwd: request.cwd,
1155
+ env: request.env ? { ...process.env, ...request.env } : undefined,
1156
+ stdio: ["ignore", "pipe", "pipe"],
1157
+ windowsHide: true
1158
+ });
1159
+ let stdout = "";
1160
+ let stderr = "";
1161
+ let settled = false;
1162
+ const cleanup = () => {
1163
+ signal?.removeEventListener("abort", abort);
1164
+ };
1165
+ const fail = (error) => {
1166
+ if (settled) {
1167
+ return;
1168
+ }
1169
+ settled = true;
1170
+ cleanup();
1171
+ reject(error);
1172
+ };
1173
+ const abort = () => {
1174
+ try {
1175
+ child.kill("SIGTERM");
1176
+ }
1177
+ catch {
1178
+ // Best effort; close/error will settle the promise.
1179
+ }
1180
+ };
1181
+ if (signal?.aborted) {
1182
+ abort();
1183
+ }
1184
+ else {
1185
+ signal?.addEventListener("abort", abort, { once: true });
1186
+ }
1187
+ child.on("error", fail);
1188
+ const readers = [
1189
+ readProcessLines(child.stdout, (line) => {
1190
+ stdout += `${line}\n`;
1191
+ return handlers.onStdoutLine?.(line);
1192
+ }),
1193
+ readProcessLines(child.stderr, (line) => {
1194
+ stderr += `${line}\n`;
1195
+ return handlers.onStderrLine?.(line);
1196
+ })
1197
+ ];
1198
+ child.on("close", (code) => {
1199
+ Promise.allSettled(readers).then((readerResults) => {
1200
+ const rejected = readerResults.find((result) => result.status === "rejected");
1201
+ if (rejected?.status === "rejected") {
1202
+ fail(rejected.reason);
1203
+ return;
1204
+ }
1205
+ if (settled) {
1206
+ return;
1207
+ }
1208
+ settled = true;
1209
+ cleanup();
1210
+ resolve({
1211
+ exitCode: code ?? 1,
1212
+ stdout,
1213
+ stderr
1214
+ });
1215
+ }).catch(fail);
1216
+ });
82
1217
  });
1218
+ }
1219
+ }
1220
+ async function resolveProviderProcessLaunch(command, args) {
1221
+ if (process.platform !== "win32") {
1222
+ return { command, args };
1223
+ }
1224
+ const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
1225
+ if (cursorDirect) {
1226
+ return cursorDirect;
1227
+ }
1228
+ const resolved = await resolveWindowsCommand(command);
1229
+ return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
1230
+ }
1231
+ async function resolveWindowsCommand(command) {
1232
+ if (path.isAbsolute(command)) {
1233
+ return command;
1234
+ }
1235
+ try {
1236
+ const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
1237
+ return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
1238
+ }
1239
+ catch {
1240
+ return null;
1241
+ }
1242
+ }
1243
+ export function chooseWindowsCommandCandidate(candidates) {
1244
+ const normalized = candidates
1245
+ .map((candidate) => candidate.trim())
1246
+ .filter((candidate) => candidate.length > 0);
1247
+ if (normalized.length === 0) {
1248
+ return null;
1249
+ }
1250
+ const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
1251
+ for (const extension of preferredExtensions) {
1252
+ const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
1253
+ if (candidate) {
1254
+ return candidate;
1255
+ }
1256
+ }
1257
+ return normalized[0];
1258
+ }
1259
+ export function buildWindowsLaunchCommand(commandPath, args) {
1260
+ const extension = path.extname(commandPath).toLowerCase();
1261
+ if (extension === ".ps1") {
83
1262
  return {
84
- summary: "forge-bridge QA passed."
1263
+ command: powershellExecutable(),
1264
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
85
1265
  };
86
1266
  }
1267
+ if (extension === ".cmd" || extension === ".bat") {
1268
+ return {
1269
+ command: process.env.ComSpec ?? "cmd.exe",
1270
+ args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
1271
+ };
1272
+ }
1273
+ return { command: commandPath, args };
1274
+ }
1275
+ function powershellExecutable() {
1276
+ const systemRoot = process.env.SystemRoot;
1277
+ return systemRoot
1278
+ ? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
1279
+ : "powershell.exe";
1280
+ }
1281
+ function windowsCommandLine(command, args) {
1282
+ return [command, ...args].map(quoteWindowsCommandLineArg).join(" ");
1283
+ }
1284
+ function quoteWindowsCommandLineArg(value) {
1285
+ if (value.length > 0 && !/[\s"]/.test(value)) {
1286
+ return value;
1287
+ }
1288
+ return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
1289
+ }
1290
+ async function readProcessLines(stream, onLine) {
1291
+ const reader = readline.createInterface({ input: stream });
1292
+ try {
1293
+ for await (const line of reader) {
1294
+ await onLine(line);
1295
+ }
1296
+ }
1297
+ finally {
1298
+ reader.close();
1299
+ }
1300
+ }
1301
+ function isFakeWorkerModel(model) {
1302
+ return model.trim().toLowerCase() === fakeWorkerModel;
87
1303
  }
88
1304
  function sha256(content) {
89
1305
  return crypto.createHash("sha256").update(content).digest("hex");
@@ -91,21 +1307,564 @@ function sha256(content) {
91
1307
  export function formatProviderCliCommand(command) {
92
1308
  return [command.command, ...command.args].map(singleLine).join(" ");
93
1309
  }
94
- function yamlQuotedScalar(value) {
95
- return JSON.stringify(singleLine(value));
96
- }
97
1310
  function singleLine(value) {
98
1311
  return value.replace(/\s+/g, " ").trim();
99
1312
  }
100
- export function buildProviderCliCommand(dispatch) {
1313
+ export function buildProviderCliCommand(dispatch, run) {
101
1314
  const provider = dispatch.execution.provider.trim();
102
1315
  const normalizedProvider = provider.toLowerCase();
103
1316
  const model = dispatch.execution.model.trim();
104
1317
  if (normalizedProvider === "codex") {
105
- return { command: "codex", args: ["exec", "--model", model] };
1318
+ const args = ["exec"];
1319
+ if (run?.completionTools) {
1320
+ args.push(...codexMcpConfigArgs(run.completionTools));
1321
+ }
1322
+ args.push("--model", model);
1323
+ if (run) {
1324
+ args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
1325
+ if (run.worktreePath) {
1326
+ args.push("--cd", run.worktreePath);
1327
+ }
1328
+ args.push(run.prompt ?? "");
1329
+ }
1330
+ return { command: "codex", args };
106
1331
  }
107
1332
  if (normalizedProvider === "cursor") {
108
- return { command: "cursor-agent", args: ["--model", model] };
1333
+ const args = ["--print", "--output-format", "stream-json", "--model", model];
1334
+ if (run?.worktreePath) {
1335
+ args.push("--workspace", run.worktreePath);
1336
+ }
1337
+ if (run?.prompt) {
1338
+ args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
1339
+ }
1340
+ return { command: "cursor-agent", args };
1341
+ }
1342
+ const args = ["--model", model];
1343
+ if (run?.prompt) {
1344
+ args.push(run.prompt);
1345
+ }
1346
+ return { command: provider, args };
1347
+ }
1348
+ function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1349
+ return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
1350
+
1351
+ Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
1352
+ ${phaseWorkInstruction(phase)}
1353
+ ${qaReworkImplementationInstruction(dispatch)}
1354
+ Use the repository's existing conventions. Run relevant tests when practical.
1355
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
1356
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
1357
+
1358
+ ${completionPromptForPhase(phase)}
1359
+
1360
+ Finish with a concise summary of changed files and verification after calling the completion tool.`;
1361
+ }
1362
+ function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1363
+ return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
1364
+
1365
+ 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.
1366
+ 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.
1367
+ ${qaReworkImplementationInstruction(dispatch)}
1368
+ Use the repository's existing conventions. Run relevant tests when practical.
1369
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
1370
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
1371
+
1372
+ ${completionPromptForDevelopCycle(phase)}
1373
+
1374
+ 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.`;
1375
+ }
1376
+ function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1377
+ return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
1378
+
1379
+ Read .forge/work-items/${dispatch.workItem.id}/spec.md, reproduce or characterize the bug, isolate root cause, apply the smallest safe fix, then prove the regression in this same provider session.
1380
+ Start in the ${phase.replace(/_/g, " ")} gate. Do not stop after a passing Debug gate; continue through the next Debug MCP instruction returned by the tool server until debug_regression is accepted or the current gate records a non-pass blocker.
1381
+ ${debugQaReworkInstruction(dispatch)}
1382
+ Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
1383
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
1384
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
1385
+
1386
+ ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
1387
+
1388
+ Finish with a concise summary of changed files and verification after the debug_regression completion tool has accepted the work, or after the current Debug gate tool records a non-pass blocker.`;
1389
+ }
1390
+ function qaReworkImplementationInstruction(dispatch) {
1391
+ if (!dispatch.qaRework) {
1392
+ return "";
1393
+ }
1394
+ return `
1395
+ QA rework context:
1396
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1397
+ - Rework packet: ${dispatch.qaRework.packetPath}
1398
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1399
+ 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.`;
1400
+ }
1401
+ function debugQaReworkInstruction(dispatch) {
1402
+ if (!dispatch.qaRework) {
1403
+ return "";
1404
+ }
1405
+ return `
1406
+ QA rework context for Debug:
1407
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1408
+ - Rework packet: ${dispatch.qaRework.packetPath}
1409
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1410
+ Read the packet JSON, reproduce or characterize each listed finding, fix or explicitly dispute it, and include resolved_findings entries for every required QA ID in forge.complete_debug_fix with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.`;
1411
+ }
1412
+ function qaReworkRetestInstruction(dispatch) {
1413
+ if (!dispatch.qaRework) {
1414
+ return "";
1415
+ }
1416
+ return `
1417
+ QA retest context:
1418
+ - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1419
+ - Rework packet: ${dispatch.qaRework.packetPath}
1420
+ - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1421
+ Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
1422
+ }
1423
+ function phaseWorkInstruction(phase) {
1424
+ if (phase === "self_review") {
1425
+ return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
1426
+ }
1427
+ if (phase === "validation") {
1428
+ return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
1429
+ }
1430
+ return "Implement the work item and keep the change focused.";
1431
+ }
1432
+ function qaBrowserInstruction(dispatch) {
1433
+ const qaBrowser = dispatch.qaBrowser;
1434
+ if (!qaBrowser) {
1435
+ return "Browser/app launch context: not provided by Forge.";
1436
+ }
1437
+ const launchTarget = qaBrowser.launchTarget;
1438
+ if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
1439
+ return `Browser/app launch context:\n- UI/browser QA is required for this item.\n- No app launch target was provided.\n- Return blocked with blocker_reason: missing_app_launch_target instead of pretending browser testing occurred.\n- Artifact sidecars path when available: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
1440
+ }
1441
+ if (!launchTarget) {
1442
+ return `Browser/app launch context:\n- UI/browser QA is not required by Forge heuristics for this item.\n- If you determine browser testing is needed, return blocked with blocker_reason: missing_app_launch_target unless you can safely identify a launch target from the repo.\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
1443
+ }
1444
+ const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
1445
+ return `Browser/app launch context:\n- Browser QA required: ${qaBrowser.required ? "yes" : "no, unless the diff/AC requires it"}\n- URL: ${launchTarget.url || "not specified"}\n- Ready URL: ${launchTarget.ready_url || "not specified"}\n- Launch command: ${launchTarget.command || "not specified"}\n- Working directory: ${launchTarget.working_directory || "repo root"}\n- Routes to cover: ${routes}\n- Notes: ${launchTarget.notes || "none"}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
1446
+ }
1447
+ function buildQaPrompt(dispatch, laneSpec) {
1448
+ return `You are Forge's QA lane running locally in a prepared git worktree.
1449
+
1450
+ First read and follow the injected QA lane command at .forge/work-items/${dispatch.workItem.id}/spec.md. It defines the required gated QA skill workflow for this run.
1451
+
1452
+ Injected QA lane command and work item spec:
1453
+ ${laneSpec}
1454
+
1455
+ ---
1456
+
1457
+ Work item: ${dispatch.workItem.id}
1458
+ Title: ${dispatch.workItem.title}
1459
+ Description:
1460
+ ${dispatch.workItem.description || "Not provided."}
1461
+
1462
+ Acceptance criteria:
1463
+ ${dispatch.workItem.acceptanceCriteria || "Not specified."}
1464
+
1465
+ Repro steps / scenario:
1466
+ ${dispatch.workItem.reproSteps || "Not provided."}
1467
+
1468
+ System info / environment notes:
1469
+ ${dispatch.workItem.systemInfo || "Not provided."}
1470
+
1471
+ Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1472
+ ${qaBrowserInstruction(dispatch)}
1473
+ ${qaReworkRetestInstruction(dispatch)}
1474
+ QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
1475
+ Record concrete evidence. For UI/browser work, include browser_checks with URLs/routes, actions, observed results, screenshots/traces when available, console errors, failed network requests, and responsive checks. Store browser sidecars under .forge/work-items/${dispatch.workItem.id}/artifacts/qa/.
1476
+ Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
1477
+ Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
1478
+
1479
+ ${completionPromptForQaCycle()}
1480
+
1481
+ Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
1482
+ }
1483
+ function buildConflictResolvePrompt(dispatch, branchName) {
1484
+ const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
1485
+ return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
1486
+
1487
+ The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
1488
+ Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
1489
+ Keep the original work item intent intact:
1490
+ - Work item: ${dispatch.workItem.id}
1491
+ - Title: ${dispatch.workItem.title}
1492
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
1493
+
1494
+ Finish with a concise summary of the conflicts resolved and verification performed.`;
1495
+ }
1496
+ function buildPullRequestCommentsPrompt(dispatch, branchName) {
1497
+ const pr = dispatch.pullRequest;
1498
+ const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
1499
+ const prLocator = pr
1500
+ ? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
1501
+ : "the open pull request for this work item";
1502
+ return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
1503
+
1504
+ The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
1505
+ PR context:
1506
+ - Provider: ${pr?.provider || "not provided"}
1507
+ - Source branch: ${pr?.sourceBranch || branchName}
1508
+ - Target branch: ${targetBranch}
1509
+ - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
1510
+
1511
+ Use the PR URL, local git metadata, and available GitHub tooling/auth to inspect unresolved review threads. Make focused code or test changes that answer the feedback, commit the changes, and push ${branchName} to origin.
1512
+ If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
1513
+ Keep the original work item intent intact:
1514
+ - Work item: ${dispatch.workItem.id}
1515
+ - Title: ${dispatch.workItem.title}
1516
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
1517
+
1518
+ Finish with a concise summary of comments addressed and verification performed.`;
1519
+ }
1520
+ function isPullRequestCommentsDispatch(dispatch) {
1521
+ return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
1522
+ }
1523
+ async function cleanupCompletionTools(completionTools, emit) {
1524
+ try {
1525
+ await completionTools.cleanup();
1526
+ }
1527
+ catch (error) {
1528
+ await emit({
1529
+ role: "runner",
1530
+ kind: "checkpoint",
1531
+ content: `Forge completion tool cleanup failed and was ignored: ${clip(messageFromError(error), 600)}`,
1532
+ eventType: "completion_tools_cleanup_failed"
1533
+ }).catch(() => undefined);
1534
+ }
1535
+ }
1536
+ async function commitWorktreeChanges(git, worktreePath, workItemId) {
1537
+ await git.run(worktreePath, ["add", "-A"]);
1538
+ await git.run(worktreePath, ["reset", "--", ".forge"]).catch(() => "");
1539
+ const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
1540
+ .split(/\r?\n/)
1541
+ .map((line) => line.trim())
1542
+ .filter(Boolean);
1543
+ if (changedFiles.length > 0) {
1544
+ await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
1545
+ }
1546
+ else {
1547
+ await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
1548
+ }
1549
+ const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
1550
+ return { commitSha, changedFiles };
1551
+ }
1552
+ function messageFromError(error) {
1553
+ return error instanceof Error ? error.message : String(error);
1554
+ }
1555
+ function clip(value, maxLength) {
1556
+ if (value.length <= maxLength) {
1557
+ return value;
1558
+ }
1559
+ return `${value.slice(0, maxLength)}...`;
1560
+ }
1561
+ function createProviderOutputState(provider) {
1562
+ return provider.trim().toLowerCase() === "cursor"
1563
+ ? new CursorStreamJsonState()
1564
+ : new CodexJsonState();
1565
+ }
1566
+ class CursorStreamJsonState {
1567
+ sessionId = null;
1568
+ finalMessage = null;
1569
+ emittedSession = false;
1570
+ accumulatedUsage = null;
1571
+ get sessionLabel() {
1572
+ return this.sessionId ? `session ${this.sessionId}` : null;
1573
+ }
1574
+ get usage() {
1575
+ return this.accumulatedUsage;
1576
+ }
1577
+ consume(line) {
1578
+ const event = parseJsonLine(line);
1579
+ if (!event) {
1580
+ return null;
1581
+ }
1582
+ const type = stringField(event, "type");
1583
+ if (type === "system" && stringField(event, "subtype") === "init") {
1584
+ this.sessionId = stringField(event, "session_id");
1585
+ if (this.sessionId && !this.emittedSession) {
1586
+ this.emittedSession = true;
1587
+ return {
1588
+ role: "runner",
1589
+ kind: "checkpoint",
1590
+ content: `Cursor session started: ${this.sessionId}.`,
1591
+ eventType: "provider_thread_started"
1592
+ };
1593
+ }
1594
+ }
1595
+ if (type === "assistant") {
1596
+ const text = assistantMessageText(event);
1597
+ if (text) {
1598
+ this.finalMessage = clip(text, 4000);
1599
+ return {
1600
+ role: "assistant",
1601
+ kind: "message",
1602
+ content: this.finalMessage,
1603
+ eventType: "provider_message"
1604
+ };
1605
+ }
1606
+ }
1607
+ if (type === "tool_call") {
1608
+ const subtype = stringField(event, "subtype");
1609
+ const toolCall = objectField(event, "tool_call");
1610
+ if (subtype === "started") {
1611
+ const summary = formatCursorToolCallStarted(toolCall);
1612
+ if (summary) {
1613
+ return {
1614
+ role: "worker",
1615
+ kind: "checkpoint",
1616
+ content: summary,
1617
+ eventType: "provider_tool_call"
1618
+ };
1619
+ }
1620
+ }
1621
+ if (subtype === "completed") {
1622
+ const completed = formatCursorToolCallCompleted(toolCall);
1623
+ if (completed) {
1624
+ return {
1625
+ role: "worker",
1626
+ kind: completed.kind,
1627
+ content: completed.content,
1628
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
1629
+ };
1630
+ }
1631
+ }
1632
+ }
1633
+ if (type === "result" && stringField(event, "subtype") === "success") {
1634
+ const result = stringField(event, "result");
1635
+ if (result) {
1636
+ this.finalMessage = clip(result, 4000);
1637
+ }
1638
+ this.accumulateUsage(event);
1639
+ }
1640
+ if (type === "error" || (type === "result" && event.is_error === true)) {
1641
+ return {
1642
+ role: "runner",
1643
+ kind: "error",
1644
+ content: clip(line.trim(), 1000),
1645
+ eventType: "provider_cli_error"
1646
+ };
1647
+ }
1648
+ return null;
1649
+ }
1650
+ accumulateUsage(event) {
1651
+ const usage = objectField(event, "usage");
1652
+ const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
1653
+ if (Object.keys(usage).length === 0 && durationMs === 0) {
1654
+ return;
1655
+ }
1656
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
1657
+ inputTokens: readUsageNumber(usage, "inputTokens"),
1658
+ outputTokens: readUsageNumber(usage, "outputTokens"),
1659
+ cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
1660
+ cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
1661
+ providerDurationMs: durationMs > 0 ? durationMs : null,
1662
+ source: "provider_reported"
1663
+ });
1664
+ }
1665
+ }
1666
+ function formatCursorToolCallStarted(toolCall) {
1667
+ const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
1668
+ const readPath = stringField(readArgs, "path");
1669
+ if (readPath) {
1670
+ return `Reading ${readPath}`;
109
1671
  }
110
- return { command: provider, args: ["--model", model] };
1672
+ const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
1673
+ const writePath = stringField(writeArgs, "path");
1674
+ if (writePath) {
1675
+ return `Writing ${writePath}`;
1676
+ }
1677
+ const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
1678
+ const command = stringField(shellArgs, "command");
1679
+ if (command) {
1680
+ return `Shell command started: ${clip(command, 500)}`;
1681
+ }
1682
+ const fn = objectField(toolCall, "function");
1683
+ const name = stringField(fn, "name");
1684
+ if (name) {
1685
+ return `Tool call started: ${name}`;
1686
+ }
1687
+ return null;
1688
+ }
1689
+ function formatCursorToolCallCompleted(toolCall) {
1690
+ const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
1691
+ const writePath = stringField(writeArgs, "path");
1692
+ const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
1693
+ const writtenPath = stringField(writeResult, "path") ?? writePath;
1694
+ if (writtenPath) {
1695
+ return {
1696
+ kind: "file_edit",
1697
+ content: `Wrote ${writtenPath}`
1698
+ };
1699
+ }
1700
+ const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
1701
+ const readPath = stringField(readArgs, "path");
1702
+ if (readPath) {
1703
+ const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
1704
+ const totalLines = readResult.totalLines;
1705
+ const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
1706
+ return {
1707
+ kind: "checkpoint",
1708
+ content: `Read ${readPath}${lineSummary}`
1709
+ };
1710
+ }
1711
+ const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
1712
+ const command = stringField(shellArgs, "command");
1713
+ if (command) {
1714
+ return {
1715
+ kind: "checkpoint",
1716
+ content: `Shell command completed: ${clip(command, 500)}`
1717
+ };
1718
+ }
1719
+ const fn = objectField(toolCall, "function");
1720
+ const name = stringField(fn, "name");
1721
+ if (name) {
1722
+ return {
1723
+ kind: "checkpoint",
1724
+ content: `Tool call completed: ${name}`
1725
+ };
1726
+ }
1727
+ return null;
1728
+ }
1729
+ function assistantMessageText(event) {
1730
+ const message = objectField(event, "message");
1731
+ const content = message.content;
1732
+ if (!Array.isArray(content)) {
1733
+ return null;
1734
+ }
1735
+ const parts = content
1736
+ .map((entry) => {
1737
+ if (!entry || typeof entry !== "object") {
1738
+ return null;
1739
+ }
1740
+ const block = entry;
1741
+ return stringField(block, "text");
1742
+ })
1743
+ .filter((text) => Boolean(text));
1744
+ if (parts.length === 0) {
1745
+ return null;
1746
+ }
1747
+ return parts.join("");
1748
+ }
1749
+ function parseJsonLine(line) {
1750
+ const trimmed = line.trim();
1751
+ if (!trimmed.startsWith("{")) {
1752
+ return null;
1753
+ }
1754
+ let parsed;
1755
+ try {
1756
+ parsed = JSON.parse(trimmed);
1757
+ }
1758
+ catch {
1759
+ return null;
1760
+ }
1761
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
1762
+ ? parsed
1763
+ : null;
1764
+ }
1765
+ class CodexJsonState {
1766
+ threadId = null;
1767
+ finalMessage = null;
1768
+ emittedThread = false;
1769
+ accumulatedUsage = null;
1770
+ get sessionLabel() {
1771
+ return this.threadId ? `thread ${this.threadId}` : null;
1772
+ }
1773
+ get usage() {
1774
+ return this.accumulatedUsage;
1775
+ }
1776
+ consume(line) {
1777
+ const event = parseJsonLine(line);
1778
+ if (!event) {
1779
+ return null;
1780
+ }
1781
+ const type = stringField(event, "type") ?? "";
1782
+ if (type === "thread.started") {
1783
+ this.threadId = stringField(event, "thread_id");
1784
+ if (this.threadId && !this.emittedThread) {
1785
+ this.emittedThread = true;
1786
+ return {
1787
+ role: "runner",
1788
+ kind: "checkpoint",
1789
+ content: `Codex thread started: ${this.threadId}.`,
1790
+ eventType: "provider_thread_started"
1791
+ };
1792
+ }
1793
+ }
1794
+ if (type === "turn.completed") {
1795
+ this.accumulateUsage(event);
1796
+ return {
1797
+ role: "runner",
1798
+ kind: "checkpoint",
1799
+ content: "Codex turn completed.",
1800
+ eventType: "provider_turn_completed"
1801
+ };
1802
+ }
1803
+ if (type === "turn.failed" || type === "error") {
1804
+ return {
1805
+ role: "runner",
1806
+ kind: "error",
1807
+ content: clip(line.trim(), 1000),
1808
+ eventType: "provider_cli_error"
1809
+ };
1810
+ }
1811
+ if (type === "item.completed" || type === "item.updated") {
1812
+ const item = objectField(event, "item");
1813
+ const itemType = stringField(item, "type");
1814
+ if (itemType === "agent_message") {
1815
+ const text = stringField(item, "text");
1816
+ if (text) {
1817
+ this.finalMessage = clip(text, 4000);
1818
+ return {
1819
+ role: "assistant",
1820
+ kind: "message",
1821
+ content: this.finalMessage,
1822
+ eventType: "provider_message"
1823
+ };
1824
+ }
1825
+ }
1826
+ if (itemType === "command_execution") {
1827
+ const command = stringField(item, "command");
1828
+ const status = stringField(item, "status");
1829
+ if (command) {
1830
+ return {
1831
+ role: "worker",
1832
+ kind: "checkpoint",
1833
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
1834
+ eventType: "provider_command"
1835
+ };
1836
+ }
1837
+ }
1838
+ }
1839
+ return null;
1840
+ }
1841
+ accumulateUsage(event) {
1842
+ const usage = objectField(event, "usage");
1843
+ if (Object.keys(usage).length === 0) {
1844
+ return;
1845
+ }
1846
+ this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
1847
+ inputTokens: readUsageNumber(usage, "input_tokens"),
1848
+ outputTokens: readUsageNumber(usage, "output_tokens"),
1849
+ cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
1850
+ reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
1851
+ source: "provider_reported"
1852
+ });
1853
+ }
1854
+ }
1855
+ function objectField(source, key) {
1856
+ const value = source[key];
1857
+ return value && typeof value === "object" && !Array.isArray(value)
1858
+ ? value
1859
+ : {};
1860
+ }
1861
+ function stringField(source, key) {
1862
+ const value = source[key];
1863
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
1864
+ }
1865
+ function normalizedString(value) {
1866
+ return value.trim().toLowerCase().replace(/-/g, "_");
1867
+ }
1868
+ function isNodeError(error) {
1869
+ return error instanceof Error && "code" in error;
111
1870
  }