@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.028808a841c8

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 (185) hide show
  1. package/README.md +89 -3
  2. package/dist/bridge/bridge-chat.types.d.ts +111 -0
  3. package/dist/bridge/bridge-chat.types.js +401 -0
  4. package/dist/bridge/bridge.base.d.ts +4 -1
  5. package/dist/bridge/bridge.service.d.ts +83 -3
  6. package/dist/bridge/bridge.service.js +1609 -152
  7. package/dist/bridge/bridge.types.d.ts +52 -1
  8. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  9. package/dist/bridge/dispatch-result-outbox.js +87 -0
  10. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  11. package/dist/bridge/dispatch-result-worker.js +122 -0
  12. package/dist/bridge/internals.d.ts +2 -0
  13. package/dist/bridge/internals.js +1 -0
  14. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  15. package/dist/bridge/readiness-result-outbox.js +54 -0
  16. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  17. package/dist/bridge/readiness-result-worker.js +121 -0
  18. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  19. package/dist/bridge/runner-host-capabilities.js +93 -0
  20. package/dist/cleanup/cleanup.service.d.ts +1 -0
  21. package/dist/cleanup/cleanup.service.js +70 -9
  22. package/dist/cli/cli.help.js +4 -4
  23. package/dist/cli/cli.service.d.ts +14 -6
  24. package/dist/cli/cli.service.js +75 -16
  25. package/dist/cli/local-config.d.ts +1 -0
  26. package/dist/cli/local-config.js +4 -0
  27. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  28. package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
  29. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  30. package/dist/runtime/attempt-database-broker.js +390 -0
  31. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  32. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  33. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  34. package/dist/runtime/attempt-path-operation.js +94 -0
  35. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  36. package/dist/runtime/attempt-private-directory.js +54 -0
  37. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  38. package/dist/runtime/attempt-process-supervisor.js +144 -23
  39. package/dist/runtime/canonical-source-file.d.ts +3 -0
  40. package/dist/runtime/canonical-source-file.js +54 -0
  41. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  42. package/dist/runtime/docker-engine-probe.js +333 -0
  43. package/dist/runtime/generated-output-reset.d.ts +10 -0
  44. package/dist/runtime/generated-output-reset.js +62 -8
  45. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  46. package/dist/runtime/host-database-capability-boundary.js +63 -0
  47. package/dist/runtime/host-diagnostics.d.ts +11 -0
  48. package/dist/runtime/host-diagnostics.js +192 -0
  49. package/dist/runtime/host-execution-root.d.ts +4 -0
  50. package/dist/runtime/host-execution-root.js +39 -0
  51. package/dist/runtime/host-facts.d.ts +35 -0
  52. package/dist/runtime/host-facts.js +95 -0
  53. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  54. package/dist/runtime/host-listener-inspector.js +121 -60
  55. package/dist/runtime/host-load-sampler.d.ts +83 -0
  56. package/dist/runtime/host-load-sampler.js +164 -0
  57. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  58. package/dist/runtime/host-pressure-stall.js +121 -0
  59. package/dist/runtime/host-runtime-contract.d.ts +13 -1
  60. package/dist/runtime/host-runtime-contract.js +170 -55
  61. package/dist/runtime/host-runtime-lease.d.ts +92 -8
  62. package/dist/runtime/host-runtime-lease.js +1193 -120
  63. package/dist/runtime/host-runtime-promotion.d.ts +12 -3
  64. package/dist/runtime/host-runtime-promotion.js +59 -12
  65. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  66. package/dist/runtime/managed-command-teardown.js +607 -0
  67. package/dist/runtime/memory-capacity.d.ts +70 -0
  68. package/dist/runtime/memory-capacity.js +123 -0
  69. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  70. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  71. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  72. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  73. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  74. package/dist/runtime/pinned-directory-process.js +61 -0
  75. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  76. package/dist/runtime/pinned-source-directory.js +94 -0
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +12 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +100 -58
  81. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  82. package/dist/runtime/prepared-runtime-identity.js +218 -0
  83. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  84. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  85. package/dist/runtime/runtime-isolation-lease.js +4 -1
  86. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  87. package/dist/runtime/workspace-resource-estimator.js +174 -0
  88. package/dist/sandbox/preflight.d.ts +31 -1
  89. package/dist/sandbox/preflight.js +237 -51
  90. package/dist/sandbox/repository-lock.d.ts +2 -1
  91. package/dist/sandbox/repository-lock.js +19 -9
  92. package/dist/sandbox/runtime.d.ts +6 -1
  93. package/dist/sandbox/runtime.js +137 -107
  94. package/dist/sandbox/sandbox.types.d.ts +7 -0
  95. package/dist/sandbox/workspace.service.js +2 -0
  96. package/dist/session/managed-attempt-tools.d.ts +42 -1
  97. package/dist/session/managed-attempt-tools.js +692 -40
  98. package/dist/session/managed-build-coordinator.d.ts +5 -0
  99. package/dist/session/managed-build-coordinator.js +109 -0
  100. package/dist/session/managed-build-receipt.d.ts +21 -0
  101. package/dist/session/managed-build-receipt.js +337 -0
  102. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  103. package/dist/session/managed-verification-timeouts.js +17 -0
  104. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  105. package/dist/session/phase-completion.artifacts.js +228 -22
  106. package/dist/session/phase-completion.d.ts +11 -1
  107. package/dist/session/phase-completion.helpers.d.ts +5 -0
  108. package/dist/session/phase-completion.helpers.js +30 -7
  109. package/dist/session/phase-completion.js +14 -3
  110. package/dist/session/phase-completion.prompts.js +17 -18
  111. package/dist/session/phase-completion.runtime.d.ts +3 -1
  112. package/dist/session/phase-completion.runtime.js +148 -34
  113. package/dist/session/phase-completion.schemas.js +49 -2
  114. package/dist/session/phase-completion.validation.d.ts +1 -0
  115. package/dist/session/phase-completion.validation.js +111 -21
  116. package/dist/session/pre-publication-process.d.ts +20 -0
  117. package/dist/session/pre-publication-process.js +97 -0
  118. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  119. package/dist/session/pre-publication-skipped-tests.js +109 -0
  120. package/dist/session/pre-publication-validation.d.ts +75 -0
  121. package/dist/session/pre-publication-validation.js +631 -0
  122. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  123. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  124. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  125. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  126. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  127. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  128. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  129. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  131. package/dist/session/provider-cli/provider-cli.process.d.ts +80 -0
  132. package/dist/session/provider-cli/provider-cli.process.js +694 -28
  133. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  134. package/dist/session/provider-cli/provider-cli.prompts.js +151 -16
  135. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  136. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  138. package/dist/session/provider-cli/provider-cli.runtime.js +54 -3
  139. package/dist/session/provider-cli/provider-cli.service.d.ts +30 -5
  140. package/dist/session/provider-cli/provider-cli.service.js +858 -77
  141. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  143. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  144. package/dist/session/provider-cli/provider-output-state.d.ts +16 -0
  145. package/dist/session/provider-cli/provider-output-state.js +370 -17
  146. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  147. package/dist/session/provider-cli/provider-usage.js +28 -5
  148. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  149. package/dist/session/publishable-worktree-changes.js +193 -0
  150. package/dist/session/session-redaction.js +434 -9
  151. package/dist/session/session.service.js +145 -23
  152. package/dist/session/session.types.d.ts +147 -2
  153. package/dist/session/session.types.js +599 -7
  154. package/dist/session/unreferenced-exports.d.ts +12 -0
  155. package/dist/session/unreferenced-exports.js +59 -0
  156. package/dist/shared/format/format-bytes.d.ts +1 -0
  157. package/dist/shared/format/format-bytes.js +9 -0
  158. package/dist/shared/git/git.js +2 -1
  159. package/dist/shared/path/path.d.ts +1 -0
  160. package/dist/shared/path/path.js +18 -0
  161. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  162. package/dist/shared/process/dotnet-toolchain.js +307 -0
  163. package/dist/shared/process/host-process-recovery.js +3 -2
  164. package/dist/shared/process/host-process-supervisor.d.ts +2 -0
  165. package/dist/shared/process/host-process-supervisor.js +60 -11
  166. package/dist/shared/process/process.d.ts +2 -0
  167. package/dist/shared/process/process.js +12 -7
  168. package/dist/shared/provider-capabilities.d.ts +3 -0
  169. package/dist/shared/provider-capabilities.js +85 -0
  170. package/dist/shared/redaction/redaction.d.ts +1 -0
  171. package/dist/shared/redaction/redaction.js +39 -3
  172. package/dist/shared/time/monotonic.d.ts +1 -0
  173. package/dist/shared/time/monotonic.js +8 -0
  174. package/dist/version.d.ts +1 -1
  175. package/dist/version.js +1 -1
  176. package/dist/worktree/dependency-warmer.d.ts +41 -9
  177. package/dist/worktree/dependency-warmer.js +571 -22
  178. package/dist/worktree/index.d.ts +1 -1
  179. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  180. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  181. package/dist/worktree/worktree.service.d.ts +7 -0
  182. package/dist/worktree/worktree.service.js +253 -21
  183. package/dist/worktree/worktree.types.d.ts +7 -1
  184. package/package.json +7 -5
  185. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -2,10 +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";
