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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { execFile, spawn } from "node:child_process";
5
6
  import readline from "node:readline";
@@ -8,11 +9,52 @@ import { GitClient } from "../../shared/git/git.js";
8
9
  import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
9
10
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
10
11
  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 { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDebugCycle, completionPromptForDevelopCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, qaCompletionGateOrder } from "../phase-completion.js";
12
13
  import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
13
14
  const fakeWorkerModel = "server-local-fake-worker";
14
15
  const execFileAsync = promisify(execFile);
15
16
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
17
+ const allowedProviderParentEnvNames = [
18
+ "PATH",
19
+ "HOME",
20
+ "USERPROFILE",
21
+ "TMPDIR",
22
+ "TEMP",
23
+ "TMP",
24
+ "LANG"
25
+ ];
26
+ const windowsAllowedProviderParentEnvNames = [
27
+ "SystemRoot",
28
+ "ComSpec",
29
+ "PATHEXT",
30
+ "APPDATA",
31
+ "LOCALAPPDATA"
32
+ ];
33
+ function buildProviderChildEnvironment(requestEnv) {
34
+ const env = {};
35
+ for (const [key, value] of Object.entries(process.env)) {
36
+ if (typeof value === "string" && isAllowedProviderParentEnv(key)) {
37
+ env[key] = value;
38
+ }
39
+ }
40
+ if (requestEnv) {
41
+ for (const [key, value] of Object.entries(requestEnv)) {
42
+ const trimmedKey = key.trim();
43
+ if (trimmedKey.length > 0) {
44
+ env[trimmedKey] = value;
45
+ }
46
+ }
47
+ }
48
+ return env;
49
+ }
50
+ function isAllowedProviderParentEnv(key) {
51
+ return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
52
+ || key.toUpperCase().startsWith("LC_")
53
+ || (process.platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
54
+ }
55
+ function isAllowedProviderParentEnvName(key, allowedNames) {
56
+ return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
57
+ }
16
58
  export class RoutingProviderCliService {
17
59
  realProvider;
18
60
  deterministicProvider;
@@ -40,6 +82,11 @@ export class RoutingProviderCliService {
40
82
  ? await this.deterministicProvider.runQa(context)
41
83
  : await this.realProvider.runQa(context);
42
84
  }
85
+ async runDraft(context) {
86
+ return isFakeWorkerModel(context.dispatch.execution.model)
87
+ ? await this.deterministicProvider.runDraft(context)
88
+ : await this.realProvider.runDraft(context);
89
+ }
43
90
  }
44
91
  export class ProcessBackedProviderCliService {
45
92
  processRunner;
@@ -48,6 +95,60 @@ export class ProcessBackedProviderCliService {
48
95
  this.processRunner = processRunner;
49
96
  this.git = git;
50
97
  }
98
+ async runDraft(context) {
99
+ const { dispatch } = context;
100
+ if (!dispatch.draft) {
101
+ throw new Error("Draft dispatch context is missing.");
102
+ }
103
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "forge-bridge-draft-"));
104
+ const command = buildProviderCliCommand(dispatch, {
105
+ worktreePath: tempDir,
106
+ prompt: buildDraftPrompt(dispatch),
107
+ skipGitRepoCheck: true
108
+ });
109
+ await context.emit({
110
+ role: "runner",
111
+ kind: "checkpoint",
112
+ content: `Starting provider CLI Draft: ${formatProviderCliCommand(command)}`,
113
+ eventType: "provider_cli_started"
114
+ });
115
+ const outputState = createProviderOutputState(dispatch.execution.provider);
116
+ try {
117
+ const result = await this.processRunner.run({
118
+ command: command.command,
119
+ args: command.args,
120
+ cwd: tempDir,
121
+ env: providerProcessEnv(dispatch)
122
+ }, {
123
+ onStdoutLine: async (line) => {
124
+ for (const event of outputState.consume(line)) {
125
+ await context.emit(event);
126
+ }
127
+ }
128
+ }, context.signal);
129
+ if (result.exitCode !== 0) {
130
+ throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
131
+ }
132
+ const content = outputState.finalMessage ?? result.stdout.trim();
133
+ if (!content) {
134
+ throw new Error("Provider CLI completed without returning a draft.");
135
+ }
136
+ const json = extractJsonObject(content);
137
+ await context.emit({
138
+ role: "assistant",
139
+ kind: "message",
140
+ content: json,
141
+ eventType: "draft_complete"
142
+ });
143
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
144
+ return {
145
+ summary: "Draft generated through Forge Runner."
146
+ };
147
+ }
148
+ finally {
149
+ await fs.rm(tempDir, { recursive: true, force: true });
150
+ }
151
+ }
51
152
  async runImplementation(context) {
52
153
  const { dispatch, worktree } = context;
53
154
  const phase = completionPhaseFromDispatch(dispatch);
@@ -98,11 +199,10 @@ export class ProcessBackedProviderCliService {
98
199
  command: command.command,
99
200
  args: command.args,
100
201
  cwd: worktree.worktreePath,
101
- env: providerRedactionEnv(dispatch)
202
+ env: providerProcessEnv(dispatch)
102
203
  }, {
103
204
  onStdoutLine: async (line) => {
104
- const event = outputState.consume(line);
105
- if (event) {
205
+ for (const event of outputState.consume(line)) {
106
206
  await context.emit(event);
107
207
  }
108
208
  }
@@ -184,35 +284,46 @@ export class ProcessBackedProviderCliService {
184
284
  eventType: "completion_tools_configured"
185
285
  });
186
286
  const outputState = createProviderOutputState(dispatch.execution.provider);
287
+ const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
187
288
  let result;
188
289
  try {
290
+ liveArchitectEvents.start();
189
291
  result = await this.processRunner.run({
190
292
  command: command.command,
191
293
  args: command.args,
192
294
  cwd: worktree.worktreePath,
193
- env: providerRedactionEnv(dispatch)
295
+ env: providerProcessEnv(dispatch)
194
296
  }, {
195
297
  onStdoutLine: async (line) => {
196
- const event = outputState.consume(line);
197
- if (event) {
298
+ for (const event of outputState.consume(line)) {
198
299
  await context.emit(event);
199
300
  }
200
301
  }
201
302
  }, context.signal);
202
303
  }
203
304
  finally {
305
+ await liveArchitectEvents.stop();
204
306
  await cleanupCompletionTools(completionTools, context.emit);
205
307
  }
206
308
  if (result.exitCode !== 0) {
207
309
  const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
208
310
  throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
209
311
  }
312
+ await context.emit({
313
+ role: "runner",
314
+ kind: "checkpoint",
315
+ content: `Provider CLI Architect completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
316
+ eventType: "provider_cli_completed"
317
+ });
210
318
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
211
319
  const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
212
320
  if (!architectArtifact) {
213
321
  throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
214
322
  }
215
- await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
323
+ if (!liveArchitectEvents.hasEmitted()) {
324
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
325
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, architectArtifact);
326
+ }
216
327
  await context.emit({
217
328
  role: "assistant",
218
329
  kind: "message",
@@ -274,11 +385,10 @@ export class ProcessBackedProviderCliService {
274
385
  command: command.command,
275
386
  args: command.args,
276
387
  cwd: worktree.worktreePath,
277
- env: providerRedactionEnv(dispatch)
388
+ env: providerProcessEnv(dispatch)
278
389
  }, {
279
390
  onStdoutLine: async (line) => {
280
- const event = outputState.consume(line);
281
- if (event) {
391
+ for (const event of outputState.consume(line)) {
282
392
  await context.emit(event);
283
393
  }
284
394
  }
@@ -299,7 +409,7 @@ export class ProcessBackedProviderCliService {
299
409
  eventType: "provider_cli_completed"
300
410
  });
301
411
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
302
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
412
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
303
413
  if (!qaArtifact) {
304
414
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
305
415
  throw new Error(verdictOnly
@@ -309,7 +419,7 @@ export class ProcessBackedProviderCliService {
309
419
  enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
310
420
  if (!liveQaEvents.hasEmitted()) {
311
421
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
312
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
422
+ await emitQaStructuredEvents(context.emit, qaArtifact);
313
423
  }
314
424
  const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
315
425
  const statusSummary = status === "pass"
@@ -349,11 +459,11 @@ export class ProcessBackedProviderCliService {
349
459
  const result = await this.processRunner.run({
350
460
  command: command.command,
351
461
  args: command.args,
352
- cwd: worktree.worktreePath
462
+ cwd: worktree.worktreePath,
463
+ env: providerProcessEnv(dispatch)
353
464
  }, {
354
465
  onStdoutLine: async (line) => {
355
- const event = outputState.consume(line);
356
- if (event) {
466
+ for (const event of outputState.consume(line)) {
357
467
  await context.emit(event);
358
468
  }
359
469
  }
@@ -385,6 +495,17 @@ export class DeterministicProviderCliService {
385
495
  constructor(git = new GitClient()) {
386
496
  this.git = git;
387
497
  }
498
+ async runDraft(context) {
499
+ const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
500
+ await context.emit({
501
+ role: "assistant",
502
+ kind: "message",
503
+ content,
504
+ eventType: "draft_complete"
505
+ });
506
+ await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
507
+ return { summary: "forge-bridge generated deterministic draft." };
508
+ }
388
509
  async runImplementation(context) {
389
510
  const { dispatch, worktree } = context;
390
511
  const phase = completionPhaseFromDispatch(dispatch);
@@ -484,6 +605,7 @@ export class DeterministicProviderCliService {
484
605
  throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
485
606
  }
486
607
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
608
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
487
609
  await context.emit({
488
610
  role: "assistant",
489
611
  kind: "message",
@@ -515,7 +637,7 @@ export class DeterministicProviderCliService {
515
637
  const launchTarget = qaBrowser?.launchTarget ?? null;
516
638
  const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
517
639
  const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
518
- ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget)
640
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
519
641
  : null;
520
642
  const browserChecks = browserSidecar && launchTarget
521
643
  ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
@@ -532,7 +654,9 @@ export class DeterministicProviderCliService {
532
654
  phase: "qa",
533
655
  producedBy: "forge-bridge",
534
656
  redactionSecrets: exactRedactionSecrets(dispatch),
535
- qaCycle: true
657
+ qaCycle: true,
658
+ ownerType: dispatch.cycleRun.ownerType ?? undefined,
659
+ ownerId: dispatch.cycleRun.ownerId ?? undefined
536
660
  }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
537
661
  gate,
538
662
  criterion,
@@ -541,19 +665,17 @@ export class DeterministicProviderCliService {
541
665
  browserChecks,
542
666
  sidecars
543
667
  }));
544
- await context.emit({
545
- role: "hook",
546
- kind: "checkpoint",
547
- content: `qa_gate: ${gate} artifact accepted.`,
548
- eventType: "qa_gate"
549
- });
668
+ const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
669
+ if (gateArtifact) {
670
+ await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
671
+ }
550
672
  }
551
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
673
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
552
674
  if (!qaArtifact) {
553
675
  throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
554
676
  }
555
677
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
556
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
678
+ await emitQaStructuredEvents(context.emit, qaArtifact);
557
679
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
558
680
  return {
559
681
  summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
@@ -869,16 +991,25 @@ const qaArtifactFileNames = {
869
991
  verdict: "qa.verdict.json",
870
992
  report: "qa.report.md"
871
993
  };
994
+ const qaGateArtifactFileNames = {
995
+ qa_plan: "qa.plan.json",
996
+ qa_regression: "qa.regression.json",
997
+ qa_api: "qa.api.json",
998
+ qa_manual_web: "qa.manual-web.json",
999
+ qa_bug_repro: "qa.bug-repro.json",
1000
+ qa_findings: "qa.findings.json",
1001
+ qa_verdict: "qa.verdict.json"
1002
+ };
872
1003
  function hasLaunchTarget(target) {
873
1004
  return Boolean(target?.url?.trim()
874
1005
  || target?.ready_url?.trim()
875
1006
  || target?.command?.trim()
876
1007
  || (target?.routes ?? []).some((route) => route.trim().length > 0));
877
1008
  }
878
- function deterministicBrowserSidecar(workItemId, target) {
1009
+ function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
879
1010
  const route = primaryLaunchRoute(target);
880
1011
  return {
881
- relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt"),
1012
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
882
1013
  content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
883
1014
  };
884
1015
  }
@@ -935,16 +1066,29 @@ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
935
1066
  eventType: "phase_gate"
936
1067
  });
937
1068
  }
938
- async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
939
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
940
- if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
1069
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1070
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1071
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
941
1072
  return null;
942
1073
  }
943
- await validateQaBundleSidecarReferences(worktreePath, workItemId);
944
- return artifact;
1074
+ const artifactRoot = ownerType && ownerId
1075
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1076
+ : artifactRootFor(worktreePath, workItemId);
1077
+ const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1078
+ const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1079
+ const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1080
+ await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1081
+ return {
1082
+ ...artifact,
1083
+ planJson,
1084
+ evidenceJson,
1085
+ findingsJson
1086
+ };
945
1087
  }
946
- async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
947
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1088
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1089
+ const artifactRoot = ownerType && ownerId
1090
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1091
+ : artifactRootFor(worktreePath, workItemId);
948
1092
  for (const fileName of Object.values(qaArtifactFileNames)) {
949
1093
  try {
950
1094
  const stat = await fs.stat(path.join(artifactRoot, fileName));
@@ -973,8 +1117,10 @@ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
973
1117
  throw new Error("QA browser testing is required but no app launch target was provided; provider must return blocked with blocker_reason missing_app_launch_target.");
974
1118
  }
975
1119
  }
976
- async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
977
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1120
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1121
+ const artifactRoot = ownerType && ownerId
1122
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1123
+ : artifactRootFor(worktreePath, workItemId);
978
1124
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
979
1125
  const sidecars = arrayField(evidence, "sidecars");
980
1126
  if (sidecars.length === 0) {
@@ -993,7 +1139,9 @@ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
993
1139
  }
994
1140
  const fullPath = path.resolve(worktreePath, sidecarPath);
995
1141
  if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
996
- throw new Error(`QA sidecar ${index} path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
1142
+ const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1143
+ const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1144
+ throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
997
1145
  }
998
1146
  const stat = await fs.lstat(fullPath).catch((error) => {
999
1147
  if (isNodeError(error) && error.code === "ENOENT") {
@@ -1014,8 +1162,8 @@ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
1014
1162
  }
1015
1163
  }
1016
1164
  }
1017
- async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
1018
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1165
+ async function emitQaStructuredEvents(emit, artifact) {
1166
+ const artifactRoot = path.dirname(artifact.path);
1019
1167
  const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
1020
1168
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1021
1169
  const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
@@ -1055,12 +1203,76 @@ async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact)
1055
1203
  eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
1056
1204
  });
1057
1205
  }
1206
+ function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1207
+ return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1208
+ ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1209
+ : artifactRootFor(worktreePath, workItemId);
1210
+ }
1211
+ async function readQaGateArtifact(artifactRoot, gate) {
1212
+ const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1213
+ try {
1214
+ const stat = await fs.stat(artifactPath);
1215
+ if (!stat.isFile()) {
1216
+ return null;
1217
+ }
1218
+ }
1219
+ catch (error) {
1220
+ if (isNodeError(error) && error.code === "ENOENT") {
1221
+ return null;
1222
+ }
1223
+ throw error;
1224
+ }
1225
+ const payload = await readJsonObjectFile(artifactPath);
1226
+ return {
1227
+ gate,
1228
+ path: artifactPath,
1229
+ status: stringField(payload, "status") ?? "unknown",
1230
+ producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1231
+ contentHash: stringField(payload, "content_hash") ?? undefined
1232
+ };
1233
+ }
1234
+ function nextQaGate(gate) {
1235
+ const index = qaCompletionGateOrder.indexOf(gate);
1236
+ return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1237
+ }
1238
+ async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1239
+ const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1240
+ await emit({
1241
+ role: "hook",
1242
+ kind: artifact.status === "blocked" ? "error" : "checkpoint",
1243
+ content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1244
+ eventType: "phase_gate",
1245
+ data: JSON.stringify({
1246
+ phase: "qa",
1247
+ qa_gate: artifact.gate,
1248
+ status: artifact.status,
1249
+ artifact_relative_paths: [relativePath],
1250
+ content_hash: artifact.contentHash ?? null,
1251
+ produced_by: artifact.producedBy ?? null
1252
+ })
1253
+ });
1254
+ if (!nextGate) {
1255
+ return;
1256
+ }
1257
+ await emit({
1258
+ role: "hook",
1259
+ kind: "checkpoint",
1260
+ content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1261
+ eventType: "phase_gate",
1262
+ data: JSON.stringify({
1263
+ phase: "qa",
1264
+ from_gate: artifact.gate,
1265
+ to_gate: nextGate
1266
+ })
1267
+ });
1268
+ }
1058
1269
  class LiveQaArtifactEmitter {
1059
1270
  worktreePath;
1060
1271
  workItemId;
1061
1272
  dispatch;
1062
1273
  emit;
1063
- emitted = false;
1274
+ emittedBundle = false;
1275
+ emittedGates = new Set();
1064
1276
  timer = null;
1065
1277
  pending = Promise.resolve();
1066
1278
  constructor(worktreePath, workItemId, dispatch, emit) {
@@ -1083,7 +1295,7 @@ class LiveQaArtifactEmitter {
1083
1295
  await this.pollQueued();
1084
1296
  }
1085
1297
  hasEmitted() {
1086
- return this.emitted;
1298
+ return this.emittedBundle;
1087
1299
  }
1088
1300
  pollQueued() {
1089
1301
  this.pending = this.pending
@@ -1092,19 +1304,125 @@ class LiveQaArtifactEmitter {
1092
1304
  return this.pending;
1093
1305
  }
1094
1306
  async poll() {
1095
- if (this.emitted) {
1307
+ await this.emitAvailableGateEvents();
1308
+ if (this.emittedBundle) {
1096
1309
  return;
1097
1310
  }
1098
- const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
1311
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
1099
1312
  if (!artifact) {
1100
1313
  return;
1101
1314
  }
1102
1315
  enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
1103
- this.emitted = true;
1316
+ this.emittedBundle = true;
1104
1317
  await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
1105
- await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1318
+ await emitQaStructuredEvents(this.emit, artifact);
1319
+ }
1320
+ async emitAvailableGateEvents() {
1321
+ const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1322
+ for (const gate of qaCompletionGateOrder) {
1323
+ if (this.emittedGates.has(gate)) {
1324
+ continue;
1325
+ }
1326
+ const artifact = await readQaGateArtifact(artifactRoot, gate);
1327
+ if (!artifact) {
1328
+ return;
1329
+ }
1330
+ this.emittedGates.add(gate);
1331
+ await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
1332
+ }
1106
1333
  }
1107
1334
  }
1335
+ class LiveArchitectArtifactEmitter {
1336
+ worktreePath;
1337
+ workItemId;
1338
+ emit;
1339
+ emitted = false;
1340
+ timer = null;
1341
+ pending = Promise.resolve();
1342
+ constructor(worktreePath, workItemId, emit) {
1343
+ this.worktreePath = worktreePath;
1344
+ this.workItemId = workItemId;
1345
+ this.emit = emit;
1346
+ }
1347
+ start() {
1348
+ void this.pollQueued();
1349
+ this.timer = setInterval(() => {
1350
+ void this.pollQueued();
1351
+ }, 250);
1352
+ }
1353
+ async stop() {
1354
+ if (this.timer) {
1355
+ clearInterval(this.timer);
1356
+ this.timer = null;
1357
+ }
1358
+ await this.pollQueued();
1359
+ }
1360
+ hasEmitted() {
1361
+ return this.emitted;
1362
+ }
1363
+ pollQueued() {
1364
+ this.pending = this.pending
1365
+ .then(() => this.poll())
1366
+ .catch(() => undefined);
1367
+ return this.pending;
1368
+ }
1369
+ async poll() {
1370
+ if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
1371
+ return;
1372
+ }
1373
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
1374
+ if (!artifact) {
1375
+ return;
1376
+ }
1377
+ this.emitted = true;
1378
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1379
+ await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1380
+ }
1381
+ }
1382
+ async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1383
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1384
+ for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1385
+ try {
1386
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1387
+ if (!stat.isFile()) {
1388
+ return false;
1389
+ }
1390
+ }
1391
+ catch (error) {
1392
+ if (isNodeError(error) && error.code === "ENOENT") {
1393
+ return false;
1394
+ }
1395
+ throw error;
1396
+ }
1397
+ }
1398
+ return true;
1399
+ }
1400
+ async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1401
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1402
+ const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1403
+ const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1404
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1405
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1406
+ const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1407
+ await emit({
1408
+ role: "worker",
1409
+ kind: "checkpoint",
1410
+ content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1411
+ eventType: "architect_plan"
1412
+ });
1413
+ await emit({
1414
+ role: "worker",
1415
+ kind: "checkpoint",
1416
+ content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1417
+ eventType: "architect_qa_seed"
1418
+ });
1419
+ await emit({
1420
+ role: "hook",
1421
+ kind: status === "pass" ? "checkpoint" : "error",
1422
+ content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1423
+ eventType: "architect_mcp_complete"
1424
+ });
1425
+ }
1108
1426
  async function readJsonObjectFile(filePath) {
1109
1427
  const content = await fs.readFile(filePath, "utf8").catch(() => "");
1110
1428
  return parseJsonLine(content) ?? {};
@@ -1129,16 +1447,36 @@ function summarizeQaObject(source) {
1129
1447
  ?? stringField(source, "id")
1130
1448
  ?? JSON.stringify(source), 500);
1131
1449
  }
