@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 0.1.3-dev.fbe15023cdfe

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +78 -0
  2. package/dist/bridge/bridge.base.d.ts +6 -1
  3. package/dist/bridge/bridge.service.d.ts +60 -3
  4. package/dist/bridge/bridge.service.js +970 -24
  5. package/dist/bridge/bridge.types.d.ts +172 -1
  6. package/dist/cleanup/cleanup.service.d.ts +13 -2
  7. package/dist/cleanup/cleanup.service.js +435 -3
  8. package/dist/cleanup/cleanup.types.d.ts +10 -0
  9. package/dist/cleanup/index.d.ts +1 -1
  10. package/dist/cleanup/index.js +1 -1
  11. package/dist/cleanup/internals.d.ts +2 -2
  12. package/dist/cleanup/internals.js +1 -1
  13. package/dist/cli/cli.help.d.ts +2 -0
  14. package/dist/cli/cli.help.js +217 -0
  15. package/dist/cli/cli.service.d.ts +42 -2
  16. package/dist/cli/cli.service.js +356 -205
  17. package/dist/cli/local-config.d.ts +6 -0
  18. package/dist/cli/local-config.js +47 -3
  19. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  20. package/dist/runtime/attempt-node-runtime-launcher.js +101 -0
  21. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  22. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  23. package/dist/runtime/attempt-process-supervisor.d.ts +86 -0
  24. package/dist/runtime/attempt-process-supervisor.js +350 -0
  25. package/dist/runtime/generated-output-reset.d.ts +10 -0
  26. package/dist/runtime/generated-output-reset.js +103 -0
  27. package/dist/runtime/host-listener-inspector.d.ts +44 -0
  28. package/dist/runtime/host-listener-inspector.js +324 -0
  29. package/dist/runtime/host-port-broker.d.ts +76 -0
  30. package/dist/runtime/host-port-broker.js +333 -0
  31. package/dist/runtime/host-runtime-contract.d.ts +47 -0
  32. package/dist/runtime/host-runtime-contract.js +700 -0
  33. package/dist/runtime/host-runtime-lease.d.ts +133 -0
  34. package/dist/runtime/host-runtime-lease.js +1460 -0
  35. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  36. package/dist/runtime/host-runtime-promotion.js +159 -0
  37. package/dist/runtime/node-host-runtime-adapter.d.ts +51 -0
  38. package/dist/runtime/node-host-runtime-adapter.js +268 -0
  39. package/dist/runtime/playwright-host-runtime-adapter.d.ts +20 -0
  40. package/dist/runtime/playwright-host-runtime-adapter.js +220 -0
  41. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  42. package/dist/runtime/runtime-isolation-lease.js +158 -0
  43. package/dist/sandbox/command-runner.d.ts +4 -0
  44. package/dist/sandbox/command-runner.js +47 -0
  45. package/dist/sandbox/contract.d.ts +5 -0
  46. package/dist/sandbox/contract.js +276 -0
  47. package/dist/sandbox/event-budget.d.ts +11 -0
  48. package/dist/sandbox/event-budget.js +27 -0
  49. package/dist/sandbox/image-policy.d.ts +35 -0
  50. package/dist/sandbox/image-policy.js +247 -0
  51. package/dist/sandbox/index.d.ts +5 -0
  52. package/dist/sandbox/index.js +5 -0
  53. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  54. package/dist/sandbox/lease-watchdog.js +67 -0
  55. package/dist/sandbox/preflight.d.ts +54 -0
  56. package/dist/sandbox/preflight.js +335 -0
  57. package/dist/sandbox/process.d.ts +20 -0
  58. package/dist/sandbox/process.js +209 -0
  59. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  60. package/dist/sandbox/provider-auth/codex.js +212 -0
  61. package/dist/sandbox/repository-lock.d.ts +5 -0
  62. package/dist/sandbox/repository-lock.js +119 -0
  63. package/dist/sandbox/runtime.d.ts +297 -0
  64. package/dist/sandbox/runtime.js +2338 -0
  65. package/dist/sandbox/sandbox.types.d.ts +86 -0
  66. package/dist/sandbox/sandbox.types.js +1 -0
  67. package/dist/sandbox/smoke.d.ts +76 -0
  68. package/dist/sandbox/smoke.js +380 -0
  69. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  70. package/dist/sandbox/worker-supervisor.js +36 -0
  71. package/dist/sandbox/worker.d.ts +1 -0
  72. package/dist/sandbox/worker.js +225 -0
  73. package/dist/sandbox/workspace.service.d.ts +13 -0
  74. package/dist/sandbox/workspace.service.js +72 -0
  75. package/dist/session/managed-attempt-tools.d.ts +12 -0
  76. package/dist/session/managed-attempt-tools.js +561 -0
  77. package/dist/session/phase-completion.artifacts.d.ts +10 -0
  78. package/dist/session/phase-completion.artifacts.js +627 -0
  79. package/dist/session/phase-completion.d.ts +43 -42
  80. package/dist/session/phase-completion.helpers.d.ts +112 -0
  81. package/dist/session/phase-completion.helpers.js +684 -0
  82. package/dist/session/phase-completion.js +114 -3007
  83. package/dist/session/phase-completion.prompts.d.ts +14 -0
  84. package/dist/session/phase-completion.prompts.js +234 -0
  85. package/dist/session/phase-completion.runtime.d.ts +47 -0
  86. package/dist/session/phase-completion.runtime.js +731 -0
  87. package/dist/session/phase-completion.schemas.d.ts +3 -0
  88. package/dist/session/phase-completion.schemas.js +812 -0
  89. package/dist/session/phase-completion.validation.d.ts +37 -0
  90. package/dist/session/phase-completion.validation.js +828 -0
  91. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  92. package/dist/session/provider-cli/ci-repair-readiness.js +90 -0
  93. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +93 -0
  94. package/dist/session/provider-cli/provider-cli.artifacts.js +778 -0
  95. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  96. package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
  97. package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
  98. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
  99. package/dist/session/provider-cli/provider-cli.deterministic.js +375 -0
  100. package/dist/session/provider-cli/provider-cli.process.d.ts +48 -0
  101. package/dist/session/provider-cli/provider-cli.process.js +474 -0
  102. package/dist/session/provider-cli/provider-cli.prompts.d.ts +47 -0
  103. package/dist/session/provider-cli/provider-cli.prompts.js +595 -0
  104. package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
  105. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
  106. package/dist/session/provider-cli/provider-cli.runtime.d.ts +9 -0
  107. package/dist/session/provider-cli/provider-cli.runtime.js +41 -0
  108. package/dist/session/provider-cli/provider-cli.service.d.ts +22 -53
  109. package/dist/session/provider-cli/provider-cli.service.js +587 -2530
  110. package/dist/session/provider-cli/provider-cli.types.d.ts +6 -0
  111. package/dist/session/provider-cli/provider-output-state.d.ts +22 -0
  112. package/dist/session/provider-cli/provider-output-state.js +473 -0
  113. package/dist/session/session-redaction.d.ts +3 -0
  114. package/dist/session/session-redaction.js +23 -0
  115. package/dist/session/session.base.d.ts +6 -1
  116. package/dist/session/session.service.d.ts +8 -2
  117. package/dist/session/session.service.js +463 -58
  118. package/dist/session/session.types.d.ts +177 -1
  119. package/dist/session/session.types.js +352 -3
  120. package/dist/shared/path/path.js +3 -1
  121. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  122. package/dist/shared/process/host-process-recovery.js +78 -0
  123. package/dist/shared/process/host-process-supervisor.d.ts +57 -0
  124. package/dist/shared/process/host-process-supervisor.js +282 -0
  125. package/dist/shared/process/process.d.ts +1 -0
  126. package/dist/shared/process/process.js +1 -0
  127. package/dist/shared/process/windows-launch.d.ts +8 -0
  128. package/dist/shared/process/windows-launch.js +41 -0
  129. package/dist/shared/provider-capabilities.d.ts +1 -0
  130. package/dist/shared/provider-capabilities.js +3 -0
  131. package/dist/shared/redaction/redaction.js +10 -3
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/artifact-injector.d.ts +3 -2
  135. package/dist/worktree/artifact-injector.js +82 -10
  136. package/dist/worktree/dependency-warmer.d.ts +21 -1
  137. package/dist/worktree/dependency-warmer.js +138 -5
  138. package/dist/worktree/index.d.ts +1 -0
  139. package/dist/worktree/index.js +1 -0
  140. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  141. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  142. package/dist/worktree/worktree-paths.d.ts +4 -0
  143. package/dist/worktree/worktree-paths.js +30 -0
  144. package/dist/worktree/worktree.base.d.ts +3 -0
  145. package/dist/worktree/worktree.service.d.ts +9 -3
  146. package/dist/worktree/worktree.service.js +100 -52
  147. package/dist/worktree/worktree.types.d.ts +3 -1
  148. package/package.json +6 -3
  149. package/runtime/windows-job-supervisor.ps1 +356 -0
  150. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -1,148 +1,209 @@
1
- import crypto from "node:crypto";
2
1
  import fs from "node:fs/promises";
3
- import os from "node:os";
4
2
  import path from "node:path";
5
- import { execFile, spawn } from "node:child_process";
6
- import readline from "node:readline";
7
- import { promisify } from "node:util";
8
3
  import { GitClient } from "../../shared/git/git.js";