10
+ const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
11
+ const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
7
12
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
8
- const nonPublishableWorktreePaths = [".forge", ".local"];
9
13
  export async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
10
14
  const draftArtifactFiles = {
11
15
  draft_intent: "draft.intent.json",
@@ -146,24 +150,28 @@ export async function cleanupCompletionTools(completionTools, emit) {
146
150
  }).catch(() => undefined);
147
151
  }
148
152
  }
149
- export async function commitWorktreeChanges(git, worktreePath, workItemId) {
150
- await git.run(worktreePath, ["add", "-A"]);
151
- for (const reservedPath of nonPublishableWorktreePaths) {
152
- await git.run(worktreePath, ["reset", "--", reservedPath]).catch(() => "");
153
- }
154
- const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
155
- .split(/\r?\n/)
156
- .map((line) => line.trim())
157
- .filter(Boolean);
158
- if (changedFiles.length > 0) {
159
- await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
160
- }
161
- else {
162
- await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
153
+ export async function commitWorktreeChanges(git, worktreePath, workItemId, alreadyStagedChangedFiles) {
154
+ const changedFiles = alreadyStagedChangedFiles ?? await stagePublishableWorktreeChanges(git, worktreePath);
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
+ ]);
163
168
  }
164
169
  const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
165
170
  return { commitSha, changedFiles };