1132
- function qaArtifactRelativePath(workItemId, fileName) {
1450
+ function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1451
+ if (ownerType && ownerId) {
1452
+ const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1453
+ return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1454
+ }
1133
1455
  return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
1134
1456
  }
1135
1457
  async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
1136
1458
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1459
+ await emit({
1460
+ role: "tool",
1461
+ kind: "checkpoint",
1462
+ content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1463
+ eventType: "completion_tool_validation_passed",
1464
+ data: JSON.stringify({
1465
+ phase: artifact.phase ?? "unknown",
1466
+ status: artifact.status,
1467
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1468
+ })
1469
+ });
1137
1470
  await emit({
1138
1471
  role: "tool",
1139
1472
  kind: "tool_result",
1140
1473
  content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
1141
- eventType: "completion_tool_artifact_recorded"
1474
+ eventType: "completion_tool_artifact_recorded",
1475
+ data: JSON.stringify({
1476
+ phase: artifact.phase ?? "unknown",
1477
+ status: artifact.status,
1478
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1479
+ })
1142
1480
  });
1143
1481
  }
1144
1482
  async function emitPhaseCompletionEvent(emit, artifact) {
@@ -1185,7 +1523,7 @@ async function emitPhaseGateEvents(emit, artifact) {
1185
1523
  function completionPhaseFromArtifact(artifact) {
1186
1524
  const phase = artifact.phase?.trim();
1187
1525
  return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1188
- || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1526
+ || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1189
1527
  ? phase
1190
1528
  : "implementation";
1191
1529
  }
@@ -1282,10 +1620,24 @@ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, de
1282
1620
  }
1283
1621
  return artifacts;
1284
1622
  }
