@loucompanion/forge-bridge 0.1.3-dev.b6be5e7f9668 → 0.1.3-dev.bca7d0ccee53

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