@loucompanion/forge-bridge 0.1.4-dev.86fc5d1208e6 → 0.1.4-dev.894bcbd53d64

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 (269) hide show
  1. package/README.md +144 -3
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +101 -15
  16. package/dist/bridge/bridge.service.js +472 -345
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  19. package/dist/bridge/dispatch-result-outbox.js +31 -6
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +74 -12
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  56. package/dist/runtime/attempt-process-supervisor.d.ts +21 -0
  57. package/dist/runtime/attempt-process-supervisor.js +62 -6
  58. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  59. package/dist/runtime/docker-engine-probe.js +7 -0
  60. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  61. package/dist/runtime/dotnet-build-outputs.js +402 -0
  62. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  64. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  65. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  66. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  67. package/dist/runtime/host-database-capability-boundary.js +1 -0
  68. package/dist/runtime/host-facts.d.ts +36 -0
  69. package/dist/runtime/host-facts.js +95 -0
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +156 -0
  85. package/dist/runtime/host-load-sampler.js +298 -0
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  99. package/dist/runtime/host-pressure-stall.js +168 -0
  100. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  101. package/dist/runtime/host-runtime-contract.js +35 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  103. package/dist/runtime/host-runtime-lease.js +343 -67
  104. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  105. package/dist/runtime/host-runtime-promotion.js +48 -0
  106. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  107. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  108. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  109. package/dist/runtime/host-runtime-requirements.js +117 -0
  110. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  111. package/dist/runtime/managed-command-teardown.js +596 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  113. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  114. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  115. package/dist/runtime/playwright-browser-cache.js +227 -0
  116. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  117. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  118. package/dist/runtime/runner-settings.d.ts +104 -0
  119. package/dist/runtime/runner-settings.js +236 -0
  120. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  121. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  122. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  123. package/dist/sandbox/host-capacity-broker.js +336 -0
  124. package/dist/sandbox/managed-branch.d.ts +13 -0
  125. package/dist/sandbox/managed-branch.js +90 -0
  126. package/dist/sandbox/provider-auth/codex.js +11 -11
  127. package/dist/sandbox/runtime.d.ts +10 -1
  128. package/dist/sandbox/runtime.js +47 -8
  129. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  130. package/dist/sandbox/sandbox-cgroups.js +42 -0
  131. package/dist/session/architect-waits.d.ts +2 -0
  132. package/dist/session/architect-waits.js +138 -0
  133. package/dist/session/managed-attempt-tools.d.ts +27 -7
  134. package/dist/session/managed-attempt-tools.js +406 -123
  135. package/dist/session/managed-build-coordinator.d.ts +17 -1
  136. package/dist/session/managed-build-coordinator.js +14 -1
  137. package/dist/session/managed-build-receipt.d.ts +5 -0
  138. package/dist/session/managed-build-receipt.js +8 -3
  139. package/dist/session/managed-command-host-load.d.ts +47 -0
  140. package/dist/session/managed-command-host-load.js +83 -0
  141. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  142. package/dist/session/mcp-argument-coercion.js +121 -0
  143. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  144. package/dist/session/phase-completion.artifacts.js +100 -26
  145. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  146. package/dist/session/phase-completion.command-validation.js +77 -0
  147. package/dist/session/phase-completion.d.ts +12 -0
  148. package/dist/session/phase-completion.helpers.js +13 -12
  149. package/dist/session/phase-completion.js +5 -0
  150. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  151. package/dist/session/phase-completion.mcp-args.js +156 -0
  152. package/dist/session/phase-completion.prompts.js +6 -1
  153. package/dist/session/phase-completion.runtime.d.ts +5 -11
  154. package/dist/session/phase-completion.runtime.js +111 -230
  155. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  156. package/dist/session/phase-completion.schema-parts.js +188 -0
  157. package/dist/session/phase-completion.schemas.d.ts +3 -3
  158. package/dist/session/phase-completion.schemas.js +208 -231
  159. package/dist/session/phase-completion.validation.d.ts +2 -3
  160. package/dist/session/phase-completion.validation.js +49 -93
  161. package/dist/session/pre-publication-host-load.d.ts +27 -0
  162. package/dist/session/pre-publication-host-load.js +111 -0
  163. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  164. package/dist/session/pre-publication-native-postgres.js +111 -0
  165. package/dist/session/pre-publication-pass.d.ts +61 -0
  166. package/dist/session/pre-publication-pass.js +148 -0
  167. package/dist/session/pre-publication-process.d.ts +23 -0
  168. package/dist/session/pre-publication-process.js +109 -0
  169. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  170. package/dist/session/pre-publication-skipped-tests.js +109 -0
  171. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  172. package/dist/session/pre-publication-step-execution.js +50 -0
  173. package/dist/session/pre-publication-validation.d.ts +37 -21
  174. package/dist/session/pre-publication-validation.js +228 -219
  175. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  176. package/dist/session/provider-cli/claude-background-work.js +181 -0
  177. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  178. package/dist/session/provider-cli/host-build-lock.js +30 -0
  179. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  180. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  181. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  182. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  183. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  184. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  185. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  186. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  187. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  188. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  189. package/dist/session/provider-cli/provider-cli.process.d.ts +46 -31
  190. package/dist/session/provider-cli/provider-cli.process.js +286 -403
  191. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  192. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  193. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  195. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  196. package/dist/session/provider-cli/provider-cli.service.js +207 -192
  197. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  198. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  199. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  200. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  201. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  202. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  203. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  204. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  205. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  206. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  207. package/dist/session/provider-cli/provider-output-state.js +15 -0
  208. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  209. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  210. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  211. package/dist/session/publishable-worktree-changes.js +193 -0
  212. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  213. package/dist/session/qa-sidecar-validation.js +28 -0
  214. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  215. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  216. package/dist/session/session-redaction.js +31 -181
  217. package/dist/session/session.base.d.ts +9 -1
  218. package/dist/session/session.service.d.ts +11 -2
  219. package/dist/session/session.service.js +189 -69
  220. package/dist/session/session.types.d.ts +3 -0
  221. package/dist/session/session.types.js +15 -3
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  225. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  226. package/dist/shared/fs/file-identity.d.ts +10 -0
  227. package/dist/shared/fs/file-identity.js +15 -0
  228. package/dist/shared/fs/replace-file.d.ts +7 -0
  229. package/dist/shared/fs/replace-file.js +33 -0
  230. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  231. package/dist/shared/process/host-process-recovery.js +23 -3
  232. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  233. package/dist/shared/process/host-process-supervisor.js +67 -15
  234. package/dist/shared/process/process-tree.d.ts +52 -0
  235. package/dist/shared/process/process-tree.js +144 -0
  236. package/dist/shared/process/process.d.ts +67 -0
  237. package/dist/shared/process/process.js +213 -11
  238. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  239. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  240. package/dist/shared/process/windows-launch.d.ts +18 -0
  241. package/dist/shared/process/windows-launch.js +68 -0
  242. package/dist/shared/provider-capabilities.js +14 -7
  243. package/dist/version.d.ts +1 -1
  244. package/dist/version.js +1 -1
  245. package/dist/worktree/dependency-warmer.d.ts +25 -0
  246. package/dist/worktree/dependency-warmer.js +120 -10
  247. package/dist/worktree/orphan-relink.d.ts +19 -0
  248. package/dist/worktree/orphan-relink.js +106 -0
  249. package/dist/worktree/wip-git.d.ts +33 -0
  250. package/dist/worktree/wip-git.js +122 -0
  251. package/dist/worktree/wip-refs.d.ts +62 -0
  252. package/dist/worktree/wip-refs.js +119 -0
  253. package/dist/worktree/wip-restore.d.ts +38 -0
  254. package/dist/worktree/wip-restore.js +190 -0
  255. package/dist/worktree/wip-snapshot.d.ts +50 -0
  256. package/dist/worktree/wip-snapshot.js +268 -0
  257. package/dist/worktree/worktree-inputs.d.ts +8 -0
  258. package/dist/worktree/worktree-inputs.js +134 -0
  259. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  260. package/dist/worktree/worktree-origin-sync.js +127 -0
  261. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  262. package/dist/worktree/worktree-wip-events.js +98 -0
  263. package/dist/worktree/worktree-wip.d.ts +50 -0
  264. package/dist/worktree/worktree-wip.js +185 -0
  265. package/dist/worktree/worktree.base.d.ts +7 -1
  266. package/dist/worktree/worktree.service.d.ts +36 -5
  267. package/dist/worktree/worktree.service.js +124 -155
  268. package/dist/worktree/worktree.types.d.ts +38 -0
  269. package/package.json +2 -2