166
171
  }
172
+ export async function stagePublishableWorktreeChanges(git, worktreePath) {
173
+ return (await stagePublishableWorktreeChangeSet(git, worktreePath)).publishable;
174
+ }
167
175
  export function phaseCompleteEventType(phase) {
168
176
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
169
177
  }
@@ -212,12 +220,13 @@ export async function readQaCompletionArtifactBundle(worktreePath, workItemId, o
212
220
  const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
213
221
  const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
214
222
  const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
215
- await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
223
+ const sidecars = await readQaBundleSidecars(worktreePath, workItemId, ownerType, ownerId);
216
224
  return {
217
225
  ...artifact,
218
226
  planJson,
219
227
  evidenceJson,
220
- findingsJson
228
+ findingsJson,
229
+ sidecars
221
230
  };
222
231
  }
223
232
  export async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
@@ -274,15 +283,21 @@ function hasPassingRepositoryPlaywrightEvidence(evidence) {
274
283
  });
275
284
  }
276
285
  export async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
286
+ await readQaBundleSidecars(worktreePath, workItemId, ownerType, ownerId);
287
+ }
288
+ export async function readQaBundleSidecars(worktreePath, workItemId, ownerType, ownerId) {
277
289
  const artifactRoot = ownerType && ownerId
278
290
  ? artifactRootForOwner(worktreePath, ownerType, ownerId)
279
291
  : artifactRootFor(worktreePath, workItemId);
280
292
  const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
281
293
  const sidecars = arrayField(evidence, "sidecars");
282
294
  if (sidecars.length === 0) {
283
- return;
295
+ return [];
284
296
  }
285
297
  const qaSidecarRoot = path.resolve(artifactRoot, "qa");
298
+ const transported = [];
299
+ const transportedByPath = new Map();
300
+ let totalBytes = 0;
286
301
  for (const [index, sidecar] of sidecars.entries()) {
287
302
  const sidecarPath = stringField(sidecar, "path");
288
303
  const expectedHash = stringField(sidecar, "content_hash");
@@ -312,11 +327,36 @@ export async function validateQaBundleSidecarReferences(worktreePath, workItemId
312
327
  if (stat.size !== expectedBytes) {
313
328
  throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
314
329
  }
330
+ if (stat.size > maxTransportedQaSidecarBytes) {
331
+ throw new Error(`QA sidecar ${index} exceeds the ${maxTransportedQaSidecarBytes}-byte transport limit.`);
332
+ }
315
333
  const actualHash = await sha256File(fullPath);
316
334
  if (actualHash !== expectedHash.trim().toLowerCase()) {
317
335
  throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
318
336
  }
337
+ const canonicalPath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
338
+ const duplicateKey = canonicalPath.toLowerCase();
339
+ const existing = transportedByPath.get(duplicateKey);
340
+ if (existing) {
341
+ if (existing.contentHash !== actualHash || existing.bytes !== stat.size) {
342
+ throw new Error(`QA sidecar ${index} conflicts with another payload for ${canonicalPath}.`);
343
+ }
344
+ continue;
345
+ }
346
+ totalBytes += stat.size;
347
+ if (totalBytes > maxTransportedQaSidecarsTotalBytes) {
348
+ throw new Error(`QA sidecars exceed the ${maxTransportedQaSidecarsTotalBytes}-byte total transport limit.`);
349
+ }
350
+ const content = await fs.readFile(fullPath);
351
+ transportedByPath.set(duplicateKey, { contentHash: actualHash, bytes: stat.size });
352
+ transported.push({
353
+ path: canonicalPath,
354
+ contentBase64: content.toString("base64"),
355
+ contentHash: actualHash,
356
+ bytes: stat.size
357
+ });
319
358
  }
359
+ return transported;
320
360
  }
321
361
  export async function emitQaStructuredEvents(emit, artifact) {
322
362
  const artifactRoot = path.dirname(artifact.path);
@@ -745,11 +785,11 @@ export class LiveCompletionArtifactEmitter {
745
785
  }
746
786
  }
747
787
  }