9
- import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
10
- import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
11
4
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.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";
13
- import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
14
- const fakeWorkerModel = "server-local-fake-worker";
15
- const execFileAsync = promisify(execFile);
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
- }
5
+ import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
6
+ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, summarizeStderr, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
7
+ import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
8
+ import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
9
+ import { StreamingProviderProcessRunner } from "./provider-cli.process.js";
10
+ import { emitProviderUsageEvent, providerProcessEnv } from "./provider-cli.runtime.js";
11
+ import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
12
+ import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
13
+ export { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
14
+ export { buildProviderCliCommand, codexSandboxModeForPlatform, formatProviderCliCommand, formatProviderCliCommandForCheckpoint } from "./provider-cli.prompts.js";
15
+ export { buildProviderChildEnvironment, chooseWindowsCommandCandidate, resolveCodexNpmDirectLaunch, resolvePackageManagerDirectLaunch, resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli.process.js";
16
+ export { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
17
+ async function pushWorktreeBranch(git, worktreePath, branchName, emit) {
18
+ try {
19
+ await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
20
+ return;
55
21
  }
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
- }
22
+ catch (err) {
23
+ if (!isNonFastForwardPushError(err)) {
24
+ throw err;
25
+ }
26
+ await emit?.({
27
+ role: "runner",
28
+ kind: "checkpoint",
29
+ content: `Remote branch ${branchName} moved before push; fetching latest and rebasing local changes.`,
30
+ eventType: "worktree_branch_push_rebase"
31
+ });
32
+ try {
33
+ await git.run(worktreePath, ["fetch", "origin", remoteTrackingRefspec(branchName)]);
34
+ await git.run(worktreePath, ["rebase", `refs/remotes/origin/${branchName}`]);
35
+ await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
36
+ }
37
+ catch (retryErr) {
38
+ throw new Error(`git push origin HEAD:${branchName} was rejected because the remote branch moved, and automatic fetch/rebase failed: ${errorMessage(retryErr)}`, { cause: retryErr });
62
39
  }
63
40
  }
64
- if (platform === "win32") {
65
- normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
66
- }
67
- return env;
68
41
  }
69
- function isAllowedProviderParentEnv(key, platform = process.platform) {
70
- return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
71
- || key.toUpperCase().startsWith("LC_")
72
- || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
42
+ function providerOwnsBranchPublication(context) {
43
+ return context.dispatch.sandbox?.executionMode !== "docker";
73
44
  }
74
- function isAllowedProviderParentEnvName(key, allowedNames) {
75
- return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
45
+ function remoteTrackingRefspec(branchName) {
46
+ return `refs/heads/${branchName}:refs/remotes/origin/${branchName}`;
76
47
  }
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)) || "\\");
48
+ function isNonFastForwardPushError(err) {
49
+ const message = errorMessage(err).toLowerCase();
50
+ return message.includes("non-fast-forward")
51
+ || message.includes("fetch first")
52
+ || message.includes("tip of your current branch is behind")
53
+ || message.includes("updates were rejected because the tip of your current branch is behind")
54
+ || message.includes("stale info");
55
+ }
56
+ function errorMessage(err) {
57
+ return err instanceof Error ? err.message : String(err);
58
+ }
59
+ const defaultProviderToolHeartbeatIntervalMs = 60_000;
60
+ const defaultManagedVerificationProgressIntervalMs = 30_000;
61
+ export class ManagedVerificationProgressEmitter {
62
+ logDirectory;
63
+ emit;
64
+ intervalMs;
65
+ timer = null;
66
+ lastSignature = null;
67
+ constructor(logDirectory, emit, intervalMs = defaultManagedVerificationProgressIntervalMs) {
68
+ this.logDirectory = logDirectory;
69
+ this.emit = emit;
70
+ this.intervalMs = intervalMs;
71
+ }
72
+ start() {
73
+ if (!this.logDirectory?.trim() || this.timer)
74
+ return;
75
+ this.timer = setInterval(() => {
76
+ void this.scan().catch(() => undefined);
77
+ }, Math.max(1, this.intervalMs));
78
+ void this.scan().catch(() => undefined);
79
+ }
80
+ async stop() {
81
+ if (this.timer) {
82
+ clearInterval(this.timer);
83
+ this.timer = null;
94
84
  }
85
+ await this.scan().catch(() => undefined);
95
86
  }
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);
87
+ async scan() {
88
+ if (!this.logDirectory?.trim())
89
+ return;
90
+ const directory = path.join(this.logDirectory, "managed-commands");
91
+ const names = await fs.readdir(directory).catch(() => []);
92
+ const snapshots = await Promise.all(names
93
+ .filter(name => name.endsWith(".receipt.json"))
94
+ .map(async (name) => parseManagedVerificationSnapshot(path.join(directory, name))));
95
+ const current = snapshots
96
+ .filter((entry) => entry !== null)
97
+ .sort((left, right) => right.elapsedMs - left.elapsedMs)[0];
98
+ if (!current)
99
+ return;
100
+ const elapsedMs = current.startedAt
101
+ ? Math.max(current.elapsedMs ?? 0, Date.now() - Date.parse(current.startedAt))
102
+ : current.elapsedMs;
103
+ const progressBucket = elapsedMs === null ? "none" : Math.floor(elapsedMs / this.intervalMs);
104
+ const signature = `${current.commandId}:${current.status}:${current.outputRevision ?? "none"}:${progressBucket}`;
105
+ if (signature === this.lastSignature)
106
+ return;
107
+ const firstObservation = this.lastSignature === null;
108
+ this.lastSignature = signature;
109
+ const terminal = ["pass", "fail", "timed_out", "timeout_termination_failed", "runner_error"].includes(current.status);
110
+ const elapsed = elapsedMs === null ? "an unknown duration" : formatElapsed(elapsedMs);
111
+ const outputTail = current.stderrTail || current.stdoutTail;
112
+ await this.emit({
113
+ role: "runner",
114
+ kind: terminal && current.status !== "pass" ? "error" : "status",
115
+ content: terminal
116
+ ? `Managed verification ${current.status} after ${elapsed}${outputTail ? `: ${clip(outputTail, 600)}` : "."}`
117
+ : firstObservation
118
+ ? `QA is waiting on managed verification ${current.commandId}; Forge will keep supervising it while the provider waits.`
119
+ : `Managed verification is still running after ${elapsed}${outputTail ? `: ${clip(outputTail, 600)}` : "."}`,
120
+ eventType: terminal ? "verification_completed" : firstObservation ? "verification_waiting" : "verification_progress",
121
+ data: JSON.stringify({
122
+ command_id: current.commandId,
123
+ status: current.status,
124
+ elapsed_ms: elapsedMs,
125
+ output_revision: current.outputRevision,
126
+ last_output_at: current.lastOutputAt,
127
+ }),
128
+ });
129
+ }
130
+ }
131
+ async function parseManagedVerificationSnapshot(receiptPath) {
132
+ try {
133
+ const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
134
+ const commandId = typeof receipt.command_id === "string" ? receipt.command_id : null;
135
+ const status = typeof receipt.status === "string" ? receipt.status : null;
136
+ if (!commandId || !status)
137
+ return null;
138
+ return {
139
+ commandId,
140
+ status,
141
+ elapsedMs: typeof receipt.elapsed_ms === "number" ? receipt.elapsed_ms : null,
142
+ startedAt: typeof receipt.started_at === "string" ? receipt.started_at : null,
143
+ outputRevision: typeof receipt.output_revision === "number" ? receipt.output_revision : null,
144
+ lastOutputAt: typeof receipt.last_output_at === "string" ? receipt.last_output_at : null,
145
+ stdoutTail: tail(typeof receipt.stdout === "string" ? receipt.stdout : ""),
146
+ stderrTail: tail(typeof receipt.stderr === "string" ? receipt.stderr : ""),
147
+ };
104
148
  }
105
- if (localAppData) {
106
- setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
107
- setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
149
+ catch {
150
+ return null;
108
151
  }
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
152
  }
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;
153
+ function tail(value) {
154
+ return value.trim().split(/\r?\n/u).slice(-4).join("\n");
155
+ }
156
+ function formatElapsed(milliseconds) {
157
+ const seconds = Math.max(0, Math.round(milliseconds / 1000));
158
+ const minutes = Math.floor(seconds / 60);
159
+ return minutes > 0 ? `${minutes}m ${seconds % 60}s` : `${seconds}s`;
160
+ }
161
+ class ProviderToolActivityHeartbeat {
162
+ outputState;
163
+ emit;
164
+ intervalMs;
165
+ timer = null;
166
+ constructor(outputState, emit, intervalMs) {
167
+ this.outputState = outputState;
168
+ this.emit = emit;
169
+ this.intervalMs = intervalMs;
122
170
  }
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}`;
171
+ async consume(line) {
172
+ const events = this.outputState.consume(line);
173
+ this.sync();
174
+ for (const event of events) {
175
+ await this.emit(event);
176
+ }
127
177
  }
128
- if (homeDir && path.win32.isAbsolute(homeDir)) {
129
- return homeDir;
178
+ stop() {
179
+ if (this.timer) {
180
+ clearInterval(this.timer);
181
+ this.timer = null;
182
+ }
130
183
  }
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;
184
+ sync() {
185
+ if (!this.outputState.hasActiveToolCall) {
186
+ this.stop();
187
+ return;
188
+ }
189
+ if (this.timer) {
190
+ return;
191
+ }
192
+ this.timer = setInterval(() => {
193
+ if (!this.outputState.hasActiveToolCall) {
194
+ this.stop();
195
+ return;
196
+ }
197
+ void this.emit({
198
+ role: "runner",
199
+ kind: "status",
200
+ content: "A supervised provider tool is still running.",
201
+ eventType: "provider_tool_heartbeat",
202
+ }).catch(() => undefined);
203
+ }, Math.max(1, this.intervalMs));
143
204
  }
144
- env[name] = value;
145
205
  }
206
+ const fakeWorkerModel = "server-local-fake-worker";
146
207
  export class RoutingProviderCliService {
147
208
  realProvider;
148
209
  deterministicProvider;
@@ -160,6 +221,11 @@ export class RoutingProviderCliService {
160
221
  ? await this.deterministicProvider.runArchitect(context)
161
222
  : await this.realProvider.runArchitect(context);
162
223
  }
224
+ async runCiRepair(context) {
225
+ return isFakeWorkerModel(context.dispatch.execution.model)
226
+ ? await this.deterministicProvider.runCiRepair(context)
227
+ : await this.realProvider.runCiRepair(context);
228
+ }
163
229
  async runConflictResolve(context) {
164
230
  return isFakeWorkerModel(context.dispatch.execution.model)
165
231
  ? await this.deterministicProvider.runConflictResolve(context)
@@ -179,33 +245,36 @@ export class RoutingProviderCliService {
179
245
  export class ProcessBackedProviderCliService {
180
246
  processRunner;
181
247
  git;
182
- constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient()) {
248
+ providerToolHeartbeatIntervalMs;
249
+ constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs) {
183
250
  this.processRunner = processRunner;
184
251
  this.git = git;
252
+ this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
185
253
  }
186
254
  async runDraft(context) {
187
255
  const { dispatch } = context;
188
256
  if (!dispatch.draft) {
189
257
  throw new Error("Draft dispatch context is missing.");
190
258
  }
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);
259
+ const { worktree } = context;
260
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
200
261
  await fs.mkdir(metadataRoot, { recursive: true });
201
- await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(dispatch.draft, null, 2) + "\n", "utf8");
262
+ await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(durableDraftInput(dispatch), null, 2) + "\n", "utf8");
202
263
  await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
203
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree: draftWorktree, phase: "draft" });
264
+ const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
265
+ const decomposeDraft = isDecomposeDraftDispatch(dispatch);
266
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment });
267
+ const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
268
+ const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
269
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
204
270
  const command = buildProviderCliCommand(dispatch, {
205
- worktreePath: tempDir,
206
- prompt: buildDraftPrompt(dispatch),
271
+ worktreePath: worktree.worktreePath,
272
+ prompt: draftPrompt,
273
+ promptFromStdin: pipePromptToStdin,
207
274
  completionTools: completionTools ?? undefined,
208
- skipGitRepoCheck: true
275
+ skipGitRepoCheck: false,
276
+ imagePaths: stagedAttachments.imagePaths,
277
+ runtimeEnvironment: context.runtimeEnvironment
209
278
  });
210
279
  const draftArtifactSlugs = dispatch.artifacts
211
280
  .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
@@ -219,16 +288,19 @@ export class ProcessBackedProviderCliService {
219
288
  await context.emit({
220
289
  role: "runner",
221
290
  kind: "checkpoint",
222
- content: `Starting provider CLI Draft: ${formatProviderCliCommand(command)}`,
223
- eventType: "provider_cli_started"
291
+ content: `Starting provider CLI Draft: ${formatProviderCliCommandForCheckpoint(command)}`,
292
+ eventType: "provider_cli_starting"
224
293
  });
225
294
  await context.emit({
226
295
  role: "runner",
227
296
  kind: "checkpoint",
228
- 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.",
297
+ content: decomposeDraft
298
+ ? "Forge Decompose completion tools configured for decompose_subject_intake -> decompose_context_review -> decompose_breakdown_strategy -> decompose_child_items -> decompose_dependency_graph -> decompose_critic -> decompose_proposal; provider must call each MCP completion tool before exit."
299
+ : "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.",
229
300
  eventType: "completion_tools_configured"
230
301
  });
231
302
  const outputState = createProviderOutputState(dispatch.execution.provider);
303
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
232
304
  try {
233
305
  const providerCancellation = new AbortController();
234
306
  const abortProvider = () => providerCancellation.abort();
@@ -238,69 +310,121 @@ export class ProcessBackedProviderCliService {
238
310
  else {
239
311
  context.signal?.addEventListener("abort", abortProvider, { once: true });
240
312
  }
241
- const runPromise = this.processRunner.run({
242
- command: command.command,
243
- args: command.args,
244
- cwd: tempDir,
245
- env: providerProcessEnv(dispatch)
246
- }, {
247
- onStdoutLine: async (line) => {
248
- for (const event of outputState.consume(line)) {
249
- await context.emit(event);
313
+ try {
314
+ const runPromise = (context.processRunner ?? this.processRunner).run({
315
+ command: command.command,
316
+ args: command.args,
317
+ cwd: worktree.worktreePath,
318
+ env: providerProcessEnv(dispatch, context.runtimeEnvironment),
319
+ stdin: pipePromptToStdin ? providerPrompt : undefined
320
+ }, {
321
+ onStarted: async () => {
322
+ await context.emit({
323
+ role: "runner",
324
+ kind: "checkpoint",
325
+ content: "Provider CLI Draft is supervised and ready.",
326
+ eventType: "provider_cli_started"
327
+ });
328
+ },
329
+ onStdoutLine: async (line) => {
330
+ await toolHeartbeat.consume(line);
250
331
  }
332
+ }, providerCancellation.signal);
333
+ const artifactWaitCancellation = new AbortController();
334
+ const abortArtifactWait = () => artifactWaitCancellation.abort();
335
+ if (context.signal?.aborted) {
336
+ abortArtifactWait();
251
337
  }
252
- }, providerCancellation.signal);
253
- let result;
254
- let earlyProposalArtifact = null;
255
- const terminal = await Promise.race([
256
- runPromise.then(value => ({ kind: "process", value })),
257
- waitForDraftProposalArtifact(tempDir, dispatch.workItem.id, context.signal).then(value => ({ kind: "artifact", value }))
258
- ]);
259
- if (terminal.kind === "artifact") {
260
- earlyProposalArtifact = terminal.value;
261
- providerCancellation.abort();
262
- result = await runPromise.catch(() => ({ exitCode: 0, stdout: "", stderr: "" }));
263
- }
264
- else {
265
- result = terminal.value;
266
- }
267
- context.signal?.removeEventListener("abort", abortProvider);
268
- if (result.exitCode !== 0 && !earlyProposalArtifact) {
269
- throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
270
- }
271
- await context.emit({
272
- role: "runner",
273
- kind: "checkpoint",
274
- content: `Provider CLI Draft completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
275
- eventType: "provider_cli_completed"
276
- });
277
- await emitProviderUsageEvent(context.emit, dispatch, outputState);
278
- await emitDraftGateArtifacts(context.emit, tempDir, dispatch.workItem.id);
279
- const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(tempDir, dispatch.workItem.id, "draft");
280
- if (!proposalArtifact) {
281
- throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
282
- }
283
- const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
284
- const draftJson = proposal["draft_json"];
285
- if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
286
- throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
338
+ else {
339
+ context.signal?.addEventListener("abort", abortArtifactWait, { once: true });
340
+ }
341
+ const artifactWaitPromise = waitForCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, decomposeDraft ? "decompose" : "draft", artifactWaitCancellation.signal);
342
+ let result;
343
+ let earlyProposalArtifact = null;
344
+ try {
345
+ const terminal = await Promise.race([
346
+ runPromise.then(value => ({ kind: "process", value })),
347
+ artifactWaitPromise.then(value => ({ kind: "artifact", value }))
348
+ ]);
349
+ artifactWaitCancellation.abort();
350
+ await artifactWaitPromise.catch(() => undefined);
351
+ if (terminal.kind === "artifact") {
352
+ earlyProposalArtifact = terminal.value;
353
+ providerCancellation.abort();
354
+ result = await runPromise.catch(() => ({ exitCode: 0, stdout: "", stderr: "" }));
355
+ }
356
+ else {
357
+ result = terminal.value;
358
+ }
359
+ }
360
+ finally {
361
+ artifactWaitCancellation.abort();
362
+ context.signal?.removeEventListener("abort", abortArtifactWait);
363
+ }
364
+ if (result.exitCode !== 0 && !earlyProposalArtifact) {
365
+ throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
366
+ }
367
+ await context.emit({
368
+ role: "runner",
369
+ kind: "checkpoint",
370
+ content: `Provider CLI Draft completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
371
+ eventType: "provider_cli_completed"
372
+ });
373
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
374
+ if (decomposeDraft) {
375
+ await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
376
+ const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
377
+ if (!proposalArtifact) {
378
+ throw new Error("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.");
379
+ }
380
+ const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
381
+ const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
382
+ if (!proposalJson || typeof proposalJson !== "object" || Array.isArray(proposalJson)) {
383
+ throw new Error("Provider CLI Decompose completed but decompose.proposal.json did not contain proposal_json.");
384
+ }
385
+ const json = JSON.stringify(proposalJson);
386
+ await context.emit({
387
+ role: "assistant",
388
+ kind: "message",
389
+ content: json,
390
+ eventType: "decompose_proposal"
391
+ });
392
+ return {
393
+ summary: "Decomposition proposal generated through Forge Decompose completion cycle.",
394
+ artifact: proposalArtifact,
395
+ artifacts: [proposalArtifact]
396
+ };
397
+ }
398
+ await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
399
+ const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
400
+ if (!proposalArtifact) {
401
+ throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
402
+ }
403
+ const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
404
+ const draftJson = proposal["draft_json"];
405
+ if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
406
+ throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
407
+ }
408
+ const json = JSON.stringify(draftJson);
409
+ await context.emit({
410
+ role: "assistant",
411
+ kind: "message",
412
+ content: json,
413
+ eventType: "draft_complete"
414
+ });
415
+ return {
416
+ summary: "Draft generated through Forge Draft completion cycle.",
417
+ artifact: proposalArtifact,
418
+ artifacts: [proposalArtifact]
419
+ };
420
+ }
421
+ finally {
422
+ context.signal?.removeEventListener("abort", abortProvider);
287
423
  }
288
- const json = JSON.stringify(draftJson);
289
- await context.emit({
290
- role: "assistant",
291
- kind: "message",
292
- content: json,
293
- eventType: "draft_complete"
294
- });
295
- return {
296
- summary: "Draft generated through Forge Draft completion cycle.",
297
- artifact: proposalArtifact,
298
- artifacts: [proposalArtifact]
299
- };
300
424
  }
301
425
  finally {
426
+ toolHeartbeat.stop();
302
427
  await cleanupCompletionTools(completionTools, context.emit);
303
- await fs.rm(tempDir, { recursive: true, force: true });
304
428
  }
305
429
  }
306
430
  async runImplementation(context) {
@@ -318,21 +442,26 @@ export class ProcessBackedProviderCliService {
318
442
  const specPath = path.join(metadataRoot, "spec.md");
319
443
  await fs.writeFile(specPath, specBody, "utf8");
320
444
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
321
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
445
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment });
446
+ const implementationPrompt = debugCycle
447
+ ? buildDebugCyclePrompt(dispatch, phase)
448
+ : developCycle
449
+ ? buildDevelopCyclePrompt(dispatch, phase)
450
+ : buildImplementationPrompt(dispatch, phase);
451
+ const providerPrompt = buildProviderCliPrompt(dispatch, implementationPrompt, context.runtimeEnvironment);
452
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
322
453
  const command = buildProviderCliCommand(dispatch, {
323
454
  worktreePath: worktree.worktreePath,
324
- prompt: debugCycle
325
- ? buildDebugCyclePrompt(dispatch, phase)
326
- : developCycle
327
- ? buildDevelopCyclePrompt(dispatch, phase)
328
- : buildImplementationPrompt(dispatch, phase),
329
- completionTools
455
+ prompt: implementationPrompt,
456
+ promptFromStdin: pipePromptToStdin,
457
+ completionTools,
458
+ runtimeEnvironment: context.runtimeEnvironment
330
459
  });
331
460
  await context.emit({
332
461
  role: "runner",
333
462
  kind: "checkpoint",
334
- content: `Starting provider CLI: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
335
- eventType: "provider_cli_started"
463
+ content: `Starting provider CLI: ${formatProviderCliCommandForCheckpoint(command)} in ${worktree.worktreePath}`,
464
+ eventType: "provider_cli_starting"
336
465
  });
