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

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