@loucompanion/forge-bridge 0.1.1-dev.2ac58b6f94ce → 0.1.1-dev.2d1a116ca78d

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, completionPromptForDevelopCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, 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,10 +183,74 @@ 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
+ const draftArtifactSlugs = dispatch.artifacts
198
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
199
+ .map((artifact) => `${artifact.kind}:${artifact.slug}`);
200
+ await context.emit({
201
+ role: "runner",
202
+ kind: "checkpoint",
203
+ content: `Draft artifacts injected: ${draftArtifactSlugs.length}${draftArtifactSlugs.length ? ` (${draftArtifactSlugs.join(", ")})` : ""}. Project: ${dispatch.draft.projectName ?? dispatch.repo.name}. Repo: ${dispatch.draft.repoName ?? dispatch.repo.name}.`,
204
+ eventType: "draft_artifacts_injected"
205
+ });
206
+ await context.emit({
207
+ role: "runner",
208
+ kind: "checkpoint",
209
+ content: `Starting provider CLI Draft: ${formatProviderCliCommand(command)}`,
210
+ eventType: "provider_cli_started"
211
+ });
212
+ const outputState = createProviderOutputState(dispatch.execution.provider);
213
+ try {
214
+ const result = await this.processRunner.run({
215
+ command: command.command,
216
+ args: command.args,
217
+ cwd: tempDir,
218
+ env: providerProcessEnv(dispatch)
219
+ }, {
220
+ onStdoutLine: async (line) => {
221
+ for (const event of outputState.consume(line)) {
222
+ await context.emit(event);
223
+ }
224
+ }
225
+ }, context.signal);
226
+ if (result.exitCode !== 0) {
227
+ throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
228
+ }
229
+ const content = outputState.finalMessage ?? result.stdout.trim();
230
+ if (!content) {
231
+ throw new Error("Provider CLI completed without returning a draft.");
232
+ }
233
+ const json = extractJsonObject(content);
234
+ await context.emit({
235
+ role: "assistant",
236
+ kind: "message",
237
+ content: json,
238
+ eventType: "draft_complete"
239
+ });
240
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
241
+ return {
242
+ summary: "Draft generated through Forge Runner."
243
+ };
244
+ }
245
+ finally {
246
+ await fs.rm(tempDir, { recursive: true, force: true });
247
+ }
248
+ }
46
249
  async runImplementation(context) {
47
250
  const { dispatch, worktree } = context;
48
251
  const phase = completionPhaseFromDispatch(dispatch);
49
252
  const developCycle = usesDevelopCycleCompletion(dispatch);
253
+ const debugCycle = usesDebugCycleCompletion(dispatch);
50
254
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
51
255
  await fs.mkdir(metadataRoot, { recursive: true });
52
256
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -60,7 +264,11 @@ export class ProcessBackedProviderCliService {
60
264
  const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
61
265
  const command = buildProviderCliCommand(dispatch, {
62
266
  worktreePath: worktree.worktreePath,
63
- prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
267
+ prompt: debugCycle
268
+ ? buildDebugCyclePrompt(dispatch, phase)
269
+ : developCycle
270
+ ? buildDevelopCyclePrompt(dispatch, phase)
271
+ : buildImplementationPrompt(dispatch, phase),
64
272
  completionTools
65
273
  });
66
274
  await context.emit({
@@ -72,13 +280,15 @@ export class ProcessBackedProviderCliService {
72
280
  await context.emit({
73
281
  role: "runner",
74
282
  kind: "checkpoint",
75
- content: developCycle
76
- ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
77
- : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
283
+ content: debugCycle
284
+ ? "Forge Debug completion tools configured for debug_repro -> debug_root_cause -> debug_fix -> debug_regression; provider must call each MCP completion tool before exit."
285
+ : developCycle
286
+ ? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
287
+ : `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
78
288
  eventType: "completion_tools_configured"
79
289
  });
80
290
  const outputState = createProviderOutputState(dispatch.execution.provider);
81
- const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, context.emit);
291
+ const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
82
292
  let result;
83
293
  try {
84
294
  liveCompletionEvents.start();
@@ -86,11 +296,10 @@ export class ProcessBackedProviderCliService {
86
296
  command: command.command,
87
297
  args: command.args,
88
298
  cwd: worktree.worktreePath,
89
- env: providerRedactionEnv(dispatch)
299
+ env: providerProcessEnv(dispatch)
90
300
  }, {
91
301
  onStdoutLine: async (line) => {
92
- const event = outputState.consume(line);
93
- if (event) {
302
+ for (const event of outputState.consume(line)) {
94
303
  await context.emit(event);
95
304
  }
96
305
  }
@@ -112,7 +321,7 @@ export class ProcessBackedProviderCliService {
112
321
  });
113
322
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
114
323
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
115
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle);
324
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
116
325
  for (const artifact of completionArtifacts) {
117
326
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
118
327
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -138,7 +347,7 @@ export class ProcessBackedProviderCliService {
138
347
  });
139
348
  }
140
349
  return {
141
- summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
350
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
142
351
  spec: {
143
352
  repoPath: worktree.worktreePath,
144
353
  path: specPath,
@@ -150,6 +359,89 @@ export class ProcessBackedProviderCliService {
150
359
  artifacts: completionArtifacts
151
360
  };
152
361
  }
362
+ async runArchitect(context) {
363
+ const { dispatch, worktree } = context;
364
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
365
+ const command = buildProviderCliCommand(dispatch, {
366
+ worktreePath: worktree.worktreePath,
367
+ prompt: buildArchitectPrompt(dispatch),
368
+ completionTools
369
+ });
370
+ const commandText = formatProviderCliCommand(command);
371
+ await context.emit({
372
+ role: "runner",
373
+ kind: "checkpoint",
374
+ content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
375
+ eventType: "provider_cli_started"
376
+ });
377
+ await context.emit({
378
+ role: "runner",
379
+ kind: "checkpoint",
380
+ content: "Forge Architect completion tools configured; provider must call forge.complete_architect_plan before exit.",
381
+ eventType: "completion_tools_configured"
382
+ });
383
+ const outputState = createProviderOutputState(dispatch.execution.provider);
384
+ const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
385
+ let result;
386
+ try {
387
+ liveArchitectEvents.start();
388
+ result = await this.processRunner.run({
389
+ command: command.command,
390
+ args: command.args,
391
+ cwd: worktree.worktreePath,
392
+ env: providerProcessEnv(dispatch)
393
+ }, {
394
+ onStdoutLine: async (line) => {
395
+ for (const event of outputState.consume(line)) {
396
+ await context.emit(event);
397
+ }
398
+ }
399
+ }, context.signal);
400
+ }
401
+ finally {
402
+ await liveArchitectEvents.stop();
403
+ await cleanupCompletionTools(completionTools, context.emit);
404
+ }
405
+ if (result.exitCode !== 0) {
406
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
407
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
408
+ }
409
+ await context.emit({
410
+ role: "runner",
411
+ kind: "checkpoint",
412
+ content: `Provider CLI Architect completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
413
+ eventType: "provider_cli_completed"
414
+ });
415
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
416
+ const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
417
+ if (!architectArtifact) {
418
+ throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
419
+ }
420
+ if (!liveArchitectEvents.hasEmitted()) {
421
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
422
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, architectArtifact);
423
+ }
424
+ await context.emit({
425
+ role: "assistant",
426
+ kind: "message",
427
+ content: outputState.finalMessage || `${dispatch.execution.provider} CLI produced an Architect plan for ${worktree.branchName}.`,
428
+ eventType: "architect_complete"
429
+ });
430
+ const specPath = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id, "spec.md");
431
+ const specBody = await fs.readFile(specPath, "utf8").catch(() => `# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`);
432
+ return {
433
+ summary: `${dispatch.execution.provider} CLI Architect plan produced.`,
434
+ spec: {
435
+ repoPath: worktree.worktreePath,
436
+ path: specPath,
437
+ body: specBody,
438
+ producedBy: `${dispatch.execution.provider}-cli`,
439
+ status: "pending_approval"
440
+ },
441
+ artifact: architectArtifact,
442
+ artifacts: [architectArtifact]
443
+ };
444
+ }
153
445
  async runQa(context) {
154
446
  const { dispatch, worktree } = context;
155
447
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -190,11 +482,10 @@ export class ProcessBackedProviderCliService {
190
482
  command: command.command,
191
483
  args: command.args,
192
484
  cwd: worktree.worktreePath,
193
- env: providerRedactionEnv(dispatch)
485
+ env: providerProcessEnv(dispatch)
194
486
  }, {
195
487
  onStdoutLine: async (line) => {
196
- const event = outputState.consume(line);
197
- if (event) {
488
+ for (const event of outputState.consume(line)) {
198
489
  await context.emit(event);
199
490
  }
200
491
  }
@@ -215,7 +506,7 @@ export class ProcessBackedProviderCliService {
215
506
  eventType: "provider_cli_completed"
216
507
  });
217
508
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
218
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
509
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
219
510
  if (!qaArtifact) {
220
511
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
221
512
  throw new Error(verdictOnly
@@ -225,7 +516,7 @@ export class ProcessBackedProviderCliService {
225
516
  enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
226
517
  if (!liveQaEvents.hasEmitted()) {
227
518
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
228
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
519
+ await emitQaStructuredEvents(context.emit, qaArtifact);
229
520
  }
230
521
  const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
231
522
  const statusSummary = status === "pass"
@@ -265,11 +556,11 @@ export class ProcessBackedProviderCliService {
265
556
  const result = await this.processRunner.run({
266
557
  command: command.command,
267
558
  args: command.args,
268
- cwd: worktree.worktreePath
559
+ cwd: worktree.worktreePath,
560
+ env: providerProcessEnv(dispatch)
269
561
  }, {
270
562
  onStdoutLine: async (line) => {
271
- const event = outputState.consume(line);
272
- if (event) {
563
+ for (const event of outputState.consume(line)) {
273
564
  await context.emit(event);
274
565
  }
275
566
  }
@@ -301,10 +592,22 @@ export class DeterministicProviderCliService {
301
592
  constructor(git = new GitClient()) {
302
593
  this.git = git;
303
594
  }
595
+ async runDraft(context) {
596
+ const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
597
+ await context.emit({
598
+ role: "assistant",
599
+ kind: "message",
600
+ content,
601
+ eventType: "draft_complete"
602
+ });
603
+ await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
604
+ return { summary: "forge-bridge generated deterministic draft." };
605
+ }
304
606
  async runImplementation(context) {
305
607
  const { dispatch, worktree } = context;
306
608
  const phase = completionPhaseFromDispatch(dispatch);
307
609
  const developCycle = usesDevelopCycleCompletion(dispatch);
610
+ const debugCycle = usesDebugCycleCompletion(dispatch);
308
611
  const providerCommand = buildProviderCliCommand(dispatch);
309
612
  const providerCommandText = formatProviderCliCommand(providerCommand);
310
613
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -335,9 +638,11 @@ export class DeterministicProviderCliService {
335
638
  content: `Created bridge changeset at ${changesetPath}`,
336
639
  eventType: "changeset"
337
640
  });
338
- const phases = developCycle
339
- ? ["implementation", "self_review", "validation"]
340
- : [phase];
641
+ const phases = debugCycle
642
+ ? debugCompletionPhaseOrder
643
+ : developCycle
644
+ ? ["implementation", "self_review", "validation"]
645
+ : [phase];
341
646
  const completionArtifacts = [];
342
647
  for (const completionPhase of phases) {
343
648
  await writeCompletionArtifact({
@@ -346,7 +651,9 @@ export class DeterministicProviderCliService {
346
651
  phase: completionPhase,
347
652
  producedBy: "forge-bridge",
348
653
  redactionSecrets: exactRedactionSecrets(dispatch)
349
- }, expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
654
+ }, isDebugCompletionPhaseForProvider(completionPhase)
655
+ ? expectedDebugCompletionToolName(completionPhase)
656
+ : expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
350
657
  const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
351
658
  if (!completionArtifact) {
352
659
  throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
@@ -362,7 +669,7 @@ export class DeterministicProviderCliService {
362
669
  }
363
670
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
364
671
  return {
365
- summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
672
+ summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
366
673
  spec: {
367
674
  repoPath: worktree.worktreePath,
368
675
  path: specPath,
@@ -374,6 +681,47 @@ export class DeterministicProviderCliService {
374
681
  artifacts: completionArtifacts
375
682
  };
376
683
  }
684
+ async runArchitect(context) {
685
+ const { dispatch, worktree } = context;
686
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
687
+ await fs.mkdir(metadataRoot, { recursive: true });
688
+ 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`;
689
+ const specPath = path.join(metadataRoot, "spec.md");
690
+ await fs.writeFile(specPath, specBody, "utf8");
691
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
692
+ await writeCompletionArtifact({
693
+ worktreePath: worktree.worktreePath,
694
+ workItemId: dispatch.workItem.id,
695
+ phase: "architect",
696
+ producedBy: "forge-bridge",
697
+ redactionSecrets: exactRedactionSecrets(dispatch),
698
+ architectCycle: true
699
+ }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
700
+ const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
701
+ if (!artifact) {
702
+ throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
703
+ }
704
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
705
+ await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
706
+ await context.emit({
707
+ role: "assistant",
708
+ kind: "message",
709
+ content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
710
+ eventType: "architect_complete"
711
+ });
712
+ return {
713
+ summary: "forge-bridge completed Architect plan (deterministic).",
714
+ spec: {
715
+ repoPath: worktree.worktreePath,
716
+ path: specPath,
717
+ body: specBody,
718
+ producedBy: "forge-bridge",
719
+ status: "pending_approval"
720
+ },
721
+ artifact,
722
+ artifacts: [artifact]
723
+ };
724
+ }
377
725
  async runQa(context) {
378
726
  const { dispatch, worktree } = context;
379
727
  await context.emit({
@@ -386,7 +734,7 @@ export class DeterministicProviderCliService {
386
734
  const launchTarget = qaBrowser?.launchTarget ?? null;
387
735
  const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
388
736
  const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
389
- ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget)
737
+ ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
390
738
  : null;
391
739
  const browserChecks = browserSidecar && launchTarget
392
740
  ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
@@ -403,7 +751,9 @@ export class DeterministicProviderCliService {
403
751
  phase: "qa",
404
752
  producedBy: "forge-bridge",
405
753
  redactionSecrets: exactRedactionSecrets(dispatch),
406
- qaCycle: true
754
+ qaCycle: true,
755
+ ownerType: dispatch.cycleRun.ownerType ?? undefined,
756
+ ownerId: dispatch.cycleRun.ownerId ?? undefined
407
757
  }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
408
758
  gate,
409
759
  criterion,
@@ -412,19 +762,17 @@ export class DeterministicProviderCliService {
412
762
  browserChecks,
413
763
  sidecars
414
764
  }));
415
- await context.emit({
416
- role: "hook",
417
- kind: "checkpoint",
418
- content: `qa_gate: ${gate} artifact accepted.`,
419
- eventType: "qa_gate"
420
- });
765
+ const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
766
+ if (gateArtifact) {
767
+ await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
768
+ }
421
769
  }
422
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
770
+ const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
423
771
  if (!qaArtifact) {
424
772
  throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
425
773
  }
426
774
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
427
- await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
775
+ await emitQaStructuredEvents(context.emit, qaArtifact);
428
776
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
429
777
  return {
430
778
  summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
@@ -455,6 +803,9 @@ export class DeterministicProviderCliService {
455
803
  function phaseCompleteEventType(phase) {
456
804
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
457
805
  }
806
+ function isDebugCompletionPhaseForProvider(phase) {
807
+ return debugCompletionPhaseOrder.includes(phase);
808
+ }
458
809
  function deterministicCompletionPayload(phase, dispatch, changesetBody) {
459
810
  const changesetHash = sha256(changesetBody);
460
811
  const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
@@ -477,6 +828,56 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
477
828
  next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
478
829
  };
479
830
  }
831
+ if (phase === "debug_repro") {
832
+ return {
833
+ status: "pass",
834
+ summary: "forge-bridge reproduced the bug deterministically.",
835
+ repro_steps: ["Run the deterministic fake-worker debug reproduction."],
836
+ observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
837
+ expected: "The bug scenario should be fixed before QA handoff.",
838
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
839
+ };
840
+ }
841
+ if (phase === "debug_root_cause") {
842
+ return {
843
+ status: "pass",
844
+ summary: "forge-bridge isolated a deterministic root cause.",
845
+ root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
846
+ evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
847
+ eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
848
+ risk_area: "forge-bridge deterministic debug lane"
849
+ };
850
+ }
851
+ if (phase === "debug_fix") {
852
+ return {
853
+ status: "pass",
854
+ summary: "forge-bridge applied a deterministic debug fix.",
855
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
856
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
857
+ remaining_risks: [],
858
+ resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
859
+ qa_id: qaId,
860
+ status: "resolved",
861
+ summary: `Resolved deterministic QA finding ${qaId}.`,
862
+ evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
863
+ changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
864
+ tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
865
+ regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
866
+ }))
867
+ };
868
+ }
869
+ if (phase === "debug_regression") {
870
+ return {
871
+ status: "pass",
872
+ summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
873
+ commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
874
+ required_regressions: ["Original deterministic repro no longer fails."],
875
+ build_status: "not_applicable",
876
+ test_status: "pass",
877
+ repro_negative: true,
878
+ qa_ready: true
879
+ };
880
+ }
480
881
  if (phase === "self_review") {
481
882
  return {
482
883
  status: "pass",
@@ -537,6 +938,45 @@ function deterministicCompletionPayload(phase, dispatch, changesetBody) {
537
938
  ready_for_dev_test: true
538
939
  };
539
940
  }
941
+ function deterministicArchitectPayload(dispatch) {
942
+ const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
943
+ return {
944
+ status: "pass",
945
+ summary: "forge-bridge produced a deterministic Architect plan.",
946
+ implementation_plan: {
947
+ schema_version: 1,
948
+ plan_id: planId,
949
+ story_id: dispatch.workItem.id,
950
+ phases: [
951
+ { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
952
+ ],
953
+ tasks: [
954
+ {
955
+ id: "task-1",
956
+ title: `Implement ${dispatch.workItem.title}`,
957
+ phase: "phase-1",
958
+ summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
959
+ acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
960
+ tests: [
961
+ { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
962
+ ]
963
+ }
964
+ ],
965
+ dependencies: [],
966
+ phase_gates: [
967
+ { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
968
+ ]
969
+ },
970
+ qa_plan: {
971
+ schema_version: 1,
972
+ plan_id: planId,
973
+ final_qa: [
974
+ { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
975
+ ]
976
+ },
977
+ 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`
978
+ };
979
+ }
540
980
  function deterministicQaGatePayload(options) {
541
981
  const blocked = options.missingLaunchTarget;
542
982
  const skippedBecauseBlocked = blocked
@@ -648,16 +1088,25 @@ const qaArtifactFileNames = {
648
1088
  verdict: "qa.verdict.json",
649
1089
  report: "qa.report.md"
650
1090
  };
1091
+ const qaGateArtifactFileNames = {
1092
+ qa_plan: "qa.plan.json",
1093
+ qa_regression: "qa.regression.json",
1094
+ qa_api: "qa.api.json",
1095
+ qa_manual_web: "qa.manual-web.json",
1096
+ qa_bug_repro: "qa.bug-repro.json",
1097
+ qa_findings: "qa.findings.json",
1098
+ qa_verdict: "qa.verdict.json"
1099
+ };
651
1100
  function hasLaunchTarget(target) {
652
1101
  return Boolean(target?.url?.trim()
653
1102
  || target?.ready_url?.trim()
654
1103
  || target?.command?.trim()
655
1104
  || (target?.routes ?? []).some((route) => route.trim().length > 0));
656
1105
  }
657
- function deterministicBrowserSidecar(workItemId, target) {
1106
+ function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
658
1107
  const route = primaryLaunchRoute(target);
659
1108
  return {
660
- relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt"),
1109
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
661
1110
  content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
662
1111
  };
663
1112
  }
@@ -699,78 +1148,6 @@ async function writeQaSidecarFiles(worktreePath, files) {
699
1148
  }
700
1149
  return sidecars;
701
1150
  }
702
- async function writeQaArtifacts(request) {
703
- const artifactRoot = artifactRootFor(request.worktreePath, request.workItemId);
704
- await fs.mkdir(artifactRoot, { recursive: true });
705
- const sidecars = await writeQaSidecarFiles(request.worktreePath, request.sidecarFiles ?? []);
706
- const status = request.status ?? "pass";
707
- const criterion = request.acceptanceCriteria.trim() || "Forge QA evidence exists";
708
- const relativeEvidencePath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.evidence);
709
- const relativeFindingsPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.findings);
710
- const relativeReportPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.report);
711
- const planJson = jsonText({
712
- schema_version: 1,
713
- phase: "qa",
714
- checklist: [
715
- "Review the validated work item against acceptance criteria.",
716
- "Run relevant provider QA verification.",
717
- "Confirm no in-scope QA findings remain."
718
- ],
719
- acceptance_criteria: [criterion]
720
- });
721
- const evidenceJson = jsonText({
722
- schema_version: 1,
723
- phase: "qa",
724
- commands: status === "blocked"
725
- ? []
726
- : [
727
- {
728
- command: request.command,
729
- exit_code: 0,
730
- status: "pass",
731
- summary: `${request.provider} QA completed successfully.`
732
- }
733
- ],
734
- browser_checks: request.browserChecks ?? [],
735
- sidecars,
736
- notes: request.summary
737
- });
738
- const findingsJson = jsonText({
739
- schema_version: 1,
740
- phase: "qa",
741
- findings: [],
742
- candidate_bugs: []
743
- });
744
- const verdictJson = jsonText({
745
- schema_version: 1,
746
- phase: "qa",
747
- status,
748
- summary: request.summary,
749
- tested_acceptance_criteria: status === "blocked" ? [] : [criterion],
750
- finding_ids: [],
751
- candidate_bug_ids: [],
752
- blocker_reason: status === "blocked" ? request.blockerReason ?? "inconclusive" : null,
753
- evidence_path: relativeEvidencePath,
754
- findings_path: relativeFindingsPath,
755
- report_path: relativeReportPath
756
- });
757
- 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`;
758
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.plan), planJson, "utf8");
759
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.evidence), evidenceJson, "utf8");
760
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.findings), findingsJson, "utf8");
761
- const verdictPath = path.join(artifactRoot, qaArtifactFileNames.verdict);
762
- await fs.writeFile(verdictPath, verdictJson, "utf8");
763
- await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.report), report, "utf8");
764
- return {
765
- repoPath: request.worktreePath,
766
- path: verdictPath,
767
- verdictJson,
768
- report,
769
- producedBy: request.producedBy,
770
- status,
771
- phase: "qa"
772
- };
773
- }
774
1151
  async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
775
1152
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
776
1153
  await emit({
@@ -786,16 +1163,29 @@ async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
786
1163
  eventType: "phase_gate"
787
1164
  });
788
1165
  }
789
- async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
790
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
791
- if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
1166
+ async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1167
+ const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1168
+ if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
792
1169
  return null;
793
1170
  }
794
- await validateQaBundleSidecarReferences(worktreePath, workItemId);
795
- return artifact;
1171
+ const artifactRoot = ownerType && ownerId
1172
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1173
+ : artifactRootFor(worktreePath, workItemId);
1174
+ const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1175
+ const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1176
+ const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1177
+ await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1178
+ return {
1179
+ ...artifact,
1180
+ planJson,
1181
+ evidenceJson,
1182
+ findingsJson
1183
+ };
796
1184
  }
797
- async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
798
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1185
+ async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1186
+ const artifactRoot = ownerType && ownerId
1187
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1188
+ : artifactRootFor(worktreePath, workItemId);
799
1189
  for (const fileName of Object.values(qaArtifactFileNames)) {
800
1190
  try {
801
1191
  const stat = await fs.stat(path.join(artifactRoot, fileName));
@@ -824,8 +1214,10 @@ function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
824
1214
  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.");
825
1215
  }
826
1216
  }
827
- async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
828
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1217
+ async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1218
+ const artifactRoot = ownerType && ownerId
1219
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1220
+ : artifactRootFor(worktreePath, workItemId);
829
1221
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
830
1222
  const sidecars = arrayField(evidence, "sidecars");
831
1223
  if (sidecars.length === 0) {
@@ -844,7 +1236,9 @@ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
844
1236
  }
845
1237
  const fullPath = path.resolve(worktreePath, sidecarPath);
846
1238
  if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
847
- throw new Error(`QA sidecar ${index} path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
1239
+ const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1240
+ const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1241
+ throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
848
1242
  }
849
1243
  const stat = await fs.lstat(fullPath).catch((error) => {
850
1244
  if (isNodeError(error) && error.code === "ENOENT") {
@@ -865,8 +1259,8 @@ async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
865
1259
  }
866
1260
  }
867
1261
  }
868
- async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
869
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1262
+ async function emitQaStructuredEvents(emit, artifact) {
1263
+ const artifactRoot = path.dirname(artifact.path);
870
1264
  const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
871
1265
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
872
1266
  const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
@@ -906,12 +1300,76 @@ async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact)
906
1300
  eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
907
1301
  });
908
1302
  }
1303
+ function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1304
+ return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1305
+ ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1306
+ : artifactRootFor(worktreePath, workItemId);
1307
+ }
1308
+ async function readQaGateArtifact(artifactRoot, gate) {
1309
+ const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1310
+ try {
1311
+ const stat = await fs.stat(artifactPath);
1312
+ if (!stat.isFile()) {
1313
+ return null;
1314
+ }
1315
+ }
1316
+ catch (error) {
1317
+ if (isNodeError(error) && error.code === "ENOENT") {
1318
+ return null;
1319
+ }
1320
+ throw error;
1321
+ }
1322
+ const payload = await readJsonObjectFile(artifactPath);
1323
+ return {
1324
+ gate,
1325
+ path: artifactPath,
1326
+ status: stringField(payload, "status") ?? "unknown",
1327
+ producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1328
+ contentHash: stringField(payload, "content_hash") ?? undefined
1329
+ };
1330
+ }
1331
+ function nextQaGate(gate) {
1332
+ const index = qaCompletionGateOrder.indexOf(gate);
1333
+ return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1334
+ }
1335
+ async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1336
+ const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1337
+ await emit({
1338
+ role: "hook",
1339
+ kind: artifact.status === "blocked" ? "error" : "checkpoint",
1340
+ content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1341
+ eventType: "phase_gate",
1342
+ data: JSON.stringify({
1343
+ phase: "qa",
1344
+ qa_gate: artifact.gate,
1345
+ status: artifact.status,
1346
+ artifact_relative_paths: [relativePath],
1347
+ content_hash: artifact.contentHash ?? null,
1348
+ produced_by: artifact.producedBy ?? null
1349
+ })
1350
+ });
1351
+ if (!nextGate) {
1352
+ return;
1353
+ }
1354
+ await emit({
1355
+ role: "hook",
1356
+ kind: "checkpoint",
1357
+ content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1358
+ eventType: "phase_gate",
1359
+ data: JSON.stringify({
1360
+ phase: "qa",
1361
+ from_gate: artifact.gate,
1362
+ to_gate: nextGate
1363
+ })
1364
+ });
1365
+ }
909
1366
  class LiveQaArtifactEmitter {
910
1367
  worktreePath;
911
1368
  workItemId;
912
1369
  dispatch;
913
1370
  emit;
914
- emitted = false;
1371
+ emittedBundle = false;
1372
+ emittedGates = new Set();
915
1373
  timer = null;
916
1374
  pending = Promise.resolve();
917
1375
  constructor(worktreePath, workItemId, dispatch, emit) {
@@ -934,7 +1392,7 @@ class LiveQaArtifactEmitter {
934
1392
  await this.pollQueued();
935
1393
  }
936
1394
  hasEmitted() {
937
- return this.emitted;
1395
+ return this.emittedBundle;
938
1396
  }
939
1397
  pollQueued() {
940
1398
  this.pending = this.pending
@@ -943,19 +1401,125 @@ class LiveQaArtifactEmitter {
943
1401
  return this.pending;
944
1402
  }
945
1403
  async poll() {
946
- if (this.emitted) {
1404
+ await this.emitAvailableGateEvents();
1405
+ if (this.emittedBundle) {
947
1406
  return;
948
1407
  }
949
- const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
1408
+ const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
950
1409
  if (!artifact) {
951
1410
  return;
952
1411
  }
953
1412
  enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
954
- this.emitted = true;
1413
+ this.emittedBundle = true;
955
1414
  await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
956
- await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1415
+ await emitQaStructuredEvents(this.emit, artifact);
1416
+ }
1417
+ async emitAvailableGateEvents() {
1418
+ const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1419
+ for (const gate of qaCompletionGateOrder) {
1420
+ if (this.emittedGates.has(gate)) {
1421
+ continue;
1422
+ }
1423
+ const artifact = await readQaGateArtifact(artifactRoot, gate);
1424
+ if (!artifact) {
1425
+ return;
1426
+ }
1427
+ this.emittedGates.add(gate);
1428
+ await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
1429
+ }
1430
+ }
1431
+ }
1432
+ class LiveArchitectArtifactEmitter {
1433
+ worktreePath;
1434
+ workItemId;
1435
+ emit;
1436
+ emitted = false;
1437
+ timer = null;
1438
+ pending = Promise.resolve();
1439
+ constructor(worktreePath, workItemId, emit) {
1440
+ this.worktreePath = worktreePath;
1441
+ this.workItemId = workItemId;
1442
+ this.emit = emit;
1443
+ }
1444
+ start() {
1445
+ void this.pollQueued();
1446
+ this.timer = setInterval(() => {
1447
+ void this.pollQueued();
1448
+ }, 250);
1449
+ }
1450
+ async stop() {
1451
+ if (this.timer) {
1452
+ clearInterval(this.timer);
1453
+ this.timer = null;
1454
+ }
1455
+ await this.pollQueued();
1456
+ }
1457
+ hasEmitted() {
1458
+ return this.emitted;
1459
+ }
1460
+ pollQueued() {
1461
+ this.pending = this.pending
1462
+ .then(() => this.poll())
1463
+ .catch(() => undefined);
1464
+ return this.pending;
1465
+ }
1466
+ async poll() {
1467
+ if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
1468
+ return;
1469
+ }
1470
+ const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
1471
+ if (!artifact) {
1472
+ return;
1473
+ }
1474
+ this.emitted = true;
1475
+ await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1476
+ await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
957
1477
  }
958
1478
  }
1479
+ async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1480
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1481
+ for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1482
+ try {
1483
+ const stat = await fs.stat(path.join(artifactRoot, fileName));
1484
+ if (!stat.isFile()) {
1485
+ return false;
1486
+ }
1487
+ }
1488
+ catch (error) {
1489
+ if (isNodeError(error) && error.code === "ENOENT") {
1490
+ return false;
1491
+ }
1492
+ throw error;
1493
+ }
1494
+ }
1495
+ return true;
1496
+ }
1497
+ async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1498
+ const artifactRoot = artifactRootFor(worktreePath, workItemId);
1499
+ const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1500
+ const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1501
+ const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1502
+ const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1503
+ const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1504
+ await emit({
1505
+ role: "worker",
1506
+ kind: "checkpoint",
1507
+ content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1508
+ eventType: "architect_plan"
1509
+ });
1510
+ await emit({
1511
+ role: "worker",
1512
+ kind: "checkpoint",
1513
+ content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1514
+ eventType: "architect_qa_seed"
1515
+ });
1516
+ await emit({
1517
+ role: "hook",
1518
+ kind: status === "pass" ? "checkpoint" : "error",
1519
+ content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1520
+ eventType: "architect_mcp_complete"
1521
+ });
1522
+ }
959
1523
  async function readJsonObjectFile(filePath) {
960
1524
  const content = await fs.readFile(filePath, "utf8").catch(() => "");
961
1525
  return parseJsonLine(content) ?? {};
@@ -980,19 +1544,36 @@ function summarizeQaObject(source) {
980
1544
  ?? stringField(source, "id")
981
1545
  ?? JSON.stringify(source), 500);
982
1546
  }
983
- function qaArtifactRelativePath(workItemId, fileName) {
1547
+ function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1548
+ if (ownerType && ownerId) {
1549
+ const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1550
+ return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1551
+ }
984
1552
  return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
985
1553
  }
986
- function jsonText(value) {
987
- return `${JSON.stringify(value, null, 2)}\n`;
988
- }
989
1554
  async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
990
1555
  const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1556
+ await emit({
1557
+ role: "tool",
1558
+ kind: "checkpoint",
1559
+ content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1560
+ eventType: "completion_tool_validation_passed",
1561
+ data: JSON.stringify({
1562
+ phase: artifact.phase ?? "unknown",
1563
+ status: artifact.status,
1564
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1565
+ })
1566
+ });
991
1567
  await emit({
992
1568
  role: "tool",
993
1569
  kind: "tool_result",
994
1570
  content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
995
- eventType: "completion_tool_artifact_recorded"
1571
+ eventType: "completion_tool_artifact_recorded",
1572
+ data: JSON.stringify({
1573
+ phase: artifact.phase ?? "unknown",
1574
+ status: artifact.status,
1575
+ artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1576
+ })
996
1577
  });
997
1578
  }
998
1579
  async function emitPhaseCompletionEvent(emit, artifact) {
@@ -1020,7 +1601,15 @@ async function emitPhaseGateEvents(emit, artifact) {
1020
1601
  ? "phase_progression: implementation -> self_review"
1021
1602
  : phase === "self_review"
1022
1603
  ? "phase_progression: self_review -> validation"
1023
- : "phase_progression: validation -> QA ready";
1604
+ : phase === "debug_repro"
1605
+ ? "phase_progression: debug_repro -> debug_root_cause"
1606
+ : phase === "debug_root_cause"
1607
+ ? "phase_progression: debug_root_cause -> debug_fix"
1608
+ : phase === "debug_fix"
1609
+ ? "phase_progression: debug_fix -> debug_regression"
1610
+ : phase === "debug_regression"
1611
+ ? "phase_progression: debug_regression -> QA ready"
1612
+ : "phase_progression: validation -> QA ready";
1024
1613
  await emit({
1025
1614
  role: "hook",
1026
1615
  kind: "checkpoint",
@@ -1031,6 +1620,7 @@ async function emitPhaseGateEvents(emit, artifact) {
1031
1620
  function completionPhaseFromArtifact(artifact) {
1032
1621
  const phase = artifact.phase?.trim();
1033
1622
  return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1623
+ || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1034
1624
  ? phase
1035
1625
  : "implementation";
1036
1626
  }
@@ -1042,13 +1632,18 @@ class LiveCompletionArtifactEmitter {
1042
1632
  emitted = new Set();
1043
1633
  timer = null;
1044
1634
  pending = Promise.resolve();
1045
- constructor(worktreePath, workItemId, phase, developCycle, emit) {
1635
+ constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
1046
1636
  this.worktreePath = worktreePath;
1047
1637
  this.workItemId = workItemId;
1048
1638
  this.emit = emit;
1049
- this.phases = developCycle
1050
- ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1051
- : [phase];
1639
+ if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
1640
+ this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
1641
+ }
1642
+ else {
1643
+ this.phases = developCycle
1644
+ ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1645
+ : [phase];
1646
+ }
1052
1647
  }
1053
1648
  start() {
1054
1649
  void this.pollQueued();
@@ -1091,20 +1686,23 @@ class LiveCompletionArtifactEmitter {
1091
1686
  }
1092
1687
  }
1093
1688
  }
1094
- async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle) {
1095
- if (!developCycle) {
1689
+ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
1690
+ if (!developCycle && !debugCycle) {
1096
1691
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
1097
1692
  if (!artifact) {
1098
1693
  throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
1099
1694
  }
1100
1695
  return [artifact];
1101
1696
  }
1697
+ const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
1698
+ ? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
1699
+ : ["implementation", "self_review", "validation"];
1102
1700
  const artifacts = [];
1103
- for (const expectedPhase of ["implementation", "self_review", "validation"]) {
1701
+ for (const expectedPhase of expectedPhases) {
1104
1702
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
1105
1703
  if (!artifact) {
1106
1704
  if (artifacts.length === 0) {
1107
- throw new Error("Provider CLI completed but did not call the Forge implementation completion tool.");
1705
+ throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
1108
1706
  }
1109
1707
  const previous = artifacts[artifacts.length - 1];
1110
1708
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
@@ -1119,10 +1717,24 @@ async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, de
1119
1717
  }
1120
1718
  return artifacts;
1121
1719
  }
1122
- function providerRedactionEnv(dispatch) {
1123
- const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
1720
+ function providerProcessEnv(dispatch) {
1721
+ const env = {
1722
+ ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1723
+ ...providerCredentialEnv(dispatch)
1724
+ };
1124
1725
  return Object.keys(env).length > 0 ? env : undefined;
1125
1726
  }
1727
+ function providerCredentialEnv(dispatch) {
1728
+ const secret = dispatch.apiKeySecretGrant?.secret;
1729
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1730
+ return {};
1731
+ }
1732
+ const provider = dispatch.execution.provider.trim().toLowerCase();
1733
+ if (provider === "codex" || provider === "openai") {
1734
+ return { OPENAI_API_KEY: secret };
1735
+ }
1736
+ return {};
1737
+ }
1126
1738
  function exactRedactionSecrets(dispatch) {
1127
1739
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
1128
1740
  }
@@ -1145,7 +1757,7 @@ export class StreamingProviderProcessRunner {
1145
1757
  return await new Promise((resolve, reject) => {
1146
1758
  const child = spawn(launch.command, launch.args, {
1147
1759
  cwd: request.cwd,
1148
- env: request.env ? { ...process.env, ...request.env } : undefined,
1760
+ env: buildProviderChildEnvironment(request.env),
1149
1761
  stdio: ["ignore", "pipe", "pipe"],
1150
1762
  windowsHide: true
1151
1763
  });
@@ -1280,9 +1892,6 @@ function quoteWindowsCommandLineArg(value) {
1280
1892
  }
1281
1893
  return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
1282
1894
  }
1283
- async function fileExists(inputPath) {
1284
- return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
1285
- }
1286
1895
  async function readProcessLines(stream, onLine) {
1287
1896
  const reader = readline.createInterface({ input: stream });
1288
1897
  try {
@@ -1300,12 +1909,83 @@ function isFakeWorkerModel(model) {
1300
1909
  function sha256(content) {
1301
1910
  return crypto.createHash("sha256").update(content).digest("hex");
1302
1911
  }
1912
+ function buildDraftPrompt(dispatch) {
1913
+ const draft = dispatch.draft;
1914
+ if (!draft) {
1915
+ throw new Error("Draft prompt is missing.");
1916
+ }
1917
+ const draftArtifacts = dispatch.artifacts
1918
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
1919
+ .map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
1920
+ .join("\n\n");
1921
+ const artifactSection = draftArtifacts
1922
+ ? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
1923
+ : "";
1924
+ const projectSection = [
1925
+ draft.projectName ? `Project: ${draft.projectName}` : null,
1926
+ draft.repoName ? `Repository: ${draft.repoName}` : null
1927
+ ].filter(Boolean).join("\n");
1928
+ const scopedProjectSection = projectSection ? `\n\n# Selected project context\n\n${projectSection}` : "";
1929
+ return `${draft.systemPrompt}${scopedProjectSection}${artifactSection}
1930
+
1931
+ Draft kind: ${draft.kind}
1932
+
1933
+ ${draft.userPrompt}
1934
+
1935
+ This Draft path is a single draft-generation pass. Use the injected command/skills/hooks as planning instructions and cite their influence in the JSON content when relevant, but do not claim you used tool calls.
1936
+
1937
+ Return ONLY the requested JSON object. Do not wrap it in markdown and do not modify files.`;
1938
+ }
1939
+ function extractJsonObject(content) {
1940
+ let trimmed = content.trim();
1941
+ if (trimmed.startsWith("```")) {
1942
+ const firstNewline = trimmed.indexOf("\n");
1943
+ const lastFence = trimmed.lastIndexOf("```");
1944
+ if (firstNewline >= 0 && lastFence > firstNewline) {
1945
+ trimmed = trimmed.slice(firstNewline + 1, lastFence).trim();
1946
+ }
1947
+ }
1948
+ const start = trimmed.indexOf("{");
1949
+ const end = trimmed.lastIndexOf("}");
1950
+ return start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed;
1951
+ }
1952
+ function summarizeStderr(stderr) {
1953
+ const trimmed = stderr.trim();
1954
+ return trimmed ? `: ${clip(trimmed, 1000)}` : "";
1955
+ }
1956
+ function deterministicDraftPayload(dispatch) {
1957
+ const kind = dispatch.draft?.kind ?? "work_item";
1958
+ if (kind === "work_order") {
1959
+ return {
1960
+ title: "Deterministic runner Work Order draft",
1961
+ summary: "Forge Runner generated this deterministic Work Order draft.",
1962
+ objective: "Validate runner-backed Draft generation.",
1963
+ planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
1964
+ decompositionContext: "Use this deterministic fixture only in bridge tests.",
1965
+ assumptions: ["Forge Runner dispatch is available."],
1966
+ warnings: []
1967
+ };
1968
+ }
1969
+ if (kind === "story") {
1970
+ return {
1971
+ title: "Deterministic runner Story draft",
1972
+ description: "Forge Runner generated this deterministic Story draft.",
1973
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
1974
+ points: 3
1975
+ };
1976
+ }
1977
+ return {
1978
+ title: "Deterministic runner Work Item draft",
1979
+ description: "Forge Runner generated this deterministic Work Item draft.",
1980
+ acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
1981
+ reproSteps: "Run Draft with a Forge Runner provider selected.",
1982
+ systemInfo: "forge-bridge deterministic provider",
1983
+ points: 1
1984
+ };
1985
+ }
1303
1986
  export function formatProviderCliCommand(command) {
1304
1987
  return [command.command, ...command.args].map(singleLine).join(" ");
1305
1988
  }
1306
- function yamlQuotedScalar(value) {
1307
- return JSON.stringify(singleLine(value));
1308
- }
1309
1989
  function singleLine(value) {
1310
1990
  return value.replace(/\s+/g, " ").trim();
1311
1991
  }
@@ -1314,16 +1994,19 @@ export function buildProviderCliCommand(dispatch, run) {
1314
1994
  const normalizedProvider = provider.toLowerCase();
1315
1995
  const model = dispatch.execution.model.trim();
1316
1996
  if (normalizedProvider === "codex") {
1317
- const args = ["exec"];
1997
+ const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
1318
1998
  if (run?.completionTools) {
1319
1999
  args.push(...codexMcpConfigArgs(run.completionTools));
1320
2000
  }
1321
2001
  args.push("--model", model);
1322
2002
  if (run) {
1323
- args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
2003
+ args.push("--json");
1324
2004
  if (run.worktreePath) {
1325
2005
  args.push("--cd", run.worktreePath);
1326
2006
  }
2007
+ if (run.skipGitRepoCheck) {
2008
+ args.push("--skip-git-repo-check");
2009
+ }
1327
2010
  args.push(run.prompt ?? "");
1328
2011
  }
1329
2012
  return { command: "codex", args };
@@ -1344,6 +2027,35 @@ export function buildProviderCliCommand(dispatch, run) {
1344
2027
  }
1345
2028
  return { command: provider, args };
1346
2029
  }
2030
+ export function codexSandboxModeForPlatform(platform = process.platform) {
2031
+ return platform === "win32" ? "danger-full-access" : "workspace-write";
2032
+ }
2033
+ function buildArchitectPrompt(dispatch) {
2034
+ return `You are Forge's Architect lane running locally in a prepared git worktree.
2035
+
2036
+ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
2037
+
2038
+ Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
2039
+ 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.
2040
+ 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.
2041
+ ${architectRevisionInstruction(dispatch)}
2042
+ Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
2043
+
2044
+ ${completionPromptForPhase("architect")}
2045
+
2046
+ Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
2047
+ }
2048
+ function architectRevisionInstruction(dispatch) {
2049
+ if (!dispatch.architectRevision) {
2050
+ return "";
2051
+ }
2052
+ return `
2053
+ Architect revision context:
2054
+ - Previous plan id: ${dispatch.architectRevision.priorPlanId}
2055
+ - Previous content hash: ${dispatch.architectRevision.priorContentHash}
2056
+ - Reviewer feedback: ${dispatch.architectRevision.feedback}
2057
+ Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
2058
+ }
1347
2059
  function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
1348
2060
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
1349
2061
 
@@ -1372,6 +2084,20 @@ ${completionPromptForDevelopCycle(phase)}
1372
2084
 
1373
2085
  Finish with a concise summary of changed files and verification after the validation completion tool has accepted the work, or after the current phase tool records a non-pass blocker.`;
1374
2086
  }
2087
+ function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2088
+ return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
2089
+
2090
+ Read .forge/work-items/${dispatch.workItem.id}/spec.md, reproduce or characterize the bug, isolate root cause, apply the smallest safe fix, then prove the regression in this same provider session.
2091
+ Start in the ${phase.replace(/_/g, " ")} gate. Do not stop after a passing Debug gate; continue through the next Debug MCP instruction returned by the tool server until debug_regression is accepted or the current gate records a non-pass blocker.
2092
+ ${debugQaReworkInstruction(dispatch)}
2093
+ Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
2094
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
2095
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
2096
+
2097
+ ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
2098
+
2099
+ Finish with a concise summary of changed files and verification after the debug_regression completion tool has accepted the work, or after the current Debug gate tool records a non-pass blocker.`;
2100
+ }
1375
2101
  function qaReworkImplementationInstruction(dispatch) {
1376
2102
  if (!dispatch.qaRework) {
1377
2103
  return "";
@@ -1381,7 +2107,20 @@ QA rework context:
1381
2107
  - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
1382
2108
  - Rework packet: ${dispatch.qaRework.packetPath}
1383
2109
  - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
1384
- 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.`;
2110
+ 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.
2111
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2112
+ }
2113
+ function debugQaReworkInstruction(dispatch) {
2114
+ if (!dispatch.qaRework) {
2115
+ return "";
2116
+ }
2117
+ return `
2118
+ QA rework context for Debug:
2119
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2120
+ - Rework packet: ${dispatch.qaRework.packetPath}
2121
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2122
+ 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.
2123
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
1385
2124
  }
1386
2125
  function qaReworkRetestInstruction(dispatch) {
1387
2126
  if (!dispatch.qaRework) {
@@ -1418,6 +2157,39 @@ function qaBrowserInstruction(dispatch) {
1418
2157
  const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
1419
2158
  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`}`;
1420
2159
  }
2160
+ function storyQaInstruction(dispatch) {
2161
+ const storyQa = dispatch.storyQa;
2162
+ if (!storyQa) {
2163
+ return "";
2164
+ }
2165
+ const childLines = storyQa.childTasks.map((child) => {
2166
+ const dependencies = child.dependencyWorkItemIds.length > 0
2167
+ ? child.dependencyWorkItemIds.join(", ")
2168
+ : "none";
2169
+ const validation = child.validationArtifact
2170
+ ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2171
+ : "missing";
2172
+ const childQa = child.qaArtifact
2173
+ ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2174
+ : "not present";
2175
+ return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2176
+ }).join("\n");
2177
+ const finalQa = storyQa.finalQaChecks.length > 0
2178
+ ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2179
+ : "- No final QA checks were provided in qa.plan.final_qa.";
2180
+ return `Story QA integration context:
2181
+ - Story work item: ${storyQa.storyWorkItemId}
2182
+ - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2183
+ - Story worktree: ${storyQa.worktreeKey}
2184
+ - Branch: ${storyQa.branch}
2185
+ - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2186
+ - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2187
+ Materialized child tasks and evidence:
2188
+ ${childLines || "- No child tasks were provided."}
2189
+ Architect final QA checks:
2190
+ ${finalQa}
2191
+ 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.`;
2192
+ }
1421
2193
  function buildQaPrompt(dispatch, laneSpec) {
1422
2194
  return `You are Forge's QA lane running locally in a prepared git worktree.
1423
2195
 
@@ -1442,6 +2214,7 @@ ${dispatch.workItem.reproSteps || "Not provided."}
1442
2214
  System info / environment notes:
1443
2215
  ${dispatch.workItem.systemInfo || "Not provided."}
1444
2216
 
2217
+ ${storyQaInstruction(dispatch)}
1445
2218
  Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
1446
2219
  ${qaBrowserInstruction(dispatch)}
1447
2220
  ${qaReworkRetestInstruction(dispatch)}
@@ -1483,6 +2256,7 @@ PR context:
1483
2256
  - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
1484
2257
 
1485
2258
  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.
2259
+ After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
1486
2260
  If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
1487
2261
  Keep the original work item intent intact:
1488
2262
  - Work item: ${dispatch.workItem.id}
@@ -1551,31 +2325,31 @@ class CursorStreamJsonState {
1551
2325
  consume(line) {
1552
2326
  const event = parseJsonLine(line);
1553
2327
  if (!event) {
1554
- return null;
2328
+ return [];
1555
2329
  }
1556
2330
  const type = stringField(event, "type");
1557
2331
  if (type === "system" && stringField(event, "subtype") === "init") {
1558
2332
  this.sessionId = stringField(event, "session_id");
1559
2333
  if (this.sessionId && !this.emittedSession) {
1560
2334
  this.emittedSession = true;
1561
- return {
1562
- role: "runner",
1563
- kind: "checkpoint",
1564
- content: `Cursor session started: ${this.sessionId}.`,
1565
- eventType: "provider_thread_started"
1566
- };
2335
+ return [{
2336
+ role: "runner",
2337
+ kind: "checkpoint",
2338
+ content: `Cursor session started: ${this.sessionId}.`,
2339
+ eventType: "provider_thread_started"
2340
+ }];
1567
2341
  }
1568
2342
  }
1569
2343
  if (type === "assistant") {
1570
2344
  const text = assistantMessageText(event);
1571
2345
  if (text) {
1572
2346
  this.finalMessage = clip(text, 4000);
1573
- return {
1574
- role: "assistant",
1575
- kind: "message",
1576
- content: this.finalMessage,
1577
- eventType: "provider_message"
1578
- };
2347
+ return [{
2348
+ role: "assistant",
2349
+ kind: "message",
2350
+ content: this.finalMessage,
2351
+ eventType: "provider_message"
2352
+ }];
1579
2353
  }
1580
2354
  }
1581
2355
  if (type === "tool_call") {
@@ -1584,23 +2358,23 @@ class CursorStreamJsonState {
1584
2358
  if (subtype === "started") {
1585
2359
  const summary = formatCursorToolCallStarted(toolCall);
1586
2360
  if (summary) {
1587
- return {
1588
- role: "worker",
1589
- kind: "checkpoint",
1590
- content: summary,
1591
- eventType: "provider_tool_call"
1592
- };
2361
+ return [{
2362
+ role: "worker",
2363
+ kind: "checkpoint",
2364
+ content: summary,
2365
+ eventType: "provider_tool_call"
2366
+ }];
1593
2367
  }
1594
2368
  }
1595
2369
  if (subtype === "completed") {
1596
2370
  const completed = formatCursorToolCallCompleted(toolCall);
1597
2371
  if (completed) {
1598
- return {
1599
- role: "worker",
1600
- kind: completed.kind,
1601
- content: completed.content,
1602
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
1603
- };
2372
+ return [{
2373
+ role: "worker",
2374
+ kind: completed.kind,
2375
+ content: completed.content,
2376
+ eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2377
+ }];
1604
2378
  }
1605
2379
  }
1606
2380
  }
@@ -1612,14 +2386,14 @@ class CursorStreamJsonState {
1612
2386
  this.accumulateUsage(event);
1613
2387
  }
1614
2388
  if (type === "error" || (type === "result" && event.is_error === true)) {
1615
- return {
1616
- role: "runner",
1617
- kind: "error",
1618
- content: clip(line.trim(), 1000),
1619
- eventType: "provider_cli_error"
1620
- };
2389
+ return [{
2390
+ role: "runner",
2391
+ kind: "error",
2392
+ content: clip(line.trim(), 1000),
2393
+ eventType: "provider_cli_error"
2394
+ }];
1621
2395
  }
1622
- return null;
2396
+ return [];
1623
2397
  }
1624
2398
  accumulateUsage(event) {
1625
2399
  const usage = objectField(event, "usage");
@@ -1750,37 +2524,37 @@ class CodexJsonState {
1750
2524
  consume(line) {
1751
2525
  const event = parseJsonLine(line);
1752
2526
  if (!event) {
1753
- return null;
2527
+ return [];
1754
2528
  }
1755
2529
  const type = stringField(event, "type") ?? "";
1756
2530
  if (type === "thread.started") {
1757
2531
  this.threadId = stringField(event, "thread_id");
1758
2532
  if (this.threadId && !this.emittedThread) {
1759
2533
  this.emittedThread = true;
1760
- return {
1761
- role: "runner",
1762
- kind: "checkpoint",
1763
- content: `Codex thread started: ${this.threadId}.`,
1764
- eventType: "provider_thread_started"
1765
- };
2534
+ return [{
2535
+ role: "runner",
2536
+ kind: "checkpoint",
2537
+ content: `Codex thread started: ${this.threadId}.`,
2538
+ eventType: "provider_thread_started"
2539
+ }];
1766
2540
  }
1767
2541
  }
1768
2542
  if (type === "turn.completed") {
1769
2543
  this.accumulateUsage(event);
1770
- return {
1771
- role: "runner",
1772
- kind: "checkpoint",
1773
- content: "Codex turn completed.",
1774
- eventType: "provider_turn_completed"
1775
- };
2544
+ return [{
2545
+ role: "runner",
2546
+ kind: "checkpoint",
2547
+ content: "Codex turn completed.",
2548
+ eventType: "provider_turn_completed"
2549
+ }];
1776
2550
  }
1777
2551
  if (type === "turn.failed" || type === "error") {
1778
- return {
1779
- role: "runner",
1780
- kind: "error",
1781
- content: clip(line.trim(), 1000),
1782
- eventType: "provider_cli_error"
1783
- };
2552
+ return [{
2553
+ role: "runner",
2554
+ kind: "error",
2555
+ content: clip(line.trim(), 1000),
2556
+ eventType: "provider_cli_error"
2557
+ }];
1784
2558
  }
1785
2559
  if (type === "item.completed" || type === "item.updated") {
1786
2560
  const item = objectField(event, "item");
@@ -1789,28 +2563,32 @@ class CodexJsonState {
1789
2563
  const text = stringField(item, "text");
1790
2564
  if (text) {
1791
2565
  this.finalMessage = clip(text, 4000);
1792
- return {
1793
- role: "assistant",
1794
- kind: "message",
1795
- content: this.finalMessage,
1796
- eventType: "provider_message"
1797
- };
2566
+ return [{
2567
+ role: "assistant",
2568
+ kind: "message",
2569
+ content: this.finalMessage,
2570
+ eventType: "provider_message"
2571
+ }];
1798
2572
  }
1799
2573
  }
1800
2574
  if (itemType === "command_execution") {
1801
2575
  const command = stringField(item, "command");
1802
2576
  const status = stringField(item, "status");
1803
2577
  if (command) {
1804
- return {
1805
- role: "worker",
1806
- kind: "checkpoint",
1807
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
1808
- eventType: "provider_command"
1809
- };
2578
+ return [{
2579
+ role: "worker",
2580
+ kind: "checkpoint",
2581
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2582
+ eventType: "provider_command"
2583
+ }];
1810
2584
  }
1811
2585
  }
1812
2586
  }
1813
- return null;
2587
+ const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2588
+ if (mcpEvents.length > 0) {
2589
+ return mcpEvents;
2590
+ }
2591
+ return [];
1814
2592
  }
1815
2593
  accumulateUsage(event) {
1816
2594
  const usage = objectField(event, "usage");
@@ -1826,6 +2604,113 @@ class CodexJsonState {
1826
2604
  });
1827
2605
  }
1828
2606
  }
2607
+ function formatCodexMcpToolCallEvents(type, event) {
2608
+ if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2609
+ return [];
2610
+ }
2611
+ const item = objectField(event, "item");
2612
+ const itemType = stringField(item, "type") ?? "";
2613
+ const serverName = mcpServerName(item);
2614
+ const toolName = mcpToolName(item);
2615
+ const isMcpItem = itemType.toLowerCase().includes("mcp")
2616
+ || Boolean(serverName)
2617
+ || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2618
+ if (!isMcpItem || !toolName) {
2619
+ return [];
2620
+ }
2621
+ const status = normalizedString(stringField(item, "status")
2622
+ ?? stringField(event, "status")
2623
+ ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2624
+ const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2625
+ const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2626
+ const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2627
+ const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2628
+ const label = `${serverName ?? "unknown"}.${toolName}`;
2629
+ if (failed) {
2630
+ const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2631
+ const events = [{
2632
+ role: "tool",
2633
+ kind: "error",
2634
+ content: `MCP tool call failed: ${label} - ${summary}`,
2635
+ eventType: "provider_mcp_call_failed",
2636
+ data
2637
+ }];
2638
+ if (isForgeCompletionTool(toolName)) {
2639
+ events.push({
2640
+ role: "tool",
2641
+ kind: "error",
2642
+ content: `Forge completion tool validation failed: ${label} - ${summary}`,
2643
+ eventType: "completion_tool_validation_failed",
2644
+ data
2645
+ });
2646
+ }
2647
+ return events;
2648
+ }
2649
+ if (completed) {
2650
+ return [{
2651
+ role: "tool",
2652
+ kind: "checkpoint",
2653
+ content: `MCP tool call completed: ${label}.`,
2654
+ eventType: "provider_mcp_call_completed",
2655
+ data
2656
+ }];
2657
+ }
2658
+ if (started) {
2659
+ return [{
2660
+ role: "tool",
2661
+ kind: "checkpoint",
2662
+ content: `MCP tool call started: ${label}.`,
2663
+ eventType: "provider_mcp_call_started",
2664
+ data
2665
+ }];
2666
+ }
2667
+ return [];
2668
+ }
2669
+ function mcpServerName(item) {
2670
+ return stringField(item, "server")
2671
+ ?? stringField(item, "server_name")
2672
+ ?? stringField(item, "mcp_server")
2673
+ ?? stringField(objectField(item, "mcp"), "server")
2674
+ ?? stringField(objectField(item, "mcp"), "server_name");
2675
+ }
2676
+ function mcpToolName(item) {
2677
+ return stringField(item, "tool")
2678
+ ?? stringField(item, "tool_name")
2679
+ ?? stringField(item, "name")
2680
+ ?? stringField(objectField(item, "function"), "name")
2681
+ ?? stringField(objectField(item, "mcp"), "tool")
2682
+ ?? stringField(objectField(item, "mcp"), "tool_name");
2683
+ }
2684
+ function mcpErrorSummary(item) {
2685
+ const direct = stringField(item, "error")
2686
+ ?? stringField(item, "error_message")
2687
+ ?? stringField(item, "message");
2688
+ if (direct) {
2689
+ return clip(direct, 600);
2690
+ }
2691
+ const error = objectField(item, "error");
2692
+ return stringField(error, "message")
2693
+ ?? stringField(error, "summary")
2694
+ ?? stringField(objectField(item, "result"), "error")
2695
+ ?? null;
2696
+ }
2697
+ function safeProviderMcpData(item, serverName, toolName, status) {
2698
+ const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2699
+ return JSON.stringify(stripUndefined({
2700
+ server_name: serverName,
2701
+ tool_name: toolName,
2702
+ status,
2703
+ elapsed_ms: elapsedMs,
2704
+ error_summary: mcpErrorSummary(item)
2705
+ }));
2706
+ }
2707
+ function isForgeCompletionTool(toolName) {
2708
+ const normalized = toolName.trim().toLowerCase();
2709
+ return normalized.startsWith("forge.complete_")
2710
+ || normalized.startsWith("complete_")
2711
+ || normalized.includes("forge.complete_")
2712
+ || normalized.includes("complete_architect_plan");
2713
+ }
1829
2714
  function objectField(source, key) {
1830
2715
  const value = source[key];
1831
2716
  return value && typeof value === "object" && !Array.isArray(value)
@@ -1836,6 +2721,13 @@ function stringField(source, key) {
1836
2721
  const value = source[key];
1837
2722
  return typeof value === "string" && value.trim().length > 0 ? value : null;
1838
2723
  }
2724
+ function numericField(source, key) {
2725
+ const value = source[key];
2726
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2727
+ }
2728
+ function stripUndefined(value) {
2729
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2730
+ }
1839
2731
  function normalizedString(value) {
1840
2732
  return value.trim().toLowerCase().replace(/-/g, "_");
1841
2733
  }