@loucompanion/forge-bridge 0.1.1-dev.9acab970e5d1 → 0.1.1-dev.a8025fe64c0a

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,140 @@ 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
+ "SystemDrive",
29
+ "ComSpec",
30
+ "PATHEXT",
31
+ "APPDATA",
32
+ "LOCALAPPDATA",
33
+ "USERNAME",
34
+ "USERDOMAIN",
35
+ "HOMEDRIVE",
36
+ "HOMEPATH",
37
+ "ProgramData",
38
+ "ProgramFiles",
39
+ "ProgramFiles(x86)",
40
+ "ProgramW6432",
41
+ "DOTNET_ROOT",
42
+ "DOTNET_ROOT(x86)",
43
+ "DOTNET_CLI_HOME",
44
+ "NUGET_PACKAGES",
45
+ "NUGET_HTTP_CACHE_PATH"
46
+ ];
47
+ export function buildProviderChildEnvironment(requestEnv, options = {}) {
48
+ const parentEnv = options.parentEnv ?? process.env;
49
+ const platform = options.platform ?? process.platform;
50
+ const env = {};
51
+ for (const [key, value] of Object.entries(parentEnv)) {
52
+ if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
53
+ env[key] = value;
54
+ }
55
+ }
56
+ if (requestEnv) {
57
+ for (const [key, value] of Object.entries(requestEnv)) {
58
+ const trimmedKey = key.trim();
59
+ if (trimmedKey.length > 0) {
60
+ env[trimmedKey] = value;
61
+ }
62
+ }
63
+ }
64
+ if (platform === "win32") {
65
+ normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
66
+ }
67
+ return env;
68
+ }
69
+ function isAllowedProviderParentEnv(key, platform = process.platform) {
70
+ return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
71
+ || key.toUpperCase().startsWith("LC_")
72
+ || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
73
+ }
74
+ function isAllowedProviderParentEnvName(key, allowedNames) {
75
+ return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
76
+ }
77
+ function normalizeWindowsDotNetEnvironment(env, parentEnv, homeDir) {
78
+ const systemRoot = readEnvironmentValue(env, "SystemRoot") ?? readEnvironmentValue(parentEnv, "SystemRoot") ?? "C:\\Windows";
79
+ const systemDrive = path.win32.parse(systemRoot).root.replace(/\\$/, "") || "C:";
80
+ setEnvironmentValueIfMissing(env, "SystemRoot", systemRoot);
81
+ setEnvironmentValueIfMissing(env, "SystemDrive", readEnvironmentValue(parentEnv, "SystemDrive") ?? systemDrive);
82
+ setEnvironmentValueIfMissing(env, "ComSpec", readEnvironmentValue(parentEnv, "ComSpec") ?? path.win32.join(systemRoot, "System32", "cmd.exe"));
83
+ setEnvironmentValueIfMissing(env, "PATHEXT", readEnvironmentValue(parentEnv, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL");
84
+ const userProfile = resolveWindowsUserProfile(env, parentEnv, homeDir);
85
+ if (userProfile) {
86
+ setEnvironmentValueIfMissing(env, "USERPROFILE", userProfile);
87
+ setEnvironmentValueIfMissing(env, "HOME", userProfile);
88
+ setEnvironmentValueIfMissing(env, "DOTNET_CLI_HOME", userProfile);
89
+ setEnvironmentValueIfMissing(env, "NUGET_PACKAGES", path.win32.join(userProfile, ".nuget", "packages"));
90
+ const parsed = path.win32.parse(userProfile);
91
+ if (parsed.root) {
92
+ setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
93
+ setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
94
+ }
95
+ }
96
+ const appData = readEnvironmentValue(env, "APPDATA")
97
+ ?? readEnvironmentValue(parentEnv, "APPDATA")
98
+ ?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
99
+ const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
100
+ ?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
101
+ ?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
102
+ if (appData) {
103
+ setEnvironmentValueIfMissing(env, "APPDATA", appData);
104
+ }
105
+ if (localAppData) {
106
+ setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
107
+ setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
108
+ }
109
+ setEnvironmentValueIfMissing(env, "DOTNET_NOLOGO", "1");
110
+ setEnvironmentValueIfMissing(env, "DOTNET_CLI_TELEMETRY_OPTOUT", "1");
111
+ setEnvironmentValueIfMissing(env, "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
112
+ setEnvironmentValueIfMissing(env, "NUGET_XMLDOC_MODE", "skip");
113
+ }
114
+ function resolveWindowsUserProfile(env, parentEnv, homeDir) {
115
+ const existing = readEnvironmentValue(env, "USERPROFILE") ?? readEnvironmentValue(parentEnv, "USERPROFILE");
116
+ if (existing) {
117
+ return existing;
118
+ }
119
+ const home = readEnvironmentValue(env, "HOME") ?? readEnvironmentValue(parentEnv, "HOME");
120
+ if (home && path.win32.isAbsolute(home)) {
121
+ return home;
122
+ }
123
+ const homeDrive = readEnvironmentValue(env, "HOMEDRIVE") ?? readEnvironmentValue(parentEnv, "HOMEDRIVE");
124
+ const homePath = readEnvironmentValue(env, "HOMEPATH") ?? readEnvironmentValue(parentEnv, "HOMEPATH");
125
+ if (homeDrive && homePath) {
126
+ return `${homeDrive}${homePath}`;
127
+ }
128
+ if (homeDir && path.win32.isAbsolute(homeDir)) {
129
+ return homeDir;
130
+ }
131
+ const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
132
+ const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
133
+ return username ? path.win32.join(systemDrive, "Users", username) : undefined;
134
+ }
135
+ function readEnvironmentValue(env, name) {
136
+ const entry = Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase());
137
+ const value = entry?.[1];
138
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
139
+ }
140
+ function setEnvironmentValueIfMissing(env, name, value) {
141
+ if (readEnvironmentValue(env, name)) {
142
+ return;
143
+ }
144
+ env[name] = value;
145
+ }
16
146
  export class RoutingProviderCliService {
17
147
  realProvider;
18
148
  deterministicProvider;
@@ -25,6 +155,11 @@ export class RoutingProviderCliService {
25
155
  ? await this.deterministicProvider.runImplementation(context)
26
156
  : await this.realProvider.runImplementation(context);
27
157
  }
158
+ async runArchitect(context) {
159
+ return isFakeWorkerModel(context.dispatch.execution.model)
160
+ ? await this.deterministicProvider.runArchitect(context)
161
+ : await this.realProvider.runArchitect(context);
162
+ }
28
163
  async runConflictResolve(context) {
29
164
  return isFakeWorkerModel(context.dispatch.execution.model)
30
165
  ? await this.deterministicProvider.runConflictResolve(context)
@@ -35,6 +170,11 @@ export class RoutingProviderCliService {
35
170
  ? await this.deterministicProvider.runQa(context)
36
171
  : await this.realProvider.runQa(context);
37
172
  }
173
+ async runDraft(context) {
174
+ return isFakeWorkerModel(context.dispatch.execution.model)
175
+ ? await this.deterministicProvider.runDraft(context)
176
+ : await this.realProvider.runDraft(context);
177
+ }
38
178
  }
39
179
  export class ProcessBackedProviderCliService {
40
180
  processRunner;
@@ -43,6 +183,60 @@ export class ProcessBackedProviderCliService {
43
183
  this.processRunner = processRunner;
44
184
  this.git = git;
45
185
  }
186
+ async runDraft(context) {
187
+ const { dispatch } = context;
188
+ if (!dispatch.draft) {
189
+ throw new Error("Draft dispatch context is missing.");
190
+ }
191
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "forge-bridge-draft-"));
192
+ const command = buildProviderCliCommand(dispatch, {
193
+ worktreePath: tempDir,
194
+ prompt: buildDraftPrompt(dispatch),
195
+ skipGitRepoCheck: true
196
+ });
197
+ await context.emit({
198
+ role: "runner",
199
+ kind: "checkpoint",
200
+ content: `Starting provider CLI Draft: ${formatProviderCliCommand(command)}`,
201
+ eventType: "provider_cli_started"
202
+ });
203
+ const outputState = createProviderOutputState(dispatch.execution.provider);
204
+ try {
205
+ const result = await this.processRunner.run({
206
+ command: command.command,
207
+ args: command.args,
208
+ cwd: tempDir,
209
+ env: providerProcessEnv(dispatch)
210
+ }, {
211
+ onStdoutLine: async (line) => {
212
+ for (const event of outputState.consume(line)) {
213
+ await context.emit(event);
214
+ }
215
+ }
216
+ }, context.signal);
217
+ if (result.exitCode !== 0) {
218
+ throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
219
+ }
220
+ const content = outputState.finalMessage ?? result.stdout.trim();
221
+ if (!content) {
222
+ throw new Error("Provider CLI completed without returning a draft.");
223
+ }
224
+ const json = extractJsonObject(content);
225
+ await context.emit({
226
+ role: "assistant",
227
+ kind: "message",
228
+ content: json,
229
+ eventType: "draft_complete"
230
+ });
231
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
232
+ return {
233
+ summary: "Draft generated through Forge Runner."
234
+ };
235
+ }
236
+ finally {
237
+ await fs.rm(tempDir, { recursive: true, force: true });
238
+ }
239
+ }
46
240
  async runImplementation(context) {
47
241
  const { dispatch, worktree } = context;
48
242
  const phase = completionPhaseFromDispatch(dispatch);
@@ -93,11 +287,10 @@ export class ProcessBackedProviderCliService {
93
287
  command: command.command,
94
288
  args: command.args,
95
289
  cwd: worktree.worktreePath,
96
- env: providerRedactionEnv(dispatch)
290
+ env: providerProcessEnv(dispatch)
97
291
  }, {
98
292
  onStdoutLine: async (line) => {
99
- const event = outputState.consume(line);
100
- if (event) {
293
+ for (const event of outputState.consume(line)) {
101
294
  await context.emit(event);
102
295
  }
103
296
  }
@@ -157,6 +350,89 @@ export class ProcessBackedProviderCliService {
157
350
  artifacts: completionArtifacts
158
351
  };
159
352
  }
353
+ async runArchitect(context) {
354
+ const { dispatch, worktree } = context;
355
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
356
+ const command = buildProviderCliCommand(dispatch, {
357
+ worktreePath: worktree.worktreePath,
358
+ prompt: buildArchitectPrompt(dispatch),
359
+ completionTools
360
+ });
361
+ const commandText = formatProviderCliCommand(command);
362
+ await context.emit({
363
+ role: "runner",
364
+ kind: "checkpoint",
365
+ content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
366
+ eventType: "provider_cli_started"
367
+ });
368
+ await context.emit({
369
+ role: "runner",
370
+ kind: "checkpoint",
371
+ content: "Forge Architect completion tools configured; provider must call forge.complete_architect_plan before exit.",
372
+ eventType: "completion_tools_configured"
373
+ });
374
+ const outputState = createProviderOutputState(dispatch.execution.provider);
375
+ const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
376
+ let result;
377
+ try {
378
+ liveArchitectEvents.start();
379
+ result = await this.processRunner.run({
380
+ command: command.command,
381
+ args: command.args,
382
+ cwd: worktree.worktreePath,
383
+ env: providerProcessEnv(dispatch)
384
+ }, {
385
+ onStdoutLine: async (line) => {
386
+ for (const event of outputState.consume(line)) {
387
+ await context.emit(event);
388
+ }
389
+ }
390
+ }, context.signal);
391
+ }
392
+ finally {
393
+ await liveArchitectEvents.stop();
394
+ await cleanupCompletionTools(completionTools, context.emit);
395
+ }
396
+ if (result.exitCode !== 0) {
397
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
398
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
399
+ }
400
+ await context.emit({
401
+ role: "runner",
402
+ kind: "checkpoint",
403
+ content: `Provider CLI Architect completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
404
+ eventType: "provider_cli_completed"
405
+ });
406
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
407
+ const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
408
+ if (!architectArtifact) {
409
+ throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
410
+ }
411
+ if (!liveArchitectEvents.hasEmitted()) {
412
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
413
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, architectArtifact);
414
+ }
415
+ await context.emit({
416
+ role: "assistant",
417
+ kind: "message",
418
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI produced an Architect plan for ${worktree.branchName}.`,
419
+ eventType: "architect_complete"
420
+ });
421
+ const specPath = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id, "spec.md");
422
+ const specBody = await fs.readFile(specPath, "utf8").catch(() => `# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`);
423
+ return {
424
+ summary: `${dispatch.execution.provider} CLI Architect plan produced.`,
425
+ spec: {
426
+ repoPath: worktree.worktreePath,
427
+ path: specPath,
428
+ body: specBody,
429
+ producedBy: `${dispatch.execution.provider}-cli`,
430
+ status: "pending_approval"
431
+ },
432
+ artifact: architectArtifact,
433
+ artifacts: [architectArtifact]
434
+ };
435
+ }
160
436
  async runQa(context) {
161
437
  const { dispatch, worktree } = context;
162
438
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -197,11 +473,10 @@ export class ProcessBackedProviderCliService {
197
473
  command: command.command,
198
474
  args: command.args,
199
475
  cwd: worktree.worktreePath,
200
- env: providerRedactionEnv(dispatch)
476
+ env: providerProcessEnv(dispatch)
201
477
  }, {
202
478
  onStdoutLine: async (line) => {
203
- const event = outputState.consume(line);
204
- if (event) {
479
+ for (const event of outputState.consume(line)) {
205
480
  await context.emit(event);
206
481
  }
207
482
  }
@@ -222,7 +497,7 @@ export class ProcessBackedProviderCliService {
222
497
  eventType: "provider_cli_completed"
223
498
  });
224
499
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
225
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
500
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
226
501
  if (!qaArtifact) {
227
502
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
228
503
  throw new Error(verdictOnly
@@ -232,7 +507,7 @@ export class ProcessBackedProviderCliService {
232
507
  enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
233
508
  if (!liveQaEvents.hasEmitted()) {
234
509
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
235
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
510
+ await emitQaStructuredEvents(context.emit, qaArtifact);
236
511
  }
237
512
  const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
238
513
  const statusSummary = status === "pass"
@@ -272,11 +547,11 @@ export class ProcessBackedProviderCliService {
272
547
  const result = await this.processRunner.run({
273
548
  command: command.command,
274
549
  args: command.args,
275
- cwd: worktree.worktreePath
550
+ cwd: worktree.worktreePath,
551
+ env: providerProcessEnv(dispatch)
276
552
  }, {
277
553
  onStdoutLine: async (line) => {
278
- const event = outputState.consume(line);
279
- if (event) {
554
+ for (const event of outputState.consume(line)) {
280
555
  await context.emit(event);
281
556
  }
282
557
  }
@@ -308,6 +583,17 @@ export class DeterministicProviderCliService {
308
583
  constructor(git = new GitClient()) {
309
584
  this.git = git;
310
585
  }
586
+ async runDraft(context) {
587
+ const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
588
+ await context.emit({
589
+ role: "assistant",
590
+ kind: "message",
591
+ content,
592
+ eventType: "draft_complete"
593
+ });
594
+ await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
595
+ return { summary: "forge-bridge generated deterministic draft." };
596
+ }
311
597
  async runImplementation(context) {
312
598
  const { dispatch, worktree } = context;
313
599
  const phase = completionPhaseFromDispatch(dispatch);
@@ -386,6 +672,47 @@ export class DeterministicProviderCliService {
386
672
  artifacts: completionArtifacts
387
673
  };
388
674
  }
675
+ async runArchitect(context) {
676
+ const { dispatch, worktree } = context;
677
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
678
+ await fs.mkdir(metadataRoot, { recursive: true });
679
+ const specBody = `---\ntitle: "${dispatch.workItem.title}"\nstatus: pending_approval\nproduced_by: forge-bridge\n---\n\n# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`;
680
+ const specPath = path.join(metadataRoot, "spec.md");
681
+ await fs.writeFile(specPath, specBody, "utf8");
682
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
683
+ await writeCompletionArtifact({
684
+ worktreePath: worktree.worktreePath,
685
+ workItemId: dispatch.workItem.id,
686
+ phase: "architect",
687
+ producedBy: "forge-bridge",
688
+ redactionSecrets: exactRedactionSecrets(dispatch),
689
+ architectCycle: true
690
+ }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
691
+ const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
692
+ if (!artifact) {
693
+ throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
694
+ }
695
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
696
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
697
+ await context.emit({
698
+ role: "assistant",
699
+ kind: "message",
700
+ content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
701
+ eventType: "architect_complete"
702
+ });
703
+ return {
704
+ summary: "forge-bridge completed Architect plan (deterministic).",
705
+ spec: {
706
+ repoPath: worktree.worktreePath,
707
+ path: specPath,
708
+ body: specBody,
709
+ producedBy: "forge-bridge",
710
+ status: "pending_approval"
711
+ },
712
+ artifact,
713
+ artifacts: [artifact]
714
+ };
715
+ }
389
716
  async runQa(context) {
390
717
  const { dispatch, worktree } = context;
391
718
  await context.emit({
@@ -398,7 +725,7 @@ export class DeterministicProviderCliService {
398
725
  const launchTarget = qaBrowser?.launchTarget ?? null;
399
726
  const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
400
727
  const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
401
- ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget)
728
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
402
729
  : null;
403
730
  const browserChecks = browserSidecar && launchTarget
404
731
  ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
@@ -415,7 +742,9 @@ export class DeterministicProviderCliService {
415
742
  phase: "qa",
416
743
  producedBy: "forge-bridge",
417
744
  redactionSecrets: exactRedactionSecrets(dispatch),
418
- qaCycle: true
745
+ qaCycle: true,
746
+ ownerType: dispatch.cycleRun.ownerType ?? undefined,
747
+ ownerId: dispatch.cycleRun.ownerId ?? undefined
419
748
  }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
420
749
  gate,
421
750
  criterion,
@@ -424,19 +753,17 @@ export class DeterministicProviderCliService {
424
753
  browserChecks,
425
754
  sidecars
426
755
  }));
427
- await context.emit({
428
- role: "hook",
429
- kind: "checkpoint",
430
- content: `qa_gate: ${gate} artifact accepted.`,
431
- eventType: "qa_gate"
432
- });
756
+ const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
757
+ if (gateArtifact) {
758
+ await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
759
+ }
433
760
  }
434
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
761
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
435
762
  if (!qaArtifact) {
436
763
  throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
437
764
  }
438
765
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
439
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
766
+ await emitQaStructuredEvents(context.emit, qaArtifact);
440
767
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
441
768
  return {
442
769
  summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
@@ -602,6 +929,45 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
602
929
  ready_for_dev_test: true
603
930
  };
604
931
  }
932
+ function deterministicArchitectPayload(dispatch) {
933
+ const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
934
+ return {
935
+ status: "pass",
936
+ summary: "forge-bridge produced a deterministic Architect plan.",
937
+ implementation_plan: {
938
+ schema_version: 1,
939
+ plan_id: planId,
940
+ story_id: dispatch.workItem.id,
941
+ phases: [
942
+ { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
943
+ ],
944
+ tasks: [
945
+ {
946
+ id: "task-1",
947
+ title: `Implement ${dispatch.workItem.title}`,
948
+ phase: "phase-1",
949
+ summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
950
+ acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
951
+ tests: [
952
+ { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
953
+ ]
954
+ }
955
+ ],
956
+ dependencies: [],
957
+ phase_gates: [
958
+ { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
959
+ ]
960
+ },
961
+ qa_plan: {
962
+ schema_version: 1,
963
+ plan_id: planId,
964
+ final_qa: [
965
+ { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
966
+ ]
967
+ },
968
+ report_markdown: `# Architect Report\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\n\nVerdict: pass\n\nDeterministic bridge Architect plan produced for pending approval.\n`
969
+ };
970
+ }
605
971
  function deterministicQaGatePayload(options) {
606
972
  const blocked = options.missingLaunchTarget;
607
973
  const skippedBecauseBlocked = blocked
@@ -713,16 +1079,25 @@ const qaArtifactFileNames = {
713
1079
  verdict: "qa.verdict.json",
714
1080
  report: "qa.report.md"
715
1081
  };
1082
+ const qaGateArtifactFileNames = {
1083
+ qa_plan: "qa.plan.json",
1084
+ qa_regression: "qa.regression.json",
1085
+ qa_api: "qa.api.json",
1086
+ qa_manual_web: "qa.manual-web.json",
1087
+ qa_bug_repro: "qa.bug-repro.json",
1088
+ qa_findings: "qa.findings.json",
1089
+ qa_verdict: "qa.verdict.json"
1090
+ };
716
1091
  function hasLaunchTarget(target) {
717
1092
  return Boolean(target?.url?.trim()
718
1093
  || target?.ready_url?.trim()
719
1094
  || target?.command?.trim()
720
1095
  || (target?.routes ?? []).some((route) => route.trim().length > 0));
721
1096
  }
722
- function deterministicBrowserSidecar(workItemId, target) {
1097
+ function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
723
1098
  const route = primaryLaunchRoute(target);
724
1099
  return {
725
- relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt"),
1100
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
726
1101
  content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
727
1102
  };
728
1103
  }
@@ -764,78 +1139,6 @@ async function writeQaSidecarFiles(worktreePath, files) {
764
1139
  }
765
1140
  return sidecars;
766
1141
  }
767
- async function writeQaArtifacts(request) {
768
- const artifactRoot = artifactRootFor(request.worktreePath, request.workItemId);
769
- await fs.mkdir(artifactRoot, { recursive: true });
770
- const sidecars = await writeQaSidecarFiles(request.worktreePath, request.sidecarFiles ?? []);
771
- const status = request.status ?? "pass";
772
- const criterion = request.acceptanceCriteria.trim() || "Forge QA evidence exists";
773
- const relativeEvidencePath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.evidence);
774
- const relativeFindingsPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.findings);
775
- const relativeReportPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.report);
776
- const planJson = jsonText({
777
- schema_version: 1,
778
- phase: "qa",
779
- checklist: [
780
- "Review the validated work item against acceptance criteria.",
781
- "Run relevant provider QA verification.",
782
- "Confirm no in-scope QA findings remain."
783
- ],
784
- acceptance_criteria: [criterion]
785
- });
786
- const evidenceJson = jsonText({
787
- schema_version: 1,
788
- phase: "qa",
789
- commands: status === "blocked"
790
- ? []
791
- : [
792
- {
793
- command: request.command,
794
- exit_code: 0,
795
- status: "pass",
796
- summary: `${request.provider} QA completed successfully.`
797
- }
798
- ],
799
- browser_checks: request.browserChecks ?? [],
800
- sidecars,
801
- notes: request.summary
802
- });
803
- const findingsJson = jsonText({
804
- schema_version: 1,
805
- phase: "qa",
806
- findings: [],
807
- candidate_bugs: []
808
- });
809
- const verdictJson = jsonText({
810
- schema_version: 1,
811
- phase: "qa",
812
- status,
813
- summary: request.summary,
814
- tested_acceptance_criteria: status === "blocked" ? [] : [criterion],
815
- finding_ids: [],
816
- candidate_bug_ids: [],
817
- blocker_reason: status === "blocked" ? request.blockerReason ?? "inconclusive" : null,
818
- evidence_path: relativeEvidencePath,
819
- findings_path: relativeFindingsPath,
820
- report_path: relativeReportPath
821
- });
822
- const report = `# QA report\n\n${request.summary}\n\n- Provider: ${singleLine(request.provider)}\n- Model: ${singleLine(request.model)}\n- Command: ${singleLine(request.command)}\n`;
823
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.plan), planJson, "utf8");
824
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.evidence), evidenceJson, "utf8");
825
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.findings), findingsJson, "utf8");
826
- const verdictPath = path.join(artifactRoot, qaArtifactFileNames.verdict);
827
- await fs.writeFile(verdictPath, verdictJson, "utf8");
828
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.report), report, "utf8");
829
- return {
830
- repoPath: request.worktreePath,
831
- path: verdictPath,
832
- verdictJson,
833
- report,
834
- producedBy: request.producedBy,
835
- status,
836
- phase: "qa"
837
- };
838
- }
839
1142
  async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
840
1143
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
841
1144
  await emit({
@@ -851,16 +1154,29 @@ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
851
1154
  eventType: "phase_gate"
852
1155
  });
853
1156
  }
854
- async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
855
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
856
- if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
1157
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1158
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1159
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
857
1160
  return null;
858
1161
  }
859
- await validateQaBundleSidecarReferences(worktreePath, workItemId);
860
- return artifact;
1162
+ const artifactRoot = ownerType && ownerId
1163
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1164
+ : artifactRootFor(worktreePath, workItemId);
1165
+ const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1166
+ const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1167
+ const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1168
+ await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1169
+ return {
1170
+ ...artifact,
1171
+ planJson,
1172
+ evidenceJson,
1173
+ findingsJson
1174
+ };
861
1175
  }
862
- async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
863
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1176
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1177
+ const artifactRoot = ownerType && ownerId
1178
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1179
+ : artifactRootFor(worktreePath, workItemId);
864
1180
  for (const fileName of Object.values(qaArtifactFileNames)) {
865
1181
  try {
866
1182
  const stat = await fs.stat(path.join(artifactRoot, fileName));
@@ -889,8 +1205,10 @@ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
889
1205
  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.");
890
1206
  }
891
1207
  }
892
- async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
893
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1208
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1209
+ const artifactRoot = ownerType && ownerId
1210
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1211
+ : artifactRootFor(worktreePath, workItemId);
894
1212
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
895
1213
  const sidecars = arrayField(evidence, "sidecars");
896
1214
  if (sidecars.length === 0) {
@@ -909,7 +1227,9 @@ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
909
1227
  }
910
1228
  const fullPath = path.resolve(worktreePath, sidecarPath);
911
1229
  if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
912
- throw new Error(`QA sidecar ${index} path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
1230
+ const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1231
+ const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1232
+ throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
913
1233
  }
914
1234
  const stat = await fs.lstat(fullPath).catch((error) => {
915
1235
  if (isNodeError(error) && error.code === "ENOENT") {
@@ -930,8 +1250,8 @@ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
930
1250
  }
931
1251
  }
932
1252
  }
933
- async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
934
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1253
+ async function emitQaStructuredEvents(emit, artifact) {
1254
+ const artifactRoot = path.dirname(artifact.path);
935
1255
  const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
936
1256
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
937
1257
  const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
@@ -971,12 +1291,76 @@ async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact)
971
1291
  eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
972
1292
  });
973
1293
  }
1294
+ function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1295
+ return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1296
+ ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1297
+ : artifactRootFor(worktreePath, workItemId);
1298
+ }
1299
+ async function readQaGateArtifact(artifactRoot, gate) {
1300
+ const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1301
+ try {
1302
+ const stat = await fs.stat(artifactPath);
1303
+ if (!stat.isFile()) {
1304
+ return null;
1305
+ }
1306
+ }
1307
+ catch (error) {
1308
+ if (isNodeError(error) && error.code === "ENOENT") {
1309
+ return null;
1310
+ }
1311
+ throw error;
1312
+ }
1313
+ const payload = await readJsonObjectFile(artifactPath);
1314
+ return {
1315
+ gate,
1316
+ path: artifactPath,
1317
+ status: stringField(payload, "status") ?? "unknown",
1318
+ producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1319
+ contentHash: stringField(payload, "content_hash") ?? undefined
1320
+ };
1321
+ }
1322
+ function nextQaGate(gate) {
1323
+ const index = qaCompletionGateOrder.indexOf(gate);
1324
+ return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1325
+ }
1326
+ async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1327
+ const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1328
+ await emit({
1329
+ role: "hook",
1330
+ kind: artifact.status === "blocked" ? "error" : "checkpoint",
1331
+ content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1332
+ eventType: "phase_gate",
1333
+ data: JSON.stringify({
1334
+ phase: "qa",
1335
+ qa_gate: artifact.gate,
1336
+ status: artifact.status,
1337
+ artifact_relative_paths: [relativePath],
1338
+ content_hash: artifact.contentHash ?? null,
1339
+ produced_by: artifact.producedBy ?? null
1340
+ })
1341
+ });
1342
+ if (!nextGate) {
1343
+ return;
1344
+ }
1345
+ await emit({
1346
+ role: "hook",
1347
+ kind: "checkpoint",
1348
+ content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1349
+ eventType: "phase_gate",
1350
+ data: JSON.stringify({
1351
+ phase: "qa",
1352
+ from_gate: artifact.gate,
1353
+ to_gate: nextGate
1354
+ })
1355
+ });
1356
+ }
974
1357
  class LiveQaArtifactEmitter {
975
1358
  worktreePath;
976
1359
  workItemId;
977
1360
  dispatch;
978
1361
  emit;
979
- emitted = false;
1362
+ emittedBundle = false;
1363
+ emittedGates = new Set();
980
1364
  timer = null;
981
1365
  pending = Promise.resolve();
982
1366
  constructor(worktreePath, workItemId, dispatch, emit) {
@@ -999,7 +1383,7 @@ class LiveQaArtifactEmitter {
999
1383
  await this.pollQueued();
1000
1384
  }
1001
1385
  hasEmitted() {
1002
- return this.emitted;
1386
+ return this.emittedBundle;
1003
1387
  }
1004
1388
  pollQueued() {
1005
1389
  this.pending = this.pending
@@ -1008,19 +1392,125 @@ class LiveQaArtifactEmitter {
1008
1392
  return this.pending;
1009
1393
  }
1010
1394
  async poll() {
1011
- if (this.emitted) {
1395
+ await this.emitAvailableGateEvents();
1396
+ if (this.emittedBundle) {
1012
1397
  return;
1013
1398
  }
1014
- const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
1399
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
1015
1400
  if (!artifact) {
1016
1401
  return;
1017
1402
  }
1018
1403
  enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
1019
- this.emitted = true;
1404
+ this.emittedBundle = true;
1020
1405
  await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
1021
- await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1406
+ await emitQaStructuredEvents(this.emit, artifact);
1407
+ }
1408
+ async emitAvailableGateEvents() {
1409
+ const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1410
+ for (const gate of qaCompletionGateOrder) {
1411
+ if (this.emittedGates.has(gate)) {
1412
+ continue;
1413
+ }
1414
+ const artifact = await readQaGateArtifact(artifactRoot, gate);
1415
+ if (!artifact) {
1416
+ return;
1417
+ }
1418
+ this.emittedGates.add(gate);
1419
+ await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
1420
+ }
1022
1421
  }
1023
1422
  }
1423
+ class LiveArchitectArtifactEmitter {
1424
+ worktreePath;
1425
+ workItemId;
1426
+ emit;
1427
+ emitted = false;
1428
+ timer = null;
1429
+ pending = Promise.resolve();
1430
+ constructor(worktreePath, workItemId, emit) {
1431
+ this.worktreePath = worktreePath;
1432
+ this.workItemId = workItemId;
1433
+ this.emit = emit;
1434
+ }
1435
+ start() {
1436
+ void this.pollQueued();
1437
+ this.timer = setInterval(() => {
1438
+ void this.pollQueued();
1439
+ }, 250);
1440
+ }
1441
+ async stop() {
1442
+ if (this.timer) {
1443
+ clearInterval(this.timer);
1444
+ this.timer = null;
1445
+ }
1446
+ await this.pollQueued();
1447
+ }
1448
+ hasEmitted() {
1449
+ return this.emitted;
1450
+ }
1451
+ pollQueued() {
1452
+ this.pending = this.pending
1453
+ .then(() => this.poll())
1454
+ .catch(() => undefined);
1455
+ return this.pending;
1456
+ }
1457
+ async poll() {
1458
+ if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
1459
+ return;
1460
+ }
1461
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
1462
+ if (!artifact) {
1463
+ return;
1464
+ }
1465
+ this.emitted = true;
1466
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1467
+ await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1468
+ }
1469
+ }
1470
+ async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1471
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1472
+ for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1473
+ try {
1474
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1475
+ if (!stat.isFile()) {
1476
+ return false;
1477
+ }
1478
+ }
1479
+ catch (error) {
1480
+ if (isNodeError(error) && error.code === "ENOENT") {
1481
+ return false;
1482
+ }
1483
+ throw error;
1484
+ }
1485
+ }
1486
+ return true;
1487
+ }
1488
+ async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1489
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1490
+ const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1491
+ const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1492
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1493
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1494
+ const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1495
+ await emit({
1496
+ role: "worker",
1497
+ kind: "checkpoint",
1498
+ content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1499
+ eventType: "architect_plan"
1500
+ });
1501
+ await emit({
1502
+ role: "worker",
1503
+ kind: "checkpoint",
1504
+ content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1505
+ eventType: "architect_qa_seed"
1506
+ });
1507
+ await emit({
1508
+ role: "hook",
1509
+ kind: status === "pass" ? "checkpoint" : "error",
1510
+ content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1511
+ eventType: "architect_mcp_complete"
1512
+ });
1513
+ }
1024
1514
  async function readJsonObjectFile(filePath) {
1025
1515
  const content = await fs.readFile(filePath, "utf8").catch(() => "");
1026
1516
  return parseJsonLine(content) ?? {};
@@ -1045,19 +1535,36 @@ function summarizeQaObject(source) {
1045
1535
  ?? stringField(source, "id")
1046
1536
  ?? JSON.stringify(source), 500);
1047
1537
  }
1048
- function qaArtifactRelativePath(workItemId, fileName) {
1538
+ function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1539
+ if (ownerType && ownerId) {
1540
+ const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1541
+ return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1542
+ }
1049
1543
  return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
1050
1544
  }
1051
- function jsonText(value) {
1052
- return `${JSON.stringify(value, null, 2)}\n`;
1053
- }
1054
1545
  async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
1055
1546
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1547
+ await emit({
1548
+ role: "tool",
1549
+ kind: "checkpoint",
1550
+ content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1551
+ eventType: "completion_tool_validation_passed",
1552
+ data: JSON.stringify({
1553
+ phase: artifact.phase ?? "unknown",
1554
+ status: artifact.status,
1555
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1556
+ })
1557
+ });
1056
1558
  await emit({
1057
1559
  role: "tool",
1058
1560
  kind: "tool_result",
1059
1561
  content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
1060
- eventType: "completion_tool_artifact_recorded"
1562
+ eventType: "completion_tool_artifact_recorded",
1563
+ data: JSON.stringify({
1564
+ phase: artifact.phase ?? "unknown",
1565
+ status: artifact.status,
1566
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1567
+ })
1061
1568
  });
1062
1569
  }
1063
1570
  async function emitPhaseCompletionEvent(emit, artifact) {
@@ -1104,7 +1611,7 @@ async function emitPhaseGateEvents(emit, artifact) {
1104
1611
  function completionPhaseFromArtifact(artifact) {
1105
1612
  const phase = artifact.phase?.trim();
1106
1613
  return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1107
- || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1614
+ || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1108
1615
  ? phase
1109
1616
  : "implementation";
1110
1617
  }
@@ -1201,10 +1708,24 @@ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, de
1201
1708
  }
1202
1709
  return artifacts;
1203
1710
  }
1204
- function providerRedactionEnv(dispatch) {
1205
- const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
1711
+ function providerProcessEnv(dispatch) {
1712
+ const env = {
1713
+ ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1714
+ ...providerCredentialEnv(dispatch)
1715
+ };
1206
1716
  return Object.keys(env).length > 0 ? env : undefined;
1207
1717
  }
1718
+ function providerCredentialEnv(dispatch) {
1719
+ const secret = dispatch.apiKeySecretGrant?.secret;
1720
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1721
+ return {};
1722
+ }
1723
+ const provider = dispatch.execution.provider.trim().toLowerCase();
1724
+ if (provider === "codex" || provider === "openai") {
1725
+ return { OPENAI_API_KEY: secret };
1726
+ }
1727
+ return {};
1728
+ }
1208
1729
  function exactRedactionSecrets(dispatch) {
1209
1730
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
1210
1731
  }
@@ -1227,7 +1748,7 @@ export class StreamingProviderProcessRunner {
1227
1748
  return await new Promise((resolve, reject) => {
1228
1749
  const child = spawn(launch.command, launch.args, {
1229
1750
  cwd: request.cwd,
1230
- env: request.env ? { ...process.env, ...request.env } : undefined,
1751
+ env: buildProviderChildEnvironment(request.env),
1231
1752
  stdio: ["ignore", "pipe", "pipe"],
1232
1753
  windowsHide: true
1233
1754
  });
@@ -1362,9 +1883,6 @@ function quoteWindowsCommandLineArg(value) {
1362
1883
  }
1363
1884
  return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
1364
1885
  }
1365
- async function fileExists(inputPath) {
1366
- return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
1367
- }
1368
1886
  async function readProcessLines(stream, onLine) {
1369
1887
  const reader = readline.createInterface({ input: stream });
1370
1888
  try {
@@ -1382,12 +1900,69 @@ function isFakeWorkerModel(model) {
1382
1900
  function sha256(content) {
1383
1901
  return crypto.createHash("sha256").update(content).digest("hex");
1384
1902
  }
1903
+ function buildDraftPrompt(dispatch) {
1904
+ const draft = dispatch.draft;
1905
+ if (!draft) {
1906
+ throw new Error("Draft prompt is missing.");
1907
+ }
1908
+ return `${draft.systemPrompt}
1909
+
1910
+ Draft kind: ${draft.kind}
1911
+
1912
+ ${draft.userPrompt}
1913
+
1914
+ Return ONLY the requested JSON object. Do not wrap it in markdown and do not modify files.`;
1915
+ }
1916
+ function extractJsonObject(content) {
1917
+ let trimmed = content.trim();
1918
+ if (trimmed.startsWith("```")) {
1919
+ const firstNewline = trimmed.indexOf("\n");
1920
+ const lastFence = trimmed.lastIndexOf("```");
1921
+ if (firstNewline >= 0 && lastFence > firstNewline) {
1922
+ trimmed = trimmed.slice(firstNewline + 1, lastFence).trim();
1923
+ }
1924
+ }
1925
+ const start = trimmed.indexOf("{");
1926
+ const end = trimmed.lastIndexOf("}");
1927
+ return start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed;
1928
+ }
1929
+ function summarizeStderr(stderr) {
1930
+ const trimmed = stderr.trim();
1931
+ return trimmed ? `: ${clip(trimmed, 1000)}` : "";
1932
+ }
1933
+ function deterministicDraftPayload(dispatch) {
1934
+ const kind = dispatch.draft?.kind ?? "work_item";
1935
+ if (kind === "work_order") {
1936
+ return {
1937
+ title: "Deterministic runner Work Order draft",
1938
+ summary: "Forge Runner generated this deterministic Work Order draft.",
1939
+ objective: "Validate runner-backed Draft generation.",
1940
+ planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
1941
+ decompositionContext: "Use this deterministic fixture only in bridge tests.",
1942
+ assumptions: ["Forge Runner dispatch is available."],
1943
+ warnings: []
1944
+ };
1945
+ }
1946
+ if (kind === "story") {
1947
+ return {
1948
+ title: "Deterministic runner Story draft",
1949
+ description: "Forge Runner generated this deterministic Story draft.",
1950
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
1951
+ points: 3
1952
+ };
1953
+ }
1954
+ return {
1955
+ title: "Deterministic runner Work Item draft",
1956
+ description: "Forge Runner generated this deterministic Work Item draft.",
1957
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
1958
+ reproSteps: "Run Draft with a Forge Runner provider selected.",
1959
+ systemInfo: "forge-bridge deterministic provider",
1960
+ points: 1
1961
+ };
1962
+ }
1385
1963
  export function formatProviderCliCommand(command) {
1386
1964
  return [command.command, ...command.args].map(singleLine).join(" ");
1387
1965
  }
1388
- function yamlQuotedScalar(value) {
1389
- return JSON.stringify(singleLine(value));
1390
- }
1391
1966
  function singleLine(value) {
1392
1967
  return value.replace(/\s+/g, " ").trim();
1393
1968
  }
@@ -1396,16 +1971,19 @@ export function buildProviderCliCommand(dispatch, run) {
1396
1971
  const normalizedProvider = provider.toLowerCase();
1397
1972
  const model = dispatch.execution.model.trim();
1398
1973
  if (normalizedProvider === "codex") {
1399
- const args = ["exec"];
1974
+ const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
1400
1975
  if (run?.completionTools) {
1401
1976
  args.push(...codexMcpConfigArgs(run.completionTools));
1402
1977
  }
1403
1978
  args.push("--model", model);
1404
1979
  if (run) {
1405
- args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
1980
+ args.push("--json");
1406
1981
  if (run.worktreePath) {
1407
1982
  args.push("--cd", run.worktreePath);
1408
1983
  }
1984
+ if (run.skipGitRepoCheck) {
1985
+ args.push("--skip-git-repo-check");
1986
+ }
1409
1987
  args.push(run.prompt ?? "");
1410
1988
  }
1411
1989
  return { command: "codex", args };
@@ -1426,6 +2004,35 @@ export function buildProviderCliCommand(dispatch, run) {
1426
2004
  }
1427
2005
  return { command: provider, args };
1428
2006
  }
2007
+ export function codexSandboxModeForPlatform(platform = process.platform) {
2008
+ return platform === "win32" ? "danger-full-access" : "workspace-write";
2009
+ }
2010
+ function buildArchitectPrompt(dispatch) {
2011
+ return `You are Forge's Architect lane running locally in a prepared git worktree.
2012
+
2013
+ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
2014
+
2015
+ Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
2016
+ 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.
2017
+ Implementation DAG tasks are Develop child tasks only: include focused repo/product implementation changes. Do not create child Develop tasks for parent-story QA, sign-off, materialized child inventory, child-count evidence, parent plan artifact checks, or final integrated acceptance proof; put those checks in qa_plan.final_qa.
2018
+ ${architectRevisionInstruction(dispatch)}
2019
+ Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
2020
+
2021
+ ${completionPromptForPhase("architect")}
2022
+
2023
+ Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
2024
+ }
2025
+ function architectRevisionInstruction(dispatch) {
2026
+ if (!dispatch.architectRevision) {
2027
+ return "";
2028
+ }
2029
+ return `
2030
+ Architect revision context:
2031
+ - Previous plan id: ${dispatch.architectRevision.priorPlanId}
2032
+ - Previous content hash: ${dispatch.architectRevision.priorContentHash}
2033
+ - Reviewer feedback: ${dispatch.architectRevision.feedback}
2034
+ Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
2035
+ }
1429
2036
  function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1430
2037
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
1431
2038
 
@@ -1477,7 +2084,8 @@ QA rework context:
1477
2084
  - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1478
2085
  - Rework packet: ${dispatch.qaRework.packetPath}
1479
2086
  - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1480
- 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.`;
2087
+ 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.
2088
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
1481
2089
  }
1482
2090
  function debugQaReworkInstruction(dispatch) {
1483
2091
  if (!dispatch.qaRework) {
@@ -1488,7 +2096,8 @@ QA rework context for Debug:
1488
2096
  - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1489
2097
  - Rework packet: ${dispatch.qaRework.packetPath}
1490
2098
  - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1491
- 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.`;
2099
+ 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.
2100
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
1492
2101
  }
1493
2102
  function qaReworkRetestInstruction(dispatch) {
1494
2103
  if (!dispatch.qaRework) {
@@ -1525,6 +2134,39 @@ function qaBrowserInstruction(dispatch) {
1525
2134
  const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
1526
2135
  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`}`;
1527
2136
  }
2137
+ function storyQaInstruction(dispatch) {
2138
+ const storyQa = dispatch.storyQa;
2139
+ if (!storyQa) {
2140
+ return "";
2141
+ }
2142
+ const childLines = storyQa.childTasks.map((child) => {
2143
+ const dependencies = child.dependencyWorkItemIds.length > 0
2144
+ ? child.dependencyWorkItemIds.join(", ")
2145
+ : "none";
2146
+ const validation = child.validationArtifact
2147
+ ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2148
+ : "missing";
2149
+ const childQa = child.qaArtifact
2150
+ ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2151
+ : "not present";
2152
+ return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2153
+ }).join("\n");
2154
+ const finalQa = storyQa.finalQaChecks.length > 0
2155
+ ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2156
+ : "- No final QA checks were provided in qa.plan.final_qa.";
2157
+ return `Story QA integration context:
2158
+ - Story work item: ${storyQa.storyWorkItemId}
2159
+ - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2160
+ - Story worktree: ${storyQa.worktreeKey}
2161
+ - Branch: ${storyQa.branch}
2162
+ - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2163
+ - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2164
+ Materialized child tasks and evidence:
2165
+ ${childLines || "- No child tasks were provided."}
2166
+ Architect final QA checks:
2167
+ ${finalQa}
2168
+ 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.`;
2169
+ }
1528
2170
  function buildQaPrompt(dispatch, laneSpec) {
1529
2171
  return `You are Forge's QA lane running locally in a prepared git worktree.
1530
2172
 
@@ -1549,6 +2191,7 @@ ${dispatch.workItem.reproSteps || "Not provided."}
1549
2191
  System info / environment notes:
1550
2192
  ${dispatch.workItem.systemInfo || "Not provided."}
1551
2193
 
2194
+ ${storyQaInstruction(dispatch)}
1552
2195
  Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1553
2196
  ${qaBrowserInstruction(dispatch)}
1554
2197
  ${qaReworkRetestInstruction(dispatch)}
@@ -1590,6 +2233,7 @@ PR context:
1590
2233
  - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
1591
2234
 
1592
2235
  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.
2236
+ After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
1593
2237
  If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
1594
2238
  Keep the original work item intent intact:
1595
2239
  - Work item: ${dispatch.workItem.id}
@@ -1658,31 +2302,31 @@ class CursorStreamJsonState {
1658
2302
  consume(line) {
1659
2303
  const event = parseJsonLine(line);
1660
2304
  if (!event) {
1661
- return null;
2305
+ return [];
1662
2306
  }
1663
2307
  const type = stringField(event, "type");
1664
2308
  if (type === "system" && stringField(event, "subtype") === "init") {
1665
2309
  this.sessionId = stringField(event, "session_id");
1666
2310
  if (this.sessionId && !this.emittedSession) {
1667
2311
  this.emittedSession = true;
1668
- return {
1669
- role: "runner",
1670
- kind: "checkpoint",
1671
- content: `Cursor session started: ${this.sessionId}.`,
1672
- eventType: "provider_thread_started"
1673
- };
2312
+ return [{
2313
+ role: "runner",
2314
+ kind: "checkpoint",
2315
+ content: `Cursor session started: ${this.sessionId}.`,
2316
+ eventType: "provider_thread_started"
2317
+ }];
1674
2318
  }
1675
2319
  }
1676
2320
  if (type === "assistant") {
1677
2321
  const text = assistantMessageText(event);
1678
2322
  if (text) {
1679
2323
  this.finalMessage = clip(text, 4000);
1680
- return {
1681
- role: "assistant",
1682
- kind: "message",
1683
- content: this.finalMessage,
1684
- eventType: "provider_message"
1685
- };
2324
+ return [{
2325
+ role: "assistant",
2326
+ kind: "message",
2327
+ content: this.finalMessage,
2328
+ eventType: "provider_message"
2329
+ }];
1686
2330
  }
1687
2331
  }
1688
2332
  if (type === "tool_call") {
@@ -1691,23 +2335,23 @@ class CursorStreamJsonState {
1691
2335
  if (subtype === "started") {
1692
2336
  const summary = formatCursorToolCallStarted(toolCall);
1693
2337
  if (summary) {
1694
- return {
1695
- role: "worker",
1696
- kind: "checkpoint",
1697
- content: summary,
1698
- eventType: "provider_tool_call"
1699
- };
2338
+ return [{
2339
+ role: "worker",
2340
+ kind: "checkpoint",
2341
+ content: summary,
2342
+ eventType: "provider_tool_call"
2343
+ }];
1700
2344
  }
1701
2345
  }
1702
2346
  if (subtype === "completed") {
1703
2347
  const completed = formatCursorToolCallCompleted(toolCall);
1704
2348
  if (completed) {
1705
- return {
1706
- role: "worker",
1707
- kind: completed.kind,
1708
- content: completed.content,
1709
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
1710
- };
2349
+ return [{
2350
+ role: "worker",
2351
+ kind: completed.kind,
2352
+ content: completed.content,
2353
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2354
+ }];
1711
2355
  }
1712
2356
  }
1713
2357
  }
@@ -1719,14 +2363,14 @@ class CursorStreamJsonState {
1719
2363
  this.accumulateUsage(event);
1720
2364
  }
1721
2365
  if (type === "error" || (type === "result" && event.is_error === true)) {
1722
- return {
1723
- role: "runner",
1724
- kind: "error",
1725
- content: clip(line.trim(), 1000),
1726
- eventType: "provider_cli_error"
1727
- };
2366
+ return [{
2367
+ role: "runner",
2368
+ kind: "error",
2369
+ content: clip(line.trim(), 1000),
2370
+ eventType: "provider_cli_error"
2371
+ }];
1728
2372
  }
1729
- return null;
2373
+ return [];
1730
2374
  }
1731
2375
  accumulateUsage(event) {
1732
2376
  const usage = objectField(event, "usage");
@@ -1857,37 +2501,37 @@ class CodexJsonState {
1857
2501
  consume(line) {
1858
2502
  const event = parseJsonLine(line);
1859
2503
  if (!event) {
1860
- return null;
2504
+ return [];
1861
2505
  }
1862
2506
  const type = stringField(event, "type") ?? "";
1863
2507
  if (type === "thread.started") {
1864
2508
  this.threadId = stringField(event, "thread_id");
1865
2509
  if (this.threadId && !this.emittedThread) {
1866
2510
  this.emittedThread = true;
1867
- return {
1868
- role: "runner",
1869
- kind: "checkpoint",
1870
- content: `Codex thread started: ${this.threadId}.`,
1871
- eventType: "provider_thread_started"
1872
- };
2511
+ return [{
2512
+ role: "runner",
2513
+ kind: "checkpoint",
2514
+ content: `Codex thread started: ${this.threadId}.`,
2515
+ eventType: "provider_thread_started"
2516
+ }];
1873
2517
  }
1874
2518
  }
1875
2519
  if (type === "turn.completed") {
1876
2520
  this.accumulateUsage(event);
1877
- return {
1878
- role: "runner",
1879
- kind: "checkpoint",
1880
- content: "Codex turn completed.",
1881
- eventType: "provider_turn_completed"
1882
- };
2521
+ return [{
2522
+ role: "runner",
2523
+ kind: "checkpoint",
2524
+ content: "Codex turn completed.",
2525
+ eventType: "provider_turn_completed"
2526
+ }];
1883
2527
  }
1884
2528
  if (type === "turn.failed" || type === "error") {
1885
- return {
1886
- role: "runner",
1887
- kind: "error",
1888
- content: clip(line.trim(), 1000),
1889
- eventType: "provider_cli_error"
1890
- };
2529
+ return [{
2530
+ role: "runner",
2531
+ kind: "error",
2532
+ content: clip(line.trim(), 1000),
2533
+ eventType: "provider_cli_error"
2534
+ }];
1891
2535
  }
1892
2536
  if (type === "item.completed" || type === "item.updated") {
1893
2537
  const item = objectField(event, "item");
@@ -1896,28 +2540,32 @@ class CodexJsonState {
1896
2540
  const text = stringField(item, "text");
1897
2541
  if (text) {
1898
2542
  this.finalMessage = clip(text, 4000);
1899
- return {
1900
- role: "assistant",
1901
- kind: "message",
1902
- content: this.finalMessage,
1903
- eventType: "provider_message"
1904
- };
2543
+ return [{
2544
+ role: "assistant",
2545
+ kind: "message",
2546
+ content: this.finalMessage,
2547
+ eventType: "provider_message"
2548
+ }];
1905
2549
  }
1906
2550
  }
1907
2551
  if (itemType === "command_execution") {
1908
2552
  const command = stringField(item, "command");
1909
2553
  const status = stringField(item, "status");
1910
2554
  if (command) {
1911
- return {
1912
- role: "worker",
1913
- kind: "checkpoint",
1914
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
1915
- eventType: "provider_command"
1916
- };
2555
+ return [{
2556
+ role: "worker",
2557
+ kind: "checkpoint",
2558
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2559
+ eventType: "provider_command"
2560
+ }];
1917
2561
  }
1918
2562
  }
1919
2563
  }
1920
- return null;
2564
+ const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2565
+ if (mcpEvents.length > 0) {
2566
+ return mcpEvents;
2567
+ }
2568
+ return [];
1921
2569
  }
1922
2570
  accumulateUsage(event) {
1923
2571
  const usage = objectField(event, "usage");
@@ -1933,6 +2581,113 @@ class CodexJsonState {
1933
2581
  });
1934
2582
  }
1935
2583
  }
2584
+ function formatCodexMcpToolCallEvents(type, event) {
2585
+ if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2586
+ return [];
2587
+ }
2588
+ const item = objectField(event, "item");
2589
+ const itemType = stringField(item, "type") ?? "";
2590
+ const serverName = mcpServerName(item);
2591
+ const toolName = mcpToolName(item);
2592
+ const isMcpItem = itemType.toLowerCase().includes("mcp")
2593
+ || Boolean(serverName)
2594
+ || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2595
+ if (!isMcpItem || !toolName) {
2596
+ return [];
2597
+ }
2598
+ const status = normalizedString(stringField(item, "status")
2599
+ ?? stringField(event, "status")
2600
+ ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2601
+ const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2602
+ const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2603
+ const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2604
+ const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2605
+ const label = `${serverName ?? "unknown"}.${toolName}`;
2606
+ if (failed) {
2607
+ const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2608
+ const events = [{
2609
+ role: "tool",
2610
+ kind: "error",
2611
+ content: `MCP tool call failed: ${label} - ${summary}`,
2612
+ eventType: "provider_mcp_call_failed",
2613
+ data
2614
+ }];
2615
+ if (isForgeCompletionTool(toolName)) {
2616
+ events.push({
2617
+ role: "tool",
2618
+ kind: "error",
2619
+ content: `Forge completion tool validation failed: ${label} - ${summary}`,
2620
+ eventType: "completion_tool_validation_failed",
2621
+ data
2622
+ });
2623
+ }
2624
+ return events;
2625
+ }
2626
+ if (completed) {
2627
+ return [{
2628
+ role: "tool",
2629
+ kind: "checkpoint",
2630
+ content: `MCP tool call completed: ${label}.`,
2631
+ eventType: "provider_mcp_call_completed",
2632
+ data
2633
+ }];
2634
+ }
2635
+ if (started) {
2636
+ return [{
2637
+ role: "tool",
2638
+ kind: "checkpoint",
2639
+ content: `MCP tool call started: ${label}.`,
2640
+ eventType: "provider_mcp_call_started",
2641
+ data
2642
+ }];
2643
+ }
2644
+ return [];
2645
+ }
2646
+ function mcpServerName(item) {
2647
+ return stringField(item, "server")
2648
+ ?? stringField(item, "server_name")
2649
+ ?? stringField(item, "mcp_server")
2650
+ ?? stringField(objectField(item, "mcp"), "server")
2651
+ ?? stringField(objectField(item, "mcp"), "server_name");
2652
+ }
2653
+ function mcpToolName(item) {
2654
+ return stringField(item, "tool")
2655
+ ?? stringField(item, "tool_name")
2656
+ ?? stringField(item, "name")
2657
+ ?? stringField(objectField(item, "function"), "name")
2658
+ ?? stringField(objectField(item, "mcp"), "tool")
2659
+ ?? stringField(objectField(item, "mcp"), "tool_name");
2660
+ }
2661
+ function mcpErrorSummary(item) {
2662
+ const direct = stringField(item, "error")
2663
+ ?? stringField(item, "error_message")
2664
+ ?? stringField(item, "message");
2665
+ if (direct) {
2666
+ return clip(direct, 600);
2667
+ }
2668
+ const error = objectField(item, "error");
2669
+ return stringField(error, "message")
2670
+ ?? stringField(error, "summary")
2671
+ ?? stringField(objectField(item, "result"), "error")
2672
+ ?? null;
2673
+ }
2674
+ function safeProviderMcpData(item, serverName, toolName, status) {
2675
+ const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2676
+ return JSON.stringify(stripUndefined({
2677
+ server_name: serverName,
2678
+ tool_name: toolName,
2679
+ status,
2680
+ elapsed_ms: elapsedMs,
2681
+ error_summary: mcpErrorSummary(item)
2682
+ }));
2683
+ }
2684
+ function isForgeCompletionTool(toolName) {
2685
+ const normalized = toolName.trim().toLowerCase();
2686
+ return normalized.startsWith("forge.complete_")
2687
+ || normalized.startsWith("complete_")
2688
+ || normalized.includes("forge.complete_")
2689
+ || normalized.includes("complete_architect_plan");
2690
+ }
1936
2691
  function objectField(source, key) {
1937
2692
  const value = source[key];
1938
2693
  return value && typeof value === "object" && !Array.isArray(value)
@@ -1943,6 +2698,13 @@ function stringField(source, key) {
1943
2698
  const value = source[key];
1944
2699
  return typeof value === "string" && value.trim().length > 0 ? value : null;
1945
2700
  }
2701
+ function numericField(source, key) {
2702
+ const value = source[key];
2703
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2704
+ }
2705
+ function stripUndefined(value) {
2706
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2707
+ }
1946
2708
  function normalizedString(value) {
1947
2709
  return value.trim().toLowerCase().replace(/-/g, "_");
1948
2710
  }