@loucompanion/forge-bridge 0.1.1-dev.895607f4402a → 0.1.1-dev.9219f8477b8a

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, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, 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,125 @@ 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 draftWorktree = {
193
+ repoPath: tempDir,
194
+ worktreePath: tempDir,
195
+ branchName: "draft",
196
+ baseBranch: dispatch.cycleRun.baseBranch || dispatch.repo.defaultBranch || "draft",
197
+ cleanupWorktrees: true
198
+ };
199
+ const metadataRoot = path.join(tempDir, ".forge", "work-items", dispatch.workItem.id);
200
+ await fs.mkdir(metadataRoot, { recursive: true });
201
+ await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(dispatch.draft, null, 2) + "\n", "utf8");
202
+ await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
203
+ const isDecomposePrompt = isDecomposeDraftKind(dispatch.draft.kind);
204
+ const completionTools = isDecomposePrompt
205
+ ? null
206
+ : await prepareCompletionToolRuntime({ dispatch, worktree: draftWorktree, phase: "draft" });
207
+ const command = buildProviderCliCommand(dispatch, {
208
+ worktreePath: tempDir,
209
+ prompt: buildDraftPrompt(dispatch),
210
+ completionTools: completionTools ?? undefined,
211
+ skipGitRepoCheck: true
212
+ });
213
+ const draftArtifactSlugs = dispatch.artifacts
214
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
215
+ .map((artifact) => `${artifact.kind}:${artifact.slug}`);
216
+ await context.emit({
217
+ role: "runner",
218
+ kind: "checkpoint",
219
+ content: `${isDecomposePrompt ? "Structured prompt" : "Draft"} artifacts injected: ${draftArtifactSlugs.length}${draftArtifactSlugs.length ? ` (${draftArtifactSlugs.join(", ")})` : ""}. Project: ${dispatch.draft.projectName ?? dispatch.repo.name}. Repo: ${dispatch.draft.repoName ?? dispatch.repo.name}.`,
220
+ eventType: isDecomposePrompt ? "structured_prompt_artifacts_injected" : "draft_artifacts_injected"
221
+ });
222
+ await context.emit({
223
+ role: "runner",
224
+ kind: "checkpoint",
225
+ content: `Starting provider CLI ${isDecomposePrompt ? "structured prompt" : "Draft"}: ${formatProviderCliCommand(command)}`,
226
+ eventType: "provider_cli_started"
227
+ });
228
+ if (completionTools) {
229
+ await context.emit({
230
+ role: "runner",
231
+ kind: "checkpoint",
232
+ content: "Forge Draft completion tools configured for draft_intent -> draft_repo_context -> draft_graph_context -> draft_product_scope -> draft_work_order_plan -> draft_critic -> draft_proposal; provider must call each MCP completion tool before exit.",
233
+ eventType: "completion_tools_configured"
234
+ });
235
+ }
236
+ const outputState = createProviderOutputState(dispatch.execution.provider);
237
+ try {
238
+ const result = await this.processRunner.run({
239
+ command: command.command,
240
+ args: command.args,
241
+ cwd: tempDir,
242
+ env: providerProcessEnv(dispatch)
243
+ }, {
244
+ onStdoutLine: async (line) => {
245
+ for (const event of outputState.consume(line)) {
246
+ await context.emit(event);
247
+ }
248
+ }
249
+ }, context.signal);
250
+ if (result.exitCode !== 0) {
251
+ throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
252
+ }
253
+ await context.emit({
254
+ role: "runner",
255
+ kind: "checkpoint",
256
+ content: `Provider CLI ${isDecomposePrompt ? "structured prompt" : "Draft"} completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
257
+ eventType: "provider_cli_completed"
258
+ });
259
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
260
+ if (isDecomposePrompt) {
261
+ const structuredJson = parseJsonLine(outputState.finalMessage ?? "");
262
+ if (!structuredJson || typeof structuredJson !== "object" || Array.isArray(structuredJson)) {
263
+ throw new Error("Provider CLI structured prompt completed but did not return a JSON object.");
264
+ }
265
+ await context.emit({
266
+ role: "assistant",
267
+ kind: "message",
268
+ content: JSON.stringify(structuredJson),
269
+ eventType: "draft_complete"
270
+ });
271
+ return {
272
+ summary: "Structured prompt generated JSON through provider CLI."
273
+ };
274
+ }
275
+ await emitDraftGateArtifacts(context.emit, tempDir, dispatch.workItem.id);
276
+ const proposalArtifact = await readCompletionArtifact(tempDir, dispatch.workItem.id, "draft");
277
+ if (!proposalArtifact) {
278
+ throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
279
+ }
280
+ const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
281
+ const draftJson = proposal["draft_json"];
282
+ if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
283
+ throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
284
+ }
285
+ const json = JSON.stringify(draftJson);
286
+ await context.emit({
287
+ role: "assistant",
288
+ kind: "message",
289
+ content: json,
290
+ eventType: "draft_complete"
291
+ });
292
+ return {
293
+ summary: "Draft generated through Forge Draft completion cycle.",
294
+ artifact: proposalArtifact,
295
+ artifacts: [proposalArtifact]
296
+ };
297
+ }
298
+ finally {
299
+ if (completionTools) {
300
+ await cleanupCompletionTools(completionTools, context.emit);
301
+ }
302
+ await fs.rm(tempDir, { recursive: true, force: true });
303
+ }
304
+ }
46
305
  async runImplementation(context) {
47
306
  const { dispatch, worktree } = context;
48
307
  const phase = completionPhaseFromDispatch(dispatch);
@@ -93,11 +352,10 @@ export class ProcessBackedProviderCliService {
93
352
  command: command.command,
94
353
  args: command.args,
95
354
  cwd: worktree.worktreePath,
96
- env: providerRedactionEnv(dispatch)
355
+ env: providerProcessEnv(dispatch)
97
356
  }, {
98
357
  onStdoutLine: async (line) => {
99
- const event = outputState.consume(line);
100
- if (event) {
358
+ for (const event of outputState.consume(line)) {
101
359
  await context.emit(event);
102
360
  }
103
361
  }
@@ -157,6 +415,89 @@ export class ProcessBackedProviderCliService {
157
415
  artifacts: completionArtifacts
158
416
  };
159
417
  }
418
+ async runArchitect(context) {
419
+ const { dispatch, worktree } = context;
420
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
421
+ const command = buildProviderCliCommand(dispatch, {
422
+ worktreePath: worktree.worktreePath,
423
+ prompt: buildArchitectPrompt(dispatch),
424
+ completionTools
425
+ });
426
+ const commandText = formatProviderCliCommand(command);
427
+ await context.emit({
428
+ role: "runner",
429
+ kind: "checkpoint",
430
+ content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
431
+ eventType: "provider_cli_started"
432
+ });
433
+ await context.emit({
434
+ role: "runner",
435
+ kind: "checkpoint",
436
+ content: "Forge Architect completion tools configured; provider must call forge.complete_architect_plan before exit.",
437
+ eventType: "completion_tools_configured"
438
+ });
439
+ const outputState = createProviderOutputState(dispatch.execution.provider);
440
+ const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
441
+ let result;
442
+ try {
443
+ liveArchitectEvents.start();
444
+ result = await this.processRunner.run({
445
+ command: command.command,
446
+ args: command.args,
447
+ cwd: worktree.worktreePath,
448
+ env: providerProcessEnv(dispatch)
449
+ }, {
450
+ onStdoutLine: async (line) => {
451
+ for (const event of outputState.consume(line)) {
452
+ await context.emit(event);
453
+ }
454
+ }
455
+ }, context.signal);
456
+ }
457
+ finally {
458
+ await liveArchitectEvents.stop();
459
+ await cleanupCompletionTools(completionTools, context.emit);
460
+ }
461
+ if (result.exitCode !== 0) {
462
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
463
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
464
+ }
465
+ await context.emit({
466
+ role: "runner",
467
+ kind: "checkpoint",
468
+ content: `Provider CLI Architect completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
469
+ eventType: "provider_cli_completed"
470
+ });
471
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
472
+ const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
473
+ if (!architectArtifact) {
474
+ throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
475
+ }
476
+ if (!liveArchitectEvents.hasEmitted()) {
477
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
478
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, architectArtifact);
479
+ }
480
+ await context.emit({
481
+ role: "assistant",
482
+ kind: "message",
483
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI produced an Architect plan for ${worktree.branchName}.`,
484
+ eventType: "architect_complete"
485
+ });
486
+ const specPath = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id, "spec.md");
487
+ const specBody = await fs.readFile(specPath, "utf8").catch(() => `# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`);
488
+ return {
489
+ summary: `${dispatch.execution.provider} CLI Architect plan produced.`,
490
+ spec: {
491
+ repoPath: worktree.worktreePath,
492
+ path: specPath,
493
+ body: specBody,
494
+ producedBy: `${dispatch.execution.provider}-cli`,
495
+ status: "pending_approval"
496
+ },
497
+ artifact: architectArtifact,
498
+ artifacts: [architectArtifact]
499
+ };
500
+ }
160
501
  async runQa(context) {
161
502
  const { dispatch, worktree } = context;
162
503
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -197,11 +538,10 @@ export class ProcessBackedProviderCliService {
197
538
  command: command.command,
198
539
  args: command.args,
199
540
  cwd: worktree.worktreePath,
200
- env: providerRedactionEnv(dispatch)
541
+ env: providerProcessEnv(dispatch)
201
542
  }, {
202
543
  onStdoutLine: async (line) => {
203
- const event = outputState.consume(line);
204
- if (event) {
544
+ for (const event of outputState.consume(line)) {
205
545
  await context.emit(event);
206
546
  }
207
547
  }
@@ -222,7 +562,7 @@ export class ProcessBackedProviderCliService {
222
562
  eventType: "provider_cli_completed"
223
563
  });
224
564
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
225
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
565
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
226
566
  if (!qaArtifact) {
227
567
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
228
568
  throw new Error(verdictOnly
@@ -232,7 +572,7 @@ export class ProcessBackedProviderCliService {
232
572
  enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
233
573
  if (!liveQaEvents.hasEmitted()) {
234
574
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
235
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
575
+ await emitQaStructuredEvents(context.emit, qaArtifact);
236
576
  }
237
577
  const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
238
578
  const statusSummary = status === "pass"
@@ -272,11 +612,11 @@ export class ProcessBackedProviderCliService {
272
612
  const result = await this.processRunner.run({
273
613
  command: command.command,
274
614
  args: command.args,
275
- cwd: worktree.worktreePath
615
+ cwd: worktree.worktreePath,
616
+ env: providerProcessEnv(dispatch)
276
617
  }, {
277
618
  onStdoutLine: async (line) => {
278
- const event = outputState.consume(line);
279
- if (event) {
619
+ for (const event of outputState.consume(line)) {
280
620
  await context.emit(event);
281
621
  }
282
622
  }
@@ -308,6 +648,17 @@ export class DeterministicProviderCliService {
308
648
  constructor(git = new GitClient()) {
309
649
  this.git = git;
310
650
  }
651
+ async runDraft(context) {
652
+ const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
653
+ await context.emit({
654
+ role: "assistant",
655
+ kind: "message",
656
+ content,
657
+ eventType: "draft_complete"
658
+ });
659
+ await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
660
+ return { summary: "forge-bridge generated deterministic draft." };
661
+ }
311
662
  async runImplementation(context) {
312
663
  const { dispatch, worktree } = context;
313
664
  const phase = completionPhaseFromDispatch(dispatch);
@@ -386,6 +737,47 @@ export class DeterministicProviderCliService {
386
737
  artifacts: completionArtifacts
387
738
  };
388
739
  }
740
+ async runArchitect(context) {
741
+ const { dispatch, worktree } = context;
742
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
743
+ await fs.mkdir(metadataRoot, { recursive: true });
744
+ 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`;
745
+ const specPath = path.join(metadataRoot, "spec.md");
746
+ await fs.writeFile(specPath, specBody, "utf8");
747
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
748
+ await writeCompletionArtifact({
749
+ worktreePath: worktree.worktreePath,
750
+ workItemId: dispatch.workItem.id,
751
+ phase: "architect",
752
+ producedBy: "forge-bridge",
753
+ redactionSecrets: exactRedactionSecrets(dispatch),
754
+ architectCycle: true
755
+ }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
756
+ const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
757
+ if (!artifact) {
758
+ throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
759
+ }
760
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
761
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
762
+ await context.emit({
763
+ role: "assistant",
764
+ kind: "message",
765
+ content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
766
+ eventType: "architect_complete"
767
+ });
768
+ return {
769
+ summary: "forge-bridge completed Architect plan (deterministic).",
770
+ spec: {
771
+ repoPath: worktree.worktreePath,
772
+ path: specPath,
773
+ body: specBody,
774
+ producedBy: "forge-bridge",
775
+ status: "pending_approval"
776
+ },
777
+ artifact,
778
+ artifacts: [artifact]
779
+ };
780
+ }
389
781
  async runQa(context) {
390
782
  const { dispatch, worktree } = context;
391
783
  await context.emit({
@@ -398,7 +790,7 @@ export class DeterministicProviderCliService {
398
790
  const launchTarget = qaBrowser?.launchTarget ?? null;
399
791
  const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
400
792
  const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
401
- ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget)
793
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
402
794
  : null;
403
795
  const browserChecks = browserSidecar && launchTarget
404
796
  ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
@@ -415,7 +807,9 @@ export class DeterministicProviderCliService {
415
807
  phase: "qa",
416
808
  producedBy: "forge-bridge",
417
809
  redactionSecrets: exactRedactionSecrets(dispatch),
418
- qaCycle: true
810
+ qaCycle: true,
811
+ ownerType: dispatch.cycleRun.ownerType ?? undefined,
812
+ ownerId: dispatch.cycleRun.ownerId ?? undefined
419
813
  }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
420
814
  gate,
421
815
  criterion,
@@ -424,19 +818,17 @@ export class DeterministicProviderCliService {
424
818
  browserChecks,
425
819
  sidecars
426
820
  }));
427
- await context.emit({
428
- role: "hook",
429
- kind: "checkpoint",
430
- content: `qa_gate: ${gate} artifact accepted.`,
431
- eventType: "qa_gate"
432
- });
821
+ const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
822
+ if (gateArtifact) {
823
+ await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
824
+ }
433
825
  }
434
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
826
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
435
827
  if (!qaArtifact) {
436
828
  throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
437
829
  }
438
830
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
439
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
831
+ await emitQaStructuredEvents(context.emit, qaArtifact);
440
832
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
441
833
  return {
442
834
  summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
@@ -602,6 +994,45 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
602
994
  ready_for_dev_test: true
603
995
  };
604
996
  }
997
+ function deterministicArchitectPayload(dispatch) {
998
+ const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
999
+ return {
1000
+ status: "pass",
1001
+ summary: "forge-bridge produced a deterministic Architect plan.",
1002
+ implementation_plan: {
1003
+ schema_version: 1,
1004
+ plan_id: planId,
1005
+ story_id: dispatch.workItem.id,
1006
+ phases: [
1007
+ { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
1008
+ ],
1009
+ tasks: [
1010
+ {
1011
+ id: "task-1",
1012
+ title: `Implement ${dispatch.workItem.title}`,
1013
+ phase: "phase-1",
1014
+ summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
1015
+ acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
1016
+ tests: [
1017
+ { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
1018
+ ]
1019
+ }
1020
+ ],
1021
+ dependencies: [],
1022
+ phase_gates: [
1023
+ { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
1024
+ ]
1025
+ },
1026
+ qa_plan: {
1027
+ schema_version: 1,
1028
+ plan_id: planId,
1029
+ final_qa: [
1030
+ { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
1031
+ ]
1032
+ },
1033
+ 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`
1034
+ };
1035
+ }
605
1036
  function deterministicQaGatePayload(options) {
606
1037
  const blocked = options.missingLaunchTarget;
607
1038
  const skippedBecauseBlocked = blocked
@@ -713,16 +1144,25 @@ const qaArtifactFileNames = {
713
1144
  verdict: "qa.verdict.json",
714
1145
  report: "qa.report.md"
715
1146
  };
1147
+ const qaGateArtifactFileNames = {
1148
+ qa_plan: "qa.plan.json",
1149
+ qa_regression: "qa.regression.json",
1150
+ qa_api: "qa.api.json",
1151
+ qa_manual_web: "qa.manual-web.json",
1152
+ qa_bug_repro: "qa.bug-repro.json",
1153
+ qa_findings: "qa.findings.json",
1154
+ qa_verdict: "qa.verdict.json"
1155
+ };
716
1156
  function hasLaunchTarget(target) {
717
1157
  return Boolean(target?.url?.trim()
718
1158
  || target?.ready_url?.trim()
719
1159
  || target?.command?.trim()
720
1160
  || (target?.routes ?? []).some((route) => route.trim().length > 0));
721
1161
  }
722
- function deterministicBrowserSidecar(workItemId, target) {
1162
+ function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
723
1163
  const route = primaryLaunchRoute(target);
724
1164
  return {
725
- relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt"),
1165
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
726
1166
  content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
727
1167
  };
728
1168
  }
@@ -779,16 +1219,29 @@ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
779
1219
  eventType: "phase_gate"
780
1220
  });
781
1221
  }
782
- async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
783
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
784
- if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
1222
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1223
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1224
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
785
1225
  return null;
786
1226
  }
787
- await validateQaBundleSidecarReferences(worktreePath, workItemId);
788
- return artifact;
1227
+ const artifactRoot = ownerType && ownerId
1228
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1229
+ : artifactRootFor(worktreePath, workItemId);
1230
+ const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1231
+ const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1232
+ const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1233
+ await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1234
+ return {
1235
+ ...artifact,
1236
+ planJson,
1237
+ evidenceJson,
1238
+ findingsJson
1239
+ };
789
1240
  }
790
- async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
791
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1241
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1242
+ const artifactRoot = ownerType && ownerId
1243
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1244
+ : artifactRootFor(worktreePath, workItemId);
792
1245
  for (const fileName of Object.values(qaArtifactFileNames)) {
793
1246
  try {
794
1247
  const stat = await fs.stat(path.join(artifactRoot, fileName));
@@ -817,8 +1270,10 @@ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
817
1270
  throw new Error("QA browser testing is required but no app launch target was provided; provider must return blocked with blocker_reason missing_app_launch_target.");
818
1271
  }
819
1272
  }
820
- async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
821
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1273
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1274
+ const artifactRoot = ownerType && ownerId
1275
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1276
+ : artifactRootFor(worktreePath, workItemId);
822
1277
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
823
1278
  const sidecars = arrayField(evidence, "sidecars");
824
1279
  if (sidecars.length === 0) {
@@ -837,7 +1292,9 @@ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
837
1292
  }
838
1293
  const fullPath = path.resolve(worktreePath, sidecarPath);
839
1294
  if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
840
- throw new Error(`QA sidecar ${index} path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
1295
+ const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1296
+ const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1297
+ throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
841
1298
  }
842
1299
  const stat = await fs.lstat(fullPath).catch((error) => {
843
1300
  if (isNodeError(error) && error.code === "ENOENT") {
@@ -858,8 +1315,8 @@ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
858
1315
  }
859
1316
  }
860
1317
  }
861
- async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
862
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1318
+ async function emitQaStructuredEvents(emit, artifact) {
1319
+ const artifactRoot = path.dirname(artifact.path);
863
1320
  const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
864
1321
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
865
1322
  const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
@@ -899,12 +1356,76 @@ async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact)
899
1356
  eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
900
1357
  });
901
1358
  }
1359
+ function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1360
+ return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1361
+ ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1362
+ : artifactRootFor(worktreePath, workItemId);
1363
+ }
1364
+ async function readQaGateArtifact(artifactRoot, gate) {
1365
+ const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1366
+ try {
1367
+ const stat = await fs.stat(artifactPath);
1368
+ if (!stat.isFile()) {
1369
+ return null;
1370
+ }
1371
+ }
1372
+ catch (error) {
1373
+ if (isNodeError(error) && error.code === "ENOENT") {
1374
+ return null;
1375
+ }
1376
+ throw error;
1377
+ }
1378
+ const payload = await readJsonObjectFile(artifactPath);
1379
+ return {
1380
+ gate,
1381
+ path: artifactPath,
1382
+ status: stringField(payload, "status") ?? "unknown",
1383
+ producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1384
+ contentHash: stringField(payload, "content_hash") ?? undefined
1385
+ };
1386
+ }
1387
+ function nextQaGate(gate) {
1388
+ const index = qaCompletionGateOrder.indexOf(gate);
1389
+ return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1390
+ }
1391
+ async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1392
+ const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1393
+ await emit({
1394
+ role: "hook",
1395
+ kind: artifact.status === "blocked" ? "error" : "checkpoint",
1396
+ content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1397
+ eventType: "phase_gate",
1398
+ data: JSON.stringify({
1399
+ phase: "qa",
1400
+ qa_gate: artifact.gate,
1401
+ status: artifact.status,
1402
+ artifact_relative_paths: [relativePath],
1403
+ content_hash: artifact.contentHash ?? null,
1404
+ produced_by: artifact.producedBy ?? null
1405
+ })
1406
+ });
1407
+ if (!nextGate) {
1408
+ return;
1409
+ }
1410
+ await emit({
1411
+ role: "hook",
1412
+ kind: "checkpoint",
1413
+ content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1414
+ eventType: "phase_gate",
1415
+ data: JSON.stringify({
1416
+ phase: "qa",
1417
+ from_gate: artifact.gate,
1418
+ to_gate: nextGate
1419
+ })
1420
+ });
1421
+ }
902
1422
  class LiveQaArtifactEmitter {
903
1423
  worktreePath;
904
1424
  workItemId;
905
1425
  dispatch;
906
1426
  emit;
907
- emitted = false;
1427
+ emittedBundle = false;
1428
+ emittedGates = new Set();
908
1429
  timer = null;
909
1430
  pending = Promise.resolve();
910
1431
  constructor(worktreePath, workItemId, dispatch, emit) {
@@ -927,7 +1448,7 @@ class LiveQaArtifactEmitter {
927
1448
  await this.pollQueued();
928
1449
  }
929
1450
  hasEmitted() {
930
- return this.emitted;
1451
+ return this.emittedBundle;
931
1452
  }
932
1453
  pollQueued() {
933
1454
  this.pending = this.pending
@@ -936,19 +1457,125 @@ class LiveQaArtifactEmitter {
936
1457
  return this.pending;
937
1458
  }
938
1459
  async poll() {
939
- if (this.emitted) {
1460
+ await this.emitAvailableGateEvents();
1461
+ if (this.emittedBundle) {
940
1462
  return;
941
1463
  }
942
- const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
1464
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
943
1465
  if (!artifact) {
944
1466
  return;
945
1467
  }
946
1468
  enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
947
- this.emitted = true;
1469
+ this.emittedBundle = true;
948
1470
  await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
949
- await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1471
+ await emitQaStructuredEvents(this.emit, artifact);
1472
+ }
1473
+ async emitAvailableGateEvents() {
1474
+ const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1475
+ for (const gate of qaCompletionGateOrder) {
1476
+ if (this.emittedGates.has(gate)) {
1477
+ continue;
1478
+ }
1479
+ const artifact = await readQaGateArtifact(artifactRoot, gate);
1480
+ if (!artifact) {
1481
+ return;
1482
+ }
1483
+ this.emittedGates.add(gate);
1484
+ await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
1485
+ }
950
1486
  }
951
1487
  }
1488
+ class LiveArchitectArtifactEmitter {
1489
+ worktreePath;
1490
+ workItemId;
1491
+ emit;
1492
+ emitted = false;
1493
+ timer = null;
1494
+ pending = Promise.resolve();
1495
+ constructor(worktreePath, workItemId, emit) {
1496
+ this.worktreePath = worktreePath;
1497
+ this.workItemId = workItemId;
1498
+ this.emit = emit;
1499
+ }
1500
+ start() {
1501
+ void this.pollQueued();
1502
+ this.timer = setInterval(() => {
1503
+ void this.pollQueued();
1504
+ }, 250);
1505
+ }
1506
+ async stop() {
1507
+ if (this.timer) {
1508
+ clearInterval(this.timer);
1509
+ this.timer = null;
1510
+ }
1511
+ await this.pollQueued();
1512
+ }
1513
+ hasEmitted() {
1514
+ return this.emitted;
1515
+ }
1516
+ pollQueued() {
1517
+ this.pending = this.pending
1518
+ .then(() => this.poll())
1519
+ .catch(() => undefined);
1520
+ return this.pending;
1521
+ }
1522
+ async poll() {
1523
+ if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
1524
+ return;
1525
+ }
1526
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
1527
+ if (!artifact) {
1528
+ return;
1529
+ }
1530
+ this.emitted = true;
1531
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1532
+ await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1533
+ }
1534
+ }
1535
+ async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1536
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1537
+ for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1538
+ try {
1539
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1540
+ if (!stat.isFile()) {
1541
+ return false;
1542
+ }
1543
+ }
1544
+ catch (error) {
1545
+ if (isNodeError(error) && error.code === "ENOENT") {
1546
+ return false;
1547
+ }
1548
+ throw error;
1549
+ }
1550
+ }
1551
+ return true;
1552
+ }
1553
+ async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1554
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1555
+ const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1556
+ const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1557
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1558
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1559
+ const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1560
+ await emit({
1561
+ role: "worker",
1562
+ kind: "checkpoint",
1563
+ content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1564
+ eventType: "architect_plan"
1565
+ });
1566
+ await emit({
1567
+ role: "worker",
1568
+ kind: "checkpoint",
1569
+ content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1570
+ eventType: "architect_qa_seed"
1571
+ });
1572
+ await emit({
1573
+ role: "hook",
1574
+ kind: status === "pass" ? "checkpoint" : "error",
1575
+ content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1576
+ eventType: "architect_mcp_complete"
1577
+ });
1578
+ }
952
1579
  async function readJsonObjectFile(filePath) {
953
1580
  const content = await fs.readFile(filePath, "utf8").catch(() => "");
954
1581
  return parseJsonLine(content) ?? {};
@@ -973,16 +1600,36 @@ function summarizeQaObject(source) {
973
1600
  ?? stringField(source, "id")
974
1601
  ?? JSON.stringify(source), 500);
975
1602
  }
976
- function qaArtifactRelativePath(workItemId, fileName) {
1603
+ function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1604
+ if (ownerType && ownerId) {
1605
+ const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1606
+ return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1607
+ }
977
1608
  return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
978
1609
  }
979
1610
  async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
980
1611
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1612
+ await emit({
1613
+ role: "tool",
1614
+ kind: "checkpoint",
1615
+ content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1616
+ eventType: "completion_tool_validation_passed",
1617
+ data: JSON.stringify({
1618
+ phase: artifact.phase ?? "unknown",
1619
+ status: artifact.status,
1620
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1621
+ })
1622
+ });
981
1623
  await emit({
982
1624
  role: "tool",
983
1625
  kind: "tool_result",
984
1626
  content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
985
- eventType: "completion_tool_artifact_recorded"
1627
+ eventType: "completion_tool_artifact_recorded",
1628
+ data: JSON.stringify({
1629
+ phase: artifact.phase ?? "unknown",
1630
+ status: artifact.status,
1631
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1632
+ })
986
1633
  });
987
1634
  }
988
1635
  async function emitPhaseCompletionEvent(emit, artifact) {
@@ -1029,7 +1676,7 @@ async function emitPhaseGateEvents(emit, artifact) {
1029
1676
  function completionPhaseFromArtifact(artifact) {
1030
1677
  const phase = artifact.phase?.trim();
1031
1678
  return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1032
- || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1679
+ || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1033
1680
  ? phase
1034
1681
  : "implementation";
1035
1682
  }
@@ -1126,10 +1773,24 @@ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, de
1126
1773
  }
1127
1774
  return artifacts;
1128
1775
  }
1129
- function providerRedactionEnv(dispatch) {
1130
- const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
1776
+ function providerProcessEnv(dispatch) {
1777
+ const env = {
1778
+ ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1779
+ ...providerCredentialEnv(dispatch)
1780
+ };
1131
1781
  return Object.keys(env).length > 0 ? env : undefined;
1132
1782
  }
1783
+ function providerCredentialEnv(dispatch) {
1784
+ const secret = dispatch.apiKeySecretGrant?.secret;
1785
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1786
+ return {};
1787
+ }
1788
+ const provider = dispatch.execution.provider.trim().toLowerCase();
1789
+ if (provider === "codex" || provider === "openai") {
1790
+ return { OPENAI_API_KEY: secret };
1791
+ }
1792
+ return {};
1793
+ }
1133
1794
  function exactRedactionSecrets(dispatch) {
1134
1795
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
1135
1796
  }
@@ -1152,7 +1813,7 @@ export class StreamingProviderProcessRunner {
1152
1813
  return await new Promise((resolve, reject) => {
1153
1814
  const child = spawn(launch.command, launch.args, {
1154
1815
  cwd: request.cwd,
1155
- env: request.env ? { ...process.env, ...request.env } : undefined,
1816
+ env: buildProviderChildEnvironment(request.env),
1156
1817
  stdio: ["ignore", "pipe", "pipe"],
1157
1818
  windowsHide: true
1158
1819
  });
@@ -1304,6 +1965,146 @@ function isFakeWorkerModel(model) {
1304
1965
  function sha256(content) {
1305
1966
  return crypto.createHash("sha256").update(content).digest("hex");
1306
1967
  }
1968
+ function buildDraftSpec(dispatch) {
1969
+ return `# Draft Generation Context
1970
+
1971
+ Project: ${dispatch.draft?.projectName ?? dispatch.repo.name}
1972
+ Repository: ${dispatch.draft?.repoName ?? dispatch.repo.name}
1973
+ Draft kind: ${dispatch.draft?.kind ?? "draft"}
1974
+
1975
+ ## User Prompt
1976
+
1977
+ ${dispatch.draft?.userPrompt ?? ""}
1978
+ `;
1979
+ }
1980
+ async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
1981
+ const draftArtifactFiles = {
1982
+ draft_intent: "draft.intent.json",
1983
+ draft_repo_context: "draft.repo-context.json",
1984
+ draft_graph_context: "draft.graph-context.json",
1985
+ draft_product_scope: "draft.product-scope.json",
1986
+ draft_work_order_plan: "draft.work-order-plan.json",
1987
+ draft_critic: "draft.critic.json",
1988
+ draft_proposal: "draft.proposal.json"
1989
+ };
1990
+ for (const gate of draftCompletionGateOrder) {
1991
+ const actualPath = path.join(worktreePath, ".forge", "work-items", workItemId, "artifacts", draftArtifactFiles[gate]);
1992
+ if (!await fileExists(actualPath)) {
1993
+ continue;
1994
+ }
1995
+ const relativePath = path.relative(worktreePath, actualPath).split(path.sep).join("/");
1996
+ await emit({
1997
+ role: "tool",
1998
+ kind: "tool_result",
1999
+ content: `Forge Draft completion tool recorded ${gate} artifact ${relativePath}.`,
2000
+ eventType: "completion_tool_artifact_recorded",
2001
+ data: JSON.stringify({ phase: "draft", draft_gate: gate, artifact_relative_paths: [relativePath] })
2002
+ });
2003
+ await emit({
2004
+ role: "hook",
2005
+ kind: "checkpoint",
2006
+ content: `phase_gate: ${gate} artifact accepted with status pass.`,
2007
+ eventType: "phase_gate"
2008
+ });
2009
+ const next = draftCompletionGateOrder[draftCompletionGateOrder.indexOf(gate) + 1];
2010
+ if (next) {
2011
+ await emit({
2012
+ role: "hook",
2013
+ kind: "checkpoint",
2014
+ content: `phase_progression: ${gate} -> ${next}`,
2015
+ eventType: "phase_gate"
2016
+ });
2017
+ }
2018
+ }
2019
+ }
2020
+ async function fileExists(filePath) {
2021
+ try {
2022
+ await fs.access(filePath);
2023
+ return true;
2024
+ }
2025
+ catch {
2026
+ return false;
2027
+ }
2028
+ }
2029
+ function buildDraftPrompt(dispatch) {
2030
+ const draft = dispatch.draft;
2031
+ if (!draft) {
2032
+ throw new Error("Draft prompt is missing.");
2033
+ }
2034
+ const draftArtifacts = dispatch.artifacts
2035
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
2036
+ .map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
2037
+ .join("\n\n");
2038
+ const artifactSection = draftArtifacts
2039
+ ? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
2040
+ : "";
2041
+ const projectSection = [
2042
+ draft.projectName ? `Project: ${draft.projectName}` : null,
2043
+ draft.repoName ? `Repository: ${draft.repoName}` : null
2044
+ ].filter(Boolean).join("\n");
2045
+ const scopedProjectSection = projectSection ? `\n\n# Selected project context\n\n${projectSection}` : "";
2046
+ return `${draft.systemPrompt}${scopedProjectSection}${artifactSection}
2047
+
2048
+ Draft kind: ${draft.kind}
2049
+
2050
+ ${draft.userPrompt}
2051
+
2052
+ ${completionPromptForDraftCycle("draft_intent")}
2053
+
2054
+ Use the injected command/skills/hooks as lane instructions. You must call each Forge Draft MCP completion tool in order. Do not claim the Draft is complete until forge.complete_draft_proposal accepts the final draft_json.
2055
+
2056
+ Do not modify source files.`;
2057
+ }
2058
+ function extractJsonObject(content) {
2059
+ let trimmed = content.trim();
2060
+ if (trimmed.startsWith("```")) {
2061
+ const firstNewline = trimmed.indexOf("\n");
2062
+ const lastFence = trimmed.lastIndexOf("```");
2063
+ if (firstNewline >= 0 && lastFence > firstNewline) {
2064
+ trimmed = trimmed.slice(firstNewline + 1, lastFence).trim();
2065
+ }
2066
+ }
2067
+ const start = trimmed.indexOf("{");
2068
+ const end = trimmed.lastIndexOf("}");
2069
+ return start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed;
2070
+ }
2071
+ function summarizeStderr(stderr) {
2072
+ const trimmed = stderr.trim();
2073
+ return trimmed ? `: ${clip(trimmed, 1000)}` : "";
2074
+ }
2075
+ function isDecomposeDraftKind(kind) {
2076
+ return kind === "work_order_decomposition" || kind === "feature_decomposition";
2077
+ }
2078
+ function deterministicDraftPayload(dispatch) {
2079
+ const kind = dispatch.draft?.kind ?? "work_item";
2080
+ if (kind === "work_order") {
2081
+ return {
2082
+ title: "Deterministic runner Work Order draft",
2083
+ summary: "Forge Runner generated this deterministic Work Order draft.",
2084
+ objective: "Validate runner-backed Draft generation.",
2085
+ planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
2086
+ decompositionContext: "Use this deterministic fixture only in bridge tests.",
2087
+ assumptions: ["Forge Runner dispatch is available."],
2088
+ warnings: []
2089
+ };
2090
+ }
2091
+ if (kind === "story") {
2092
+ return {
2093
+ title: "Deterministic runner Story draft",
2094
+ description: "Forge Runner generated this deterministic Story draft.",
2095
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
2096
+ points: 3
2097
+ };
2098
+ }
2099
+ return {
2100
+ title: "Deterministic runner Work Item draft",
2101
+ description: "Forge Runner generated this deterministic Work Item draft.",
2102
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
2103
+ reproSteps: "Run Draft with a Forge Runner provider selected.",
2104
+ systemInfo: "forge-bridge deterministic provider",
2105
+ points: 1
2106
+ };
2107
+ }
1307
2108
  export function formatProviderCliCommand(command) {
1308
2109
  return [command.command, ...command.args].map(singleLine).join(" ");
1309
2110
  }
@@ -1315,16 +2116,19 @@ export function buildProviderCliCommand(dispatch, run) {
1315
2116
  const normalizedProvider = provider.toLowerCase();
1316
2117
  const model = dispatch.execution.model.trim();
1317
2118
  if (normalizedProvider === "codex") {
1318
- const args = ["exec"];
2119
+ const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
1319
2120
  if (run?.completionTools) {
1320
2121
  args.push(...codexMcpConfigArgs(run.completionTools));
1321
2122
  }
1322
2123
  args.push("--model", model);
1323
2124
  if (run) {
1324
- args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
2125
+ args.push("--json");
1325
2126
  if (run.worktreePath) {
1326
2127
  args.push("--cd", run.worktreePath);
1327
2128
  }
2129
+ if (run.skipGitRepoCheck) {
2130
+ args.push("--skip-git-repo-check");
2131
+ }
1328
2132
  args.push(run.prompt ?? "");
1329
2133
  }
1330
2134
  return { command: "codex", args };
@@ -1345,6 +2149,35 @@ export function buildProviderCliCommand(dispatch, run) {
1345
2149
  }
1346
2150
  return { command: provider, args };
1347
2151
  }
2152
+ export function codexSandboxModeForPlatform(platform = process.platform) {
2153
+ return platform === "win32" ? "danger-full-access" : "workspace-write";
2154
+ }
2155
+ function buildArchitectPrompt(dispatch) {
2156
+ return `You are Forge's Architect lane running locally in a prepared git worktree.
2157
+
2158
+ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
2159
+
2160
+ Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
2161
+ 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.
2162
+ 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.
2163
+ ${architectRevisionInstruction(dispatch)}
2164
+ Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
2165
+
2166
+ ${completionPromptForPhase("architect")}
2167
+
2168
+ Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
2169
+ }
2170
+ function architectRevisionInstruction(dispatch) {
2171
+ if (!dispatch.architectRevision) {
2172
+ return "";
2173
+ }
2174
+ return `
2175
+ Architect revision context:
2176
+ - Previous plan id: ${dispatch.architectRevision.priorPlanId}
2177
+ - Previous content hash: ${dispatch.architectRevision.priorContentHash}
2178
+ - Reviewer feedback: ${dispatch.architectRevision.feedback}
2179
+ Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
2180
+ }
1348
2181
  function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1349
2182
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
1350
2183
 
@@ -1396,7 +2229,8 @@ QA rework context:
1396
2229
  - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1397
2230
  - Rework packet: ${dispatch.qaRework.packetPath}
1398
2231
  - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1399
- Read the packet JSON and fix or explicitly dispute each listed finding. The implementation completion artifact must include resolved_findings entries for every required QA ID with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.`;
2232
+ 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.
2233
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
1400
2234
  }
1401
2235
  function debugQaReworkInstruction(dispatch) {
1402
2236
  if (!dispatch.qaRework) {
@@ -1407,7 +2241,8 @@ QA rework context for Debug:
1407
2241
  - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1408
2242
  - Rework packet: ${dispatch.qaRework.packetPath}
1409
2243
  - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1410
- Read the packet JSON, reproduce or characterize each listed finding, fix or explicitly dispute it, and include resolved_findings entries for every required QA ID in forge.complete_debug_fix with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.`;
2244
+ 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.
2245
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
1411
2246
  }
1412
2247
  function qaReworkRetestInstruction(dispatch) {
1413
2248
  if (!dispatch.qaRework) {
@@ -1444,6 +2279,39 @@ function qaBrowserInstruction(dispatch) {
1444
2279
  const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
1445
2280
  return `Browser/app launch context:\n- Browser QA required: ${qaBrowser.required ? "yes" : "no, unless the diff/AC requires it"}\n- URL: ${launchTarget.url || "not specified"}\n- Ready URL: ${launchTarget.ready_url || "not specified"}\n- Launch command: ${launchTarget.command || "not specified"}\n- Working directory: ${launchTarget.working_directory || "repo root"}\n- Routes to cover: ${routes}\n- Notes: ${launchTarget.notes || "none"}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
1446
2281
  }
2282
+ function storyQaInstruction(dispatch) {
2283
+ const storyQa = dispatch.storyQa;
2284
+ if (!storyQa) {
2285
+ return "";
2286
+ }
2287
+ const childLines = storyQa.childTasks.map((child) => {
2288
+ const dependencies = child.dependencyWorkItemIds.length > 0
2289
+ ? child.dependencyWorkItemIds.join(", ")
2290
+ : "none";
2291
+ const validation = child.validationArtifact
2292
+ ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2293
+ : "missing";
2294
+ const childQa = child.qaArtifact
2295
+ ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2296
+ : "not present";
2297
+ return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2298
+ }).join("\n");
2299
+ const finalQa = storyQa.finalQaChecks.length > 0
2300
+ ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2301
+ : "- No final QA checks were provided in qa.plan.final_qa.";
2302
+ return `Story QA integration context:
2303
+ - Story work item: ${storyQa.storyWorkItemId}
2304
+ - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2305
+ - Story worktree: ${storyQa.worktreeKey}
2306
+ - Branch: ${storyQa.branch}
2307
+ - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2308
+ - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2309
+ Materialized child tasks and evidence:
2310
+ ${childLines || "- No child tasks were provided."}
2311
+ Architect final QA checks:
2312
+ ${finalQa}
2313
+ 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.`;
2314
+ }
1447
2315
  function buildQaPrompt(dispatch, laneSpec) {
1448
2316
  return `You are Forge's QA lane running locally in a prepared git worktree.
1449
2317
 
@@ -1468,6 +2336,7 @@ ${dispatch.workItem.reproSteps || "Not provided."}
1468
2336
  System info / environment notes:
1469
2337
  ${dispatch.workItem.systemInfo || "Not provided."}
1470
2338
 
2339
+ ${storyQaInstruction(dispatch)}
1471
2340
  Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1472
2341
  ${qaBrowserInstruction(dispatch)}
1473
2342
  ${qaReworkRetestInstruction(dispatch)}
@@ -1509,6 +2378,7 @@ PR context:
1509
2378
  - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
1510
2379
 
1511
2380
  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.
2381
+ After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
1512
2382
  If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
1513
2383
  Keep the original work item intent intact:
1514
2384
  - Work item: ${dispatch.workItem.id}
@@ -1577,31 +2447,31 @@ class CursorStreamJsonState {
1577
2447
  consume(line) {
1578
2448
  const event = parseJsonLine(line);
1579
2449
  if (!event) {
1580
- return null;
2450
+ return [];
1581
2451
  }
1582
2452
  const type = stringField(event, "type");
1583
2453
  if (type === "system" && stringField(event, "subtype") === "init") {
1584
2454
  this.sessionId = stringField(event, "session_id");
1585
2455
  if (this.sessionId && !this.emittedSession) {
1586
2456
  this.emittedSession = true;
1587
- return {
1588
- role: "runner",
1589
- kind: "checkpoint",
1590
- content: `Cursor session started: ${this.sessionId}.`,
1591
- eventType: "provider_thread_started"
1592
- };
2457
+ return [{
2458
+ role: "runner",
2459
+ kind: "checkpoint",
2460
+ content: `Cursor session started: ${this.sessionId}.`,
2461
+ eventType: "provider_thread_started"
2462
+ }];
1593
2463
  }
1594
2464
  }
1595
2465
  if (type === "assistant") {
1596
2466
  const text = assistantMessageText(event);
1597
2467
  if (text) {
1598
2468
  this.finalMessage = clip(text, 4000);
1599
- return {
1600
- role: "assistant",
1601
- kind: "message",
1602
- content: this.finalMessage,
1603
- eventType: "provider_message"
1604
- };
2469
+ return [{
2470
+ role: "assistant",
2471
+ kind: "message",
2472
+ content: this.finalMessage,
2473
+ eventType: "provider_message"
2474
+ }];
1605
2475
  }
1606
2476
  }
1607
2477
  if (type === "tool_call") {
@@ -1610,23 +2480,23 @@ class CursorStreamJsonState {
1610
2480
  if (subtype === "started") {
1611
2481
  const summary = formatCursorToolCallStarted(toolCall);
1612
2482
  if (summary) {
1613
- return {
1614
- role: "worker",
1615
- kind: "checkpoint",
1616
- content: summary,
1617
- eventType: "provider_tool_call"
1618
- };
2483
+ return [{
2484
+ role: "worker",
2485
+ kind: "checkpoint",
2486
+ content: summary,
2487
+ eventType: "provider_tool_call"
2488
+ }];
1619
2489
  }
1620
2490
  }
1621
2491
  if (subtype === "completed") {
1622
2492
  const completed = formatCursorToolCallCompleted(toolCall);
1623
2493
  if (completed) {
1624
- return {
1625
- role: "worker",
1626
- kind: completed.kind,
1627
- content: completed.content,
1628
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
1629
- };
2494
+ return [{
2495
+ role: "worker",
2496
+ kind: completed.kind,
2497
+ content: completed.content,
2498
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2499
+ }];
1630
2500
  }
1631
2501
  }
1632
2502
  }
@@ -1638,14 +2508,14 @@ class CursorStreamJsonState {
1638
2508
  this.accumulateUsage(event);
1639
2509
  }
1640
2510
  if (type === "error" || (type === "result" && event.is_error === true)) {
1641
- return {
1642
- role: "runner",
1643
- kind: "error",
1644
- content: clip(line.trim(), 1000),
1645
- eventType: "provider_cli_error"
1646
- };
2511
+ return [{
2512
+ role: "runner",
2513
+ kind: "error",
2514
+ content: clip(line.trim(), 1000),
2515
+ eventType: "provider_cli_error"
2516
+ }];
1647
2517
  }
1648
- return null;
2518
+ return [];
1649
2519
  }
1650
2520
  accumulateUsage(event) {
1651
2521
  const usage = objectField(event, "usage");
@@ -1776,37 +2646,37 @@ class CodexJsonState {
1776
2646
  consume(line) {
1777
2647
  const event = parseJsonLine(line);
1778
2648
  if (!event) {
1779
- return null;
2649
+ return [];
1780
2650
  }
1781
2651
  const type = stringField(event, "type") ?? "";
1782
2652
  if (type === "thread.started") {
1783
2653
  this.threadId = stringField(event, "thread_id");
1784
2654
  if (this.threadId && !this.emittedThread) {
1785
2655
  this.emittedThread = true;
1786
- return {
1787
- role: "runner",
1788
- kind: "checkpoint",
1789
- content: `Codex thread started: ${this.threadId}.`,
1790
- eventType: "provider_thread_started"
1791
- };
2656
+ return [{
2657
+ role: "runner",
2658
+ kind: "checkpoint",
2659
+ content: `Codex thread started: ${this.threadId}.`,
2660
+ eventType: "provider_thread_started"
2661
+ }];
1792
2662
  }
1793
2663
  }
1794
2664
  if (type === "turn.completed") {
1795
2665
  this.accumulateUsage(event);
1796
- return {
1797
- role: "runner",
1798
- kind: "checkpoint",
1799
- content: "Codex turn completed.",
1800
- eventType: "provider_turn_completed"
1801
- };
2666
+ return [{
2667
+ role: "runner",
2668
+ kind: "checkpoint",
2669
+ content: "Codex turn completed.",
2670
+ eventType: "provider_turn_completed"
2671
+ }];
1802
2672
  }
1803
2673
  if (type === "turn.failed" || type === "error") {
1804
- return {
1805
- role: "runner",
1806
- kind: "error",
1807
- content: clip(line.trim(), 1000),
1808
- eventType: "provider_cli_error"
1809
- };
2674
+ return [{
2675
+ role: "runner",
2676
+ kind: "error",
2677
+ content: clip(line.trim(), 1000),
2678
+ eventType: "provider_cli_error"
2679
+ }];
1810
2680
  }
1811
2681
  if (type === "item.completed" || type === "item.updated") {
1812
2682
  const item = objectField(event, "item");
@@ -1815,28 +2685,32 @@ class CodexJsonState {
1815
2685
  const text = stringField(item, "text");
1816
2686
  if (text) {
1817
2687
  this.finalMessage = clip(text, 4000);
1818
- return {
1819
- role: "assistant",
1820
- kind: "message",
1821
- content: this.finalMessage,
1822
- eventType: "provider_message"
1823
- };
2688
+ return [{
2689
+ role: "assistant",
2690
+ kind: "message",
2691
+ content: this.finalMessage,
2692
+ eventType: "provider_message"
2693
+ }];
1824
2694
  }
1825
2695
  }
1826
2696
  if (itemType === "command_execution") {
1827
2697
  const command = stringField(item, "command");
1828
2698
  const status = stringField(item, "status");
1829
2699
  if (command) {
1830
- return {
1831
- role: "worker",
1832
- kind: "checkpoint",
1833
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
1834
- eventType: "provider_command"
1835
- };
2700
+ return [{
2701
+ role: "worker",
2702
+ kind: "checkpoint",
2703
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2704
+ eventType: "provider_command"
2705
+ }];
1836
2706
  }
1837
2707
  }
1838
2708
  }
1839
- return null;
2709
+ const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2710
+ if (mcpEvents.length > 0) {
2711
+ return mcpEvents;
2712
+ }
2713
+ return [];
1840
2714
  }
1841
2715
  accumulateUsage(event) {
1842
2716
  const usage = objectField(event, "usage");
@@ -1852,6 +2726,113 @@ class CodexJsonState {
1852
2726
  });
1853
2727
  }
1854
2728
  }
2729
+ function formatCodexMcpToolCallEvents(type, event) {
2730
+ if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2731
+ return [];
2732
+ }
2733
+ const item = objectField(event, "item");
2734
+ const itemType = stringField(item, "type") ?? "";
2735
+ const serverName = mcpServerName(item);
2736
+ const toolName = mcpToolName(item);
2737
+ const isMcpItem = itemType.toLowerCase().includes("mcp")
2738
+ || Boolean(serverName)
2739
+ || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2740
+ if (!isMcpItem || !toolName) {
2741
+ return [];
2742
+ }
2743
+ const status = normalizedString(stringField(item, "status")
2744
+ ?? stringField(event, "status")
2745
+ ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2746
+ const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2747
+ const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2748
+ const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2749
+ const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2750
+ const label = `${serverName ?? "unknown"}.${toolName}`;
2751
+ if (failed) {
2752
+ const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2753
+ const events = [{
2754
+ role: "tool",
2755
+ kind: "error",
2756
+ content: `MCP tool call failed: ${label} - ${summary}`,
2757
+ eventType: "provider_mcp_call_failed",
2758
+ data
2759
+ }];
2760
+ if (isForgeCompletionTool(toolName)) {
2761
+ events.push({
2762
+ role: "tool",
2763
+ kind: "error",
2764
+ content: `Forge completion tool validation failed: ${label} - ${summary}`,
2765
+ eventType: "completion_tool_validation_failed",
2766
+ data
2767
+ });
2768
+ }
2769
+ return events;
2770
+ }
2771
+ if (completed) {
2772
+ return [{
2773
+ role: "tool",
2774
+ kind: "checkpoint",
2775
+ content: `MCP tool call completed: ${label}.`,
2776
+ eventType: "provider_mcp_call_completed",
2777
+ data
2778
+ }];
2779
+ }
2780
+ if (started) {
2781
+ return [{
2782
+ role: "tool",
2783
+ kind: "checkpoint",
2784
+ content: `MCP tool call started: ${label}.`,
2785
+ eventType: "provider_mcp_call_started",
2786
+ data
2787
+ }];
2788
+ }
2789
+ return [];
2790
+ }
2791
+ function mcpServerName(item) {
2792
+ return stringField(item, "server")
2793
+ ?? stringField(item, "server_name")
2794
+ ?? stringField(item, "mcp_server")
2795
+ ?? stringField(objectField(item, "mcp"), "server")
2796
+ ?? stringField(objectField(item, "mcp"), "server_name");
2797
+ }
2798
+ function mcpToolName(item) {
2799
+ return stringField(item, "tool")
2800
+ ?? stringField(item, "tool_name")
2801
+ ?? stringField(item, "name")
2802
+ ?? stringField(objectField(item, "function"), "name")
2803
+ ?? stringField(objectField(item, "mcp"), "tool")
2804
+ ?? stringField(objectField(item, "mcp"), "tool_name");
2805
+ }
2806
+ function mcpErrorSummary(item) {
2807
+ const direct = stringField(item, "error")
2808
+ ?? stringField(item, "error_message")
2809
+ ?? stringField(item, "message");
2810
+ if (direct) {
2811
+ return clip(direct, 600);
2812
+ }
2813
+ const error = objectField(item, "error");
2814
+ return stringField(error, "message")
2815
+ ?? stringField(error, "summary")
2816
+ ?? stringField(objectField(item, "result"), "error")
2817
+ ?? null;
2818
+ }
2819
+ function safeProviderMcpData(item, serverName, toolName, status) {
2820
+ const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2821
+ return JSON.stringify(stripUndefined({
2822
+ server_name: serverName,
2823
+ tool_name: toolName,
2824
+ status,
2825
+ elapsed_ms: elapsedMs,
2826
+ error_summary: mcpErrorSummary(item)
2827
+ }));
2828
+ }
2829
+ function isForgeCompletionTool(toolName) {
2830
+ const normalized = toolName.trim().toLowerCase();
2831
+ return normalized.startsWith("forge.complete_")
2832
+ || normalized.startsWith("complete_")
2833
+ || normalized.includes("forge.complete_")
2834
+ || normalized.includes("complete_architect_plan");
2835
+ }
1855
2836
  function objectField(source, key) {
1856
2837
  const value = source[key];
1857
2838
  return value && typeof value === "object" && !Array.isArray(value)
@@ -1862,6 +2843,13 @@ function stringField(source, key) {
1862
2843
  const value = source[key];
1863
2844
  return typeof value === "string" && value.trim().length > 0 ? value : null;
1864
2845
  }
2846
+ function numericField(source, key) {
2847
+ const value = source[key];
2848
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2849
+ }
2850
+ function stripUndefined(value) {
2851
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2852
+ }
1865
2853
  function normalizedString(value) {
1866
2854
  return value.trim().toLowerCase().replace(/-/g, "_");
1867
2855
  }