748
- export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
788
+ export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle, providerResult) {
749
789
  if (!developCycle && !debugCycle) {
750
790
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
751
791
  if (!artifact) {
752
- 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);
753
793
  }
754
794
  return [artifact];
755
795
  }
@@ -761,11 +801,11 @@ export async function readCompletionArtifactsForRun(worktreePath, workItemId, ph
761
801
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
762
802
  if (!artifact) {
763
803
  if (artifacts.length === 0) {
764
- 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);
765
805
  }
766
806
  const previous = artifacts[artifacts.length - 1];
767
807
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
768
- 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);
769
809
  }
770
810
  return artifacts;
771
811
  }
@@ -3,12 +3,13 @@ import path from "node:path";
3
3
  import { GitClient } from "../../shared/git/git.js";
4
4
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
5
5
  import { completionPhaseFromDispatch, debugCompletionPhaseOrder, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, qaCompletionGateOrder, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact } from "../phase-completion.js";
6
- import { emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitQaArtifactRecorded, emitQaGateAccepted, emitQaStructuredEvents, isDebugCompletionPhaseForProvider, nextQaGate, phaseCompleteEventType, qaArtifactRootForDispatch, readQaCompletionArtifactBundle, readQaGateArtifact } from "./provider-cli.artifacts.js";
6
+ import { commitWorktreeChanges, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitQaArtifactRecorded, emitQaGateAccepted, emitQaStructuredEvents, isDebugCompletionPhaseForProvider, nextQaGate, phaseCompleteEventType, qaArtifactRootForDispatch, readQaCompletionArtifactBundle, readQaGateArtifact } from "./provider-cli.artifacts.js";
7
7
  import { deterministicBrowserCheck, deterministicBrowserSidecar, hasLaunchTarget, writeQaSidecarFiles } from "./provider-cli.qa-sidecars.js";
