@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 0.1.4-dev.1ff37038366e

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