1285
- function providerRedactionEnv(dispatch) {
1286
- const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
1623
+ function providerProcessEnv(dispatch) {
1624
+ const env = {
1625
+ ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1626
+ ...providerCredentialEnv(dispatch)
1627
+ };
1287
1628
  return Object.keys(env).length > 0 ? env : undefined;
1288
1629
  }
1630
+ function providerCredentialEnv(dispatch) {
1631
+ const secret = dispatch.apiKeySecretGrant?.secret;
1632
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1633
+ return {};
1634
+ }
1635
+ const provider = dispatch.execution.provider.trim().toLowerCase();
1636
+ if (provider === "codex" || provider === "openai") {
1637
+ return { OPENAI_API_KEY: secret };
1638
+ }
1639
+ return {};
1640
+ }
1289
1641
  function exactRedactionSecrets(dispatch) {
1290
1642
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
1291
1643
  }
@@ -1308,7 +1660,7 @@ export class StreamingProviderProcessRunner {
1308
1660
  return await new Promise((resolve, reject) => {
1309
1661
  const child = spawn(launch.command, launch.args, {
1310
1662
  cwd: request.cwd,
1311
- env: request.env ? { ...process.env, ...request.env } : undefined,
1663
+ env: buildProviderChildEnvironment(request.env),
1312
1664
  stdio: ["ignore", "pipe", "pipe"],
1313
1665
  windowsHide: true
1314
1666
  });
@@ -1460,6 +1812,66 @@ function isFakeWorkerModel(model) {
1460
1812
  function sha256(content) {
1461
1813
  return crypto.createHash("sha256").update(content).digest("hex");
1462
1814
  }
1815
+ function buildDraftPrompt(dispatch) {
1816
+ const draft = dispatch.draft;
1817
+ if (!draft) {
1818
+ throw new Error("Draft prompt is missing.");
1819
+ }
1820
+ return `${draft.systemPrompt}
1821
+
1822
+ Draft kind: ${draft.kind}
1823
+
1824
+ ${draft.userPrompt}
1825
+
1826
+ Return ONLY the requested JSON object. Do not wrap it in markdown and do not modify files.`;
1827
+ }
1828
+ function extractJsonObject(content) {
1829
+ let trimmed = content.trim();
1830
+ if (trimmed.startsWith("```")) {
1831
+ const firstNewline = trimmed.indexOf("\n");
1832
+ const lastFence = trimmed.lastIndexOf("```");
1833
+ if (firstNewline >= 0 && lastFence > firstNewline) {
1834
+ trimmed = trimmed.slice(firstNewline + 1, lastFence).trim();
1835
+ }
1836
+ }
1837
+ const start = trimmed.indexOf("{");
1838
+ const end = trimmed.lastIndexOf("}");
1839
+ return start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed;
1840
+ }
1841
+ function summarizeStderr(stderr) {
1842
+ const trimmed = stderr.trim();
1843
+ return trimmed ? `: ${clip(trimmed, 1000)}` : "";
1844
+ }
1845
+ function deterministicDraftPayload(dispatch) {
1846
+ const kind = dispatch.draft?.kind ?? "work_item";
1847
+ if (kind === "work_order") {
1848
+ return {
1849
+ title: "Deterministic runner Work Order draft",
1850
+ summary: "Forge Runner generated this deterministic Work Order draft.",
1851
+ objective: "Validate runner-backed Draft generation.",
1852
+ planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
1853
+ decompositionContext: "Use this deterministic fixture only in bridge tests.",
1854
+ assumptions: ["Forge Runner dispatch is available."],
1855
+ warnings: []
1856
+ };
1857
+ }
1858
+ if (kind === "story") {
1859
+ return {
1860
+ title: "Deterministic runner Story draft",
1861
+ description: "Forge Runner generated this deterministic Story draft.",
1862
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
1863
+ points: 3
1864
+ };
1865
+ }
1866
+ return {
1867
+ title: "Deterministic runner Work Item draft",
1868
+ description: "Forge Runner generated this deterministic Work Item draft.",
1869
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
1870
+ reproSteps: "Run Draft with a Forge Runner provider selected.",
1871
+ systemInfo: "forge-bridge deterministic provider",
1872
+ points: 1
1873
+ };
1874
+ }
1463
1875
  export function formatProviderCliCommand(command) {
1464
1876
  return [command.command, ...command.args].map(singleLine).join(" ");
1465
1877
  }
@@ -1471,16 +1883,19 @@ export function buildProviderCliCommand(dispatch, run) {
1471
1883
  const normalizedProvider = provider.toLowerCase();
1472
1884
  const model = dispatch.execution.model.trim();
1473
1885
  if (normalizedProvider === "codex") {
1474
- const args = ["exec"];
1886
+ const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
1475
1887
  if (run?.completionTools) {
1476
1888
  args.push(...codexMcpConfigArgs(run.completionTools));
1477
1889
  }
1478
1890
  args.push("--model", model);
1479
1891
  if (run) {
1480
- args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
1892
+ args.push("--json");
1481
1893
  if (run.worktreePath) {
1482
1894
  args.push("--cd", run.worktreePath);
1483
1895
  }
1896
+ if (run.skipGitRepoCheck) {
1897
+ args.push("--skip-git-repo-check");
1898
+ }
1484
1899
  args.push(run.prompt ?? "");
1485
1900
  }
1486
1901
  return { command: "codex", args };
@@ -1501,6 +1916,9 @@ export function buildProviderCliCommand(dispatch, run) {
1501
1916
  }
1502
1917
  return { command: provider, args };
1503
1918
  }
1919
+ export function codexSandboxModeForPlatform(platform = process.platform) {
1920
+ return platform === "win32" ? "danger-full-access" : "workspace-write";
1921
+ }
1504
1922
  function buildArchitectPrompt(dispatch) {
1505
1923
  return `You are Forge's Architect lane running locally in a prepared git worktree.
1506
1924
 
@@ -1508,12 +1926,24 @@ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
1508
1926
 
1509
1927
  Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
1510
1928
  Read injected Forge context under .forge plus the repository shape, then produce a repo-grounded implementation DAG with task tests, phase gates, final QA coverage, and a pending-approval spec.
1929
+ ${architectRevisionInstruction(dispatch)}
1511
1930
  Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
1512
1931
 
1513
1932
  ${completionPromptForPhase("architect")}
1514
1933
 
1515
1934
  Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
1516
1935
  }
1936
+ function architectRevisionInstruction(dispatch) {
1937
+ if (!dispatch.architectRevision) {
1938
+ return "";
1939
+ }
1940
+ return `
1941
+ Architect revision context:
1942
+ - Previous plan id: ${dispatch.architectRevision.priorPlanId}
1943
+ - Previous content hash: ${dispatch.architectRevision.priorContentHash}
1944
+ - Reviewer feedback: ${dispatch.architectRevision.feedback}
1945
+ Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
1946
+ }
1517
1947
  function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1518
1948
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
1519
1949
 
@@ -1565,7 +1995,8 @@ QA rework context:
1565
1995
  - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1566
1996
  - Rework packet: ${dispatch.qaRework.packetPath}
1567
1997
  - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1568
- 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.`;
1998
+ Read the packet JSON and fix or explicitly dispute each listed finding. The implementation completion artifact must include resolved_findings entries for every required QA ID with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.
1999
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
1569
2000
  }
1570
2001
  function debugQaReworkInstruction(dispatch) {
1571
2002
  if (!dispatch.qaRework) {
@@ -1576,7 +2007,8 @@ QA rework context for Debug:
1576
2007
  - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1577
2008
  - Rework packet: ${dispatch.qaRework.packetPath}
1578
2009
  - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1579
- 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.`;
2010
+ Read the packet JSON, reproduce or characterize each listed finding, fix or explicitly dispute it, and include resolved_findings entries for every required QA ID in forge.complete_debug_fix with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.
2011
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
1580
2012
  }
1581
2013
  function qaReworkRetestInstruction(dispatch) {
1582
2014
  if (!dispatch.qaRework) {
@@ -1613,6 +2045,39 @@ function qaBrowserInstruction(dispatch) {
1613
2045
  const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
1614
2046
  return `Browser/app launch context:\n- Browser QA required: ${qaBrowser.required ? "yes" : "no, unless the diff/AC requires it"}\n- URL: ${launchTarget.url || "not specified"}\n- Ready URL: ${launchTarget.ready_url || "not specified"}\n- Launch command: ${launchTarget.command || "not specified"}\n- Working directory: ${launchTarget.working_directory || "repo root"}\n- Routes to cover: ${routes}\n- Notes: ${launchTarget.notes || "none"}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
1615
2047
  }
2048
+ function storyQaInstruction(dispatch) {
2049
+ const storyQa = dispatch.storyQa;
2050
+ if (!storyQa) {
2051
+ return "";
2052
+ }
2053
+ const childLines = storyQa.childTasks.map((child) => {
2054
+ const dependencies = child.dependencyWorkItemIds.length > 0
2055
+ ? child.dependencyWorkItemIds.join(", ")
2056
+ : "none";
2057
+ const validation = child.validationArtifact
2058
+ ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2059
+ : "missing";
2060
+ const childQa = child.qaArtifact
2061
+ ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2062
+ : "not present";
2063
+ return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2064
+ }).join("\n");
2065
+ const finalQa = storyQa.finalQaChecks.length > 0
2066
+ ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2067
+ : "- No final QA checks were provided in qa.plan.final_qa.";
2068
+ return `Story QA integration context:
2069
+ - Story work item: ${storyQa.storyWorkItemId}
2070
+ - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2071
+ - Story worktree: ${storyQa.worktreeKey}
2072
+ - Branch: ${storyQa.branch}
2073
+ - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2074
+ - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2075
+ Materialized child tasks and evidence:
2076
+ ${childLines || "- No child tasks were provided."}
2077
+ Architect final QA checks:
2078
+ ${finalQa}
2079
+ This is parent Story QA: inspect the integrated Story result, all current-plan child specs/evidence, and the final worktree state. Do not treat the final child task as separately signed off.`;
2080
+ }
1616
2081
  function buildQaPrompt(dispatch, laneSpec) {
1617
2082
  return `You are Forge's QA lane running locally in a prepared git worktree.
1618
2083
 
@@ -1637,6 +2102,7 @@ ${dispatch.workItem.reproSteps || "Not provided."}
1637
2102
  System info / environment notes:
1638
2103
  ${dispatch.workItem.systemInfo || "Not provided."}
1639
2104
 
2105
+ ${storyQaInstruction(dispatch)}
1640
2106
  Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1641
2107
  ${qaBrowserInstruction(dispatch)}
1642
2108
  ${qaReworkRetestInstruction(dispatch)}
@@ -1678,6 +2144,7 @@ PR context:
1678
2144
  - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
1679
2145
 
1680
2146
  Use the PR URL, local git metadata, and available GitHub tooling/auth to inspect unresolved review threads. Make focused code or test changes that answer the feedback, commit the changes, and push ${branchName} to origin.
2147
+ After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
1681
2148
  If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
1682
2149
  Keep the original work item intent intact:
1683
2150
  - Work item: ${dispatch.workItem.id}
@@ -1746,31 +2213,31 @@ class CursorStreamJsonState {
1746
2213
  consume(line) {
1747
2214
  const event = parseJsonLine(line);
1748
2215
  if (!event) {
1749
- return null;
2216
+ return [];
1750
2217
  }
1751
2218
  const type = stringField(event, "type");
1752
2219
  if (type === "system" && stringField(event, "subtype") === "init") {
1753
2220
  this.sessionId = stringField(event, "session_id");
1754
2221
  if (this.sessionId && !this.emittedSession) {
1755
2222
  this.emittedSession = true;
1756
- return {
1757
- role: "runner",
1758
- kind: "checkpoint",
1759
- content: `Cursor session started: ${this.sessionId}.`,
1760
- eventType: "provider_thread_started"
1761
- };
2223
+ return [{
2224
+ role: "runner",
2225
+ kind: "checkpoint",
2226
+ content: `Cursor session started: ${this.sessionId}.`,
2227
+ eventType: "provider_thread_started"
2228
+ }];
1762
2229
  }
1763
2230
  }
1764
2231
  if (type === "assistant") {
1765
2232
  const text = assistantMessageText(event);
1766
2233
  if (text) {
1767
2234
  this.finalMessage = clip(text, 4000);
1768
- return {
1769
- role: "assistant",
1770
- kind: "message",
1771
- content: this.finalMessage,
1772
- eventType: "provider_message"
1773
- };
2235
+ return [{
2236
+ role: "assistant",
2237
+ kind: "message",
2238
+ content: this.finalMessage,
2239
+ eventType: "provider_message"
2240
+ }];
1774
2241
  }
1775
2242
  }
1776
2243
  if (type === "tool_call") {
@@ -1779,23 +2246,23 @@ class CursorStreamJsonState {
1779
2246
  if (subtype === "started") {
1780
2247
  const summary = formatCursorToolCallStarted(toolCall);
1781
2248
  if (summary) {
1782
- return {
1783
- role: "worker",
1784
- kind: "checkpoint",
1785
- content: summary,
1786
- eventType: "provider_tool_call"
1787
- };
2249
+ return [{
2250
+ role: "worker",
2251
+ kind: "checkpoint",
2252
+ content: summary,
2253
+ eventType: "provider_tool_call"
2254
+ }];
1788
2255
  }
1789
2256
  }
1790
2257
  if (subtype === "completed") {
1791
2258
  const completed = formatCursorToolCallCompleted(toolCall);
1792
2259
  if (completed) {
1793
- return {
1794
- role: "worker",
1795
- kind: completed.kind,
1796
- content: completed.content,
1797
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
1798
- };
2260
+ return [{
2261
+ role: "worker",
2262
+ kind: completed.kind,
2263
+ content: completed.content,
2264
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2265
+ }];
1799
2266
  }
1800
2267
  }
1801
2268
  }
@@ -1807,14 +2274,14 @@ class CursorStreamJsonState {
1807
2274
  this.accumulateUsage(event);
1808
2275
  }
1809
2276
  if (type === "error" || (type === "result" && event.is_error === true)) {
1810
- return {
1811
- role: "runner",
1812
- kind: "error",
1813
- content: clip(line.trim(), 1000),
1814
- eventType: "provider_cli_error"
1815
- };
2277
+ return [{
2278
+ role: "runner",
2279
+ kind: "error",
2280
+ content: clip(line.trim(), 1000),
2281
+ eventType: "provider_cli_error"
2282
+ }];
1816
2283
  }
1817
- return null;
2284
+ return [];
1818
2285
  }
1819
2286
  accumulateUsage(event) {
1820
2287
  const usage = objectField(event, "usage");
@@ -1945,37 +2412,37 @@ class CodexJsonState {
1945
2412
  consume(line) {
1946
2413
  const event = parseJsonLine(line);
1947
2414
  if (!event) {
1948
- return null;
2415
+ return [];
1949
2416
  }
1950
2417
  const type = stringField(event, "type") ?? "";
1951
2418
  if (type === "thread.started") {
1952
2419
  this.threadId = stringField(event, "thread_id");
1953
2420
  if (this.threadId && !this.emittedThread) {
1954
2421
  this.emittedThread = true;
1955
- return {
1956
- role: "runner",
1957
- kind: "checkpoint",
1958
- content: `Codex thread started: ${this.threadId}.`,
1959
- eventType: "provider_thread_started"
1960
- };
2422
+ return [{
2423
+ role: "runner",
2424
+ kind: "checkpoint",
2425
+ content: `Codex thread started: ${this.threadId}.`,
2426
+ eventType: "provider_thread_started"
2427
+ }];
1961
2428
  }
1962
2429
  }
1963
2430
  if (type === "turn.completed") {
1964
2431
  this.accumulateUsage(event);
1965
- return {
1966
- role: "runner",
1967
- kind: "checkpoint",
1968
- content: "Codex turn completed.",
1969
- eventType: "provider_turn_completed"
1970
- };
2432
+ return [{
2433
+ role: "runner",
2434
+ kind: "checkpoint",
2435
+ content: "Codex turn completed.",
2436
+ eventType: "provider_turn_completed"
2437
+ }];
1971
2438
  }
1972
2439
  if (type === "turn.failed" || type === "error") {
1973
- return {
1974
- role: "runner",
1975
- kind: "error",
1976
- content: clip(line.trim(), 1000),
1977
- eventType: "provider_cli_error"
1978
- };
2440
+ return [{
2441
+ role: "runner",
2442
+ kind: "error",
2443
+ content: clip(line.trim(), 1000),
2444
+ eventType: "provider_cli_error"
2445
+ }];
1979
2446
  }
1980
2447
  if (type === "item.completed" || type === "item.updated") {
1981
2448
  const item = objectField(event, "item");
@@ -1984,28 +2451,32 @@ class CodexJsonState {
1984
2451
  const text = stringField(item, "text");
1985
2452
  if (text) {
1986
2453
  this.finalMessage = clip(text, 4000);
1987
- return {
1988
- role: "assistant",
1989
- kind: "message",
1990
- content: this.finalMessage,
1991
- eventType: "provider_message"
1992
- };
2454
+ return [{
2455
+ role: "assistant",
2456
+ kind: "message",
2457
+ content: this.finalMessage,
2458
+ eventType: "provider_message"
2459
+ }];
1993
2460
  }
1994
2461
  }
1995
2462
  if (itemType === "command_execution") {
1996
2463
  const command = stringField(item, "command");
1997
2464
  const status = stringField(item, "status");
1998
2465
  if (command) {
1999
- return {
2000
- role: "worker",
2001
- kind: "checkpoint",
2002
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2003
- eventType: "provider_command"
2004
- };
2466
+ return [{
2467
+ role: "worker",
2468
+ kind: "checkpoint",
2469
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2470
+ eventType: "provider_command"
2471
+ }];
2005
2472
  }
2006
2473
  }
2007
2474
  }
2008
- return null;
2475
+ const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2476
+ if (mcpEvents.length > 0) {
2477
+ return mcpEvents;
2478
+ }
2479
+ return [];
2009
2480
  }
2010
2481
  accumulateUsage(event) {
2011
2482
  const usage = objectField(event, "usage");
@@ -2021,6 +2492,113 @@ class CodexJsonState {
2021
2492
  });
2022
2493
  }
2023
2494
  }
2495
+ function formatCodexMcpToolCallEvents(type, event) {
2496
+ if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2497
+ return [];
2498
+ }
2499
+ const item = objectField(event, "item");
2500
+ const itemType = stringField(item, "type") ?? "";
2501
+ const serverName = mcpServerName(item);
2502
+ const toolName = mcpToolName(item);
2503
+ const isMcpItem = itemType.toLowerCase().includes("mcp")
2504
+ || Boolean(serverName)
2505
+ || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2506
+ if (!isMcpItem || !toolName) {
2507
+ return [];
2508
+ }
2509
+ const status = normalizedString(stringField(item, "status")
2510
+ ?? stringField(event, "status")
2511
+ ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2512
+ const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2513
+ const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2514
+ const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2515
+ const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2516
+ const label = `${serverName ?? "unknown"}.${toolName}`;
2517
+ if (failed) {
2518
+ const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2519
+ const events = [{
2520
+ role: "tool",
2521
+ kind: "error",
2522
+ content: `MCP tool call failed: ${label} - ${summary}`,
2523
+ eventType: "provider_mcp_call_failed",
2524
+ data
2525
+ }];
2526
+ if (isForgeCompletionTool(toolName)) {
2527
+ events.push({
2528
+ role: "tool",
2529
+ kind: "error",
2530
+ content: `Forge completion tool validation failed: ${label} - ${summary}`,
2531
+ eventType: "completion_tool_validation_failed",
2532
+ data
2533
+ });
2534
+ }
2535
+ return events;
2536
+ }
2537
+ if (completed) {
2538
+ return [{
2539
+ role: "tool",
2540
+ kind: "checkpoint",
2541
+ content: `MCP tool call completed: ${label}.`,
2542
+ eventType: "provider_mcp_call_completed",
2543
+ data
2544
+ }];
2545
+ }
2546
+ if (started) {
2547
+ return [{
2548
+ role: "tool",
2549
+ kind: "checkpoint",
2550
+ content: `MCP tool call started: ${label}.`,
2551
+ eventType: "provider_mcp_call_started",
2552
+ data
2553
+ }];
2554
+ }
2555
+ return [];
2556
+ }
2557
+ function mcpServerName(item) {
2558
+ return stringField(item, "server")
2559
+ ?? stringField(item, "server_name")
2560
+ ?? stringField(item, "mcp_server")
2561
+ ?? stringField(objectField(item, "mcp"), "server")
2562
+ ?? stringField(objectField(item, "mcp"), "server_name");
2563
+ }
2564
+ function mcpToolName(item) {
2565
+ return stringField(item, "tool")
2566
+ ?? stringField(item, "tool_name")
2567
+ ?? stringField(item, "name")
2568
+ ?? stringField(objectField(item, "function"), "name")
2569
+ ?? stringField(objectField(item, "mcp"), "tool")
2570
+ ?? stringField(objectField(item, "mcp"), "tool_name");
2571
+ }
2572
+ function mcpErrorSummary(item) {
2573
+ const direct = stringField(item, "error")
2574
+ ?? stringField(item, "error_message")
2575
+ ?? stringField(item, "message");
2576
+ if (direct) {
2577
+ return clip(direct, 600);
2578
+ }
2579
+ const error = objectField(item, "error");
2580
+ return stringField(error, "message")
2581
+ ?? stringField(error, "summary")
2582
+ ?? stringField(objectField(item, "result"), "error")
2583
+ ?? null;
2584
+ }
2585
+ function safeProviderMcpData(item, serverName, toolName, status) {
2586
+ const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2587
+ return JSON.stringify(stripUndefined({
2588
+ server_name: serverName,
2589
+ tool_name: toolName,
2590
+ status,
2591
+ elapsed_ms: elapsedMs,
2592
+ error_summary: mcpErrorSummary(item)
2593
+ }));
2594
+ }
2595
+ function isForgeCompletionTool(toolName) {
2596
+ const normalized = toolName.trim().toLowerCase();
2597
+ return normalized.startsWith("forge.complete_")
2598
+ || normalized.startsWith("complete_")
2599
+ || normalized.includes("forge.complete_")
2600
+ || normalized.includes("complete_architect_plan");
2601
+ }
2024
2602
  function objectField(source, key) {
2025
2603
  const value = source[key];
2026
2604
  return value && typeof value === "object" && !Array.isArray(value)
@@ -2031,6 +2609,13 @@ function stringField(source, key) {
2031
2609
  const value = source[key];
2032
2610
  return typeof value === "string" && value.trim().length > 0 ? value : null;
2033
2611
  }
2612
+ function numericField(source, key) {
2613
+ const value = source[key];
2614
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2615
+ }
2616
+ function stripUndefined(value) {
2617
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2618
+ }
2034
2619
  function normalizedString(value) {
2035
2620
  return value.trim().toLowerCase().replace(/-/g, "_");
2036
2621
  }