8
8
  import { buildProviderCliCommand, formatProviderCliCommand, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch, singleLine } from "./provider-cli.prompts.js";
9
9
  import { estimatedDeterministicUsage, exactRedactionSecrets } from "./provider-cli.runtime.js";
10
10
  import { buildProviderUsageEvent } from "./provider-usage.js";
11
11
  import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
12
+ import { assertRepairHeadEpoch } from "./provider-cli.repair-epoch.js";
12
13
  import { deterministicArchitectPayload, deterministicCompletionPayload, deterministicQaGatePayload } from "./provider-cli.deterministic-payloads.js";
13
14
  export class DeterministicProviderCliService {
14
15
  git;
@@ -211,6 +212,7 @@ export class DeterministicProviderCliService {
211
212
  }
212
213
  async runPullRequestRepair(context, route) {
213
214
  const { dispatch, worktree } = context;
215
+ await assertRepairHeadEpoch(context, this.git);
214
216
  const repairChecks = route === "ci_repair" || isPullRequestCheckRepairDispatch(dispatch);
215
217
  const addressComments = isPullRequestCommentsDispatch(dispatch);
216
218
  let repairArtifact = null;
@@ -238,7 +240,37 @@ export class DeterministicProviderCliService {
238
240
  throw new Error(`Deterministic CI repair did not produce ${reference.path}.`);
239
241
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, repairArtifact);
240
242
  }
241
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${repairChecks ? "ci repair" : addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
243
+ if (addressComments) {
244
+ const actionable = dispatch.pullRequest?.reviewFindings.filter(finding => finding.actionable) ?? [];
245
+ if (actionable.length === 0 || !dispatch.pullRequest?.reviewIssueKey || !dispatch.pullRequest.headSha) {
246
+ throw new Error("Deterministic comment repair requires a durable actionable finding snapshot.");
247
+ }
248
+ await writeCompletionArtifact({
249
+ worktreePath: worktree.worktreePath,
250
+ workItemId: dispatch.workItem.id,
251
+ phase: "comment_repair",
252
+ producedBy: "forge-deterministic-provider",
253
+ }, expectedCompletionToolName("comment_repair"), {
254
+ status: "pass",
255
+ summary: "Recorded deterministic decision-required outcomes without changing source.",
256
+ repair_head_sha: dispatch.pullRequest.headSha,
257
+ repair_issue_key: dispatch.pullRequest.reviewIssueKey,
258
+ dispositions: actionable.map(finding => ({
259
+ claim_id: finding.claimId,
260
+ kind: finding.kind,
261
+ body_sha256: finding.bodySha256,
262
+ disposition: "needs_decision",
263
+ evidence: "The deterministic provider cannot evaluate semantic review feedback."
264
+ })),
265
+ changed_files: [],
266
+ validation: []
267
+ });
268
+ repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
269
+ if (!repairArtifact)
270
+ throw new Error("Deterministic comment repair did not produce its completion artifact.");
271
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, repairArtifact);
272
+ }
273
+ await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
242
274
  await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
243
275
  await context.emit({
244
276
  role: "assistant",
@@ -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
+ }