337
466
  await context.emit({
338
467
  role: "runner",
@@ -345,24 +474,33 @@ export class ProcessBackedProviderCliService {
345
474
  eventType: "completion_tools_configured"
346
475
  });
347
476
  const outputState = createProviderOutputState(dispatch.execution.provider);
477
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
348
478
  const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
349
479
  let result;
350
480
  try {
351
481
  liveCompletionEvents.start();
352
- result = await this.processRunner.run({
482
+ result = await (context.processRunner ?? this.processRunner).run({
353
483
  command: command.command,
354
484
  args: command.args,
355
485
  cwd: worktree.worktreePath,
356
- env: providerProcessEnv(dispatch)
486
+ env: providerProcessEnv(dispatch, context.runtimeEnvironment),
487
+ stdin: pipePromptToStdin ? providerPrompt : undefined
357
488
  }, {
489
+ onStarted: async () => {
490
+ await context.emit({
491
+ role: "runner",
492
+ kind: "checkpoint",
493
+ content: "Provider CLI is supervised and ready.",
494
+ eventType: "provider_cli_started"
495
+ });
496
+ },
358
497
  onStdoutLine: async (line) => {
359
- for (const event of outputState.consume(line)) {
360
- await context.emit(event);
361
- }
498
+ await toolHeartbeat.consume(line);
362
499
  }
363
500
  }, context.signal);
364
501
  }
365
502
  finally {
503
+ toolHeartbeat.stop();
366
504
  await liveCompletionEvents.stop();
367
505
  await cleanupCompletionTools(completionTools, context.emit);
368
506
  }
@@ -378,8 +516,8 @@ export class ProcessBackedProviderCliService {
378
516
  });
379
517
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
380
518
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
381
- if (developCycle || debugCycle || phase === "implementation") {
382
- await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
519
+ if ((developCycle || debugCycle || phase === "implementation") && providerOwnsBranchPublication(context)) {
520
+ await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, context.emit);
383
521
  await context.emit({
384
522
  role: "runner",
385
523
  kind: "checkpoint",
@@ -437,18 +575,23 @@ export class ProcessBackedProviderCliService {
437
575
  const specPath = path.join(metadataRoot, "spec.md");
438
576
  await fs.writeFile(specPath, specBody, "utf8");
439
577
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-lane-command" }) + "\n", "utf8");
440
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
578
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment });
579
+ const architectPrompt = buildArchitectPrompt(dispatch);
580
+ const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
581
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
441
582
  const command = buildProviderCliCommand(dispatch, {
442
583
  worktreePath: worktree.worktreePath,
443
- prompt: buildArchitectPrompt(dispatch),
444
- completionTools
584
+ prompt: architectPrompt,
585
+ promptFromStdin: pipePromptToStdin,
586
+ completionTools,
587
+ runtimeEnvironment: context.runtimeEnvironment
445
588
  });
446
- const commandText = formatProviderCliCommand(command);
589
+ const commandText = formatProviderCliCommandForCheckpoint(command);
447
590
  await context.emit({
448
591
  role: "runner",
449
592
  kind: "checkpoint",
450
593
  content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
451
- eventType: "provider_cli_started"
594
+ eventType: "provider_cli_starting"
452
595
  });
453
596
  await context.emit({
454
597
  role: "runner",
@@ -457,24 +600,31 @@ export class ProcessBackedProviderCliService {
457
600
  eventType: "completion_tools_configured"
458
601
  });
459
602
  const outputState = createProviderOutputState(dispatch.execution.provider);
603
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
460
604
  const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
461
605
  let result;
462
606
  try {
463
607
  liveArchitectEvents.start();
464
- result = await this.processRunner.run({
608
+ result = await (context.processRunner ?? this.processRunner).run({
465
609
  command: command.command,
466
610
  args: command.args,
467
611
  cwd: worktree.worktreePath,
468
- env: providerProcessEnv(dispatch)
612
+ env: providerProcessEnv(dispatch, context.runtimeEnvironment),
613
+ stdin: pipePromptToStdin ? providerPrompt : undefined
469
614
  }, {
470
- onStdoutLine: async (line) => {
471
- for (const event of outputState.consume(line)) {
472
- await context.emit(event);
473
- }
474
- }
615
+ onStarted: async () => {
616
+ await context.emit({
617
+ role: "runner",
618
+ kind: "checkpoint",
619
+ content: "Provider CLI Architect is supervised and ready.",
620
+ eventType: "provider_cli_started"
621
+ });
622
+ },
623
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line)
475
624
  }, context.signal);
476
625
  }
477
626
  finally {
627
+ toolHeartbeat.stop();
478
628
  await liveArchitectEvents.stop();
479
629
  await cleanupCompletionTools(completionTools, context.emit);
480
630
  }
@@ -528,18 +678,23 @@ export class ProcessBackedProviderCliService {
528
678
  const specPath = path.join(metadataRoot, "spec.md");
529
679
  await fs.writeFile(specPath, specBody, "utf8");
530
680
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
531
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
681
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment });
682
+ const qaPrompt = buildQaPrompt(dispatch, specBody);
683
+ const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
684
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
532
685
  const command = buildProviderCliCommand(dispatch, {
533
686
  worktreePath: worktree.worktreePath,
534
- prompt: buildQaPrompt(dispatch, specBody),
535
- completionTools
687
+ prompt: qaPrompt,
688
+ promptFromStdin: pipePromptToStdin,
689
+ completionTools,
690
+ runtimeEnvironment: context.runtimeEnvironment
536
691
  });
537
- const commandText = formatProviderCliCommand(command);
692
+ const commandText = formatProviderCliCommandForCheckpoint(command);
538
693
  await context.emit({
539
694
  role: "runner",
540
695
  kind: "checkpoint",
541
696
  content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
542
- eventType: "provider_cli_started"
697
+ eventType: "provider_cli_starting"
543
698
  });
544
699
  await context.emit({
545
700
  role: "runner",
@@ -548,24 +703,34 @@ export class ProcessBackedProviderCliService {
548
703
  eventType: "completion_tools_configured"
549
704
  });
550
705
  const outputState = createProviderOutputState(dispatch.execution.provider);
706
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
707
+ const verificationProgress = new ManagedVerificationProgressEmitter(context.runtimeEnvironment?.FORGE_LOG_DIR, context.emit);
551
708
  const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
552
709
  let result;
553
710
  try {
554
711
  liveQaEvents.start();
555
- result = await this.processRunner.run({
712
+ verificationProgress.start();
713
+ result = await (context.processRunner ?? this.processRunner).run({
556
714
  command: command.command,
557
715
  args: command.args,
558
716
  cwd: worktree.worktreePath,
559
- env: providerProcessEnv(dispatch)
717
+ env: providerProcessEnv(dispatch, context.runtimeEnvironment),
718
+ stdin: pipePromptToStdin ? providerPrompt : undefined
560
719
  }, {
561
- onStdoutLine: async (line) => {
562
- for (const event of outputState.consume(line)) {
563
- await context.emit(event);
564
- }
565
- }
720
+ onStarted: async () => {
721
+ await context.emit({
722
+ role: "runner",
723
+ kind: "checkpoint",
724
+ content: "Provider CLI QA is supervised and ready.",
725
+ eventType: "provider_cli_started"
726
+ });
727
+ },
728
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line)
566
729
  }, context.signal);
567
730
  }
568
731
  finally {
732
+ toolHeartbeat.stop();
733
+ await verificationProgress.stop();
569
734
  await liveQaEvents.stop();
570
735
  await cleanupCompletionTools(completionTools, context.emit);
571
736
  }
@@ -587,7 +752,7 @@ export class ProcessBackedProviderCliService {
587
752
  ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
588
753
  : "Provider CLI QA completed but did not call the Forge QA completion tool.");
589
754
  }
590
- enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
755
+ await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
591
756
  if (!liveQaEvents.hasEmitted()) {
592
757
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
593
758
  await emitQaStructuredEvents(context.emit, qaArtifact);
@@ -611,2324 +776,216 @@ export class ProcessBackedProviderCliService {
611
776
  artifacts: [qaArtifact]
612
777
  };
613
778
  }
779
+ async runCiRepair(context) {
780
+ return await this.runPullRequestRepair(context, "ci_repair");
781
+ }
614
782
  async runConflictResolve(context) {
783
+ return await this.runPullRequestRepair(context, "conflict_resolve");
784
+ }
785
+ async runPullRequestRepair(context, route) {
615
786
  const { dispatch, worktree } = context;
616
- const addressComments = isPullRequestCommentsDispatch(dispatch);
787
+ const repairChecks = route === "ci_repair" || isPullRequestCheckRepairDispatch(dispatch);
788
+ const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
789
+ let repairSpec = null;
790
+ let repairEnvironment = context.runtimeEnvironment;
791
+ let completionTools = null;
792
+ if (repairChecks) {
793
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
794
+ await fs.mkdir(metadataRoot, { recursive: true });
795
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
796
+ if (!laneCommand) {
797
+ throw new Error(`CI repair readiness failed: lane command for '${dispatch.execution.lane}' was not resolved, so the approved spec cannot be materialized.`);
798
+ }
799
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
800
+ const specPath = path.join(metadataRoot, "spec.md");
801
+ await fs.writeFile(specPath, specBody, "utf8");
802
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
803
+ repairSpec = {
804
+ repoPath: worktree.worktreePath,
805
+ path: specPath,
806
+ body: specBody,
807
+ producedBy: "forge-lane-command",
808
+ status: "approved",
809
+ };
810
+ const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
811
+ repairEnvironment = readiness.environment;
812
+ completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment });
813
+ await context.emit({
814
+ role: "runner",
815
+ kind: "checkpoint",
816
+ content: `CI repair readiness contract prepared at ${path.relative(worktree.worktreePath, readiness.path).replaceAll(path.sep, "/")}; approved spec, attempt URLs, browser readiness, and local-equivalence policy are available before provider start.`,
817
+ eventType: "ci_repair_readiness_ready",
818
+ });
819
+ await context.emit({
820
+ role: "runner",
821
+ kind: "checkpoint",
822
+ content: "Forge CI repair completion tool configured; provider must call forge.complete_ci_repair before Bridge-owned commit and push.",
823
+ eventType: "completion_tools_configured",
824
+ });
825
+ }
826
+ const repairPrompt = repairChecks
827
+ ? buildPullRequestCheckRepairPrompt(dispatch, worktree.branchName)
828
+ : addressComments
829
+ ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
830
+ : buildConflictResolvePrompt(dispatch, worktree.branchName);
831
+ const providerPrompt = buildProviderCliPrompt(dispatch, repairPrompt, repairEnvironment);
832
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
617
833
  const command = buildProviderCliCommand(dispatch, {
618
834
  worktreePath: worktree.worktreePath,
619
- prompt: addressComments
620
- ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
621
- : buildConflictResolvePrompt(dispatch, worktree.branchName)
835
+ prompt: repairPrompt,
836
+ promptFromStdin: pipePromptToStdin,
837
+ completionTools: completionTools ?? undefined,
838
+ runtimeEnvironment: repairEnvironment
622
839
  });
623
840
  await context.emit({
624
841
  role: "runner",
625
842
  kind: "checkpoint",
626
- content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
627
- eventType: "provider_cli_started"
843
+ content: `Starting provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommandForCheckpoint(command)} in ${worktree.worktreePath}`,
844
+ eventType: "provider_cli_starting"
628
845
  });
629
846
  const outputState = createProviderOutputState(dispatch.execution.provider);
630
- const result = await this.processRunner.run({
631
- command: command.command,
632
- args: command.args,
633
- cwd: worktree.worktreePath,
634
- env: providerProcessEnv(dispatch)
635
- }, {
636
- onStdoutLine: async (line) => {
637
- for (const event of outputState.consume(line)) {
638
- await context.emit(event);
847
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
848
+ let result;
849
+ try {
850
+ result = await (context.processRunner ?? this.processRunner).run({
851
+ command: command.command,
852
+ args: command.args,
853
+ cwd: worktree.worktreePath,
854
+ env: providerProcessEnv(dispatch, repairEnvironment),
855
+ stdin: pipePromptToStdin ? providerPrompt : undefined
856
+ }, {
857
+ onStarted: async () => {
858
+ await context.emit({
859
+ role: "runner",
860
+ kind: "checkpoint",
861
+ content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} is supervised and ready.`,
862
+ eventType: "provider_cli_started"
863
+ });
864
+ },
865
+ onStdoutLine: async (line) => {
866
+ await toolHeartbeat.consume(line);
639
867
  }
868
+ }, context.signal);
869
+ }
870
+ finally {
871
+ toolHeartbeat.stop();
872
+ if (completionTools) {
873
+ await cleanupCompletionTools(completionTools, context.emit);
640
874
  }
641
- }, context.signal);
875
+ }
642
876
  if (result.exitCode !== 0) {
643
877
  const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
644
878
  throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
645
879
  }
646
- const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
647
- await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
648
- await emitProviderUsageEvent(context.emit, dispatch, outputState);
649
- await context.emit({
650
- role: "assistant",
651
- kind: "message",
652
- content: outputState.finalMessage || (addressComments
653
- ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
654
- : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
655
- eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
656
- });
657
- return {
658
- summary: addressComments
659
- ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
660
- : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
661
- };
662
- }
663
- }
664
- export class DeterministicProviderCliService {
665
- git;
666
- constructor(git = new GitClient()) {
667
- this.git = git;
668
- }
669
- async runDraft(context) {
670
- const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
671
- await context.emit({
672
- role: "assistant",
673
- kind: "message",
674
- content,
675
- eventType: "draft_complete"
676
- });
677
- await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
678
- return { summary: "forge-bridge generated deterministic draft." };
679
- }
680
- async runImplementation(context) {
681
- const { dispatch, worktree } = context;
682
- const phase = completionPhaseFromDispatch(dispatch);
683
- const developCycle = usesDevelopCycleCompletion(dispatch);
684
- const debugCycle = usesDebugCycleCompletion(dispatch);
685
- const providerCommand = buildProviderCliCommand(dispatch);
686
- const providerCommandText = formatProviderCliCommand(providerCommand);
687
- const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
688
- const artifactRoot = path.join(metadataRoot, "artifacts");
689
- await fs.mkdir(artifactRoot, { recursive: true });
690
- const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
691
- if (!laneCommand) {
692
- throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
693
- }
694
- const specBody = `${buildSpecBody(laneCommand, dispatch.workItem, phase)}
695
- ## Execution
696
-
697
- - Provider: ${singleLine(dispatch.execution.provider)}
698
- - Model: ${singleLine(dispatch.execution.model)}
699
- - Command: ${providerCommandText}
700
- `;
701
- const specPath = path.join(metadataRoot, "spec.md");
702
- await fs.writeFile(specPath, specBody, "utf8");
703
- await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
704
- const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
705
- const changesetBody = `# Forge Phase 5 bridge changeset\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\nBranch: ${worktree.branchName}\nProvider: ${singleLine(dispatch.execution.provider)}\nModel: ${singleLine(dispatch.execution.model)}\nCommand: ${providerCommandText}\n\nThis deterministic file is written by forge-bridge run-once through the shared session/worktree service path.\n`;
706
- await fs.writeFile(changesetPath, changesetBody, "utf8");
707
- await this.git.run(worktree.worktreePath, ["add", "FORGE_PHASE5_CHANGESET.md"]);
708
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge changeset for ${dispatch.workItem.id.slice(0, 8)}`]);
709
- await context.emit({
710
- role: "worker",
711
- kind: "file_edit",
712
- content: `Created bridge changeset at ${changesetPath}`,
713
- eventType: "changeset"
714
- });
715
- const phases = debugCycle
716
- ? debugCompletionPhaseOrder
717
- : developCycle
718
- ? ["implementation", "self_review", "validation"]
719
- : [phase];
720
- const completionArtifacts = [];
721
- for (const completionPhase of phases) {
722
- await writeCompletionArtifact({
723
- worktreePath: worktree.worktreePath,
724
- workItemId: dispatch.workItem.id,
725
- phase: completionPhase,
726
- producedBy: "forge-bridge",
727
- redactionSecrets: exactRedactionSecrets(dispatch)
728
- }, isDebugCompletionPhaseForProvider(completionPhase)
729
- ? expectedDebugCompletionToolName(completionPhase)
730
- : expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
731
- const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
732
- if (!completionArtifact) {
733
- throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
880
+ let repairArtifact = null;
881
+ if (repairChecks) {
882
+ repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
883
+ if (!repairArtifact) {
884
+ throw new Error("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.");
734
885
  }
735
- completionArtifacts.push(completionArtifact);
736
- await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
737
- await context.emit({
738
- role: "assistant",
739
- kind: "message",
740
- content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
741
- eventType: phaseCompleteEventType(completionPhase)
742
- });
743
- }
744
- await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
745
- return {
746
- summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
747
- spec: {
748
- repoPath: worktree.worktreePath,
749
- path: specPath,
750
- body: specBody,
751
- producedBy: "forge-lane-command",
752
- status: "approved"
753
- },
754
- artifact: completionArtifacts[0],
755
- artifacts: completionArtifacts
756
- };
757
- }
758
- async runArchitect(context) {
759
- const { dispatch, worktree } = context;
760
- const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
761
- await fs.mkdir(metadataRoot, { recursive: true });
762
- 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`;
763
- const specPath = path.join(metadataRoot, "spec.md");
764
- await fs.writeFile(specPath, specBody, "utf8");
765
- await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
766
- await writeCompletionArtifact({
767
- worktreePath: worktree.worktreePath,
768
- workItemId: dispatch.workItem.id,
769
- phase: "architect",
770
- producedBy: "forge-bridge",
771
- redactionSecrets: exactRedactionSecrets(dispatch),
772
- architectCycle: true
773
- }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
774
- const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
775
- if (!artifact) {
776
- throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
777
- }
778
- await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
779
- await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
780
- await context.emit({
781
- role: "assistant",
782
- kind: "message",
783
- content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
784
- eventType: "architect_complete"
785
- });
786
- return {
787
- summary: "forge-bridge completed Architect plan (deterministic).",
788
- spec: {
789
- repoPath: worktree.worktreePath,
790
- path: specPath,
791
- body: specBody,
792
- producedBy: "forge-bridge",
793
- status: "pending_approval"
794
- },
795
- artifact,
796
- artifacts: [artifact]
797
- };
798
- }
799
- async runQa(context) {
800
- const { dispatch, worktree } = context;
801
- await context.emit({
802
- role: "worker",
803
- kind: "message",
804
- content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
805
- eventType: "qa_plan"
806
- });
807
- const qaBrowser = dispatch.qaBrowser;
808
- const launchTarget = qaBrowser?.launchTarget ?? null;
809
- const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
810
- const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
811
- ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
812
- : null;
813
- const browserChecks = browserSidecar && launchTarget
814
- ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
815
- : [];
816
- const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
817
- const summary = missingLaunchTarget
818
- ? "QA blocked because browser testing is required but no app launch target was provided."
819
- : "All checks passed. forge-bridge QA completed.";
820
- const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
821
- for (const gate of qaCompletionGateOrder) {
822
- await writeCompletionArtifact({
823
- worktreePath: worktree.worktreePath,
824
- workItemId: dispatch.workItem.id,
825
- phase: "qa",
826
- producedBy: "forge-bridge",
827
- redactionSecrets: exactRedactionSecrets(dispatch),
828
- qaCycle: true,
829
- ownerType: dispatch.cycleRun.ownerType ?? undefined,
830
- ownerId: dispatch.cycleRun.ownerId ?? undefined
831
- }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
832
- gate,
833
- criterion,
834
- summary,
835
- missingLaunchTarget,
836
- browserChecks,
837
- sidecars
838
- }));
839
- const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
840
- if (gateArtifact) {
841
- await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
886
+ if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
887
+ throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
842
888
  }
889
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, repairArtifact);
890
+ await emitPhaseCompletionEvent(context.emit, repairArtifact);
891
+ await emitPhaseGateEvents(context.emit, repairArtifact);
843
892
  }
844
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
845
- if (!qaArtifact) {
846
- throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
893
+ const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
894
+ if (providerOwnsBranchPublication(context)) {
895
+ await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, context.emit);
847
896
  }
848
- await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
849
- await emitQaStructuredEvents(context.emit, qaArtifact);
850
- await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
851
- return {
852
- summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
853
- artifact: qaArtifact,
854
- artifacts: [qaArtifact]
855
- };
856
- }
857
- async runConflictResolve(context) {
858
- const { dispatch, worktree } = context;
859
- const addressComments = isPullRequestCommentsDispatch(dispatch);
860
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
861
- await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
897
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
862
898
  await context.emit({
863
899
  role: "assistant",
864
900
  kind: "message",
865
- content: addressComments
866
- ? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
867
- : `Deterministic conflict resolve completed for ${worktree.branchName}.`,
868
- eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
901
+ content: outputState.finalMessage || (repairChecks
902
+ ? `${dispatch.execution.provider} CLI repaired pull request checks for ${worktree.branchName}.`
903
+ : addressComments
904
+ ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
905
+ : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
906
+ eventType: repairChecks ? "pr_checks_complete" : addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
869
907
  });
870
908
  return {
871
- summary: addressComments
872
- ? `forge-bridge addressed PR comments for ${worktree.branchName}.`
873
- : `forge-bridge resolved conflicts for ${worktree.branchName}.`
909
+ summary: repairChecks
910
+ ? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
911
+ : addressComments
912
+ ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
913
+ : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`,
914
+ spec: repairSpec,
915
+ artifact: repairArtifact,
916
+ artifacts: repairArtifact ? [repairArtifact] : [],
874
917
  };
875
918
  }
876
919
  }
877
- function phaseCompleteEventType(phase) {
878
- return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
879
- }
880
- function isDebugCompletionPhaseForProvider(phase) {
881
- return debugCompletionPhaseOrder.includes(phase);
882
- }
883
- function deterministicCompletionPayload(phase, dispatch, changesetBody) {
884
- const changesetHash = sha256(changesetBody);
885
- const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
886
- if (phase === "implementation") {
887
- return {
888
- status: "pass",
889
- summary: "forge-bridge produced a deterministic implementation changeset.",
890
- plan: [{ step: "Create deterministic changeset", status: "done" }],
891
- changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
892
- tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
893
- docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
894
- acceptance_criteria: [
895
- {
896
- criterion,
897
- evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
898
- status: "satisfied"
899
- }
900
- ],
901
- known_gaps: [],
902
- next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
903
- };
904
- }
905
- if (phase === "debug_repro") {
906
- return {
907
- status: "pass",
908
- summary: "forge-bridge reproduced the bug deterministically.",
909
- repro_steps: ["Run the deterministic fake-worker debug reproduction."],
910
- observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
911
- expected: "The bug scenario should be fixed before QA handoff.",
912
- evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
913
- };
914
- }
915
- if (phase === "debug_root_cause") {
916
- return {
917
- status: "pass",
918
- summary: "forge-bridge isolated a deterministic root cause.",
919
- root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
920
- evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
921
- eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
922
- risk_area: "forge-bridge deterministic debug lane"
923
- };
924
- }
925
- if (phase === "debug_fix") {
926
- return {
927
- status: "pass",
928
- summary: "forge-bridge applied a deterministic debug fix.",
929
- changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
930
- tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
931
- remaining_risks: [],
932
- resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
933
- qa_id: qaId,
934
- status: "resolved",
935
- summary: `Resolved deterministic QA finding ${qaId}.`,
936
- evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
937
- changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
938
- tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
939
- regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
940
- }))
941
- };
942
- }
943
- if (phase === "debug_regression") {
944
- return {
945
- status: "pass",
946
- summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
947
- commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
948
- required_regressions: ["Original deterministic repro no longer fails."],
949
- build_status: "not_applicable",
950
- test_status: "pass",
951
- repro_negative: true,
952
- qa_ready: true
953
- };
954
- }
955
- if (phase === "self_review") {
956
- return {
957
- status: "pass",
958
- summary: "forge-bridge fake worker completed deterministic self-review.",
959
- reviewed_diff: true,
960
- findings: [],
961
- security_review: {
962
- status: "pass",
963
- notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
964
- },
965
- edge_case_review: {
966
- status: "pass",
967
- notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
968
- },
969
- design_review: {
970
- status: "not_applicable",
971
- screenshots: [],
972
- notes: "No UI changes."
973
- },
974
- deterministic_comparison: {
975
- status: "pass",
976
- command_or_tool: "git diff --stat HEAD~1..HEAD",
977
- notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
978
- },
979
- fixes_applied: [],
980
- remaining_risks: []
981
- };
982
- }
983
- return {
984
- status: "pass",
985
- summary: "forge-bridge fake worker completed deterministic validation.",
986
- commands: [
987
- {
988
- command: "git status --short && git diff --check",
989
- exit_code: 0,
990
- status: "pass",
991
- summary: "Deterministic validation command completed for the fake-worker changeset."
992
- }
993
- ],
994
- acceptance_criteria: [
995
- {
996
- criterion,
997
- evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
998
- status: "satisfied"
999
- }
1000
- ],
1001
- build_status: "pass",
1002
- test_status: "pass",
1003
- lint_status: "not_applicable",
1004
- design_status: "not_applicable",
1005
- drift_checks: [
1006
- {
1007
- command_or_tool: "git diff --check",
1008
- status: "pass",
1009
- summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
1010
- }
1011
- ],
1012
- ready_for_dev_test: true
1013
- };
1014
- }
1015
- function deterministicArchitectPayload(dispatch) {
1016
- const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
1017
- return {
1018
- status: "pass",
1019
- summary: "forge-bridge produced a deterministic Architect plan.",
1020
- implementation_plan: {
1021
- schema_version: 1,
1022
- plan_id: planId,
1023
- story_id: dispatch.workItem.id,
1024
- phases: [
1025
- { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
1026
- ],
1027
- tasks: [
1028
- {
1029
- id: "task-1",
1030
- title: `Implement ${dispatch.workItem.title}`,
1031
- phase: "phase-1",
1032
- summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
1033
- acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
1034
- tests: [
1035
- { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
1036
- ]
1037
- }
1038
- ],
1039
- dependencies: [],
1040
- phase_gates: [
1041
- { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
1042
- ]
1043
- },
1044
- qa_plan: {
1045
- schema_version: 1,
1046
- plan_id: planId,
1047
- final_qa: [
1048
- { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
1049
- ]
1050
- },
1051
- 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`
1052
- };
1053
- }
1054
- function deterministicQaGatePayload(options) {
1055
- const blocked = options.missingLaunchTarget;
1056
- const skippedBecauseBlocked = blocked
1057
- ? {
1058
- status: "skipped",
1059
- summary: "Skipped because browser QA was blocked by missing launch target.",
1060
- reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
1061
- }
1062
- : null;
1063
- switch (options.gate) {
1064
- case "qa_plan":
1065
- return {
1066
- status: "pass",
1067
- summary: "Deterministic QA plan recorded.",
1068
- checklist: [
1069
- "Review the validated work item against acceptance criteria.",
1070
- "Run deterministic regression evidence.",
1071
- "Confirm no in-scope QA findings remain."
1072
- ],
1073
- acceptance_criteria: [options.criterion]
1074
- };
1075
- case "qa_regression":
1076
- return {
1077
- status: "pass",
1078
- summary: "Deterministic regression QA completed.",
1079
- commands: [
1080
- {
1081
- command: "forge-bridge deterministic QA",
1082
- exit_code: 0,
1083
- status: "pass",
1084
- summary: "Deterministic regression evidence completed."
1085
- }
1086
- ],
1087
- notes: "Regression gate passed in deterministic fake-worker mode."
1088
- };
1089
- case "qa_api":
1090
- return {
1091
- status: "skipped",
1092
- summary: "No API/backend surface was identified for deterministic QA.",
1093
- reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
1094
- };
1095
- case "qa_manual_web":
1096
- return blocked
1097
- ? {
1098
- status: "blocked",
1099
- summary: "Browser QA could not run because no app launch target was provided.",
1100
- blocker_reason: "missing_app_launch_target"
1101
- }
1102
- : options.browserChecks.length > 0
1103
- ? {
1104
- status: "pass",
1105
- summary: "Deterministic browser QA exercised the configured launch target.",
1106
- browser_checks: options.browserChecks,
1107
- sidecars: options.sidecars,
1108
- notes: "Browser sidecar evidence recorded."
1109
- }
1110
- : {
1111
- status: "skipped",
1112
- summary: "Manual web QA was not required for this deterministic run.",
1113
- reason: "Forge did not require browser QA and no launch target was necessary."
1114
- };
1115
- case "qa_bug_repro":
1116
- return skippedBecauseBlocked ?? {
1117
- status: "skipped",
1118
- summary: "No failed QA observation required bug reproduction.",
1119
- reason: "No defects or candidate bugs were observed."
1120
- };
1121
- case "qa_findings":
1122
- return skippedBecauseBlocked ?? {
1123
- status: "pass",
1124
- summary: "No QA findings or candidate bugs were identified.",
1125
- findings: [],
1126
- candidate_bugs: []
1127
- };
1128
- case "qa_verdict":
1129
- return {
1130
- status: blocked ? "blocked" : "pass",
1131
- summary: options.summary,
1132
- checklist: [
1133
- "Review the validated work item against acceptance criteria.",
1134
- "Run deterministic regression evidence.",
1135
- blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
1136
- ],
1137
- tested_acceptance_criteria: blocked ? [] : [options.criterion],
1138
- commands: blocked
1139
- ? []
1140
- : [
1141
- {
1142
- command: "forge-bridge deterministic QA",
1143
- exit_code: 0,
1144
- status: "pass",
1145
- summary: "Deterministic QA command completed."
1146
- }
1147
- ],
1148
- browser_checks: blocked ? [] : options.browserChecks,
1149
- sidecars: blocked ? [] : options.sidecars,
1150
- notes: options.summary,
1151
- findings: [],
1152
- candidate_bugs: [],
1153
- blocker_reason: blocked ? "missing_app_launch_target" : null,
1154
- report_markdown: `# QA report\n\n${options.summary}\n`
1155
- };
1156
- }
1157
- }
1158
- const qaArtifactFileNames = {
1159
- plan: "qa.plan.json",
1160
- evidence: "qa.evidence.json",
1161
- findings: "qa.findings.json",
1162
- verdict: "qa.verdict.json",
1163
- report: "qa.report.md"
1164
- };
1165
- const qaGateArtifactFileNames = {
1166
- qa_plan: "qa.plan.json",
1167
- qa_regression: "qa.regression.json",
1168
- qa_api: "qa.api.json",
1169
- qa_manual_web: "qa.manual-web.json",
1170
- qa_bug_repro: "qa.bug-repro.json",
1171
- qa_findings: "qa.findings.json",
1172
- qa_verdict: "qa.verdict.json"
1173
- };
1174
- function hasLaunchTarget(target) {
1175
- return Boolean(target?.url?.trim()
1176
- || target?.ready_url?.trim()
1177
- || target?.command?.trim()
1178
- || (target?.routes ?? []).some((route) => route.trim().length > 0));
1179
- }
1180
- function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
1181
- const route = primaryLaunchRoute(target);
1182
- return {
1183
- relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
1184
- content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
1185
- };
1186
- }
1187
- function deterministicBrowserCheck(target, screenshotPath) {
1188
- const route = primaryLaunchRoute(target);
1189
- return {
1190
- route,
1191
- url: route,
1192
- status: "pass",
1193
- summary: "Deterministic browser QA exercised the configured launch target.",
1194
- actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
1195
- screenshots: [screenshotPath],
1196
- console_errors: [],
1197
- network_errors: [],
1198
- responsive_checks: ["desktop", "mobile"]
1199
- };
1200
- }
1201
- function primaryLaunchRoute(target) {
1202
- return target.ready_url?.trim()
1203
- || target.url?.trim()
1204
- || target.routes.find((route) => route.trim().length > 0)?.trim()
1205
- || "app launch command";
1206
- }
1207
- async function writeQaSidecarFiles(worktreePath, files) {
1208
- const sidecars = [];
1209
- for (const file of files) {
1210
- const fullPath = path.resolve(worktreePath, file.relativePath);
1211
- const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
1212
- if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
1213
- throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
1214
- }
1215
- await fs.mkdir(path.dirname(fullPath), { recursive: true });
1216
- await fs.writeFile(fullPath, file.content, "utf8");
1217
- sidecars.push({
1218
- path: relativePath,
1219
- content_hash: sha256(file.content),
1220
- bytes: Buffer.byteLength(file.content, "utf8")
1221
- });
1222
- }
1223
- return sidecars;
1224
- }
1225
- async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
1226
- const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1227
- await emit({
1228
- role: "tool",
1229
- kind: "tool_result",
1230
- content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
1231
- eventType: "qa_artifact_recorded"
1232
- });
1233
- await emit({
1234
- role: "hook",
1235
- kind: "checkpoint",
1236
- content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
1237
- eventType: "phase_gate"
1238
- });
1239
- }
1240
- async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1241
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1242
- if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
1243
- return null;
1244
- }
1245
- const artifactRoot = ownerType && ownerId
1246
- ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1247
- : artifactRootFor(worktreePath, workItemId);
1248
- const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1249
- const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1250
- const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1251
- await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1252
- return {
1253
- ...artifact,
1254
- planJson,
1255
- evidenceJson,
1256
- findingsJson
1257
- };
1258
- }
1259
- async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1260
- const artifactRoot = ownerType && ownerId
1261
- ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1262
- : artifactRootFor(worktreePath, workItemId);
1263
- for (const fileName of Object.values(qaArtifactFileNames)) {
1264
- try {
1265
- const stat = await fs.stat(path.join(artifactRoot, fileName));
1266
- if (!stat.isFile()) {
1267
- return false;
1268
- }
1269
- }
1270
- catch (error) {
1271
- if (isNodeError(error) && error.code === "ENOENT") {
1272
- return false;
1273
- }
1274
- throw error;
1275
- }
1276
- }
1277
- return true;
1278
- }
1279
- function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
1280
- const qaBrowser = dispatch.qaBrowser;
1281
- if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
1282
- return;
1283
- }
1284
- const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1285
- const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
1286
- const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
1287
- if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
1288
- 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.");
1289
- }
1290
- }
1291
- async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1292
- const artifactRoot = ownerType && ownerId
1293
- ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1294
- : artifactRootFor(worktreePath, workItemId);
1295
- const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1296
- const sidecars = arrayField(evidence, "sidecars");
1297
- if (sidecars.length === 0) {
1298
- return;
1299
- }
1300
- const qaSidecarRoot = path.resolve(artifactRoot, "qa");
1301
- for (const [index, sidecar] of sidecars.entries()) {
1302
- const sidecarPath = stringField(sidecar, "path");
1303
- const expectedHash = stringField(sidecar, "content_hash");
1304
- const expectedBytes = sidecar.bytes;
1305
- if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
1306
- throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
1307
- }
1308
- if (path.isAbsolute(sidecarPath)) {
1309
- throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
1310
- }
1311
- const fullPath = path.resolve(worktreePath, sidecarPath);
1312
- if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
1313
- const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1314
- const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1315
- throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
1316
- }
1317
- const stat = await fs.lstat(fullPath).catch((error) => {
1318
- if (isNodeError(error) && error.code === "ENOENT") {
1319
- throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
1320
- }
1321
- throw error;
1322
- });
1323
- if (!stat.isFile() || stat.isSymbolicLink()) {
1324
- throw new Error(`QA sidecar ${index} must reference a regular file.`);
1325
- }
1326
- await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
1327
- if (stat.size !== expectedBytes) {
1328
- throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
1329
- }
1330
- const actualHash = await sha256File(fullPath);
1331
- if (actualHash !== expectedHash.trim().toLowerCase()) {
1332
- throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
1333
- }
1334
- }
1335
- }
1336
- async function emitQaStructuredEvents(emit, artifact) {
1337
- const artifactRoot = path.dirname(artifact.path);
1338
- const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
1339
- const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1340
- const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
1341
- const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1342
- const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1343
- const checklist = stringArrayField(plan, "checklist");
1344
- await emit({
1345
- role: "worker",
1346
- kind: "message",
1347
- content: checklist.length > 0
1348
- ? `QA plan: ${checklist.join("; ")}`
1349
- : "QA plan recorded.",
1350
- eventType: "qa_plan"
1351
- });
1352
- for (const browserCheck of arrayField(evidence, "browser_checks")) {
1353
- await emit({
1354
- role: "worker",
1355
- kind: "checkpoint",
1356
- content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
1357
- eventType: "qa_browser_check"
1358
- });
1359
- }
1360
- for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
1361
- await emit({
1362
- role: "worker",
1363
- kind: "checkpoint",
1364
- content: `QA finding: ${summarizeQaObject(finding)}`,
1365
- eventType: "qa_finding"
1366
- });
1367
- }
1368
- await emit({
1369
- role: "assistant",
1370
- kind: "message",
1371
- content: status === "blocked"
1372
- ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
1373
- : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
1374
- eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
1375
- });
1376
- }
1377
- function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1378
- return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1379
- ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1380
- : artifactRootFor(worktreePath, workItemId);
1381
- }
1382
- async function readQaGateArtifact(artifactRoot, gate) {
1383
- const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1384
- try {
1385
- const stat = await fs.stat(artifactPath);
1386
- if (!stat.isFile()) {
1387
- return null;
1388
- }
1389
- }
1390
- catch (error) {
1391
- if (isNodeError(error) && error.code === "ENOENT") {
1392
- return null;
1393
- }
1394
- throw error;
1395
- }
1396
- const payload = await readJsonObjectFile(artifactPath);
1397
- return {
1398
- gate,
1399
- path: artifactPath,
1400
- status: stringField(payload, "status") ?? "unknown",
1401
- producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1402
- contentHash: stringField(payload, "content_hash") ?? undefined
1403
- };
1404
- }
1405
- function nextQaGate(gate) {
1406
- const index = qaCompletionGateOrder.indexOf(gate);
1407
- return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1408
- }
1409
- async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1410
- const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1411
- await emit({
1412
- role: "hook",
1413
- kind: artifact.status === "blocked" ? "error" : "checkpoint",
1414
- content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1415
- eventType: "phase_gate",
1416
- data: JSON.stringify({
1417
- phase: "qa",
1418
- qa_gate: artifact.gate,
1419
- status: artifact.status,
1420
- artifact_relative_paths: [relativePath],
1421
- content_hash: artifact.contentHash ?? null,
1422
- produced_by: artifact.producedBy ?? null
1423
- })
1424
- });
1425
- if (!nextGate) {
1426
- return;
1427
- }
1428
- await emit({
1429
- role: "hook",
1430
- kind: "checkpoint",
1431
- content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1432
- eventType: "phase_gate",
1433
- data: JSON.stringify({
1434
- phase: "qa",
1435
- from_gate: artifact.gate,
1436
- to_gate: nextGate
1437
- })
1438
- });
1439
- }
1440
- class LiveQaArtifactEmitter {
1441
- worktreePath;
1442
- workItemId;
1443
- dispatch;
1444
- emit;
1445
- emittedBundle = false;
1446
- emittedGates = new Set();
1447
- timer = null;
1448
- pending = Promise.resolve();
1449
- constructor(worktreePath, workItemId, dispatch, emit) {
1450
- this.worktreePath = worktreePath;
1451
- this.workItemId = workItemId;
1452
- this.dispatch = dispatch;
1453
- this.emit = emit;
1454
- }
1455
- start() {
1456
- void this.pollQueued();
1457
- this.timer = setInterval(() => {
1458
- void this.pollQueued();
1459
- }, 250);
1460
- }
1461
- async stop() {
1462
- if (this.timer) {
1463
- clearInterval(this.timer);
1464
- this.timer = null;
1465
- }
1466
- await this.pollQueued();
1467
- }
1468
- hasEmitted() {
1469
- return this.emittedBundle;
1470
- }
1471
- pollQueued() {
1472
- this.pending = this.pending
1473
- .then(() => this.poll())
1474
- .catch(() => undefined);
1475
- return this.pending;
1476
- }
1477
- async poll() {
1478
- await this.emitAvailableGateEvents();
1479
- if (this.emittedBundle) {
1480
- return;
1481
- }
1482
- const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
1483
- if (!artifact) {
1484
- return;
1485
- }
1486
- enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
1487
- this.emittedBundle = true;
1488
- await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
1489
- await emitQaStructuredEvents(this.emit, artifact);
1490
- }
1491
- async emitAvailableGateEvents() {
1492
- const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1493
- for (const gate of qaCompletionGateOrder) {
1494
- if (this.emittedGates.has(gate)) {
1495
- continue;
1496
- }
1497
- const artifact = await readQaGateArtifact(artifactRoot, gate);
1498
- if (!artifact) {
1499
- return;
1500
- }
1501
- this.emittedGates.add(gate);
1502
- await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
1503
- }
1504
- }
1505
- }
1506
- class LiveArchitectArtifactEmitter {
1507
- worktreePath;
1508
- workItemId;
1509
- emit;
1510
- emitted = false;
1511
- timer = null;
1512
- pending = Promise.resolve();
1513
- constructor(worktreePath, workItemId, emit) {
1514
- this.worktreePath = worktreePath;
1515
- this.workItemId = workItemId;
1516
- this.emit = emit;
1517
- }
1518
- start() {
1519
- void this.pollQueued();
1520
- this.timer = setInterval(() => {
1521
- void this.pollQueued();
1522
- }, 250);
1523
- }
1524
- async stop() {
1525
- if (this.timer) {
1526
- clearInterval(this.timer);
1527
- this.timer = null;
1528
- }
1529
- await this.pollQueued();
1530
- }
1531
- hasEmitted() {
1532
- return this.emitted;
1533
- }
1534
- pollQueued() {
1535
- this.pending = this.pending
1536
- .then(() => this.poll())
1537
- .catch(() => undefined);
1538
- return this.pending;
1539
- }
1540
- async poll() {
1541
- if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
1542
- return;
1543
- }
1544
- const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
1545
- if (!artifact) {
1546
- return;
1547
- }
1548
- this.emitted = true;
1549
- await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1550
- await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1551
- }
1552
- }
1553
- async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1554
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1555
- for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1556
- try {
1557
- const stat = await fs.stat(path.join(artifactRoot, fileName));
1558
- if (!stat.isFile()) {
1559
- return false;
1560
- }
1561
- }
1562
- catch (error) {
1563
- if (isNodeError(error) && error.code === "ENOENT") {
1564
- return false;
1565
- }
1566
- throw error;
1567
- }
1568
- }
1569
- return true;
1570
- }
1571
- async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1572
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1573
- const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1574
- const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1575
- const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1576
- const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1577
- const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1578
- await emit({
1579
- role: "worker",
1580
- kind: "checkpoint",
1581
- content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1582
- eventType: "architect_plan"
1583
- });
1584
- await emit({
1585
- role: "worker",
1586
- kind: "checkpoint",
1587
- content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1588
- eventType: "architect_qa_seed"
1589
- });
1590
- await emit({
1591
- role: "hook",
1592
- kind: status === "pass" ? "checkpoint" : "error",
1593
- content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1594
- eventType: "architect_mcp_complete"
1595
- });
1596
- }
1597
- async function readJsonObjectFile(filePath) {
1598
- const content = await fs.readFile(filePath, "utf8").catch(() => "");
1599
- return parseJsonLine(content) ?? {};
1600
- }
1601
- function arrayField(source, key) {
1602
- const value = source[key];
1603
- if (!Array.isArray(value)) {
1604
- return [];
1605
- }
1606
- return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
1607
- }
1608
- function stringArrayField(source, key) {
1609
- const value = source[key];
1610
- if (!Array.isArray(value)) {
1611
- return [];
1612
- }
1613
- return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
1614
- }
1615
- function summarizeQaObject(source) {
1616
- return clip(stringField(source, "title")
1617
- ?? stringField(source, "summary")
1618
- ?? stringField(source, "id")
1619
- ?? JSON.stringify(source), 500);
1620
- }
1621
- function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1622
- if (ownerType && ownerId) {
1623
- const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1624
- return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1625
- }
1626
- return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
1627
- }
1628
- async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
1629
- const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1630
- await emit({
1631
- role: "tool",
1632
- kind: "checkpoint",
1633
- content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1634
- eventType: "completion_tool_validation_passed",
1635
- data: JSON.stringify({
1636
- phase: artifact.phase ?? "unknown",
1637
- status: artifact.status,
1638
- artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1639
- })
1640
- });
1641
- await emit({
1642
- role: "tool",
1643
- kind: "tool_result",
1644
- content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
1645
- eventType: "completion_tool_artifact_recorded",
1646
- data: JSON.stringify({
1647
- phase: artifact.phase ?? "unknown",
1648
- status: artifact.status,
1649
- artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1650
- })
1651
- });
1652
- }
1653
- async function emitPhaseCompletionEvent(emit, artifact) {
1654
- const phase = completionPhaseFromArtifact(artifact);
1655
- await emit({
1656
- role: "assistant",
1657
- kind: "message",
1658
- content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
1659
- eventType: phaseCompleteEventType(phase)
1660
- });
1661
- }
1662
- async function emitPhaseGateEvents(emit, artifact) {
1663
- const phase = completionPhaseFromArtifact(artifact);
1664
- const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
1665
- await emit({
1666
- role: "hook",
1667
- kind: "checkpoint",
1668
- content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
1669
- eventType: "phase_gate"
1670
- });
1671
- if (status !== "pass") {
1672
- return;
1673
- }
1674
- const progression = phase === "implementation"
1675
- ? "phase_progression: implementation -> self_review"
1676
- : phase === "self_review"
1677
- ? "phase_progression: self_review -> validation"
1678
- : phase === "debug_repro"
1679
- ? "phase_progression: debug_repro -> debug_root_cause"
1680
- : phase === "debug_root_cause"
1681
- ? "phase_progression: debug_root_cause -> debug_fix"
1682
- : phase === "debug_fix"
1683
- ? "phase_progression: debug_fix -> debug_regression"
1684
- : phase === "debug_regression"
1685
- ? "phase_progression: debug_regression -> QA ready"
1686
- : "phase_progression: validation -> QA ready";
1687
- await emit({
1688
- role: "hook",
1689
- kind: "checkpoint",
1690
- content: progression,
1691
- eventType: "phase_gate"
1692
- });
1693
- }
1694
- function completionPhaseFromArtifact(artifact) {
1695
- const phase = artifact.phase?.trim();
1696
- return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1697
- || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1698
- ? phase
1699
- : "implementation";
1700
- }
1701
- class LiveCompletionArtifactEmitter {
1702
- worktreePath;
1703
- workItemId;
1704
- emit;
1705
- phases;
1706
- emitted = new Set();
1707
- timer = null;
1708
- pending = Promise.resolve();
1709
- constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
1710
- this.worktreePath = worktreePath;
1711
- this.workItemId = workItemId;
1712
- this.emit = emit;
1713
- if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
1714
- this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
1715
- }
1716
- else {
1717
- this.phases = developCycle
1718
- ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1719
- : [phase];
1720
- }
1721
- }
1722
- start() {
1723
- void this.pollQueued();
1724
- this.timer = setInterval(() => {
1725
- void this.pollQueued();
1726
- }, 250);
1727
- }
1728
- async stop() {
1729
- if (this.timer) {
1730
- clearInterval(this.timer);
1731
- this.timer = null;
1732
- }
1733
- await this.pollQueued();
1734
- }
1735
- hasEmitted(phase) {
1736
- return this.emitted.has(phase);
1737
- }
1738
- pollQueued() {
1739
- this.pending = this.pending
1740
- .then(() => this.poll())
1741
- .catch(() => undefined);
1742
- return this.pending;
1743
- }
1744
- async poll() {
1745
- for (const phase of this.phases) {
1746
- if (this.emitted.has(phase)) {
1747
- continue;
1748
- }
1749
- const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
1750
- if (!artifact) {
1751
- return;
1752
- }
1753
- this.emitted.add(phase);
1754
- await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1755
- await emitPhaseCompletionEvent(this.emit, artifact);
1756
- await emitPhaseGateEvents(this.emit, artifact);
1757
- if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
1758
- return;
1759
- }
1760
- }
1761
- }
1762
- }
1763
- async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
1764
- if (!developCycle && !debugCycle) {
1765
- const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
1766
- if (!artifact) {
1767
- throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
1768
- }
1769
- return [artifact];
1770
- }
1771
- const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
1772
- ? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
1773
- : ["implementation", "self_review", "validation"];
1774
- const artifacts = [];
1775
- for (const expectedPhase of expectedPhases) {
1776
- const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
1777
- if (!artifact) {
1778
- if (artifacts.length === 0) {
1779
- throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
1780
- }
1781
- const previous = artifacts[artifacts.length - 1];
1782
- if ((previous.status ?? "").trim().toLowerCase() === "pass") {
1783
- throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
1784
- }
1785
- return artifacts;
1786
- }
1787
- artifacts.push(artifact);
1788
- if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
1789
- return artifacts;
1790
- }
1791
- }
1792
- return artifacts;
1793
- }
1794
- function providerProcessEnv(dispatch) {
1795
- const env = {
1796
- ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1797
- ...providerCredentialEnv(dispatch)
1798
- };
1799
- return Object.keys(env).length > 0 ? env : undefined;
1800
- }
1801
- function providerCredentialEnv(dispatch) {
1802
- const secret = dispatch.apiKeySecretGrant?.secret;
1803
- if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1804
- return {};
1805
- }
1806
- const provider = dispatch.execution.provider.trim().toLowerCase();
1807
- if (provider === "codex" || provider === "openai") {
1808
- return { OPENAI_API_KEY: secret };
1809
- }
1810
- return {};
1811
- }
1812
- function exactRedactionSecrets(dispatch) {
1813
- return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
1814
- }
1815
- async function emitProviderUsageEvent(emit, dispatch, outputState) {
1816
- const usage = outputState.usage;
1817
- if (hasUsage(usage)) {
1818
- await emit(buildProviderUsageEvent(dispatch, usage));
1819
- }
1820
- }
1821
- function estimatedDeterministicUsage() {
1822
- return addUsage(emptyUsage("estimated"), {
1823
- inputTokens: 1000,
1824
- outputTokens: 400,
1825
- source: "estimated"
1826
- });
1827
- }
1828
- export class StreamingProviderProcessRunner {
1829
- async run(request, handlers = {}, signal) {
1830
- const launch = await resolveProviderProcessLaunch(request.command, request.args);
1831
- return await new Promise((resolve, reject) => {
1832
- const child = spawn(launch.command, launch.args, {
1833
- cwd: request.cwd,
1834
- env: buildProviderChildEnvironment(request.env),
1835
- stdio: ["ignore", "pipe", "pipe"],
1836
- windowsHide: true
1837
- });
1838
- let stdout = "";
1839
- let stderr = "";
1840
- let settled = false;
1841
- const cleanup = () => {
1842
- signal?.removeEventListener("abort", abort);
1843
- };
1844
- const fail = (error) => {
1845
- if (settled) {
1846
- return;
1847
- }
1848
- settled = true;
1849
- cleanup();
1850
- reject(error);
1851
- };
1852
- const abort = () => {
1853
- try {
1854
- child.kill("SIGTERM");
1855
- }
1856
- catch {
1857
- // Best effort; close/error will settle the promise.
1858
- }
1859
- };
1860
- if (signal?.aborted) {
1861
- abort();
1862
- }
1863
- else {
1864
- signal?.addEventListener("abort", abort, { once: true });
1865
- }
1866
- child.on("error", fail);
1867
- const readers = [
1868
- readProcessLines(child.stdout, (line) => {
1869
- stdout += `${line}\n`;
1870
- return handlers.onStdoutLine?.(line);
1871
- }),
1872
- readProcessLines(child.stderr, (line) => {
1873
- stderr += `${line}\n`;
1874
- return handlers.onStderrLine?.(line);
1875
- })
1876
- ];
1877
- child.on("close", (code) => {
1878
- Promise.allSettled(readers).then((readerResults) => {
1879
- const rejected = readerResults.find((result) => result.status === "rejected");
1880
- if (rejected?.status === "rejected") {
1881
- fail(rejected.reason);
1882
- return;
1883
- }
1884
- if (settled) {
1885
- return;
1886
- }
1887
- settled = true;
1888
- cleanup();
1889
- resolve({
1890
- exitCode: code ?? 1,
1891
- stdout,
1892
- stderr
1893
- });
1894
- }).catch(fail);
1895
- });
1896
- });
1897
- }
1898
- }
1899
- async function resolveProviderProcessLaunch(command, args) {
1900
- if (process.platform !== "win32") {
1901
- return { command, args };
1902
- }
1903
- const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
1904
- if (cursorDirect) {
1905
- return cursorDirect;
1906
- }
1907
- const resolved = await resolveWindowsCommand(command);
1908
- return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
1909
- }
1910
- async function resolveWindowsCommand(command) {
1911
- if (path.isAbsolute(command)) {
1912
- return command;
1913
- }
1914
- try {
1915
- const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
1916
- return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
1917
- }
1918
- catch {
1919
- return null;
1920
- }
1921
- }
1922
- export function chooseWindowsCommandCandidate(candidates) {
1923
- const normalized = candidates
1924
- .map((candidate) => candidate.trim())
1925
- .filter((candidate) => candidate.length > 0);
1926
- if (normalized.length === 0) {
1927
- return null;
1928
- }
1929
- const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
1930
- for (const extension of preferredExtensions) {
1931
- const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
1932
- if (candidate) {
1933
- return candidate;
1934
- }
1935
- }
1936
- return normalized[0];
1937
- }
1938
- export function buildWindowsLaunchCommand(commandPath, args) {
1939
- const extension = path.extname(commandPath).toLowerCase();
1940
- if (extension === ".ps1") {
1941
- return {
1942
- command: powershellExecutable(),
1943
- args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
1944
- };
1945
- }
1946
- if (extension === ".cmd" || extension === ".bat") {
1947
- return {
1948
- command: process.env.ComSpec ?? "cmd.exe",
1949
- args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
1950
- };
1951
- }
1952
- return { command: commandPath, args };
1953
- }
1954
- function powershellExecutable() {
1955
- const systemRoot = process.env.SystemRoot;
1956
- return systemRoot
1957
- ? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
1958
- : "powershell.exe";
1959
- }
1960
- function windowsCommandLine(command, args) {
1961
- return [command, ...args].map(quoteWindowsCommandLineArg).join(" ");
1962
- }
1963
- function quoteWindowsCommandLineArg(value) {
1964
- if (value.length > 0 && !/[\s"]/.test(value)) {
1965
- return value;
1966
- }
1967
- return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
1968
- }
1969
- async function readProcessLines(stream, onLine) {
1970
- const reader = readline.createInterface({ input: stream });
1971
- try {
1972
- for await (const line of reader) {
1973
- await onLine(line);
1974
- }
1975
- }
1976
- finally {
1977
- reader.close();
1978
- }
920
+ async function stageDraftAttachments(dispatch, metadataRoot) {
921
+ const attachments = dispatch.draft?.attachments ?? [];
922
+ const stageable = attachments.filter((attachment) => (attachment.kind === "text" && typeof attachment.textContent === "string")
923
+ || (attachment.kind === "image" && typeof attachment.contentBase64 === "string"));
924
+ if (stageable.length === 0) {
925
+ return { textReferences: [], imagePaths: [] };
926
+ }
927
+ const attachmentRoot = path.join(metadataRoot, "draft-attachments");
928
+ const worktreeRoot = path.resolve(metadataRoot, "../../..");
929
+ await fs.mkdir(attachmentRoot, { recursive: true });
930
+ const textReferences = [];
931
+ const imagePaths = [];
932
+ for (const attachment of stageable) {
933
+ const fileName = `${String(attachment.index + 1).padStart(2, "0")}-${safeAttachmentFileName(attachment.fileName)}`;
934
+ const absolutePath = path.join(attachmentRoot, fileName);
935
+ if (attachment.kind === "text") {
936
+ await fs.writeFile(absolutePath, attachment.textContent ?? "", { encoding: "utf8", mode: 0o600 });
937
+ textReferences.push({ index: attachment.index, path: path.relative(worktreeRoot, absolutePath).replaceAll(path.sep, "/") });
938
+ continue;
939
+ }
940
+ const imageContent = decodeDraftImageAttachment(attachment.contentBase64 ?? "", attachment.fileName, attachment.index);
941
+ await fs.writeFile(absolutePath, imageContent, { mode: 0o600 });
942
+ imagePaths.push(absolutePath);
943
+ }
944
+ return { textReferences, imagePaths };
945
+ }
946
+ function decodeDraftImageAttachment(contentBase64, fileName, index) {
947
+ const normalized = contentBase64.replace(/\s+/gu, "");
948
+ if (normalized.length === 0 || normalized.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(normalized)) {
949
+ throw new Error(`Draft image attachment ${index + 1} (${fileName}) is not valid base64.`);
950
+ }
951
+ const decoded = Buffer.from(normalized, "base64");
952
+ if (decoded.length === 0 || decoded.toString("base64") !== normalized) {
953
+ throw new Error(`Draft image attachment ${index + 1} (${fileName}) is not valid base64.`);
954
+ }
955
+ return decoded;
956
+ }
957
+ function safeAttachmentFileName(fileName) {
958
+ const sanitized = path.basename(fileName || "attachment.txt")
959
+ .replace(/[^a-zA-Z0-9._-]/gu, "_")
960
+ .replace(/[. ]+$/gu, "") || "attachment.txt";
961
+ const maxFileNameLength = 120;
962
+ const clipped = clipFileName(sanitized, maxFileNameLength);
963
+ const extension = path.extname(clipped);
964
+ const stem = path.basename(clipped, extension).replace(/[. ]+$/gu, "") || "attachment";
965
+ const windowsReservedName = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;
966
+ const safeStem = stem === "." || stem === ".." || windowsReservedName.test(stem) ? `attachment-${stem.replaceAll(".", "_")}` : stem;
967
+ return clipFileName(`${safeStem}${extension}`, maxFileNameLength);
968
+ }
969
+ function clipFileName(fileName, maxLength) {
970
+ if (fileName.length <= maxLength) {
971
+ return fileName;
972
+ }
973
+ const originalExtension = path.extname(fileName);
974
+ const extension = originalExtension.length > maxLength - 1
975
+ ? originalExtension.slice(0, maxLength - 1)
976
+ : originalExtension;
977
+ const stem = path.basename(fileName, originalExtension);
978
+ const maxStemLength = Math.max(1, maxLength - extension.length);
979
+ return `${stem.slice(0, maxStemLength)}${extension}`;
980
+ }
981
+ const providerPromptStdinThreshold = 8_000;
982
+ function shouldPipePromptToStdin(provider, prompt, force = false) {
983
+ return provider.trim().toLowerCase() === "codex"
984
+ && (force || Buffer.byteLength(prompt, "utf8") > providerPromptStdinThreshold);
985
+ }
986
+ function usesManagedWindowsHost(dispatch) {
987
+ return process.platform === "win32" && dispatch.sandbox?.executionMode === "host";
1979
988
  }
1980
989
  function isFakeWorkerModel(model) {
1981
990
  return model.trim().toLowerCase() === fakeWorkerModel;
1982
991
  }
1983
- function sha256(content) {
1984
- return crypto.createHash("sha256").update(content).digest("hex");
1985
- }
1986
- function buildDraftSpec(dispatch) {
1987
- return `# Draft Generation Context
1988
-
1989
- Project: ${dispatch.draft?.projectName ?? dispatch.repo.name}
1990
- Repository: ${dispatch.draft?.repoName ?? dispatch.repo.name}
1991
- Draft kind: ${dispatch.draft?.kind ?? "draft"}
1992
-
1993
- ## User Prompt
1994
-
1995
- ${dispatch.draft?.userPrompt ?? ""}
1996
- `;
1997
- }
1998
- async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
1999
- const draftArtifactFiles = {
2000
- draft_intent: "draft.intent.json",
2001
- draft_repo_context: "draft.repo-context.json",
2002
- draft_graph_context: "draft.graph-context.json",
2003
- draft_product_scope: "draft.product-scope.json",
2004
- draft_work_order_plan: "draft.work-order-plan.json",
2005
- draft_critic: "draft.critic.json",
2006
- draft_proposal: "draft.proposal.json"
2007
- };
2008
- for (const gate of draftCompletionGateOrder) {
2009
- const actualPath = path.join(worktreePath, ".forge", "work-items", workItemId, "artifacts", draftArtifactFiles[gate]);
2010
- if (!await fileExists(actualPath)) {
2011
- continue;
2012
- }
2013
- const relativePath = path.relative(worktreePath, actualPath).split(path.sep).join("/");
2014
- await emit({
2015
- role: "tool",
2016
- kind: "tool_result",
2017
- content: `Forge Draft completion tool recorded ${gate} artifact ${relativePath}.`,
2018
- eventType: "completion_tool_artifact_recorded",
2019
- data: JSON.stringify({ phase: "draft", draft_gate: gate, artifact_relative_paths: [relativePath] })
2020
- });
2021
- await emit({
2022
- role: "hook",
2023
- kind: "checkpoint",
2024
- content: `phase_gate: ${gate} artifact accepted with status pass.`,
2025
- eventType: "phase_gate"
2026
- });
2027
- const next = draftCompletionGateOrder[draftCompletionGateOrder.indexOf(gate) + 1];
2028
- if (next) {
2029
- await emit({
2030
- role: "hook",
2031
- kind: "checkpoint",
2032
- content: `phase_progression: ${gate} -> ${next}`,
2033
- eventType: "phase_gate"
2034
- });
2035
- }
2036
- }
2037
- }
2038
- async function fileExists(filePath) {
2039
- try {
2040
- await fs.access(filePath);
2041
- return true;
2042
- }
2043
- catch {
2044
- return false;
2045
- }
2046
- }
2047
- function buildDraftPrompt(dispatch) {
2048
- const draft = dispatch.draft;
2049
- if (!draft) {
2050
- throw new Error("Draft prompt is missing.");
2051
- }
2052
- const draftArtifacts = dispatch.artifacts
2053
- .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
2054
- .map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
2055
- .join("\n\n");
2056
- const artifactSection = draftArtifacts
2057
- ? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
2058
- : "";
2059
- const projectSection = [
2060
- draft.projectName ? `Project: ${draft.projectName}` : null,
2061
- draft.repoName ? `Repository: ${draft.repoName}` : null
2062
- ].filter(Boolean).join("\n");
2063
- const scopedProjectSection = projectSection ? `\n\n# Selected project context\n\n${projectSection}` : "";
2064
- return `${draft.systemPrompt}${scopedProjectSection}${artifactSection}
2065
-
2066
- Draft kind: ${draft.kind}
2067
-
2068
- ${draft.userPrompt}
2069
-
2070
- ${completionPromptForDraftCycle("draft_intent")}
2071
-
2072
- 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.
2073
-
2074
- Do not modify source files.`;
2075
- }
2076
- function summarizeStderr(stderr) {
2077
- const trimmed = stderr.trim();
2078
- return trimmed ? `: ${clip(trimmed, 1000)}` : "";
2079
- }
2080
- async function waitForDraftProposalArtifact(worktreePath, workItemId, signal) {
2081
- while (!signal?.aborted) {
2082
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "draft");
2083
- if (artifact) {
2084
- return artifact;
2085
- }
2086
- await new Promise((resolve) => setTimeout(resolve, 1000));
2087
- }
2088
- throw new Error("Draft proposal artifact wait was cancelled.");
2089
- }
2090
- function deterministicDraftPayload(dispatch) {
2091
- const kind = dispatch.draft?.kind ?? "work_item";
2092
- if (kind === "work_order_decomposition") {
2093
- return {
2094
- summary: "Fake decompose proposed a Feature DAG for the Work Order.",
2095
- blockedReason: "",
2096
- candidates: [
2097
- {
2098
- origin: "agent",
2099
- key: "intake-submission",
2100
- title: "Customer intake submission",
2101
- summary: "Collect, validate, de-duplicate, and confirm incoming customer requests.",
2102
- planningPacket: "# Customer intake submission\n\nPlan Stories for request form validation, attachment support, duplicate prevention, and submission confirmation.",
2103
- sortOrder: 10,
2104
- dependsOn: []
2105
- },
2106
- {
2107
- origin: "agent",
2108
- key: "review-queue",
2109
- title: "Reviewer triage queue",
2110
- summary: "Provide reviewer triage, assignment, notes, status transitions, and audit trail.",
2111
- planningPacket: "# Reviewer triage queue\n\nPlan Stories for queue filtering, assignment, reviewer notes, status changes, and immutable audit trail.",
2112
- sortOrder: 20,
2113
- dependsOn: ["intake-submission"]
2114
- }
2115
- ]
2116
- };
2117
- }
2118
- if (kind === "feature_decomposition") {
2119
- return {
2120
- summary: "Fake decompose proposed a Story DAG for the Feature.",
2121
- blockedReason: "",
2122
- candidates: [
2123
- {
2124
- origin: "agent",
2125
- key: "foundation",
2126
- title: "Build the feature foundation",
2127
- description: "Create the persistence, API, and UI shell needed by the feature.",
2128
- acceptanceCriteria: "Scenario: Foundation exists\nGiven the Feature is selected\nWhen the foundation is delivered\nThen downstream Stories can build on stable contracts",
2129
- points: 3,
2130
- sortOrder: 10,
2131
- dependsOn: []
2132
- },
2133
- {
2134
- origin: "agent",
2135
- key: "workflow-behavior",
2136
- title: "Implement the primary workflow behavior",
2137
- description: "Implement the main user-visible behavior for the feature after the foundation is ready.",
2138
- acceptanceCriteria: "Scenario: Workflow behavior works\nGiven the foundation Story is complete\nWhen the user performs the primary workflow\nThen the expected state change and feedback are visible",
2139
- points: 5,
2140
- sortOrder: 20,
2141
- dependsOn: ["foundation"]
2142
- },
2143
- {
2144
- origin: "agent",
2145
- key: "audit-and-tests",
2146
- title: "Add audit coverage and regression tests",
2147
- description: "Add audit/evidence behavior and automated regression coverage for the feature.",
2148
- acceptanceCriteria: "Scenario: Feature is verifiable\nGiven the workflow behavior is complete\nWhen validation runs\nThen audit evidence and tests cover the expected outcomes",
2149
- points: 3,
2150
- sortOrder: 30,
2151
- dependsOn: ["workflow-behavior"]
2152
- }
2153
- ]
2154
- };
2155
- }
2156
- if (kind === "work_order") {
2157
- return {
2158
- title: "Deterministic runner Work Order draft",
2159
- summary: "Forge Runner generated this deterministic Work Order draft.",
2160
- objective: "Validate runner-backed Draft generation.",
2161
- planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
2162
- decompositionContext: "Use this deterministic fixture only in bridge tests.",
2163
- assumptions: ["Forge Runner dispatch is available."],
2164
- warnings: []
2165
- };
2166
- }
2167
- if (kind === "story") {
2168
- return {
2169
- title: "Deterministic runner Story draft",
2170
- description: "Forge Runner generated this deterministic Story draft.",
2171
- acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
2172
- points: 3
2173
- };
2174
- }
2175
- return {
2176
- title: "Deterministic runner Work Item draft",
2177
- description: "Forge Runner generated this deterministic Work Item draft.",
2178
- acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
2179
- reproSteps: "Run Draft with a Forge Runner provider selected.",
2180
- systemInfo: "forge-bridge deterministic provider",
2181
- points: 1
2182
- };
2183
- }
2184
- export function formatProviderCliCommand(command) {
2185
- return [command.command, ...command.args].map(singleLine).join(" ");
2186
- }
2187
- function singleLine(value) {
2188
- return value.replace(/\s+/g, " ").trim();
2189
- }
2190
- export function buildProviderCliCommand(dispatch, run) {
2191
- const provider = dispatch.execution.provider.trim();
2192
- const normalizedProvider = provider.toLowerCase();
2193
- const model = dispatch.execution.model.trim();
2194
- if (normalizedProvider === "codex") {
2195
- const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
2196
- if (run?.completionTools) {
2197
- args.push(...codexMcpConfigArgs(run.completionTools));
2198
- }
2199
- args.push("--model", model);
2200
- if (run) {
2201
- args.push("--json");
2202
- if (run.worktreePath) {
2203
- args.push("--cd", run.worktreePath);
2204
- }
2205
- if (run.skipGitRepoCheck) {
2206
- args.push("--skip-git-repo-check");
2207
- }
2208
- args.push(run.prompt ?? "");
2209
- }
2210
- return { command: "codex", args };
2211
- }
2212
- if (normalizedProvider === "cursor") {
2213
- const args = ["--print", "--output-format", "stream-json", "--model", model];
2214
- if (run?.worktreePath) {
2215
- args.push("--workspace", run.worktreePath);
2216
- }
2217
- if (run?.prompt) {
2218
- args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
2219
- }
2220
- return { command: "cursor-agent", args };
2221
- }
2222
- const args = ["--model", model];
2223
- if (run?.prompt) {
2224
- args.push(run.prompt);
2225
- }
2226
- return { command: provider, args };
2227
- }
2228
- export function codexSandboxModeForPlatform(platform = process.platform) {
2229
- return platform === "win32" ? "danger-full-access" : "workspace-write";
2230
- }
2231
- function buildArchitectPrompt(dispatch) {
2232
- return `You are Forge's Architect lane running locally in a prepared git worktree.
2233
-
2234
- Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
2235
-
2236
- Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
2237
- 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.
2238
- 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.
2239
- ${architectRevisionInstruction(dispatch)}
2240
- Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
2241
-
2242
- ${completionPromptForPhase("architect")}
2243
-
2244
- Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
2245
- }
2246
- function architectRevisionInstruction(dispatch) {
2247
- if (!dispatch.architectRevision) {
2248
- return "";
2249
- }
2250
- return `
2251
- Architect revision context:
2252
- - Previous plan id: ${dispatch.architectRevision.priorPlanId}
2253
- - Previous content hash: ${dispatch.architectRevision.priorContentHash}
2254
- - Reviewer feedback: ${dispatch.architectRevision.feedback}
2255
- Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
2256
- }
2257
- function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2258
- return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
2259
-
2260
- Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
2261
- ${phaseWorkInstruction(phase)}
2262
- ${qaReworkImplementationInstruction(dispatch)}
2263
- Use the repository's existing conventions. Run relevant tests when practical.
2264
- Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
2265
- Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
2266
-
2267
- ${completionPromptForPhase(phase)}
2268
-
2269
- Finish with a concise summary of changed files and verification after calling the completion tool.`;
2270
- }
2271
- function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2272
- return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
2273
-
2274
- Read .forge/work-items/${dispatch.workItem.id}/spec.md, implement the work item, self-review the diff, then validate it in this same provider session.
2275
- Start in the ${phase.replace(/_/g, " ")} phase. Do not stop after implementation if it passes; continue through self-review and validation using the next instruction returned by each completion tool.
2276
- ${qaReworkImplementationInstruction(dispatch)}
2277
- Use the repository's existing conventions. Run relevant tests when practical.
2278
- Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
2279
- Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
2280
-
2281
- ${completionPromptForDevelopCycle(phase)}
2282
-
2283
- 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.`;
2284
- }
2285
- function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2286
- return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
2287
-
2288
- 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.
2289
- 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.
2290
- ${debugQaReworkInstruction(dispatch)}
2291
- Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
2292
- Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
2293
- Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
2294
-
2295
- ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
2296
-
2297
- 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.`;
2298
- }
2299
- function qaReworkImplementationInstruction(dispatch) {
2300
- if (!dispatch.qaRework) {
2301
- return "";
2302
- }
2303
- return `
2304
- QA rework context:
2305
- - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2306
- - Rework packet: ${dispatch.qaRework.packetPath}
2307
- - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2308
- 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.
2309
- Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2310
- }
2311
- function debugQaReworkInstruction(dispatch) {
2312
- if (!dispatch.qaRework) {
2313
- return "";
2314
- }
2315
- return `
2316
- QA rework context for Debug:
2317
- - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2318
- - Rework packet: ${dispatch.qaRework.packetPath}
2319
- - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2320
- 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.
2321
- Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2322
- }
2323
- function qaReworkRetestInstruction(dispatch) {
2324
- if (!dispatch.qaRework) {
2325
- return "";
2326
- }
2327
- return `
2328
- QA retest context:
2329
- - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2330
- - Rework packet: ${dispatch.qaRework.packetPath}
2331
- - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2332
- Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
2333
- }
2334
- function phaseWorkInstruction(phase) {
2335
- if (phase === "self_review") {
2336
- return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
2337
- }
2338
- if (phase === "validation") {
2339
- return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
2340
- }
2341
- return "Implement the work item and keep the change focused.";
2342
- }
2343
- function qaBrowserInstruction(dispatch) {
2344
- const qaBrowser = dispatch.qaBrowser;
2345
- if (!qaBrowser) {
2346
- return "Browser/app launch context: not provided by Forge.";
2347
- }
2348
- const launchTarget = qaBrowser.launchTarget;
2349
- if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
2350
- return `Browser/app launch context:\n- UI/browser QA is required for this item.\n- No app launch target was provided.\n- Return blocked with blocker_reason: missing_app_launch_target instead of pretending browser testing occurred.\n- Artifact sidecars path when available: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
2351
- }
2352
- if (!launchTarget) {
2353
- return `Browser/app launch context:\n- UI/browser QA is not required by Forge heuristics for this item.\n- If you determine browser testing is needed, return blocked with blocker_reason: missing_app_launch_target unless you can safely identify a launch target from the repo.\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
2354
- }
2355
- const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
2356
- 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`}`;
2357
- }
2358
- function storyQaInstruction(dispatch) {
2359
- const storyQa = dispatch.storyQa;
2360
- if (!storyQa) {
2361
- return "";
2362
- }
2363
- const childLines = storyQa.childTasks.map((child) => {
2364
- const dependencies = child.dependencyWorkItemIds.length > 0
2365
- ? child.dependencyWorkItemIds.join(", ")
2366
- : "none";
2367
- const validation = child.validationArtifact
2368
- ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2369
- : "missing";
2370
- const childQa = child.qaArtifact
2371
- ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2372
- : "not present";
2373
- return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2374
- }).join("\n");
2375
- const finalQa = storyQa.finalQaChecks.length > 0
2376
- ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2377
- : "- No final QA checks were provided in qa.plan.final_qa.";
2378
- return `Story QA integration context:
2379
- - Story work item: ${storyQa.storyWorkItemId}
2380
- - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2381
- - Story worktree: ${storyQa.worktreeKey}
2382
- - Branch: ${storyQa.branch}
2383
- - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2384
- - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2385
- Materialized child tasks and evidence:
2386
- ${childLines || "- No child tasks were provided."}
2387
- Architect final QA checks:
2388
- ${finalQa}
2389
- 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.`;
2390
- }
2391
- function buildQaPrompt(dispatch, laneSpec) {
2392
- return `You are Forge's QA lane running locally in a prepared git worktree.
2393
-
2394
- First read and follow the injected QA lane command at .forge/work-items/${dispatch.workItem.id}/spec.md. It defines the required gated QA skill workflow for this run.
2395
-
2396
- Injected QA lane command and work item spec:
2397
- ${laneSpec}
2398
-
2399
- ---
2400
-
2401
- Work item: ${dispatch.workItem.id}
2402
- Title: ${dispatch.workItem.title}
2403
- Description:
2404
- ${dispatch.workItem.description || "Not provided."}
2405
-
2406
- Acceptance criteria:
2407
- ${dispatch.workItem.acceptanceCriteria || "Not specified."}
2408
-
2409
- Repro steps / scenario:
2410
- ${dispatch.workItem.reproSteps || "Not provided."}
2411
-
2412
- System info / environment notes:
2413
- ${dispatch.workItem.systemInfo || "Not provided."}
2414
-
2415
- ${storyQaInstruction(dispatch)}
2416
- Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
2417
- ${qaBrowserInstruction(dispatch)}
2418
- ${qaReworkRetestInstruction(dispatch)}
2419
- QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
2420
- Record concrete evidence. For UI/browser work, include browser_checks with URLs/routes, actions, observed results, screenshots/traces when available, console errors, failed network requests, and responsive checks. Store browser sidecars under .forge/work-items/${dispatch.workItem.id}/artifacts/qa/.
2421
- Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
2422
- Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
2423
-
2424
- ${completionPromptForQaCycle()}
2425
-
2426
- Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
2427
- }
2428
- function buildConflictResolvePrompt(dispatch, branchName) {
2429
- const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
2430
- return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
2431
-
2432
- The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
2433
- Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
2434
- Keep the original work item intent intact:
2435
- - Work item: ${dispatch.workItem.id}
2436
- - Title: ${dispatch.workItem.title}
2437
- - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
2438
-
2439
- Finish with a concise summary of the conflicts resolved and verification performed.`;
2440
- }
2441
- function buildPullRequestCommentsPrompt(dispatch, branchName) {
2442
- const pr = dispatch.pullRequest;
2443
- const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
2444
- const prLocator = pr
2445
- ? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
2446
- : "the open pull request for this work item";
2447
- return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
2448
-
2449
- The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
2450
- PR context:
2451
- - Provider: ${pr?.provider || "not provided"}
2452
- - Source branch: ${pr?.sourceBranch || branchName}
2453
- - Target branch: ${targetBranch}
2454
- - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
2455
-
2456
- 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.
2457
- After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
2458
- If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
2459
- Keep the original work item intent intact:
2460
- - Work item: ${dispatch.workItem.id}
2461
- - Title: ${dispatch.workItem.title}
2462
- - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
2463
-
2464
- Finish with a concise summary of comments addressed and verification performed.`;
2465
- }
2466
- function isPullRequestCommentsDispatch(dispatch) {
2467
- return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
2468
- }
2469
- async function cleanupCompletionTools(completionTools, emit) {
2470
- try {
2471
- await completionTools.cleanup();
2472
- }
2473
- catch (error) {
2474
- await emit({
2475
- role: "runner",
2476
- kind: "checkpoint",
2477
- content: `Forge completion tool cleanup failed and was ignored: ${clip(messageFromError(error), 600)}`,
2478
- eventType: "completion_tools_cleanup_failed"
2479
- }).catch(() => undefined);
2480
- }
2481
- }
2482
- async function commitWorktreeChanges(git, worktreePath, workItemId) {
2483
- await git.run(worktreePath, ["add", "-A"]);
2484
- await git.run(worktreePath, ["reset", "--", ".forge"]).catch(() => "");
2485
- const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
2486
- .split(/\r?\n/)
2487
- .map((line) => line.trim())
2488
- .filter(Boolean);
2489
- if (changedFiles.length > 0) {
2490
- await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
2491
- }
2492
- else {
2493
- await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
2494
- }
2495
- const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
2496
- return { commitSha, changedFiles };
2497
- }
2498
- function messageFromError(error) {
2499
- return error instanceof Error ? error.message : String(error);
2500
- }
2501
- function clip(value, maxLength) {
2502
- if (value.length <= maxLength) {
2503
- return value;
2504
- }
2505
- return `${value.slice(0, maxLength)}...`;
2506
- }
2507
- function createProviderOutputState(provider) {
2508
- return provider.trim().toLowerCase() === "cursor"
2509
- ? new CursorStreamJsonState()
2510
- : new CodexJsonState();
2511
- }
2512
- class CursorStreamJsonState {
2513
- sessionId = null;
2514
- finalMessage = null;
2515
- emittedSession = false;
2516
- accumulatedUsage = null;
2517
- get sessionLabel() {
2518
- return this.sessionId ? `session ${this.sessionId}` : null;
2519
- }
2520
- get usage() {
2521
- return this.accumulatedUsage;
2522
- }
2523
- consume(line) {
2524
- const event = parseJsonLine(line);
2525
- if (!event) {
2526
- return [];
2527
- }
2528
- const type = stringField(event, "type");
2529
- if (type === "system" && stringField(event, "subtype") === "init") {
2530
- this.sessionId = stringField(event, "session_id");
2531
- if (this.sessionId && !this.emittedSession) {
2532
- this.emittedSession = true;
2533
- return [{
2534
- role: "runner",
2535
- kind: "checkpoint",
2536
- content: `Cursor session started: ${this.sessionId}.`,
2537
- eventType: "provider_thread_started"
2538
- }];
2539
- }
2540
- }
2541
- if (type === "assistant") {
2542
- const text = assistantMessageText(event);
2543
- if (text) {
2544
- this.finalMessage = text;
2545
- return [{
2546
- role: "assistant",
2547
- kind: "message",
2548
- content: clip(text, 4000),
2549
- eventType: "provider_message"
2550
- }];
2551
- }
2552
- }
2553
- if (type === "tool_call") {
2554
- const subtype = stringField(event, "subtype");
2555
- const toolCall = objectField(event, "tool_call");
2556
- if (subtype === "started") {
2557
- const summary = formatCursorToolCallStarted(toolCall);
2558
- if (summary) {
2559
- return [{
2560
- role: "worker",
2561
- kind: "checkpoint",
2562
- content: summary,
2563
- eventType: "provider_tool_call"
2564
- }];
2565
- }
2566
- }
2567
- if (subtype === "completed") {
2568
- const completed = formatCursorToolCallCompleted(toolCall);
2569
- if (completed) {
2570
- return [{
2571
- role: "worker",
2572
- kind: completed.kind,
2573
- content: completed.content,
2574
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2575
- }];
2576
- }
2577
- }
2578
- }
2579
- if (type === "result" && stringField(event, "subtype") === "success") {
2580
- const result = stringField(event, "result");
2581
- if (result) {
2582
- this.finalMessage = result;
2583
- }
2584
- this.accumulateUsage(event);
2585
- }
2586
- if (type === "error" || (type === "result" && event.is_error === true)) {
2587
- return [{
2588
- role: "runner",
2589
- kind: "error",
2590
- content: clip(line.trim(), 1000),
2591
- eventType: "provider_cli_error"
2592
- }];
2593
- }
2594
- return [];
2595
- }
2596
- accumulateUsage(event) {
2597
- const usage = objectField(event, "usage");
2598
- const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
2599
- if (Object.keys(usage).length === 0 && durationMs === 0) {
2600
- return;
2601
- }
2602
- this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
2603
- inputTokens: readUsageNumber(usage, "inputTokens"),
2604
- outputTokens: readUsageNumber(usage, "outputTokens"),
2605
- cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
2606
- cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
2607
- providerDurationMs: durationMs > 0 ? durationMs : null,
2608
- source: "provider_reported"
2609
- });
2610
- }
2611
- }
2612
- function formatCursorToolCallStarted(toolCall) {
2613
- const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
2614
- const readPath = stringField(readArgs, "path");
2615
- if (readPath) {
2616
- return `Reading ${readPath}`;
2617
- }
2618
- const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
2619
- const writePath = stringField(writeArgs, "path");
2620
- if (writePath) {
2621
- return `Writing ${writePath}`;
2622
- }
2623
- const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
2624
- const command = stringField(shellArgs, "command");
2625
- if (command) {
2626
- return `Shell command started: ${clip(command, 500)}`;
2627
- }
2628
- const fn = objectField(toolCall, "function");
2629
- const name = stringField(fn, "name");
2630
- if (name) {
2631
- return `Tool call started: ${name}`;
2632
- }
2633
- return null;
2634
- }
2635
- function formatCursorToolCallCompleted(toolCall) {
2636
- const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
2637
- const writePath = stringField(writeArgs, "path");
2638
- const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
2639
- const writtenPath = stringField(writeResult, "path") ?? writePath;
2640
- if (writtenPath) {
2641
- return {
2642
- kind: "file_edit",
2643
- content: `Wrote ${writtenPath}`
2644
- };
2645
- }
2646
- const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
2647
- const readPath = stringField(readArgs, "path");
2648
- if (readPath) {
2649
- const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
2650
- const totalLines = readResult.totalLines;
2651
- const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
2652
- return {
2653
- kind: "checkpoint",
2654
- content: `Read ${readPath}${lineSummary}`
2655
- };
2656
- }
2657
- const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
2658
- const command = stringField(shellArgs, "command");
2659
- if (command) {
2660
- return {
2661
- kind: "checkpoint",
2662
- content: `Shell command completed: ${clip(command, 500)}`
2663
- };
2664
- }
2665
- const fn = objectField(toolCall, "function");
2666
- const name = stringField(fn, "name");
2667
- if (name) {
2668
- return {
2669
- kind: "checkpoint",
2670
- content: `Tool call completed: ${name}`
2671
- };
2672
- }
2673
- return null;
2674
- }
2675
- function assistantMessageText(event) {
2676
- const message = objectField(event, "message");
2677
- const content = message.content;
2678
- if (!Array.isArray(content)) {
2679
- return null;
2680
- }
2681
- const parts = content
2682
- .map((entry) => {
2683
- if (!entry || typeof entry !== "object") {
2684
- return null;
2685
- }
2686
- const block = entry;
2687
- return stringField(block, "text");
2688
- })
2689
- .filter((text) => Boolean(text));
2690
- if (parts.length === 0) {
2691
- return null;
2692
- }
2693
- return parts.join("");
2694
- }
2695
- function parseJsonLine(line) {
2696
- const trimmed = line.trim();
2697
- if (!trimmed.startsWith("{")) {
2698
- return null;
2699
- }
2700
- let parsed;
2701
- try {
2702
- parsed = JSON.parse(trimmed);
2703
- }
2704
- catch {
2705
- return null;
2706
- }
2707
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
2708
- ? parsed
2709
- : null;
2710
- }
2711
- class CodexJsonState {
2712
- threadId = null;
2713
- finalMessage = null;
2714
- emittedThread = false;
2715
- accumulatedUsage = null;
2716
- get sessionLabel() {
2717
- return this.threadId ? `thread ${this.threadId}` : null;
2718
- }
2719
- get usage() {
2720
- return this.accumulatedUsage;
2721
- }
2722
- consume(line) {
2723
- const event = parseJsonLine(line);
2724
- if (!event) {
2725
- return [];
2726
- }
2727
- const type = stringField(event, "type") ?? "";
2728
- if (type === "thread.started") {
2729
- this.threadId = stringField(event, "thread_id");
2730
- if (this.threadId && !this.emittedThread) {
2731
- this.emittedThread = true;
2732
- return [{
2733
- role: "runner",
2734
- kind: "checkpoint",
2735
- content: `Codex thread started: ${this.threadId}.`,
2736
- eventType: "provider_thread_started"
2737
- }];
2738
- }
2739
- }
2740
- if (type === "turn.completed") {
2741
- this.accumulateUsage(event);
2742
- return [{
2743
- role: "runner",
2744
- kind: "checkpoint",
2745
- content: "Codex turn completed.",
2746
- eventType: "provider_turn_completed"
2747
- }];
2748
- }
2749
- if (type === "turn.failed" || type === "error") {
2750
- return [{
2751
- role: "runner",
2752
- kind: "error",
2753
- content: clip(line.trim(), 1000),
2754
- eventType: "provider_cli_error"
2755
- }];
2756
- }
2757
- if (type === "item.completed" || type === "item.updated") {
2758
- const item = objectField(event, "item");
2759
- const itemType = stringField(item, "type");
2760
- if (itemType === "agent_message") {
2761
- const text = stringField(item, "text");
2762
- if (text) {
2763
- this.finalMessage = text;
2764
- return [{
2765
- role: "assistant",
2766
- kind: "message",
2767
- content: clip(text, 4000),
2768
- eventType: "provider_message"
2769
- }];
2770
- }
2771
- }
2772
- if (itemType === "command_execution") {
2773
- const command = stringField(item, "command");
2774
- const status = stringField(item, "status");
2775
- if (command) {
2776
- return [{
2777
- role: "worker",
2778
- kind: "checkpoint",
2779
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2780
- eventType: "provider_command"
2781
- }];
2782
- }
2783
- }
2784
- }
2785
- const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2786
- if (mcpEvents.length > 0) {
2787
- return mcpEvents;
2788
- }
2789
- return [];
2790
- }
2791
- accumulateUsage(event) {
2792
- const usage = objectField(event, "usage");
2793
- if (Object.keys(usage).length === 0) {
2794
- return;
2795
- }
2796
- this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
2797
- inputTokens: readUsageNumber(usage, "input_tokens"),
2798
- outputTokens: readUsageNumber(usage, "output_tokens"),
2799
- cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
2800
- reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
2801
- source: "provider_reported"
2802
- });
2803
- }
2804
- }
2805
- function formatCodexMcpToolCallEvents(type, event) {
2806
- if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2807
- return [];
2808
- }
2809
- const item = objectField(event, "item");
2810
- const itemType = stringField(item, "type") ?? "";
2811
- const serverName = mcpServerName(item);
2812
- const toolName = mcpToolName(item);
2813
- const isMcpItem = itemType.toLowerCase().includes("mcp")
2814
- || Boolean(serverName)
2815
- || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2816
- if (!isMcpItem || !toolName) {
2817
- return [];
2818
- }
2819
- const status = normalizedString(stringField(item, "status")
2820
- ?? stringField(event, "status")
2821
- ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2822
- const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2823
- const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2824
- const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2825
- const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2826
- const label = `${serverName ?? "unknown"}.${toolName}`;
2827
- if (failed) {
2828
- const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2829
- const events = [{
2830
- role: "tool",
2831
- kind: "error",
2832
- content: `MCP tool call failed: ${label} - ${summary}`,
2833
- eventType: "provider_mcp_call_failed",
2834
- data
2835
- }];
2836
- if (isForgeCompletionTool(toolName)) {
2837
- events.push({
2838
- role: "tool",
2839
- kind: "error",
2840
- content: `Forge completion tool validation failed: ${label} - ${summary}`,
2841
- eventType: "completion_tool_validation_failed",
2842
- data
2843
- });
2844
- }
2845
- return events;
2846
- }
2847
- if (completed) {
2848
- return [{
2849
- role: "tool",
2850
- kind: "checkpoint",
2851
- content: `MCP tool call completed: ${label}.`,
2852
- eventType: "provider_mcp_call_completed",
2853
- data
2854
- }];
2855
- }
2856
- if (started) {
2857
- return [{
2858
- role: "tool",
2859
- kind: "checkpoint",
2860
- content: `MCP tool call started: ${label}.`,
2861
- eventType: "provider_mcp_call_started",
2862
- data
2863
- }];
2864
- }
2865
- return [];
2866
- }
2867
- function mcpServerName(item) {
2868
- return stringField(item, "server")
2869
- ?? stringField(item, "server_name")
2870
- ?? stringField(item, "mcp_server")
2871
- ?? stringField(objectField(item, "mcp"), "server")
2872
- ?? stringField(objectField(item, "mcp"), "server_name");
2873
- }
2874
- function mcpToolName(item) {
2875
- return stringField(item, "tool")
2876
- ?? stringField(item, "tool_name")
2877
- ?? stringField(item, "name")
2878
- ?? stringField(objectField(item, "function"), "name")
2879
- ?? stringField(objectField(item, "mcp"), "tool")
2880
- ?? stringField(objectField(item, "mcp"), "tool_name");
2881
- }
2882
- function mcpErrorSummary(item) {
2883
- const direct = stringField(item, "error")
2884
- ?? stringField(item, "error_message")
2885
- ?? stringField(item, "message");
2886
- if (direct) {
2887
- return clip(direct, 600);
2888
- }
2889
- const error = objectField(item, "error");
2890
- return stringField(error, "message")
2891
- ?? stringField(error, "summary")
2892
- ?? stringField(objectField(item, "result"), "error")
2893
- ?? null;
2894
- }
2895
- function safeProviderMcpData(item, serverName, toolName, status) {
2896
- const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2897
- return JSON.stringify(stripUndefined({
2898
- server_name: serverName,
2899
- tool_name: toolName,
2900
- status,
2901
- elapsed_ms: elapsedMs,
2902
- error_summary: mcpErrorSummary(item)
2903
- }));
2904
- }
2905
- function isForgeCompletionTool(toolName) {
2906
- const normalized = toolName.trim().toLowerCase();
2907
- return normalized.startsWith("forge.complete_")
2908
- || normalized.startsWith("complete_")
2909
- || normalized.includes("forge.complete_")
2910
- || normalized.includes("complete_architect_plan");
2911
- }
2912
- function objectField(source, key) {
2913
- const value = source[key];
2914
- return value && typeof value === "object" && !Array.isArray(value)
2915
- ? value
2916
- : {};
2917
- }
2918
- function stringField(source, key) {
2919
- const value = source[key];
2920
- return typeof value === "string" && value.trim().length > 0 ? value : null;
2921
- }
2922
- function numericField(source, key) {
2923
- const value = source[key];
2924
- return typeof value === "number" && Number.isFinite(value) ? value : null;
2925
- }
2926
- function stripUndefined(value) {
2927
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2928
- }
2929
- function normalizedString(value) {
2930
- return value.trim().toLowerCase().replace(/-/g, "_");
2931
- }
2932
- function isNodeError(error) {
2933
- return error instanceof Error && "code" in error;
2934
- }