@@ -2,12 +2,14 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, qaCompletionGateOrder, readCompletionArtifact } from "../phase-completion.js";
4
4
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
5
+ import { isRuntimeOnlyPath, stagePublishableWorktreeChangeSet } from "../publishable-worktree-changes.js";
6
+ import { providerCompletionToolMissingFailure } from "./provider-cli.process.js";
5
7
  import { hasLaunchTarget } from "./provider-cli.qa-sidecars.js";
6
8
  import { clip, isNodeError, messageFromError, normalizedString, parseJsonLine, stringField } from "./provider-output-state.js";
9
+ import { assertMergeResolutionPreservesUpstreamChanges, isMergeInProgress, mergeResolutionCommitNotes } from "./provider-cli.merge-integrity.js";
7
10
  const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
8
11
  const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
9
12
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
10
- const nonPublishableWorktreePaths = [".forge", ".local"];
11
13
  export async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
12
14
  const draftArtifactFiles = {
13
15
  draft_intent: "draft.intent.json",
@@ -150,21 +152,25 @@ export async function cleanupCompletionTools(completionTools, emit) {
150
152
  }
151
153
  export async function commitWorktreeChanges(git, worktreePath, workItemId, alreadyStagedChangedFiles) {
152
154
  const changedFiles = alreadyStagedChangedFiles ?? await stagePublishableWorktreeChanges(git, worktreePath);
153
- if (changedFiles.length > 0) {
154
- await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
155
+ const mergeReport = await assertMergeResolutionPreservesUpstreamChanges(git, worktreePath, { ignorePath: isRuntimeOnlyPath });
156
+ // A merge is always finalized, even when every change it brought is unpublishable
157
+ // runtime output; skipping the commit would leave MERGE_HEAD dangling.
158
+ const merging = await isMergeInProgress(git, worktreePath);
159
+ if (changedFiles.length > 0 || merging) {
160
+ const notes = mergeResolutionCommitNotes(mergeReport).flatMap(note => ["-m", note]);
161
+ await git.run(worktreePath, [
162
+ "commit",
163
+ ...(changedFiles.length === 0 ? ["--allow-empty"] : []),
164
+ "-m",
165
+ `provider cli changeset for ${workItemId.slice(0, 8)}`,
166
+ ...notes,
167
+ ]);
155
168
  }
156
169
  const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
157
170
  return { commitSha, changedFiles };
158
171
  }
159
172
  export async function stagePublishableWorktreeChanges(git, worktreePath) {
160
- await git.run(worktreePath, ["add", "-A"]);
161
- for (const reservedPath of nonPublishableWorktreePaths) {
162
- await git.run(worktreePath, ["reset", "--", reservedPath]).catch(() => "");
163
- }
164
- return (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
165
- .split(/\r?\n/)
166
- .map((line) => line.trim())
167
- .filter(Boolean);
173
+ return (await stagePublishableWorktreeChangeSet(git, worktreePath)).publishable;
168
174
  }
169
175
  export function phaseCompleteEventType(phase) {
170
176
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
@@ -779,11 +785,11 @@ export class LiveCompletionArtifactEmitter {
779
785
  }
780
786
  }
781
787
  }
782
- export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
788
+ export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle, providerResult) {
783
789
  if (!developCycle && !debugCycle) {
784
790
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
785
791
  if (!artifact) {
786
- throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
792
+ throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${phase} completion tool.`, providerResult);
787
793
  }
788
794
  return [artifact];
789
795
  }
@@ -795,11 +801,11 @@ export async function readCompletionArtifactsForRun(worktreePath, workItemId, ph
795
801
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
796
802
  if (!artifact) {
797
803
  if (artifacts.length === 0) {
798
- throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
804
+ throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
799
805
  }
800
806
  const previous = artifacts[artifacts.length - 1];
801
807
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
802
- throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
808
+ throw providerCompletionToolMissingFailure(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
803
809
  }
804
810
  return artifacts;
805
811
  }
@@ -0,0 +1,7 @@
1
+ export interface ProviderChildEnvironmentOptions {
2
+ readonly parentEnv?: NodeJS.ProcessEnv;
3
+ readonly platform?: NodeJS.Platform;
4
+ readonly homeDir?: string;
5
+ readonly arch?: string;
6
+ }
7
+ export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
@@ -0,0 +1,75 @@
1
+ import os from "node:os";
2
+ import { normalizeWindowsProviderEnvironment, windowsAllowedProviderParentEnvNames } from "./provider-cli.windows-environment.js";
3
+ // The environment a provider child process starts with: an allowlist of the Bridge's own
4
+ // variables, the request's values, the Windows defaults, then the .NET build-server settings.
5
+ // CLAUDE_CONFIG_DIR is not passed: it would point Claude Code at a user configuration directory
6
+ // of the host's choosing (provider-user-config-isolation.ts). Claude signs in from the provider
7
+ // home's default `.claude` directory under HOME or USERPROFILE, or with a Forge-granted API key.
8
+ const allowedProviderParentEnvNames = [
9
+ "PATH",
10
+ "HOME",
11
+ "USERPROFILE",
12
+ "TMPDIR",
13
+ "TEMP",
14
+ "TMP",
15
+ "LANG"
16
+ ];
17
+ export function buildProviderChildEnvironment(requestEnv, options = {}) {
18
+ const parentEnv = options.parentEnv ?? process.env;
19
+ const platform = options.platform ?? process.platform;
20
+ const env = {};
21
+ for (const [key, value] of Object.entries(parentEnv)) {
22
+ if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
23
+ env[key] = value;
24
+ }
25
+ }
26
+ if (requestEnv) {
27
+ for (const [key, value] of Object.entries(requestEnv)) {
28
+ const trimmedKey = key.trim();
29
+ if (trimmedKey.length > 0) {
30
+ env[trimmedKey] = value;
31
+ }
32
+ }
33
+ }
34
+ if (platform === "win32") {
35
+ normalizeWindowsProviderEnvironment(env, parentEnv, options.homeDir ?? os.homedir(), options.arch ?? os.arch());
36
+ }
37
+ normalizeProviderBuildEnvironment(env);
38
+ return env;
39
+ }
40
+ function normalizeProviderBuildEnvironment(env) {
41
+ // Provider sessions are long lived and commonly run many dotnet builds. Persistent
42
+ // MSBuild and Roslyn compiler servers otherwise survive individual commands and can
43
+ // retain more memory than the active Forge lane. Keep those caches process-scoped by
44
+ // default on every runner OS; an explicitly supplied request value still wins.
45
+ setCanonicalProviderBuildEnvironmentValue(env, "DOTNET_CLI_USE_MSBUILD_SERVER", "0");
46
+ setCanonicalProviderBuildEnvironmentValue(env, "MSBUILDDISABLENODEREUSE", "1");
47
+ setCanonicalProviderBuildEnvironmentValue(env, "UseSharedCompilation", "false");
48
+ }
49
+ function setCanonicalProviderBuildEnvironmentValue(env, name, value) {
50
+ // The dotnet CLI uses case-sensitive environment lookup on POSIX, while MSBuild
51
+ // property names are case-insensitive on every OS. Collapse request aliases to
52
+ // one canonical key so the explicit value wins without producing ambiguity.
53
+ const exact = env[name];
54
+ const alias = Object.entries(env).find(([key, candidate]) => key !== name
55
+ && key.toLowerCase() === name.toLowerCase()
56
+ && typeof candidate === "string"
57
+ && candidate.trim().length > 0)?.[1];
58
+ const resolved = typeof exact === "string" && exact.trim().length > 0
59
+ ? exact
60
+ : alias ?? value;
61
+ for (const key of Object.keys(env)) {
62
+ if (key !== name && key.toLowerCase() === name.toLowerCase()) {
63
+ delete env[key];
64
+ }
65
+ }
66
+ env[name] = resolved;
67
+ }
68
+ function isAllowedProviderParentEnv(key, platform = process.platform) {
69
+ return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
70
+ || key.toUpperCase().startsWith("LC_")
71
+ || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
72
+ }
73
+ function isAllowedProviderParentEnvName(key, allowedNames) {
74
+ return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
75
+ }
@@ -0,0 +1,3 @@
1
+ import type { ProviderProcessRunResult } from "./provider-cli.process.js";
2
+ export declare function isCodexModelsCacheSchemaFailure(result: ProviderProcessRunResult): boolean;
3
+ export declare function quarantineIncompatibleCodexModelsCache(requestEnv?: Readonly<Record<string, string>>): Promise<boolean>;
@@ -0,0 +1,37 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { readEnvironmentValue } from "./provider-cli.windows-environment.js";
6
+ const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
7
+ export function isCodexModelsCacheSchemaFailure(result) {
8
+ const output = `${result.stderr}\n${result.stdout}`.toLowerCase();
9
+ return output.includes("base_instructions")
10
+ && output.includes("missing field")
11
+ && (output.includes("models_cache") || output.includes("models cache") || output.includes("model cache"));
12
+ }
13
+ export async function quarantineIncompatibleCodexModelsCache(requestEnv) {
14
+ const configuredHome = readEnvironmentValue(requestEnv ?? {}, "CODEX_HOME")
15
+ ?? readEnvironmentValue(process.env, "CODEX_HOME")
16
+ ?? readEnvironmentValue(process.env, "FORGE_CODEX_HOME");
17
+ const codexHome = path.resolve(configuredHome ?? path.join(os.homedir(), ".codex"));
18
+ if (!path.isAbsolute(codexHome) || codexHome === path.parse(codexHome).root)
19
+ return false;
20
+ const cachePath = path.join(codexHome, "models_cache.json");
21
+ const cacheStat = await fs.promises.lstat(cachePath).catch(error => {
22
+ if (error.code === "ENOENT")
23
+ return null;
24
+ throw error;
25
+ });
26
+ if (!cacheStat
27
+ || !cacheStat.isFile()
28
+ || cacheStat.isSymbolicLink()
29
+ || cacheStat.nlink !== 1
30
+ || cacheStat.size <= 0
31
+ || cacheStat.size > maximumRecoverableCodexModelsCacheBytes) {
32
+ return false;
33
+ }
34
+ const quarantinePath = path.join(codexHome, `models_cache.forge-incompatible-${Date.now()}-${randomUUID()}.json`);
35
+ await fs.promises.rename(cachePath, quarantinePath);
36
+ return true;
37
+ }
@@ -0,0 +1,89 @@
1
+ import type { GitClient } from "../../shared/git/git.js";
2
+ import { ForgeFailureError } from "../session.types.js";
3
+ /**
4
+ * Publication guards for a provider-run `git merge --no-commit` that Forge Bridge
5
+ * turns into the final merge commit (the conflict-resolve lane, and any repair
6
+ * lane that merges the target branch).
7
+ *
8
+ * Forge stages with `git add -A` and then unstages worktree-local runtime paths
9
+ * such as `.forge` and `.local`. Unstaging resets those paths to HEAD, which is
10
+ * the story side of the merge. Without these guards that silently reverted every
11
+ * upstream change under those paths and re-added files the target branch had
12
+ * deleted (issue #491: 253 files on story/829e1219ee16 and story/6ac8c6c6e704).
13
+ */
14
+ type GitRunner = Pick<GitClient, "run">;
15
+ export interface InProgressMerge {
16
+ readonly headSha: string;
17
+ readonly mergeHeadSha: string;
18
+ readonly mergeBaseSha: string;
19
+ }
20
+ export interface MergeResolutionReport {
21
+ /**
22
+ * Paths the target branch deleted that the story had changed and that the
23
+ * resolution keeps. These are deliberate modify/delete decisions, recorded in
24
+ * the merge commit message so reviewers see them.
25
+ */
26
+ readonly keptOverUpstreamDeletion: readonly string[];
27
+ }
28
+ export type UnresolvedMergeConflictKind = "deleted_by_upstream" | "deleted_by_story" | "missing_while_unmerged" | "unresolved_binary" | "conflict_markers";
29
+ export interface UnresolvedMergeConflict {
30
+ readonly path: string;
31
+ readonly kind: UnresolvedMergeConflictKind;
32
+ }
33
+ /**
34
+ * The publication would re-add files that the target branch deleted, or revert
35
+ * target-branch edits, on paths the story never changed. Forge refuses to commit
36
+ * or push such a merge.
37
+ */
38
+ export declare class MergeResolutionRevertsUpstreamChangesError extends ForgeFailureError {
39
+ readonly merge: InProgressMerge;
40
+ readonly resurrectedPaths: readonly string[];
41
+ readonly revertedPaths: readonly string[];
42
+ readonly code = "merge_resolution_reverts_upstream_changes";
43
+ constructor(merge: InProgressMerge, resurrectedPaths: readonly string[], revertedPaths: readonly string[]);
44
+ }
45
+ /**
46
+ * A conflict is still unresolved when Forge would stage the merge: a
47
+ * modify/delete conflict nobody decided (`git add -A` would silently keep the
48
+ * modified side), or a content conflict whose file still has conflict markers
49
+ * (`git add -A` would commit them).
50
+ */
51
+ export declare class MergeResolutionUnresolvedConflictError extends ForgeFailureError {
52
+ readonly conflicts: readonly UnresolvedMergeConflict[];
53
+ readonly code = "merge_resolution_unresolved_conflict";
54
+ constructor(conflicts: readonly UnresolvedMergeConflict[]);
55
+ }
56
+ /** True while MERGE_HEAD exists, whether or not the histories share a merge base. */
57
+ export declare function isMergeInProgress(git: GitRunner, worktreePath: string): Promise<boolean>;
58
+ export declare function readInProgressMerge(git: GitRunner, worktreePath: string): Promise<InProgressMerge | null>;
59
+ /**
60
+ * Fails before `git add -A` can silently resolve a conflict:
61
+ * - a modify/delete conflict, by keeping whatever is on disk;
62
+ * - a binary (or other marker-less) conflict, by staging whichever side is on disk;
63
+ * - a content conflict, by staging its conflict markers. This includes markers
64
+ * the provider already staged, which clears the unmerged stages, so every path
65
+ * both sides changed is checked too.
66
+ * A text conflict the agent resolved in the working tree without `git add` is
67
+ * still unmerged here and is accepted once its markers are gone.
68
+ */
69
+ export declare function assertNoUnresolvedMergeConflicts(git: GitRunner, worktreePath: string): Promise<void>;
70
+ export declare function readUnresolvedMergeConflicts(git: GitRunner, worktreePath: string, merge: InProgressMerge): Promise<readonly UnresolvedMergeConflict[]>;
71
+ /**
72
+ * Staging excludes some worktree changes (Forge runtime output) by unstaging them
73
+ * back to HEAD. During a merge HEAD is the story side, so an excluded path the merge
74
+ * itself changed would lose the target's change. Given the excluded candidate
75
+ * paths, put the merge-owned ones back into the index: the target branch's version
76
+ * where the story never touched the path, and the agent's working-tree resolution
77
+ * where both sides changed it. Returns the restored paths; the rest stay excluded.
78
+ */
79
+ export declare function restoreMergeOwnedPaths(git: GitRunner, worktreePath: string, candidatePaths: readonly string[]): Promise<readonly string[]>;
80
+ /**
81
+ * Final check on the index Forge is about to commit. Throws when the merge
82
+ * resolution re-adds a path the target branch deleted, or drops a target-branch
83
+ * edit, on a path the story never changed.
84
+ */
85
+ export declare function assertMergeResolutionPreservesUpstreamChanges(git: GitRunner, worktreePath: string, options?: {
86
+ readonly ignorePath?: (filePath: string) => boolean;
87
+ }): Promise<MergeResolutionReport>;
88
+ export declare function mergeResolutionCommitNotes(report: MergeResolutionReport): readonly string[];
89
+ export {};
@@ -0,0 +1,310 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { ForgeFailureError } from "../session.types.js";
4
+ const maxListedPaths = 20;
5
+ const pathArgumentChunkSize = 100;
6
+ const objectIdPattern = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/iu;
7
+ /**
8
+ * The publication would re-add files that the target branch deleted, or revert
9
+ * target-branch edits, on paths the story never changed. Forge refuses to commit
10
+ * or push such a merge.
11
+ */
12
+ export class MergeResolutionRevertsUpstreamChangesError extends ForgeFailureError {
13
+ merge;
14
+ resurrectedPaths;
15
+ revertedPaths;
16
+ code = "merge_resolution_reverts_upstream_changes";
17
+ constructor(merge, resurrectedPaths, revertedPaths) {
18
+ super("merge_resolution_reverts_upstream_changes", describeRevertedUpstreamChanges(merge, resurrectedPaths, revertedPaths), "bridge");
19
+ this.merge = merge;
20
+ this.resurrectedPaths = resurrectedPaths;
21
+ this.revertedPaths = revertedPaths;
22
+ this.name = "MergeResolutionRevertsUpstreamChangesError";
23
+ }
24
+ }
25
+ /**
26
+ * A conflict is still unresolved when Forge would stage the merge: a
27
+ * modify/delete conflict nobody decided (`git add -A` would silently keep the
28
+ * modified side), or a content conflict whose file still has conflict markers
29
+ * (`git add -A` would commit them).
30
+ */
31
+ export class MergeResolutionUnresolvedConflictError extends ForgeFailureError {
32
+ conflicts;
33
+ code = "merge_resolution_unresolved_conflict";
34
+ constructor(conflicts) {
35
+ super("merge_resolution_unresolved_conflict", `merge_resolution_unresolved_conflict: ${conflicts.length} merge conflict(s) were left unresolved: ${listPaths(conflicts.map(conflict => `${conflict.path} (${conflict.kind.replaceAll("_", " ")})`))}. Resolve content conflicts by removing every conflict marker, and resolve each modify/delete or binary conflict explicitly with \`git rm <path>\` to accept the deletion or \`git add <path>\` to stage the chosen file; Forge did not commit or push the merge.`, "bridge");
36
+ this.conflicts = conflicts;
37
+ this.name = "MergeResolutionUnresolvedConflictError";
38
+ }
39
+ }
40
+ /** True while MERGE_HEAD exists, whether or not the histories share a merge base. */
41
+ export async function isMergeInProgress(git, worktreePath) {
42
+ return await tryRevParse(git, worktreePath, "MERGE_HEAD") !== null;
43
+ }
44
+ export async function readInProgressMerge(git, worktreePath) {
45
+ const mergeHeadSha = await tryRevParse(git, worktreePath, "MERGE_HEAD");
46
+ if (!mergeHeadSha)
47
+ return null;
48
+ const headSha = await tryRevParse(git, worktreePath, "HEAD");
49
+ if (!headSha)
50
+ return null;
51
+ let mergeBaseSha;
52
+ try {
53
+ mergeBaseSha = (await git.run(worktreePath, ["merge-base", headSha, mergeHeadSha])).trim();
54
+ }
55
+ catch {
56
+ // Unrelated histories have no merge base, so there is no upstream deletion to protect.
57
+ return null;
58
+ }
59
+ if (!objectIdPattern.test(mergeBaseSha))
60
+ return null;
61
+ return { headSha, mergeHeadSha, mergeBaseSha };
62
+ }
63
+ /**
64
+ * Fails before `git add -A` can silently resolve a conflict:
65
+ * - a modify/delete conflict, by keeping whatever is on disk;
66
+ * - a binary (or other marker-less) conflict, by staging whichever side is on disk;
67
+ * - a content conflict, by staging its conflict markers. This includes markers
68
+ * the provider already staged, which clears the unmerged stages, so every path
69
+ * both sides changed is checked too.
70
+ * A text conflict the agent resolved in the working tree without `git add` is
71
+ * still unmerged here and is accepted once its markers are gone.
72
+ */
73
+ export async function assertNoUnresolvedMergeConflicts(git, worktreePath) {
74
+ const merge = await readInProgressMerge(git, worktreePath);
75
+ if (!merge)
76
+ return;
77
+ const conflicts = await readUnresolvedMergeConflicts(git, worktreePath, merge);
78
+ if (conflicts.length > 0) {
79
+ throw new MergeResolutionUnresolvedConflictError(conflicts);
80
+ }
81
+ }
82
+ export async function readUnresolvedMergeConflicts(git, worktreePath, merge) {
83
+ const stagesByPath = new Map();
84
+ for (const record of splitNul(await git.run(worktreePath, ["ls-files", "--unmerged", "-z"]))) {
85
+ const tab = record.indexOf("\t");
86
+ if (tab < 0)
87
+ continue;
88
+ const stage = record.slice(0, tab).trim().split(/\s+/u).at(-1) ?? "";
89
+ const filePath = record.slice(tab + 1);
90
+ const stages = stagesByPath.get(filePath) ?? new Set();
91
+ stages.add(stage);
92
+ stagesByPath.set(filePath, stages);
93
+ }
94
+ const conflicts = [];
95
+ const contentConflicts = [];
96
+ for (const [filePath, stages] of stagesByPath) {
97
+ const ours = stages.has("2");
98
+ const theirs = stages.has("3");
99
+ if (stages.has("1") && ours && !theirs)
100
+ conflicts.push({ path: filePath, kind: "deleted_by_upstream" });
101
+ else if (stages.has("1") && theirs && !ours)
102
+ conflicts.push({ path: filePath, kind: "deleted_by_story" });
103
+ else
104
+ contentConflicts.push(filePath);
105
+ }
106
+ const binaryByAttributes = await readBinaryByAttributes(git, worktreePath, contentConflicts);
107
+ for (const filePath of contentConflicts) {
108
+ const content = await readWorkingFile(worktreePath, filePath);
109
+ // `git add -A` would stage a missing file as a deletion and clear the conflict
110
+ // stages; only an explicit `git rm` or `git add` resolves it.
111
+ if (!content)
112
+ conflicts.push({ path: filePath, kind: "missing_while_unmerged" });
113
+ // Git writes no markers into a binary conflict (by content, or via `-merge` /
114
+ // `merge=binary`, as the `binary` macro sets), so only an explicit `git add` resolves it.
115
+ else if (binaryByAttributes.has(filePath) || isBinary(content))
116
+ conflicts.push({ path: filePath, kind: "unresolved_binary" });
117
+ else if (hasConflictMarkers(content))
118
+ conflicts.push({ path: filePath, kind: "conflict_markers" });
119
+ }
120
+ const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
121
+ const bothChanged = (await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]))
122
+ .filter(filePath => storyChanged.has(filePath) && !stagesByPath.has(filePath));
123
+ for (const filePath of bothChanged) {
124
+ const content = await readWorkingFile(worktreePath, filePath);
125
+ if (content && !isBinary(content) && hasConflictMarkers(content)) {
126
+ conflicts.push({ path: filePath, kind: "conflict_markers" });
127
+ }
128
+ }
129
+ return conflicts.sort((left, right) => left.path.localeCompare(right.path));
130
+ }
131
+ /**
132
+ * Staging excludes some worktree changes (Forge runtime output) by unstaging them
133
+ * back to HEAD. During a merge HEAD is the story side, so an excluded path the merge
134
+ * itself changed would lose the target's change. Given the excluded candidate
135
+ * paths, put the merge-owned ones back into the index: the target branch's version
136
+ * where the story never touched the path, and the agent's working-tree resolution
137
+ * where both sides changed it. Returns the restored paths; the rest stay excluded.
138
+ */
139
+ export async function restoreMergeOwnedPaths(git, worktreePath, candidatePaths) {
140
+ if (candidatePaths.length === 0)
141
+ return [];
142
+ const merge = await readInProgressMerge(git, worktreePath);
143
+ if (!merge)
144
+ return [];
145
+ const candidates = new Set(candidatePaths);
146
+ const upstreamChanged = (await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]))
147
+ .filter(filePath => candidates.has(filePath));
148
+ if (upstreamChanged.length === 0)
149
+ return [];
150
+ const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
151
+ const upstreamOnly = upstreamChanged.filter(filePath => !storyChanged.has(filePath));
152
+ const bothChanged = upstreamChanged.filter(filePath => storyChanged.has(filePath));
153
+ for (const chunk of chunks(upstreamOnly)) {
154
+ // Resetting from MERGE_HEAD also removes index entries the target branch deleted.
155
+ await git.run(worktreePath, ["--literal-pathspecs", "reset", "-q", merge.mergeHeadSha, "--", ...chunk]);
156
+ }
157
+ const indexed = new Set();
158
+ for (const chunk of chunks(bothChanged)) {
159
+ for (const filePath of splitNul(await git.run(worktreePath, ["--literal-pathspecs", "ls-files", "-z", "--", ...chunk]))) {
160
+ indexed.add(filePath);
161
+ }
162
+ }
163
+ const stageable = [];
164
+ for (const filePath of bothChanged) {
165
+ if (indexed.has(filePath) || await existsOnDisk(worktreePath, filePath))
166
+ stageable.push(filePath);
167
+ }
168
+ for (const chunk of chunks(stageable)) {
169
+ await git.run(worktreePath, ["--literal-pathspecs", "add", "-A", "--", ...chunk]);
170
+ }
171
+ return [...upstreamOnly, ...stageable].sort();
172
+ }
173
+ /**
174
+ * Final check on the index Forge is about to commit. Throws when the merge
175
+ * resolution re-adds a path the target branch deleted, or drops a target-branch
176
+ * edit, on a path the story never changed.
177
+ */
178
+ export async function assertMergeResolutionPreservesUpstreamChanges(git, worktreePath, options = {}) {
179
+ const merge = await readInProgressMerge(git, worktreePath);
180
+ if (!merge)
181
+ return { keptOverUpstreamDeletion: [] };
182
+ const upstream = await diffNameStatus(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]);
183
+ if (upstream.size === 0)
184
+ return { keptOverUpstreamDeletion: [] };
185
+ const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
186
+ // Index compared with the merge base: a path absent here is identical to the base.
187
+ const indexVersusBase = await diffNameStatus(git, worktreePath, ["--cached", merge.mergeBaseSha]);
188
+ const resurrectedPaths = [];
189
+ const revertedPaths = [];
190
+ const keptOverUpstreamDeletion = [];
191
+ for (const [filePath, status] of upstream) {
192
+ // Runtime-only paths are never published, so the story's version stays by design.
193
+ if (options.ignorePath?.(filePath))
194
+ continue;
195
+ const indexStatus = indexVersusBase.get(filePath);
196
+ if (status === "D") {
197
+ const presentInIndex = indexStatus !== "D";
198
+ if (!presentInIndex)
199
+ continue;
200
+ if (storyChanged.has(filePath))
201
+ keptOverUpstreamDeletion.push(filePath);
202
+ else
203
+ resurrectedPaths.push(filePath);
204
+ continue;
205
+ }
206
+ // Equal to the base (undefined) or deleted: the target's edit is discarded. Other
207
+ // index content is a post-merge fixup on top of the target's version and is allowed.
208
+ if (!storyChanged.has(filePath) && (indexStatus === undefined || indexStatus === "D")) {
209
+ revertedPaths.push(filePath);
210
+ }
211
+ }
212
+ if (resurrectedPaths.length > 0 || revertedPaths.length > 0) {
213
+ throw new MergeResolutionRevertsUpstreamChangesError(merge, resurrectedPaths.sort(), revertedPaths.sort());
214
+ }
215
+ return { keptOverUpstreamDeletion: keptOverUpstreamDeletion.sort() };
216
+ }
217
+ export function mergeResolutionCommitNotes(report) {
218
+ if (report.keptOverUpstreamDeletion.length === 0)
219
+ return [];
220
+ return [
221
+ `Kept ${report.keptOverUpstreamDeletion.length} story-modified path(s) that the target branch deleted (modify/delete conflicts resolved by the agent):\n${report.keptOverUpstreamDeletion.map(filePath => `- ${filePath}`).join("\n")}`,
222
+ ];
223
+ }
224
+ function describeRevertedUpstreamChanges(merge, resurrectedPaths, revertedPaths) {
225
+ const parts = [];
226
+ if (resurrectedPaths.length > 0) {
227
+ parts.push(`re-adds ${resurrectedPaths.length} path(s) that ${merge.mergeHeadSha.slice(0, 12)} deleted and the story never changed: ${listPaths(resurrectedPaths)}`);
228
+ }
229
+ if (revertedPaths.length > 0) {
230
+ parts.push(`reverts or deletes ${revertedPaths.length} upstream edit(s) on path(s) the story never changed: ${listPaths(revertedPaths)}`);
231
+ }
232
+ return `merge_resolution_reverts_upstream_changes: the merge resolution ${parts.join("; and ")} (merge base ${merge.mergeBaseSha.slice(0, 12)}). Forge did not commit or push the merge.`;
233
+ }
234
+ function listPaths(paths) {
235
+ const listed = paths.slice(0, maxListedPaths).join(", ");
236
+ return paths.length > maxListedPaths ? `${listed}, and ${paths.length - maxListedPaths} more` : listed;
237
+ }
238
+ async function tryRevParse(git, worktreePath, ref) {
239
+ try {
240
+ const sha = (await git.run(worktreePath, ["rev-parse", "-q", "--verify", `${ref}^{commit}`])).trim();
241
+ return objectIdPattern.test(sha) ? sha : null;
242
+ }
243
+ catch {
244
+ return null;
245
+ }
246
+ }
247
+ async function diffNames(git, worktreePath, args) {
248
+ return splitNul(await git.run(worktreePath, ["diff", "--no-renames", "--name-only", "-z", ...args]));
249
+ }
250
+ async function diffNameStatus(git, worktreePath, args) {
251
+ const fields = splitNul(await git.run(worktreePath, ["diff", "--no-renames", "--name-status", "-z", ...args]));
252
+ const statuses = new Map();
253
+ for (let index = 0; index + 1 < fields.length; index += 2) {
254
+ statuses.set(fields[index + 1], fields[index].charAt(0));
255
+ }
256
+ return statuses;
257
+ }
258
+ function splitNul(output) {
259
+ return output.split("\0").filter(entry => entry.length > 0);
260
+ }
261
+ function chunks(paths) {
262
+ const result = [];
263
+ for (let index = 0; index < paths.length; index += pathArgumentChunkSize) {
264
+ result.push(paths.slice(index, index + pathArgumentChunkSize));
265
+ }
266
+ return result;
267
+ }
268
+ const conflictMarkerPattern = /^<{7}(?: |$)[\s\S]*^>{7}(?: |$)/mu;
269
+ function hasConflictMarkers(content) {
270
+ return conflictMarkerPattern.test(content.toString("utf8"));
271
+ }
272
+ /**
273
+ * Paths whose effective `merge` attribute selects Git's binary merge driver, which
274
+ * writes no conflict markers: `merge` unset (`-merge`, part of the `binary` macro) or
275
+ * `merge=binary`. `-text` and `-diff` do not change how Git merges, so they are ignored.
276
+ */
277
+ async function readBinaryByAttributes(git, worktreePath, filePaths) {
278
+ const binary = new Set();
279
+ for (const chunk of chunks(filePaths)) {
280
+ const fields = splitNul(await git.run(worktreePath, ["check-attr", "-z", "merge", "--", ...chunk]));
281
+ for (let index = 0; index + 2 < fields.length; index += 3) {
282
+ const [filePath, value] = [fields[index], fields[index + 2]];
283
+ if (value === "unset" || value === "binary")
284
+ binary.add(filePath);
285
+ }
286
+ }
287
+ return binary;
288
+ }
289
+ function isBinary(content) {
290
+ // Git's own heuristic: a NUL byte in the first 8000 bytes.
291
+ return content.subarray(0, 8000).includes(0);
292
+ }
293
+ async function readWorkingFile(worktreePath, filePath) {
294
+ try {
295
+ return await fs.readFile(path.join(worktreePath, ...filePath.split("/")));
296
+ }
297
+ catch {
298
+ // Missing on disk: `git add -A` stages a deletion, which the upstream-change guard checks.
299
+ return null;
300
+ }
301
+ }
302
+ async function existsOnDisk(worktreePath, filePath) {
303
+ try {
304
+ await fs.lstat(path.join(worktreePath, ...filePath.split("/")));
305
+ return true;
306
+ }
307
+ catch {
308
+ return false;
309
+ }
310
+ }