@unbrained/pm-cli 2026.11.20 → 2026.11.22

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 (265) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +1 -1
  2. package/.agents/skills/pm-sdk/SKILL.md +1 -1
  3. package/.agents/skills/pm-test-audit/SKILL.md +1 -1
  4. package/.claude-plugin/marketplace.json +1 -1
  5. package/CONTRIBUTING.md +2 -1
  6. package/dist/cli/error-guidance.js +2 -2
  7. package/dist/cli/register-history-maintenance.js +2 -2
  8. package/dist/cli/register-list-query.js +2 -2
  9. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  10. package/dist/cli-bundle/bundle-manifest.json +1 -1
  11. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +9 -0
  12. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +125 -0
  13. package/dist/cli-bundle/chunks/{chunk-4TZW4NLM.js → chunk-5ZMVLWE3.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +33 -0
  15. package/dist/cli-bundle/chunks/{chunk-GXGW6KHB.js → chunk-AR4NP5HI.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-6X2AGUOT.js → chunk-B4PPFOPY.js} +3 -3
  17. package/dist/cli-bundle/chunks/{chunk-XK25TAJZ.js → chunk-B76TFRO2.js} +47 -45
  18. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +8 -0
  19. package/dist/cli-bundle/chunks/{chunk-KDDIHGAO.js → chunk-EIGUKEV6.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-ZAO7VGX3.js → chunk-GTPCAJMZ.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +2 -0
  22. package/dist/cli-bundle/chunks/{chunk-KQSPKWFH.js → chunk-HC2OPETM.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-5LF5QZT3.js → chunk-HKUV74K3.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +115 -0
  25. package/dist/cli-bundle/chunks/{chunk-FF4TXJDH.js → chunk-J2LABXBL.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-3BOR22MC.js → chunk-J52BEBSS.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +3 -0
  28. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +3 -0
  29. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +31 -0
  30. package/dist/cli-bundle/chunks/{chunk-DG2EOOFX.js → chunk-TC6XLIYO.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-MGYAJONE.js → chunk-U7EL3AYA.js} +2 -2
  32. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +6 -0
  33. package/dist/cli-bundle/chunks/{chunk-ZVEHACE6.js → chunk-X6MIWTTT.js} +2 -2
  34. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +2 -0
  35. package/dist/cli-bundle/chunks/{chunk-KEBLUTC3.js → chunk-XFHPKXAE.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-OXG5XPC7.js → chunk-YHVLVSEZ.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-Y4LXVPA5.js → chunk-YMUSRWV4.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-HQYIKAC6.js → chunk-YR2KEBHP.js} +2 -2
  39. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-ELEMA7IW.js → indexed-receipt-blobs-ITTXIN4K.js} +2 -2
  40. package/dist/cli-bundle/chunks/{item-revision-GE2CQECR.js → item-revision-4QBMZXKX.js} +2 -2
  41. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +2 -0
  42. package/dist/cli-bundle/chunks/{mutation-actor-5GYX7LP3.js → mutation-actor-FWLYWJ37.js} +2 -2
  43. package/dist/cli-bundle/chunks/{mutation-admission-72TYKPGU.js → mutation-admission-7ZDCK3G2.js} +2 -2
  44. package/dist/cli-bundle/chunks/{register-list-query-OQZZEWEB.js → register-list-query-RR5KACJ3.js} +10 -10
  45. package/dist/cli-bundle/chunks/{register-mutation-YZEUZ6XT.js → register-mutation-57AJQWFV.js} +2 -2
  46. package/dist/cli-bundle/chunks/{register-operations-JNVCF7EW.js → register-operations-RKWST7CU.js} +2 -2
  47. package/dist/cli-bundle/chunks/{register-setup-LDKULZSD.js → register-setup-CMI23PC5.js} +2 -2
  48. package/dist/cli-bundle/chunks/{settlement-hook-E5LHZ4RD.js → settlement-hook-BXN5LEQD.js} +2 -2
  49. package/dist/cli-bundle/chunks/{stage-Q2QZ2IBG.js → stage-4KDVXC5Z.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-JUYJ7NXL.js → chunk-2ZD7275J.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-7SB6VKEI.js → chunk-324AHXJO.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-IXYBN6D2.js → chunk-3IRCYJI5.js} +3 -3
  53. package/dist/cli-bundle/focused-chunks/{chunk-DH4DHL6V.js → chunk-3V53UBHN.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +91 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-V55XZFOP.js → chunk-4JZITIJB.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +2 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +78 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +2 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-BZCLW5V7.js → chunk-BRZV7BFV.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/{chunk-PKMDWIP3.js → chunk-HDEKFSOK.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-O25KFLLA.js → chunk-IWOXAUDU.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{chunk-UATP3RK3.js → chunk-ML3JHCC6.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{chunk-ZKGGGU2K.js → chunk-OPGOOP25.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-PRFEOCNZ.js → chunk-RE7ZWT7D.js} +3 -3
  66. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +3 -0
  67. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +8 -0
  68. package/dist/cli-bundle/focused-chunks/{chunk-KQJNJZKP.js → chunk-URGHTTT3.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +13 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +102 -0
  71. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +44 -0
  72. package/dist/cli-bundle/focused-chunks/{chunk-PQXTZLK3.js → chunk-WZWXGDYY.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{chunk-5VSXKA35.js → chunk-YKSLZPLT.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ZTRFCPH7.js → indexed-receipt-blobs-AF4U3F3D.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/{item-revision-OXDZHMJ7.js → item-revision-2O6MLPEX.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +2 -0
  78. package/dist/cli-bundle/focused-chunks/{mutation-actor-6DYIF6NH.js → mutation-actor-TCYDPUGG.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/{mutation-admission-2BYXANVJ.js → mutation-admission-LY73EJWM.js} +2 -2
  80. package/dist/cli-bundle/focused-chunks/{settlement-hook-OUBUN45C.js → settlement-hook-ARYCZQY4.js} +2 -2
  81. package/dist/cli-bundle/focused-chunks/{stage-FGHSB3QX.js → stage-DQ7RQQ52.js} +2 -2
  82. package/dist/cli-bundle/main.js +25 -25
  83. package/dist/cli-bundle/sdk-authoring.js +1 -1
  84. package/dist/cli-bundle/sdk-contracts.js +2 -2
  85. package/dist/cli-bundle/sdk-core.js +1 -1
  86. package/dist/cli-bundle/sdk-governance.js +1 -1
  87. package/dist/cli-bundle/sdk-graph.js +1 -1
  88. package/dist/cli-bundle/sdk-merge.js +70 -57
  89. package/dist/cli-bundle/sdk-query.js +1 -1
  90. package/dist/cli-bundle/sdk-runtime.js +1 -1
  91. package/dist/cli-bundle/sdk-testing.js +1 -1
  92. package/dist/cli-bundle/sdk.js +11 -11
  93. package/dist/core/diagnostics/remediation.js +1 -1
  94. package/dist/core/extensions/index.d.ts +2 -0
  95. package/dist/core/extensions/index.js +1 -1
  96. package/dist/core/fs/atomic-create.js +1 -1
  97. package/dist/core/fs/file-glob.js +1 -1
  98. package/dist/core/fs/fs-utils.d.ts +3 -1
  99. package/dist/core/fs/fs-utils.js +1 -1
  100. package/dist/core/history/bridge.js +2 -0
  101. package/dist/core/history/drift-scan.js +1 -1
  102. package/dist/core/history/history-rewrite.js +1 -1
  103. package/dist/core/history/history-stream-policy.js +1 -1
  104. package/dist/core/history/history.d.ts +12 -0
  105. package/dist/core/history/history.js +2 -2
  106. package/dist/core/history/projection.js +1 -1
  107. package/dist/core/history/read.d.ts +20 -1
  108. package/dist/core/history/read.js +1 -1
  109. package/dist/core/history/replay.d.ts +46 -5
  110. package/dist/core/history/replay.js +2 -2
  111. package/dist/core/history/stream-summary.d.ts +129 -0
  112. package/dist/core/history/stream-summary.js +3 -0
  113. package/dist/core/shared/errors.d.ts +8 -0
  114. package/dist/core/shared/errors.js +1 -1
  115. package/dist/core/shared/url-credentials.js +1 -1
  116. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  117. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  118. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  119. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  120. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  121. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
  122. package/dist/sdk/completion/fish.js +3 -2
  123. package/dist/sdk/completion/zsh.js +3 -2
  124. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  125. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  126. package/dist/sdk/governance/gc.js +1 -1
  127. package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
  128. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  129. package/dist/sdk/governance/health.js +2 -2
  130. package/dist/sdk/governance/validate.js +1 -1
  131. package/dist/sdk/governance/workspace-position.js +1 -1
  132. package/dist/sdk/history/append-only-repair.d.ts +30 -0
  133. package/dist/sdk/history/append-only-repair.js +6 -0
  134. package/dist/sdk/history/maintenance.d.ts +8 -2
  135. package/dist/sdk/history/maintenance.js +1 -1
  136. package/dist/sdk/history/reanchor-refusal.js +2 -0
  137. package/dist/sdk/history/reseed.d.ts +15 -0
  138. package/dist/sdk/history/reseed.js +2 -0
  139. package/dist/sdk/history/salvage.d.ts +19 -8
  140. package/dist/sdk/history/salvage.js +5 -3
  141. package/dist/sdk/history-compact.js +1 -1
  142. package/dist/sdk/history-provenance.js +1 -1
  143. package/dist/sdk/history-redact.js +1 -1
  144. package/dist/sdk/history-repair.d.ts +8 -2
  145. package/dist/sdk/history-repair.js +1 -1
  146. package/dist/sdk/index.d.ts +1 -1
  147. package/dist/sdk/item-transaction.d.ts +33 -1
  148. package/dist/sdk/item-transaction.js +1 -1
  149. package/dist/sdk/lifecycle/restore.js +1 -1
  150. package/dist/sdk/merge/index.d.ts +1 -1
  151. package/dist/sdk/merge/index.js +1 -1
  152. package/dist/sdk/merge/install.d.ts +20 -6
  153. package/dist/sdk/merge/install.js +3 -3
  154. package/dist/sdk/merge/three-way.d.ts +22 -3
  155. package/dist/sdk/merge/three-way.js +8 -2
  156. package/dist/sdk/merge/worktree-config.js +2 -1
  157. package/dist/sdk/public-surface.json +1 -1
  158. package/dist/sdk/query/activity.d.ts +67 -5
  159. package/dist/sdk/query/activity.js +1 -1
  160. package/dist/sdk/query/context.d.ts +13 -3
  161. package/dist/sdk/query/context.js +2 -2
  162. package/dist/sdk/query.d.ts +1 -1
  163. package/dist/sdk/runtime/actions.js +1 -1
  164. package/dist/sdk/runtime-input.d.ts +6 -2
  165. package/dist/sdk/runtime-input.js +1 -1
  166. package/dist/sdk/runtime-primitives.d.ts +1 -1
  167. package/dist/sdk/runtime-primitives.js +1 -1
  168. package/dist/sdk/runtime.d.ts +7 -0
  169. package/dist/sdk/runtime.js +1 -1
  170. package/dist/sdk/structured-mutations.d.ts +5 -5
  171. package/dist/sdk/structured-mutations.js +1 -1
  172. package/dist/sdk/transactions/item-finalization.js +2 -0
  173. package/dist/types.d.ts +20 -0
  174. package/dist/types.js +1 -1
  175. package/docs/AGENT_GUIDE.md +1 -1
  176. package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
  177. package/docs/COMMANDS.md +62 -4
  178. package/docs/HISTORY_RECOVERY.md +229 -5
  179. package/docs/MERGE_SAFETY.md +8 -0
  180. package/docs/MUTATION_INTEGRITY.md +3 -1
  181. package/docs/README.md +8 -6
  182. package/docs/SDK.md +128 -5
  183. package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
  184. package/docs/TESTING.md +8 -697
  185. package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +1 -1
  186. package/marketplace.json +1 -1
  187. package/node_modules/tar/package.json +2 -3
  188. package/package.json +35 -3
  189. package/packages/pm-beads/package.json +1 -1
  190. package/packages/pm-calendar/package.json +1 -1
  191. package/packages/pm-command-kit/package.json +1 -1
  192. package/packages/pm-digital-twin/package.json +1 -1
  193. package/packages/pm-governance-audit/package.json +1 -1
  194. package/packages/pm-guide-shell/package.json +1 -1
  195. package/packages/pm-kanban/package.json +1 -1
  196. package/packages/pm-lifecycle-hooks/package.json +1 -1
  197. package/packages/pm-linked-test-adapters/package.json +1 -1
  198. package/packages/pm-search-advanced/package.json +1 -1
  199. package/packages/pm-templates/package.json +1 -1
  200. package/packages/pm-todos/package.json +1 -1
  201. package/packages/pm-vcs/package.json +1 -1
  202. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  203. package/plugins/pm-claude/package.json +1 -1
  204. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  205. package/plugins/pm-codex/package.json +1 -1
  206. package/plugins/pm-codex/plugin.json +1 -1
  207. package/runtime-dependencies.json +1 -1
  208. package/dist/cli-bundle/chunks/chunk-2IZGNOGT.js +0 -6
  209. package/dist/cli-bundle/chunks/chunk-4QQPM3IY.js +0 -2
  210. package/dist/cli-bundle/chunks/chunk-5OFMWP3Q.js +0 -3
  211. package/dist/cli-bundle/chunks/chunk-6HRPGEBF.js +0 -2
  212. package/dist/cli-bundle/chunks/chunk-7ESF676D.js +0 -125
  213. package/dist/cli-bundle/chunks/chunk-7EZZ4W7O.js +0 -20
  214. package/dist/cli-bundle/chunks/chunk-FOYRE23V.js +0 -115
  215. package/dist/cli-bundle/chunks/chunk-HJQ3XPS3.js +0 -31
  216. package/dist/cli-bundle/chunks/chunk-M5D3CEMY.js +0 -9
  217. package/dist/cli-bundle/chunks/chunk-VS565KBX.js +0 -2
  218. package/dist/cli-bundle/chunks/chunk-W4TLA5H3.js +0 -8
  219. package/dist/cli-bundle/chunks/item-transaction-YSAWJRA2.js +0 -2
  220. package/dist/cli-bundle/focused-chunks/chunk-3LRSQXCN.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +0 -2
  222. package/dist/cli-bundle/focused-chunks/chunk-FPKVHC3Q.js +0 -2
  223. package/dist/cli-bundle/focused-chunks/chunk-I7XBR2RM.js +0 -91
  224. package/dist/cli-bundle/focused-chunks/chunk-MJP3TFVW.js +0 -2
  225. package/dist/cli-bundle/focused-chunks/chunk-PZSTRYTA.js +0 -102
  226. package/dist/cli-bundle/focused-chunks/chunk-QNJQPJWO.js +0 -44
  227. package/dist/cli-bundle/focused-chunks/chunk-SIPDQBJI.js +0 -8
  228. package/dist/cli-bundle/focused-chunks/chunk-SJE3PYPI.js +0 -3
  229. package/dist/cli-bundle/focused-chunks/chunk-TNKI6WKG.js +0 -66
  230. package/dist/cli-bundle/focused-chunks/chunk-TRCXANRR.js +0 -12
  231. package/dist/cli-bundle/focused-chunks/item-transaction-54VSTT6L.js +0 -2
  232. package/dist/sdk/agent/refusal-closure.js +0 -2
  233. package/dist/sdk/agent/refusal-reachability.js +0 -4
  234. package/dist/sdk/agent/task-transcript-contracts.js +0 -2
  235. package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
  236. package/dist/sdk/authoring.js +0 -2
  237. package/dist/sdk/compose.js +0 -2
  238. package/dist/sdk/contracts.js +0 -2
  239. package/dist/sdk/core-governance.js +0 -2
  240. package/dist/sdk/core.js +0 -2
  241. package/dist/sdk/corpus-shape.js +0 -2
  242. package/dist/sdk/define.js +0 -2
  243. package/dist/sdk/environment/agent-environment.js +0 -2
  244. package/dist/sdk/governance/artifact-ledgers.js +0 -2
  245. package/dist/sdk/governance/coverage-assurance.js +0 -2
  246. package/dist/sdk/governance/reliability.js +0 -2
  247. package/dist/sdk/governance.js +0 -2
  248. package/dist/sdk/graph/adapter.js +0 -2
  249. package/dist/sdk/graph/conformance.js +0 -2
  250. package/dist/sdk/graph/index.js +0 -2
  251. package/dist/sdk/graph.js +0 -2
  252. package/dist/sdk/index.js +0 -2
  253. package/dist/sdk/query.js +0 -2
  254. package/dist/sdk/relationship-migration.js +0 -2
  255. package/dist/sdk/testing.js +0 -8
  256. package/dist/sdk/workspace-recipe.js +0 -2
  257. package/docs/AGENT_PROVENANCE_ADR.md +0 -206
  258. package/docs/DEFECT_RECURRENCE.md +0 -257
  259. package/docs/MCP_2026_07_28_CONFORMANCE.md +0 -41
  260. package/docs/PERFORMANCE.md +0 -189
  261. package/docs/QUALITY_EVIDENCE.md +0 -130
  262. package/docs/generated/FLAG_LEXICON_BUDGETS.md +0 -117
  263. package/docs/performance/cli-transport-overhead.md +0 -51
  264. package/docs/performance/runner-qualification.md +0 -36
  265. package/docs/performance/sdk-entrypoint-import-costs.md +0 -32
@@ -1,8 +1,8 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b1828465-0619-514c-8956-2a81dea9efbc")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError,readFileIfExists,writeFileAtomic}from"../../core/fs/fs-utils.js";import{access,readFile,realpath}from"node:fs/promises";import{constants}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{pathExists}from"../../core/fs/fs-utils.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{acquireLock}from"../../core/lock/lock.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{resolveAuthor}from"../../core/shared/author.js";import{nowIso}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings,resolveGovernanceKnobs}from"../../core/store/settings.js";import{isPathOutsideRoot}from"../workspace.js";import{resolveSourceContextWritePolicy}from"../environment/source-context.js";import{gitWorkspaceEnvironment,resolveMergeDriverConfigScope,writeMergeDriverGitConfig}from"./worktree-config.js";import{discoverProjectRuntimeVersionPins}from"../environment/project-runtime-compatibility.js";const execFileAsync=promisify(execFile),PM_GITATTRIBUTES_START="# pm-cli:merge-drivers:start",PM_GITATTRIBUTES_END="# pm-cli:merge-drivers:end",PM_GITATTRIBUTES_V2_START="# pm-cli:merge-drivers:v2:start",PM_GITATTRIBUTES_V2_END="# pm-cli:merge-drivers:v2:end",MERGE_FENCE_LOCK_ID="merge-fence",MERGE_ATTRIBUTES_LOCK_ID="merge-attributes";function quoteMergeDriverArgument(value){return`'${value.replaceAll("'",`'"'"'`)}'`}async function resolveMatchingBunLauncher(candidate,version){const resolvedCandidate=await realpath(candidate);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(resolvedCandidate))return;const{stdout}=await execFileAsync(candidate,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return stdout.trim()===version?resolvedCandidate:void 0}async function resolveMergeDriverCliCommand(){const packageRoot=resolvePmPackageRootFromModule(import.meta.url,["../../.."]);let executable=process.execPath,bunLauncherFound=!1;const runtimeIdentity=await realpath(process.execPath),bunVersion=process.versions.bun,pathCandidates=(process.env.PATH??"").split(path.delimiter).filter(directory=>path.isAbsolute(directory)).map(directory=>path.join(directory,bunVersion===void 0?path.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),candidates=bunVersion===void 0?pathCandidates:[process.env.npm_execpath??"",...pathCandidates,runtimeIdentity].filter(candidate=>path.isAbsolute(candidate)&&/^(?:bun|bun\.exe)$/iu.test(path.basename(candidate)));for(const candidate of candidates)try{if(await access(candidate,constants.X_OK),bunVersion!==void 0){const launcher=await resolveMatchingBunLauncher(candidate,bunVersion);if(launcher!==void 0){executable=launcher,bunLauncherFound=!0;break}continue}if(candidate!==runtimeIdentity&&await realpath(candidate)===runtimeIdentity){executable=candidate;break}}catch{}if(bunVersion!==void 0&&!bunLauncherFound)throw new PmCliError("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",EXIT_CODE.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${quoteMergeDriverArgument(executable)} ${quoteMergeDriverArgument(path.join(packageRoot,"dist","cli.js"))}`}const MERGE_DRIVER_DEFINITIONS=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function resolveMergeInstallContext(options){const explicitPath=options.explicitPath?.trim(),sourceWorkspaceRoot=options.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),sourcePmRoot=options.environment.PM_SOURCE_PM_PATH?.trim(),sourcePolicy=resolveSourceContextWritePolicy(options.environment),sourceCoordinatesAvailable=!!(sourceWorkspaceRoot&&sourcePmRoot),sourceContextSelected=explicitPath===void 0&&sourceCoordinatesAvailable&&(options.dryRun||sourcePolicy.source_writes_allowed);if(explicitPath!==void 0){const pmRoot=resolvePmRoot(options.cwd,explicitPath);return{pm_root:pmRoot,workspace_start:pmRoot,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:!1,source_policy:sourcePolicy}}return sourceContextSelected?{pm_root:path.resolve(sourcePmRoot),workspace_start:path.resolve(sourceWorkspaceRoot),source_coordinates_available:!0,source_context_selected:!0,source_policy:sourcePolicy}:{pm_root:sourceCoordinatesAvailable?resolvePmRoot(options.cwd,".agents/pm"):resolvePmRoot(options.cwd),workspace_start:options.cwd,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:!1,source_policy:sourcePolicy}}async function findGitWorkspaceRoot(cwd){try{const{stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await realpath(stdout.trim())}catch{return null}}async function resolveGitWorkspaceRoot(cwd){const workspaceRoot=await findGitWorkspaceRoot(cwd);if(workspaceRoot===null)throw new PmCliError("pm merge install requires a git repository (merge drivers are git configuration).",EXIT_CODE.USAGE);return workspaceRoot}function toPosixRelative(fromPath,toPath){return path.relative(fromPath,toPath).split(path.sep).join("/")}function literalGitAttributePath(value){return value.replace(/[\\*?[\]!]/gu,"\\$&")}function quoteGitAttributePattern(value){return`"${value.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function readSingleQuotedArgument(command,offset){if(command[offset]!=="'")return null;let value="";for(let index=offset+1;index<command.length;index+=1){if(command.startsWith(`'"'"'`,index)){value+="'",index+=4;continue}if(command[index]==="'")return{value,nextOffset:index+1};value+=command[index]}return null}async function isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,version){if(discoverProjectRuntimeVersionPins(workspaceRoot).filter(pin=>pin.constraint==="exact").some(pin=>pin.version!==version))return!1;const driverWorkspace=await findGitWorkspaceRoot(packageRoot);if(driverWorkspace!==null&&driverWorkspace!==await realpath(workspaceRoot)){const commonDirectories=await Promise.all([driverWorkspace,workspaceRoot].map(async cwd=>{const result=await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,env:gitWorkspaceEnvironment(),timeout:1e4});return realpath(result.stdout.trim())}));if(commonDirectories[0]===commonDirectories[1])return!1}return!0}async function isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot){const nodeArgument=readSingleQuotedArgument(configured,0);if(nodeArgument===null||configured[nodeArgument.nextOffset]!==" ")return!1;const cliArgument=readSingleQuotedArgument(configured,nodeArgument.nextOffset+1);if(cliArgument===null||configured.slice(cliArgument.nextOffset)!==expectedSuffix||!/^(?:node|bun)(?:\.exe)?$/iu.test(path.basename(nodeArgument.value))||path.basename(cliArgument.value)!=="cli.js"||path.basename(path.dirname(cliArgument.value))!=="dist"||!await pathExists(nodeArgument.value)||!await pathExists(cliArgument.value))return!1;try{const packageRoot=path.dirname(path.dirname(cliArgument.value)),manifest=JSON.parse(await readFile(path.join(packageRoot,"package.json"),"utf8")),pmBin=typeof manifest.bin=="string"?manifest.bin:manifest.bin?.pm;return await isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,manifest.version)?manifest.name==="@unbrained/pm-cli"&&pmBin==="dist/cli.js":!1}catch{return!1}}function buildMergeAttributePatterns(trackerRelativeRoot,typeFolders){const prefix=trackerRelativeRoot.length>0?`${literalGitAttributePath(trackerRelativeRoot)}/`:"",patterns=[`${quoteGitAttributePattern(`${prefix}**/*.toon`)} merge=pm-item-toon`,`${quoteGitAttributePattern(`${prefix}**/*.md`)} merge=pm-item-markdown`];for(const folder of typeFolders){const literalFolder=literalGitAttributePath(folder);patterns.push(`${quoteGitAttributePattern(`${prefix}${literalFolder}/*.toon`)} merge=pm-item-toon`),patterns.push(`${quoteGitAttributePattern(`${prefix}${literalFolder}/*.md`)} merge=pm-item-markdown`)}return patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.jsonl`)} merge=pm-relationship`),patterns.push(`${quoteGitAttributePattern(`${prefix}history/*.jsonl`)} merge=pm-history`),patterns.push(`${quoteGitAttributePattern(`${prefix}settings.json`)} merge=pm-json`),patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.json`)} merge=pm-json`),patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/**`)} merge=text`),patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/.managed-extensions.json`)} merge=pm-json`),patterns}function managedMergeBlocks(content){const blocks=[];let cursor=0;for(;cursor<content.length;){const legacyStart=content.indexOf(PM_GITATTRIBUTES_START,cursor),versionedStart=content.indexOf(PM_GITATTRIBUTES_V2_START,cursor),start=legacyStart===-1?versionedStart:versionedStart===-1?legacyStart:Math.min(legacyStart,versionedStart);if(start===-1)break;const versioned=start===versionedStart,startMarker=versioned?PM_GITATTRIBUTES_V2_START:PM_GITATTRIBUTES_START,endMarker=versioned?PM_GITATTRIBUTES_V2_END:PM_GITATTRIBUTES_END,closing=content.indexOf(endMarker,start+startMarker.length),end=closing===-1?content.length:closing+endMarker.length;blocks.push({start,end,closed:closing!==-1,lines:content.slice(start+startMarker.length,closing===-1?end:closing).split(`
2
- `).map(line=>line.trim()).filter(Boolean)}),cursor=end}return blocks}function blockBelongsToTracker(lines,patterns,trackerRelativeRoot){const ownedPatterns=new Set(patterns),prefix=quoteGitAttributePattern(trackerRelativeRoot.length>0?`${trackerRelativeRoot}/`:"").slice(0,-1);return lines.some(line=>ownedPatterns.has(line)||line.startsWith(prefix)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(line.slice(prefix.length)))}async function reconcileGitattributesBlock(workspaceRoot,trackerRelativeRoot,patterns,dryRun){const gitattributesPath=path.join(workspaceRoot,".gitattributes"),gitDirectory=dryRun?null:(await execFileAsync("git",["rev-parse","--absolute-git-dir"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),releaseLock=gitDirectory===null?null:await acquireLock(gitDirectory,MERGE_ATTRIBUTES_LOCK_ID,120,"merge-fence",!1,!0,5e3);try{const current=await readFileIfExists(gitattributesPath)??"",block=[PM_GITATTRIBUTES_V2_START,...patterns,PM_GITATTRIBUTES_V2_END].join(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b3b43765-c582-516a-bebc-cf08af5efbe5")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError,readFileIfExists,writeFileAtomic}from"../../core/fs/fs-utils.js";import{access,lstat,readFile,realpath}from"node:fs/promises";import{constants}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{pathExists}from"../../core/fs/fs-utils.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{acquireLock}from"../../core/lock/lock.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{resolveAuthor}from"../../core/shared/author.js";import{nowIso}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings,resolveGovernanceKnobs}from"../../core/store/settings.js";import{isPathOutsideRoot}from"../workspace.js";import{resolveSourceContextWritePolicy}from"../environment/source-context.js";import{gitWorkspaceEnvironment,resolveMergeDriverConfigScope,stripGitPathTerminator,writeMergeDriverGitConfig}from"./worktree-config.js";import{discoverProjectRuntimeVersionPins}from"../environment/project-runtime-compatibility.js";const execFileAsync=promisify(execFile),PM_GITATTRIBUTES_START="# pm-cli:merge-drivers:start",PM_GITATTRIBUTES_END="# pm-cli:merge-drivers:end",PM_GITATTRIBUTES_V2_START="# pm-cli:merge-drivers:v2:start",PM_GITATTRIBUTES_V2_END="# pm-cli:merge-drivers:v2:end",MERGE_FENCE_LOCK_ID="merge-fence",MERGE_ATTRIBUTES_LOCK_ID="merge-attributes";function quoteMergeDriverArgument(value){return`'${value.replaceAll("'",`'"'"'`)}'`}async function resolveMatchingBunLauncher(candidate,version){const resolvedCandidate=await realpath(candidate);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(resolvedCandidate))return;const{stdout}=await execFileAsync(candidate,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return stdout.trim()===version?resolvedCandidate:void 0}async function resolveMergeDriverCliCommand(){const packageRoot=resolvePmPackageRootFromModule(import.meta.url,["../../.."]);let executable=process.execPath,bunLauncherFound=!1;const runtimeIdentity=await realpath(process.execPath),bunVersion=process.versions.bun,pathCandidates=(process.env.PATH??"").split(path.delimiter).filter(directory=>path.isAbsolute(directory)).map(directory=>path.join(directory,bunVersion===void 0?path.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),candidates=bunVersion===void 0?pathCandidates:[process.env.npm_execpath??"",...pathCandidates,runtimeIdentity].filter(candidate=>path.isAbsolute(candidate)&&/^(?:bun|bun\.exe)$/iu.test(path.basename(candidate)));for(const candidate of candidates)try{if(await access(candidate,constants.X_OK),bunVersion!==void 0){const launcher=await resolveMatchingBunLauncher(candidate,bunVersion);if(launcher!==void 0){executable=launcher,bunLauncherFound=!0;break}continue}if(candidate!==runtimeIdentity&&await realpath(candidate)===runtimeIdentity){executable=candidate;break}}catch{}if(bunVersion!==void 0&&!bunLauncherFound)throw new PmCliError("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",EXIT_CODE.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${quoteMergeDriverArgument(executable)} ${quoteMergeDriverArgument(path.join(packageRoot,"dist","cli.js"))}`}const MERGE_DRIVER_DEFINITIONS=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function resolveMergeInstallContext(options){const explicitPath=options.explicitPath?.trim(),sourceWorkspaceRoot=options.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),sourcePmRoot=options.environment.PM_SOURCE_PM_PATH?.trim(),sourcePolicy=resolveSourceContextWritePolicy(options.environment),sourceCoordinatesAvailable=!!(sourceWorkspaceRoot&&sourcePmRoot),sourceContextSelected=explicitPath===void 0&&sourceCoordinatesAvailable&&(options.dryRun||sourcePolicy.source_writes_allowed);if(explicitPath!==void 0){const pmRoot=resolvePmRoot(options.cwd,explicitPath);return{pm_root:pmRoot,workspace_start:pmRoot,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:!1,source_policy:sourcePolicy}}return sourceContextSelected?{pm_root:path.resolve(sourcePmRoot),workspace_start:path.resolve(sourceWorkspaceRoot),source_coordinates_available:!0,source_context_selected:!0,source_policy:sourcePolicy}:{pm_root:sourceCoordinatesAvailable?resolvePmRoot(options.cwd,".agents/pm"):resolvePmRoot(options.cwd),workspace_start:options.cwd,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:!1,source_policy:sourcePolicy}}async function findGitWorkspaceRoot(cwd){try{const{stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await realpath(stripGitPathTerminator(stdout))}catch{return null}}async function resolveGitWorkspaceRoot(cwd){const workspaceRoot=await findGitWorkspaceRoot(cwd);if(workspaceRoot===null)throw new PmCliError("pm merge install requires a git repository (merge drivers are git configuration).",EXIT_CODE.USAGE);return workspaceRoot}function toPosixRelative(fromPath,toPath){return path.relative(fromPath,toPath).split(path.sep).join("/")}function literalGitAttributePath(value){return value.replace(/[\\*?[\]!]/gu,"\\$&")}function quoteGitAttributePattern(value){return`"${value.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function readSingleQuotedArgument(command,offset){if(command[offset]!=="'")return null;let value="";for(let index=offset+1;index<command.length;index+=1){if(command.startsWith(`'"'"'`,index)){value+="'",index+=4;continue}if(command[index]==="'")return{value,nextOffset:index+1};value+=command[index]}return null}async function isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,version){if(discoverProjectRuntimeVersionPins(workspaceRoot).filter(pin=>pin.constraint==="exact").some(pin=>pin.version!==version))return!1;const driverWorkspace=await findGitWorkspaceRoot(packageRoot);if(driverWorkspace!==null&&driverWorkspace!==await realpath(workspaceRoot)){const commonDirectories=await Promise.all([driverWorkspace,workspaceRoot].map(async cwd=>{const result=await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,env:gitWorkspaceEnvironment(),timeout:1e4});return realpath(result.stdout.trim())}));if(commonDirectories[0]===commonDirectories[1])return!1}return!0}async function isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot){const nodeArgument=readSingleQuotedArgument(configured,0);if(nodeArgument===null||configured[nodeArgument.nextOffset]!==" ")return!1;const cliArgument=readSingleQuotedArgument(configured,nodeArgument.nextOffset+1);if(cliArgument===null||configured.slice(cliArgument.nextOffset)!==expectedSuffix||!/^(?:node|bun)(?:\.exe)?$/iu.test(path.basename(nodeArgument.value))||path.basename(cliArgument.value)!=="cli.js"||path.basename(path.dirname(cliArgument.value))!=="dist"||!await pathExists(nodeArgument.value)||!await pathExists(cliArgument.value))return!1;try{const packageRoot=path.dirname(path.dirname(cliArgument.value)),manifest=JSON.parse(await readFile(path.join(packageRoot,"package.json"),"utf8")),pmBin=typeof manifest.bin=="string"?manifest.bin:manifest.bin?.pm;return await isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,manifest.version)?manifest.name==="@unbrained/pm-cli"&&pmBin==="dist/cli.js":!1}catch{return!1}}function buildMergeAttributePatterns(trackerRelativeRoot,typeFolders){const prefix=trackerRelativeRoot.length>0?`${literalGitAttributePath(trackerRelativeRoot)}/`:"",patterns=[`${quoteGitAttributePattern(`${prefix}**/*.toon`)} merge=pm-item-toon`,`${quoteGitAttributePattern(`${prefix}**/*.md`)} merge=pm-item-markdown`];for(const folder of typeFolders){const literalFolder=literalGitAttributePath(folder);patterns.push(`${quoteGitAttributePattern(`${prefix}${literalFolder}/*.toon`)} merge=pm-item-toon`),patterns.push(`${quoteGitAttributePattern(`${prefix}${literalFolder}/*.md`)} merge=pm-item-markdown`)}return patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.jsonl`)} merge=pm-relationship`),patterns.push(`${quoteGitAttributePattern(`${prefix}history/*.jsonl`)} merge=pm-history`),patterns.push(`${quoteGitAttributePattern(`${prefix}settings.json`)} merge=pm-json`),patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.json`)} merge=pm-json`),patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/**`)} merge=text`),patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/.managed-extensions.json`)} merge=pm-json`),patterns}function managedMergeBlocks(content){const blocks=[];let cursor=0;for(;cursor<content.length;){const legacyStart=content.indexOf(PM_GITATTRIBUTES_START,cursor),versionedStart=content.indexOf(PM_GITATTRIBUTES_V2_START,cursor),start=legacyStart===-1?versionedStart:versionedStart===-1?legacyStart:Math.min(legacyStart,versionedStart);if(start===-1)break;const versioned=start===versionedStart,startMarker=versioned?PM_GITATTRIBUTES_V2_START:PM_GITATTRIBUTES_START,endMarker=versioned?PM_GITATTRIBUTES_V2_END:PM_GITATTRIBUTES_END,closing=content.indexOf(endMarker,start+startMarker.length),end=closing===-1?content.length:closing+endMarker.length;blocks.push({start,end,closed:closing!==-1,lines:content.slice(start+startMarker.length,closing===-1?end:closing).split(`
2
+ `).map(line=>line.trim()).filter(Boolean)}),cursor=end}return blocks}function blockBelongsToTracker(lines,patterns,trackerRelativeRoot){const ownedPatterns=new Set(patterns),prefix=quoteGitAttributePattern(trackerRelativeRoot.length>0?`${trackerRelativeRoot}/`:"").slice(0,-1);return lines.some(line=>ownedPatterns.has(line)||line.startsWith(prefix)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(line.slice(prefix.length)))}async function reconcileGitattributesBlock(workspaceRoot,trackerRelativeRoot,patterns,dryRun){const gitattributesPath=path.join(workspaceRoot,".gitattributes"),gitDirectory=dryRun?null:stripGitPathTerminator((await execFileAsync("git",["rev-parse","--absolute-git-dir"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout),releaseLock=gitDirectory===null?null:await acquireLock(gitDirectory,MERGE_ATTRIBUTES_LOCK_ID,120,"merge-fence",!1,!0,5e3);try{const current=await readFileIfExists(gitattributesPath)??"",block=[PM_GITATTRIBUTES_V2_START,...patterns,PM_GITATTRIBUTES_V2_END].join(`
3
3
  `),blocks=managedMergeBlocks(current),owned=blocks.filter(candidate=>blockBelongsToTracker(candidate.lines,patterns,trackerRelativeRoot));owned.length===0&&trackerRelativeRoot===".agents/pm"&&blocks.length===1&&blocks[0].lines.every(line=>!line.includes("/"))&&owned.push(blocks[0]);let next;if(owned.length>0){const first=owned[0];next=current;for(const duplicate of owned.slice(1).reverse())next=`${next.slice(0,duplicate.start)}${next.slice(duplicate.end)}`;next=`${next.slice(0,first.start)}${block}${next.slice(first.end)}`}else{const prefix=current.trimEnd();next=`${prefix.length>0?`${prefix}
4
4
 
5
5
  `:""}${block}
6
- `}return next===current?{path:gitattributesPath,changed:!1}:(dryRun||await writeFileAtomic(gitattributesPath,next),{path:gitattributesPath,changed:!0})}finally{await releaseLock?.()}}function resolveProjectMergeTypeFolders(settings){const registry=resolveItemTypeRegistry(settings,null);return[...new Set(Object.values(registry.type_to_folder))].sort((left,right)=>left.localeCompare(right))}async function auditMergeAttributeFence(pmRoot,typeFolders){const resolvedRoot=path.resolve(pmRoot);let fenceDirectory=null,fenceContent="",directory=resolvedRoot;for(let depth=0;depth<8;depth+=1){const candidate=path.join(directory,".gitattributes");try{const raw=await readFile(candidate,"utf8");if(raw.includes(PM_GITATTRIBUTES_V2_START)||raw.includes(PM_GITATTRIBUTES_START)){fenceDirectory=directory,fenceContent=raw;break}}catch{}const parent=path.dirname(directory);if(parent===directory)break;directory=parent}if(fenceDirectory===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};const fencePath=path.join(fenceDirectory,".gitattributes"),relativeRoot=toPosixRelative(fenceDirectory,resolvedRoot),blocks=managedMergeBlocks(fenceContent),expected=buildMergeAttributePatterns(relativeRoot,typeFolders),owned=blocks.filter(block=>blockBelongsToTracker(block.lines,expected,relativeRoot)),committed=owned.flatMap(block=>block.closed?block.lines:[]),committedSet=new Set(committed),expectedSet=new Set(expected),missing=expected.filter(line=>!committedSet.has(line)),stale=committed.filter(line=>!expectedSet.has(line));return{status:owned.length!==1||!owned[0].closed||missing.length>0||stale.length>0?"drift":"ok",path:fencePath,missing_patterns:missing,stale_patterns:stale,schema_scope:"project"}}async function auditMergeDriverConfiguration(workspaceRoot){const missingKeys=[],driftedKeys=[];for(const definition of MERGE_DRIVER_DEFINITIONS){const key=`merge.${definition.key}.driver`,expectedSuffix=` merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`;try{const{stdout}=await execFileAsync("git",["config","--get",key],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4}),configured=stdout.trim();await isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot)||driftedKeys.push(key)}catch{missingKeys.push(key)}}return{status:missingKeys.length>0?"missing":driftedKeys.length>0?"drift":"ok",missing_keys:missingKeys,drifted_keys:driftedKeys}}async function refreshMergeAttributeFenceIfInstalled(pmRoot){let workspaceRoot;try{workspaceRoot=await resolveGitWorkspaceRoot(path.resolve(pmRoot))}catch{return{status:"no_git"}}const trackerRelativeRoot=toPosixRelative(workspaceRoot,path.resolve(pmRoot)),lockSettings=await readSettings(pmRoot),owner=resolveAuthor(void 0,lockSettings.author_default),releaseLock=await acquireLock(pmRoot,MERGE_FENCE_LOCK_ID,lockSettings.locks.ttl_seconds,owner,!1,resolveGovernanceKnobs(lockSettings).force_required_for_stale_lock,lockSettings.locks.wait_ms);try{const gitattributesPath=path.join(workspaceRoot,".gitattributes");let current;try{current=await readFile(gitattributesPath,"utf8")}catch(error){if(error instanceof Error&&"code"in error&&isFileMissingError(error))return{status:"not_installed",path:gitattributesPath};throw error}if(!current.includes(PM_GITATTRIBUTES_V2_START)&&!current.includes(PM_GITATTRIBUTES_START))return{status:"not_installed",path:gitattributesPath};const settings=await readSettings(pmRoot),typeFolders=resolveProjectMergeTypeFolders(settings),outcome=await reconcileGitattributesBlock(workspaceRoot,trackerRelativeRoot,buildMergeAttributePatterns(trackerRelativeRoot,typeFolders),!1);return{status:outcome.changed?"refreshed":"unchanged",path:outcome.path}}finally{await releaseLock()}}async function runMergeInstall(options,global2){const context=resolveMergeInstallContext({cwd:process.cwd(),explicitPath:global2.path,dryRun:options.dryRun===!0,environment:process.env}),pmRoot=context.pm_root;await assertInitializedTracker(pmRoot);const workspaceRoot=await resolveGitWorkspaceRoot(context.workspace_start);return installMergeFence({pmRoot,workspaceRoot,dryRun:options.dryRun===!0,preCommitHook:options.preCommitHook===!0})}async function installMergeDriverConfiguration(workspaceRoot,entries){const commonDirectory=(await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout.trim(),release=await acquireLock(commonDirectory,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{const scope=await resolveMergeDriverConfigScope(workspaceRoot);let stdout;try{stdout=(await execFileAsync("git",["config",scope,"--null","--get-regexp","."],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout}catch(error){if(typeof error!="object"||error===null||!("code"in error)||error.code!==1)throw error;stdout=""}const current=new Map(stdout.split("\0").filter(Boolean).map(entry=>{const separator=entry.indexOf(`
6
+ `}return next===current&&!(await lstat(gitattributesPath)).isSymbolicLink()?{path:gitattributesPath,changed:!1}:(dryRun||await writeFileAtomic(gitattributesPath,next),{path:gitattributesPath,changed:!0})}finally{await releaseLock?.()}}function resolveProjectMergeTypeFolders(settings){const registry=resolveItemTypeRegistry(settings,null);return[...new Set(Object.values(registry.type_to_folder))].sort((left,right)=>left.localeCompare(right))}async function realDirectory(directory){try{return await realpath(directory)}catch{return null}}function isWithinDirectory(root,directory){const relative=path.relative(root,directory);return relative===""||!path.isAbsolute(relative)&&relative.split(path.sep)[0]!==".."}async function readWorktreeAttributeFile(candidate){try{return(await lstat(candidate)).isFile()?await readFile(candidate,"utf8"):null}catch{return null}}async function readAttributeFile(candidate){try{return await readFile(candidate,"utf8")}catch{return null}}async function resolveFenceWalk(resolvedRoot,gitWorkspaceRoot){const requested=gitWorkspaceRoot===void 0?await findGitWorkspaceRoot(resolvedRoot):gitWorkspaceRoot;if(requested===null)return{trackerRoot:resolvedRoot,topLevel:null};const[trackerRoot,topLevel]=await Promise.all([realDirectory(resolvedRoot),realDirectory(requested)]);return trackerRoot===null||topLevel===null||!isWithinDirectory(topLevel,trackerRoot)?null:{trackerRoot,topLevel}}async function findManagedFenceFile(walk){const read=walk.topLevel===null?readAttributeFile:readWorktreeAttributeFile;let directory=walk.trackerRoot;for(let depth=0;walk.topLevel!==null||depth<8;depth+=1){const content=await read(path.join(directory,".gitattributes"));if(content!==null&&(content.includes(PM_GITATTRIBUTES_V2_START)||content.includes(PM_GITATTRIBUTES_START)))return{directory,content};const parent=path.dirname(directory);if(parent===directory||walk.topLevel!==null&&path.relative(walk.topLevel,directory)==="")return null;directory=parent}return null}async function auditMergeAttributeFence(pmRoot,typeFolders,options={}){const walk=await resolveFenceWalk(path.resolve(pmRoot),options.gitWorkspaceRoot),fence=walk===null?null:await findManagedFenceFile(walk);if(walk===null||fence===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};const fenceDirectory=fence.directory,fenceContent=fence.content,fencePath=path.join(fenceDirectory,".gitattributes"),relativeRoot=toPosixRelative(fenceDirectory,walk.trackerRoot),blocks=managedMergeBlocks(fenceContent),expected=buildMergeAttributePatterns(relativeRoot,typeFolders),owned=blocks.filter(block=>blockBelongsToTracker(block.lines,expected,relativeRoot)),committed=owned.flatMap(block=>block.closed?block.lines:[]),committedSet=new Set(committed),expectedSet=new Set(expected),missing=expected.filter(line=>!committedSet.has(line)),stale=committed.filter(line=>!expectedSet.has(line));return{status:owned.length!==1||!owned[0].closed||missing.length>0||stale.length>0?"drift":"ok",path:fencePath,missing_patterns:missing,stale_patterns:stale,schema_scope:"project"}}async function auditMergeDriverConfiguration(workspaceRoot){const missingKeys=[],driftedKeys=[];for(const definition of MERGE_DRIVER_DEFINITIONS){const key=`merge.${definition.key}.driver`,expectedSuffix=` merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`;try{const{stdout}=await execFileAsync("git",["config","--get",key],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4}),configured=stdout.trim();await isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot)||driftedKeys.push(key)}catch{missingKeys.push(key)}}return{status:missingKeys.length>0?"missing":driftedKeys.length>0?"drift":"ok",missing_keys:missingKeys,drifted_keys:driftedKeys}}async function refreshMergeAttributeFenceIfInstalled(pmRoot){let workspaceRoot;try{workspaceRoot=await resolveGitWorkspaceRoot(path.resolve(pmRoot))}catch{return{status:"no_git"}}const trackerRelativeRoot=toPosixRelative(workspaceRoot,path.resolve(pmRoot)),lockSettings=await readSettings(pmRoot),owner=resolveAuthor(void 0,lockSettings.author_default),releaseLock=await acquireLock(pmRoot,MERGE_FENCE_LOCK_ID,lockSettings.locks.ttl_seconds,owner,!1,resolveGovernanceKnobs(lockSettings).force_required_for_stale_lock,lockSettings.locks.wait_ms);try{const gitattributesPath=path.join(workspaceRoot,".gitattributes");let current;try{current=await readFile(gitattributesPath,"utf8")}catch(error){if(error instanceof Error&&"code"in error&&isFileMissingError(error))return{status:"not_installed",path:gitattributesPath};throw error}if(!current.includes(PM_GITATTRIBUTES_V2_START)&&!current.includes(PM_GITATTRIBUTES_START))return{status:"not_installed",path:gitattributesPath};const settings=await readSettings(pmRoot),typeFolders=resolveProjectMergeTypeFolders(settings),outcome=await reconcileGitattributesBlock(workspaceRoot,trackerRelativeRoot,buildMergeAttributePatterns(trackerRelativeRoot,typeFolders),!1);return{status:outcome.changed?"refreshed":"unchanged",path:outcome.path}}finally{await releaseLock()}}async function runMergeInstall(options,global2){const context=resolveMergeInstallContext({cwd:process.cwd(),explicitPath:global2.path,dryRun:options.dryRun===!0,environment:process.env}),pmRoot=context.pm_root;await assertInitializedTracker(pmRoot);const workspaceRoot=await resolveGitWorkspaceRoot(context.workspace_start);return installMergeFence({pmRoot,workspaceRoot,dryRun:options.dryRun===!0,preCommitHook:options.preCommitHook===!0})}async function installMergeDriverConfiguration(workspaceRoot,entries){const commonDirectory=(await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout.trim(),release=await acquireLock(commonDirectory,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{const scope=await resolveMergeDriverConfigScope(workspaceRoot);let stdout;try{stdout=(await execFileAsync("git",["config",scope,"--null","--get-regexp","."],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout}catch(error){if(typeof error!="object"||error===null||!("code"in error)||error.code!==1)throw error;stdout=""}const current=new Map(stdout.split("\0").filter(Boolean).map(entry=>{const separator=entry.indexOf(`
7
7
  `);return[entry.slice(0,separator),entry.slice(separator+1)]}));for(const entry of entries)current.get(entry.key)!==entry.value&&await writeMergeDriverGitConfig(workspaceRoot,[scope,entry.key,entry.value])}finally{await release()}}async function installMergeFence(options){const pmRoot=path.resolve(options.pmRoot),workspaceRoot=path.resolve(options.workspaceRoot),dryRun=options.dryRun===!0;let canonicalPmRoot,canonicalWorkspaceRoot;try{[canonicalPmRoot,canonicalWorkspaceRoot]=await Promise.all([realpath(pmRoot),realpath(workspaceRoot)])}catch(error){throw new PmCliError(`Cannot resolve tracker root ${pmRoot} or workspace root ${workspaceRoot}: ${String(error)}`,EXIT_CODE.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}const trackerRelativeRoot=toPosixRelative(canonicalWorkspaceRoot,canonicalPmRoot);if(isPathOutsideRoot(trackerRelativeRoot))throw new PmCliError(`Tracker root ${pmRoot} is outside the git repository ${workspaceRoot}; there is nothing to configure for this repository.`,EXIT_CODE.USAGE);const settings=await readSettings(canonicalPmRoot),typeFolders=resolveProjectMergeTypeFolders(settings),patterns=buildMergeAttributePatterns(trackerRelativeRoot,typeFolders),gitConfigEntries=[],cliCommand=await resolveMergeDriverCliCommand(),settlementHook=options.preCommitHook===!0?await import("./settlement-hook.js").then(async hooks=>({plan:await hooks.prepareMergeSettlementHook(canonicalWorkspaceRoot,`${cliCommand} --pm-path ${quoteMergeDriverArgument(trackerRelativeRoot||".")}`),write:hooks.writeMergeSettlementHook})):void 0;for(const definition of MERGE_DRIVER_DEFINITIONS)gitConfigEntries.push({key:`merge.${definition.key}.name`,value:definition.name}),gitConfigEntries.push({key:`merge.${definition.key}.driver`,value:`${cliCommand} merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`});if(!dryRun)try{await installMergeDriverConfiguration(canonicalWorkspaceRoot,gitConfigEntries)}catch{throw new PmCliError(`Cannot install repository-local merge drivers in ${canonicalWorkspaceRoot}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,EXIT_CODE.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}const gitattributes=await reconcileGitattributesBlock(canonicalWorkspaceRoot,trackerRelativeRoot,patterns,dryRun);return settlementHook!==void 0&&!dryRun&&await settlementHook.write(settlementHook.plan),{ok:!0,dry_run:dryRun,workspace_root:canonicalWorkspaceRoot,pm_root:canonicalPmRoot,gitattributes:{path:gitattributes.path,changed:gitattributes.changed,patterns,schema_scope:"project"},git_config:gitConfigEntries,...settlementHook===void 0?{}:{settlement_hook:{path:settlementHook.plan.path,changed:settlementHook.plan.changed}},guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:nowIso()}}export{PM_GITATTRIBUTES_END,PM_GITATTRIBUTES_START,PM_GITATTRIBUTES_V2_END,PM_GITATTRIBUTES_V2_START,auditMergeAttributeFence,auditMergeDriverConfiguration,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall};
8
8
  //# sourceMappingURL=install.js.map
@@ -1,4 +1,4 @@
1
- import{type ItemDocumentFormatOptions}from "../../core/item/item-format.js";
1
+ import{type ItemDocumentFormatOptions}from "../../core/item/item-format.js";import type{HistoryEntry}from "../../types/index.js";
2
2
  /** Restricts which side of a three-way merge wins an unresolvable conflict. */
3
3
  export type MergePreferredSide="ours"|"theirs";
4
4
  /** Declares how competing item scalar writes select their retained value. */
@@ -14,7 +14,7 @@ export declare function encodeItemScalarDecisionValue(value:unknown):unknown;
14
14
  /** Hash scalars in disjoint present/missing domains for collision-free evidence. */
15
15
  export declare function hashItemScalarDecisionValue(value:unknown):string;
16
16
  /** Restricts the strategy labels reported by the history stream merge. */
17
- export type HistoryMergeStrategy="identical"|"fast_forward_ours"|"fast_forward_theirs"|"union_reanchor";
17
+ export type HistoryMergeStrategy="identical"|"fast_forward_ours"|"fast_forward_theirs"|"equivalent_bridges"|"union_reanchor";
18
18
  /** Documents the history stream merge result payload exchanged by command, SDK, and package integrations. */
19
19
  export interface HistoryMergeResult{
20
20
  /** Merged JSONL content ready to be written as the resolved history stream. */
@@ -31,6 +31,23 @@ entries_from_theirs:number;
31
31
  entries_total:number;
32
32
  /** Whether the merged chain required hash re-anchoring (true for every union merge). */
33
33
  reanchored:boolean;}
34
+ /**
35
+ * Indexes of `merged` records that cannot be presented as historical states
36
+ * (GH-1715): copies of records either branch already marked replay_inexact
37
+ * and, when the merge dissolves bridges, every record a branch's bridge
38
+ * covers plus every record the merged order places between that segment's
39
+ * first covered record and its bridge. An event interleaved there replays
40
+ * without the unrecorded change too. Records a retained live bridge covers
41
+ * are never marked, since marking would void the digest that keeps them.
42
+ */
43
+ declare function collectUnionInexactIndexes(merged:HistoryEntry[],sides:HistoryEntry[][],bridgesDissolve:boolean,markerOnlySides?:HistoryEntry[][]):Set<number>;
44
+ /**
45
+ * Whether a repair of the runs recurs among the later records, live or as a
46
+ * neutral copy. Moving it into the shared run would then record it twice.
47
+ */
48
+ declare function repairRecursAfterRuns(runs:HistoryEntry[],rests:HistoryEntry[]):boolean;
49
+ /** Whether normalized runs may replace the recorded ones: no repair recurs later and every side verifies. */
50
+ declare function normalizationApplies(runs:HistoryEntry[],rests:HistoryEntry[],sides:HistoryEntry[][]):boolean;
34
51
  /**
35
52
  * Deterministically merge two diverged versions of one append-only history
36
53
  * JSONL stream. Identical streams and one-sided fast-forwards keep the winning
@@ -157,4 +174,6 @@ preferred:MergePreferredSide;}
157
174
  */
158
175
  export declare function mergeJsonDocuments(baseRaw:string,oursRaw:string,theirsRaw:string,options?:{
159
176
  /** Side that wins unresolvable conflicts (default "ours"). */
160
- preferred?:MergePreferredSide;}):JsonDocumentMergeResult;
177
+ preferred?:MergePreferredSide;}):JsonDocumentMergeResult;
178
+ /** Internal helpers exported only for focused tests. */
179
+ export declare const _testOnly:{collectUnionInexactIndexes:typeof collectUnionInexactIndexes;normalizationApplies:typeof normalizationApplies;repairRecursAfterRuns:typeof repairRecursAfterRuns;};export{};
@@ -1,5 +1,11 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0f1f1c8e-c7be-5615-82b8-458d6d2d7812")}catch{}})();import{cloneEmptyReplayDocument,historyEntriesToRaw,normalizeReplayPatchOps,reanchorHistoryEntries,toReplayDocument,tryApplyReplayPatch}from"../../core/history/replay.js";import jsonPatch from"fast-json-patch";import{rebaseHistoryScalarPatch}from"./history-scalar-rebase.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../../core/item/item-format.js";import{splitAcceptanceCriteria}from"../../core/item/parse.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{PmCliError}from"../../core/shared/errors.js";import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{compareTimestampStrings}from"../../core/shared/time.js";import{hasConcreteItemFieldValue}from"../../core/item/deferred-fields.js";const ITEM_SCALAR_MISSING_VALUE=Object.freeze({pm_item_scalar_missing:!0});function isItemScalarMissingValue(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length===1&&value.pm_item_scalar_missing===!0}function encodeItemScalarDecisionValue(value){return value===void 0?ITEM_SCALAR_MISSING_VALUE:value}function hashItemScalarDecisionValue(value){return sha256Hex(stableStringify(value===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value}))}function parseHistoryJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{const parsed=JSON.parse(line);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new TypeError("history entry must be an object");entries.push(parsed)}catch{throw new PmCliError(`History merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}}return entries}function historyEntryIdentity(entry){return stableStringify({ts:entry.ts,author:entry.author,op:entry.op,patch:entry.patch,message:entry.message??null})}function commonHistoryPrefixLength(ours,theirs){const limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&historyEntryIdentity(ours[shared])===historyEntryIdentity(theirs[shared]);)shared+=1;return shared}function orderHistoryUnionSuffix(ours,theirs,incoming,oursIdentities){const entries=[...ours,...incoming],positions=new Map(entries.map((entry,index)=>[entry,index])),aliases=new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),successors=entries.map(()=>new Set);for(const branch of[ours,theirs]){const coordinates=branch.map(entry=>positions.get(entry)??aliases.get(historyEntryIdentity(entry)));for(let index=1;index<coordinates.length;index+=1)coordinates[index-1]!==coordinates[index]&&successors[coordinates[index-1]].add(coordinates[index])}const predecessors=entries.map(()=>0);for(const targets of successors)for(const target of targets)predecessors[target]+=1;const ready=entries.map((_,index)=>index).filter(index=>predecessors[index]===0),result=[];for(;ready.length>0;){ready.sort((leftIndex,rightIndex)=>{const left=entries[leftIndex],right=entries[rightIndex],byTs=compareTimestampStrings(left.ts,right.ts),leftIdentity=historyEntryIdentity(left),rightIdentity=historyEntryIdentity(right);return byTs||Number(oursIdentities.has(rightIdentity))-Number(oursIdentities.has(leftIdentity))});const index=ready.shift();result.push(entries[index]);for(const target of successors[index])predecessors[target]-=1,predecessors[target]===0&&ready.push(target)}if(result.length!==entries.length)throw new PmCliError("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return result}function createHistoryBranchProjection(entries){return{entries,positions:new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),index:-1,document:cloneEmptyReplayDocument()}}function advanceHistoryBranch(state,target){const end=target??state.index;for(;state.index<end;){const applied=tryApplyReplayPatch(state.document,state.entries[state.index+1].patch);if(!applied.ok)throw new PmCliError("History union cannot preserve a patch that does not apply in its original branch.",EXIT_CODE.GENERIC_FAILURE);state.document=applied.document,state.index+=1}return state.document}function advanceOrderedHistoryBranch(state,target){if(target!==void 0&&target>state.index+1)throw new PmCliError("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return advanceHistoryBranch(state,target)}function historyUnionPatchProjection(ours,theirs,shared){if(shared===0)return;const oursBranch=createHistoryBranchProjection(ours),theirsBranch=createHistoryBranchProjection(theirs),prefix=advanceHistoryBranch(oursBranch,shared-1);advanceHistoryBranch(theirsBranch,shared-1);let position=0;const unionFields=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]);return(entry,current)=>{if(position++<shared)return entry.patch;const identity=historyEntryIdentity(entry),oursState=advanceOrderedHistoryBranch(oursBranch,oursBranch.positions.get(identity)),theirsState=advanceOrderedHistoryBranch(theirsBranch,theirsBranch.positions.get(identity)),scalarPatch=normalizeReplayPatchOps(entry.patch).filter(operation=>{const[root,field]=operation.path.slice(1).split("/");return root!=="metadata"||!unionFields.has(field)}),oursPosition=oursBranch.positions.get(identity),next=rebaseHistoryScalarPatch(current,scalarPatch,{branch:oursPosition===void 0?"theirs":"ours",line:(oursPosition??theirsBranch.positions.get(identity))+1,op:entry.op}),merged=mergeItemMetadataRecords(prefix.metadata,oursState.metadata,theirsState.metadata,"ours","latest_document_update",String(oursState.metadata.updated_at),String(theirsState.metadata.updated_at));for(const field of unionFields)Object.hasOwn(merged.merged,field)?next.metadata[field]=merged.merged[field]:delete next.metadata[field];rebaseReplayDeferrals(next.metadata,prefix.metadata,oursState.metadata,theirsState.metadata);const canonical=toReplayDocument({metadata:next.metadata,body:next.body});return jsonPatch.compare(current,canonical)}}function mergeHistoryStreams(baseRaw,oursRaw,theirsRaw){const base=parseHistoryJsonl(baseRaw,"base"),ours=parseHistoryJsonl(oursRaw,"ours"),theirs=parseHistoryJsonl(theirsRaw,"theirs"),creates=[base,ours,theirs].map(entries=>entries.filter(entry=>entry.op==="create"));if(creates[0].length===0&&creates.slice(1).every(entries=>entries.length>0)||creates.some(entries=>entries.length>1)||new Set(creates.flat().map(historyEntryIdentity)).size>1)throw new PmCliError("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict"});const shared=commonHistoryPrefixLength(ours,theirs);if(shared===ours.length&&shared===theirs.length)return{merged:historyEntriesToRaw(ours),strategy:"identical",common_entries:shared,entries_from_ours:0,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===theirs.length)return{merged:historyEntriesToRaw(ours),strategy:"fast_forward_ours",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===ours.length)return{merged:historyEntriesToRaw(theirs),strategy:"fast_forward_theirs",common_entries:shared,entries_from_ours:0,entries_from_theirs:theirs.length-shared,entries_total:theirs.length,reanchored:!1};const oursSuffix=ours.slice(shared),seenIdentities=new Set(oursSuffix.map(historyEntryIdentity)),theirsSuffix=theirs.slice(shared).filter(entry=>!seenIdentities.has(historyEntryIdentity(entry))),mergedSuffix=orderHistoryUnionSuffix(oursSuffix,theirs.slice(shared),theirsSuffix,seenIdentities),reanchored=reanchorHistoryEntries([...ours.slice(0,shared),...mergedSuffix],void 0,{continuousHashSurface:!0,projectPatch:historyUnionPatchProjection(ours,theirs,shared)});if(reanchored.skippedOps>0)throw new PmCliError(`History union cannot preserve ${reanchored.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,EXIT_CODE.GENERIC_FAILURE);return{merged:historyEntriesToRaw(reanchored.entries),strategy:"union_reanchor",common_entries:shared,entries_from_ours:oursSuffix.length,entries_from_theirs:theirsSuffix.length,entries_total:reanchored.entries.length,reanchored:!0}}function parseRelationshipJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`Relationship merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const events=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(!line)continue;let parsed;try{parsed=JSON.parse(line)}catch{throw new PmCliError(`Relationship merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)||typeof parsed.eventId!="string"||typeof parsed.sequence!="number")throw new PmCliError(`Relationship merge input (${label}) line ${index+1} is not a relationship event (eventId + sequence required).`,EXIT_CODE.GENERIC_FAILURE);events.push(parsed)}return events}function relationshipEventsToRaw(events){return events.length===0?"":`${events.map(event=>JSON.stringify(event)).join(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="daf42303-3202-5824-975c-054e24d275d4")}catch{}})();import{cloneEmptyReplayDocument,historyEntriesToRaw,normalizeReplayPatchOps,reanchorHistoryEntries,toReplayDocument,tryApplyReplayPatch,verifyHistoryChainWithVersion,collectBridgedInteriorIndexes,markHistoryEntryInexact}from"../../core/history/replay.js";import jsonPatch from"fast-json-patch";import{locateBridgedSegments,readHistoryBridge}from"../../core/history/bridge.js";import{resealHistoryRewrite}from"../../core/history/history.js";import{rebaseHistoryScalarPatch}from"./history-scalar-rebase.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../../core/item/item-format.js";import{splitAcceptanceCriteria}from"../../core/item/parse.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{PmCliError}from"../../core/shared/errors.js";import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{compareTimestampStrings}from"../../core/shared/time.js";import{hasConcreteItemFieldValue}from"../../core/item/deferred-fields.js";const ITEM_SCALAR_MISSING_VALUE=Object.freeze({pm_item_scalar_missing:!0});function isItemScalarMissingValue(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length===1&&value.pm_item_scalar_missing===!0}function encodeItemScalarDecisionValue(value){return value===void 0?ITEM_SCALAR_MISSING_VALUE:value}function hashItemScalarDecisionValue(value){return sha256Hex(stableStringify(value===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value}))}function parseHistoryJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{const parsed=JSON.parse(line);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new TypeError("history entry must be an object");entries.push(parsed)}catch{throw new PmCliError(`History merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}}return entries}function neutralizedBridgeOriginal(entry){if(entry.op!=="history_repair"||Object.hasOwn(entry,"bridge")||!Array.isArray(entry.patch)||entry.patch.length>0)return;const evidence=entry.reanchor_evidence;if(Array.isArray(evidence))return evidence.map(item=>item!==null&&typeof item=="object"?item.record:void 0).reverse().find(original=>original!==null&&typeof original=="object"&&Object.hasOwn(original,"bridge"))}function historyEntryIdentity(entry){const subject=neutralizedBridgeOriginal(entry)??entry;return historyRecordIdentity(subject)}function historyRecordIdentity(entry){return stableStringify({ts:entry.ts,author:entry.author,op:entry.op,patch:entry.patch,message:entry.message??null,...Object.hasOwn(entry,"bridge")?{bridge:entry.bridge}:{}})}function commonHistoryPrefixLength(ours,theirs){const limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&historyEntryIdentity(ours[shared])===historyEntryIdentity(theirs[shared]);)shared+=1;return shared}function orderHistoryUnionSuffix(ours,theirs,incoming,oursIdentities){const entries=[...ours,...incoming],positions=new Map(entries.map((entry,index)=>[entry,index])),aliases=new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),successors=entries.map(()=>new Set);for(const branch of[ours,theirs]){const coordinates=branch.map(entry=>positions.get(entry)??aliases.get(historyEntryIdentity(entry)));for(let index=1;index<coordinates.length;index+=1)coordinates[index-1]!==coordinates[index]&&successors[coordinates[index-1]].add(coordinates[index])}const predecessors=entries.map(()=>0);for(const targets of successors)for(const target of targets)predecessors[target]+=1;const ready=entries.map((_,index)=>index).filter(index=>predecessors[index]===0),result=[];for(;ready.length>0;){ready.sort((leftIndex,rightIndex)=>{const left=entries[leftIndex],right=entries[rightIndex],byTs=compareTimestampStrings(left.ts,right.ts),leftIdentity=historyEntryIdentity(left),rightIdentity=historyEntryIdentity(right);return byTs||Number(oursIdentities.has(rightIdentity))-Number(oursIdentities.has(leftIdentity))});const index=ready.shift();result.push(entries[index]);for(const target of successors[index])predecessors[target]-=1,predecessors[target]===0&&ready.push(target)}if(result.length!==entries.length)throw new PmCliError("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return result}function createHistoryBranchProjection(entries){return{entries,positions:new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),index:-1,document:cloneEmptyReplayDocument()}}function advanceHistoryBranch(state,target){const end=target??state.index;for(;state.index<end;){const applied=tryApplyReplayPatch(state.document,state.entries[state.index+1].patch);if(!applied.ok)throw new PmCliError("History union cannot preserve a patch that does not apply in its original branch.",EXIT_CODE.GENERIC_FAILURE);state.document=applied.document,state.index+=1}return state.document}function advanceOrderedHistoryBranch(state,target){if(target!==void 0&&target>state.index+1)throw new PmCliError("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return advanceHistoryBranch(state,target)}function historyUnionPatchProjection(ours,theirs,shared){if(shared===0)return;const oursBranch=createHistoryBranchProjection(ours),theirsBranch=createHistoryBranchProjection(theirs),prefix=advanceHistoryBranch(oursBranch,shared-1);advanceHistoryBranch(theirsBranch,shared-1);let position=0;const unionFields=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]);return(entry,current)=>{if(position++<shared)return entry.patch;const identity=historyEntryIdentity(entry),oursState=advanceOrderedHistoryBranch(oursBranch,oursBranch.positions.get(identity)),theirsState=advanceOrderedHistoryBranch(theirsBranch,theirsBranch.positions.get(identity)),scalarPatch=normalizeReplayPatchOps(entry.patch).filter(operation=>{const[root,field]=operation.path.slice(1).split("/");return root!=="metadata"||!unionFields.has(field)}),oursPosition=oursBranch.positions.get(identity),next=rebaseHistoryScalarPatch(current,scalarPatch,{branch:oursPosition===void 0?"theirs":"ours",line:(oursPosition??theirsBranch.positions.get(identity))+1,op:entry.op}),merged=mergeItemMetadataRecords(prefix.metadata,oursState.metadata,theirsState.metadata,"ours","latest_document_update",String(oursState.metadata.updated_at),String(theirsState.metadata.updated_at));for(const field of unionFields)Object.hasOwn(merged.merged,field)?next.metadata[field]=merged.merged[field]:delete next.metadata[field];rebaseReplayDeferrals(next.metadata,prefix.metadata,oursState.metadata,theirsState.metadata);const canonical=toReplayDocument({metadata:next.metadata,body:next.body});return jsonPatch.compare(current,canonical)}}function historyBridgeRepairIdentity(entry){const bridge=readHistoryBridge(entry);return typeof bridge=="object"?stableStringify({bridge,patch:entry.patch,before_hash:entry.before_hash,after_hash:entry.after_hash,item_hash_version:entry.item_hash_version,hash_algorithm:entry.hash_algorithm}):null}function collectUnionInexactIndexes(merged,sides,bridgesDissolve,markerOnlySides=[]){const position=occurrencePositions(merged).positions,marked=new Set;return[...sides,...markerOnlySides].forEach((side,sideIndex)=>{const{occurrence}=occurrencePositions(side),place=index=>mergedPosition(position,side,occurrence,index);side.forEach((entry,index)=>{entry.replay_inexact===!0&&addUnionPosition(marked,place(index))}),bridgesDissolve&&sideIndex<sides.length&&markBranchBridgeCoverage(marked,side,place)}),bridgesDissolve||releaseRetainedBridgeSegments(marked,merged),marked}function occurrencePositions(entries){const positions=new Map,occurrence=entries.map((entry,index)=>{const identity=historyEntryIdentity(entry),seen=positions.get(identity);return seen===void 0?(positions.set(identity,[index]),0):(seen.push(index),seen.length-1)});return{positions,occurrence}}function mergedPosition(merged,side,sideOccurrence,index){return merged.get(historyEntryIdentity(side[index]))?.[sideOccurrence[index]]}function addUnionPosition(marked,index){index!==void 0&&marked.add(index)}function markBranchBridgeCoverage(marked,side,place){for(const segment of locateBridgedSegments(side).segments){for(const index of collectBridgedInteriorIndexes([segment]))addUnionPosition(marked,place(index));const from=place(segment.start),to=place(segment.end);if(!(from===void 0||to===void 0))for(let index=from;index<to;index+=1)marked.add(index)}}function releaseRetainedBridgeSegments(marked,merged){for(const segment of locateBridgedSegments(merged).segments)if(segment.exact)for(let index=segment.start;index<segment.end;index+=1)marked.delete(index)}function markInexactUnionEntries(entries,indexes){let changed=!1;return{entries:entries.map((entry,index)=>entry.replay_inexact===!0||!indexes.has(index)?entry:(changed=!0,markHistoryEntryInexact(entry))),changed}}function mergeEquivalentBridgeResult(ours,theirs,shared,oursRaw,recordedSides){const neutralBridges=mergeEquivalentBridges(ours,theirs,shared);if(neutralBridges===null)return null;const output=[...ours,...neutralBridges],marked=markInexactUnionEntries(output,collectUnionInexactIndexes(output,[ours,theirs],!1,recordedSides)),oursKept=ours.every((entry,index)=>marked.entries[index]===entry),appended=marked.entries.slice(ours.length),separator=oursRaw.endsWith(`
2
+ `)||appended.length===0?"":`
3
+ `;return{merged:oursKept?`${oursRaw}${separator}${appended.map(entry=>`${JSON.stringify(entry)}
4
+ `).join("")}`:historyEntriesToRaw(marked.entries),strategy:"equivalent_bridges",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:neutralBridges.length,entries_total:output.length,reanchored:!1}}function mergeEquivalentBridges(ours,theirs,shared){const oursSuffix=ours.slice(shared),theirsSuffix=theirs.slice(shared),classes=new Set([...oursSuffix,...theirsSuffix].map(entry=>historyBridgeRepairIdentity(neutralizedBridgeOriginal(entry)??entry)));if(oursSuffix.length===0||theirsSuffix.length===0||classes.size!==1||classes.has(null))return null;const copies=neutralRepairCopies(oursSuffix,theirsSuffix,ours.at(-1).after_hash);return[ours,theirs,[...ours,...copies]].every(side=>verifyHistoryChainWithVersion(side).ok)?copies:null}function repairClassIdentity(entry){return entry===void 0?null:historyBridgeRepairIdentity(neutralizedBridgeOriginal(entry)??entry)}function neutralRepairCopies(ours,theirs,anchor){const present=new Set(ours.map(historyEntryIdentity));return theirs.filter(entry=>!present.has(historyEntryIdentity(entry))).map(entry=>{const original=neutralizedBridgeOriginal(entry)??entry,{bridge:_bridge,replay_inexact:_marker,...neutral}=original;return resealHistoryRewrite(original,{...neutral,patch:[],before_hash:anchor,after_hash:anchor,...entry.replay_inexact===!0?{replay_inexact:!0}:{}},{retainOriginalPatch:!0,retainPriorRecord:!0})})}function repairRecursAfterRuns(runs,rests){const runIdentities=new Set(runs.map(historyEntryIdentity));return rests.some(entry=>runIdentities.has(historyEntryIdentity(entry)))}function normalizationApplies(runs,rests,sides){return!repairRecursAfterRuns(runs,rests)&&sides.every(side=>verifyHistoryChainWithVersion(side).ok)}function repairRunLength(side,from,repairClass){let length=0;for(;repairClassIdentity(side[from+length])===repairClass;)length+=1;return length}function normalizeEquivalentRepairRuns(ours,theirs){const unchanged={ours,theirs,normalization:null},shared=commonHistoryPrefixLength(ours,theirs),repairClass=repairClassIdentity(ours[shared]);if(repairClass===null||repairClassIdentity(theirs[shared])!==repairClass)return unchanged;const oursRun=ours.slice(shared,shared+repairRunLength(ours,shared,repairClass)),theirsRun=theirs.slice(shared,shared+repairRunLength(theirs,shared,repairClass)),oursRest=ours.slice(shared+oursRun.length),theirsRest=theirs.slice(shared+theirsRun.length);if(oursRest.length===0&&theirsRest.length===0)return unchanged;const neutral=neutralRepairCopies(oursRun,theirsRun,oursRun.at(-1).after_hash),prefix=[...ours.slice(0,shared),...oursRun,...neutral],normalized={ours:[...prefix,...oursRest],theirs:[...prefix,...theirsRest]},sides=[ours,theirs,normalized.ours,normalized.theirs];return normalizationApplies([...oursRun,...theirsRun],[...oursRest,...theirsRest],sides)?{...normalized,normalization:{shared,neutralCopies:neutral.length}}:unchanged}function accountNormalizedMerge(result,normalization){const entriesFromTheirs=result.entries_from_theirs+normalization.neutralCopies;return{...result,strategy:result.strategy==="union_reanchor"?"union_reanchor":"equivalent_bridges",common_entries:normalization.shared,entries_from_ours:result.entries_total-normalization.shared-entriesFromTheirs,entries_from_theirs:entriesFromTheirs}}function mergeHistoryStreams(baseRaw,oursRaw,theirsRaw){const base=parseHistoryJsonl(baseRaw,"base"),recorded=[parseHistoryJsonl(oursRaw,"ours"),parseHistoryJsonl(theirsRaw,"theirs")],{ours,theirs,normalization}=normalizeEquivalentRepairRuns(recorded[0],recorded[1]),result=mergeParsedHistoryStreams(base,ours,theirs,normalization===null||normalization.neutralCopies===0?oursRaw:historyEntriesToRaw(ours),normalization===null?[]:recorded);return normalization===null?result:keepRecordedPrefixBytes(accountNormalizedMerge(result,normalization),recorded[0],oursRaw)}function keepRecordedPrefixBytes(result,recordedOurs,oursRaw){const lines=result.merged.split(`
5
+ `);return recordedOurs.every((entry,index)=>lines[index]===JSON.stringify(entry))?{...result,merged:`${oursRaw.replace(/(?<!\n)$/u,`
6
+ `)}${lines.slice(recordedOurs.length).join(`
7
+ `)}`}:result}function mergeParsedHistoryStreams(base,ours,theirs,oursRaw,recordedSides){const creates=[base,ours,theirs].map(entries=>entries.filter(entry=>entry.op==="create"));if(creates[0].length===0&&creates.slice(1).every(entries=>entries.length>0)||creates.some(entries=>entries.length>1)||new Set(creates.flat().map(historyEntryIdentity)).size>1)throw new PmCliError("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict"});const shared=commonHistoryPrefixLength(ours,theirs),keepSide=entries=>historyEntriesToRaw(markInexactUnionEntries(entries,collectUnionInexactIndexes(entries,[ours,theirs],!1,recordedSides)).entries);if(shared===ours.length&&shared===theirs.length)return{merged:keepSide(ours),strategy:"identical",common_entries:shared,entries_from_ours:0,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===theirs.length)return{merged:keepSide(ours),strategy:"fast_forward_ours",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===ours.length)return{merged:keepSide(theirs),strategy:"fast_forward_theirs",common_entries:shared,entries_from_ours:0,entries_from_theirs:theirs.length-shared,entries_total:theirs.length,reanchored:!1};const oursSuffix=ours.slice(shared),equivalent=mergeEquivalentBridgeResult(ours,theirs,shared,oursRaw,recordedSides);if(equivalent!==null)return equivalent;const seenIdentities=new Set(oursSuffix.map(historyEntryIdentity)),theirsSuffix=theirs.slice(shared).filter(entry=>!seenIdentities.has(historyEntryIdentity(entry))),mergedSuffix=orderHistoryUnionSuffix(oursSuffix,theirs.slice(shared),theirsSuffix,seenIdentities),unionInput=[...ours.slice(0,shared),...mergedSuffix],reanchored=reanchorHistoryEntries(markInexactUnionEntries(unionInput,collectUnionInexactIndexes(unionInput,[ours,theirs],!0,recordedSides)).entries,void 0,{continuousHashSurface:!0,projectPatch:historyUnionPatchProjection(ours,theirs,shared),callerMarksBridgeCoverage:!0});if(reanchored.skippedOps>0)throw new PmCliError(`History union cannot preserve ${reanchored.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,EXIT_CODE.GENERIC_FAILURE);return{merged:historyEntriesToRaw(reanchored.entries),strategy:"union_reanchor",common_entries:shared,entries_from_ours:oursSuffix.length,entries_from_theirs:theirsSuffix.length,entries_total:reanchored.entries.length,reanchored:!0}}function parseRelationshipJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`Relationship merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const events=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(!line)continue;let parsed;try{parsed=JSON.parse(line)}catch{throw new PmCliError(`Relationship merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)||typeof parsed.eventId!="string"||typeof parsed.sequence!="number")throw new PmCliError(`Relationship merge input (${label}) line ${index+1} is not a relationship event (eventId + sequence required).`,EXIT_CODE.GENERIC_FAILURE);events.push(parsed)}return events}function relationshipEventsToRaw(events){return events.length===0?"":`${events.map(event=>JSON.stringify(event)).join(`
2
8
  `)}
3
9
  `}function renumberRelationshipEvents(events){return events.map((event,index)=>({...event,sequence:index+1}))}function mergeRelationshipEventStreams(baseRaw,oursRaw,theirsRaw){parseRelationshipJsonl(baseRaw,"base");const ours=parseRelationshipJsonl(oursRaw,"ours"),theirs=parseRelationshipJsonl(theirsRaw,"theirs"),limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&ours[shared].eventId===theirs[shared].eventId;)shared+=1;if(shared===ours.length&&shared===theirs.length)return{merged:relationshipEventsToRaw(ours),strategy:"identical",common_entries:shared,entries_from_ours:0,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===theirs.length)return{merged:relationshipEventsToRaw(ours),strategy:"fast_forward_ours",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===ours.length)return{merged:relationshipEventsToRaw(theirs),strategy:"fast_forward_theirs",common_entries:shared,entries_from_ours:0,entries_from_theirs:theirs.length-shared,entries_total:theirs.length,reanchored:!1};const oursSuffix=ours.slice(shared),oursEventIds=new Set(oursSuffix.map(event=>event.eventId)),theirsSuffix=theirs.slice(shared).filter(event=>!oursEventIds.has(event.eventId)),mergedSuffix=[...oursSuffix,...theirsSuffix].sort((left,right)=>{if(left.timestamp!==void 0&&right.timestamp!==void 0){const byTs=compareTimestampStrings(left.timestamp,right.timestamp);if(byTs!==0)return byTs}else{if(left.timestamp===void 0&&right.timestamp!==void 0)return 1;if(left.timestamp!==void 0)return-1}const leftFromOurs=oursEventIds.has(left.eventId),rightFromOurs=oursEventIds.has(right.eventId);return leftFromOurs!==rightFromOurs?Number(rightFromOurs)-Number(leftFromOurs):0}),merged=renumberRelationshipEvents([...ours.slice(0,shared),...mergedSuffix]);return{merged:relationshipEventsToRaw(merged),strategy:"union_reanchor",common_entries:shared,entries_from_ours:oursSuffix.length,entries_from_theirs:theirsSuffix.length,entries_total:merged.length,reanchored:!0}}const ITEM_UNION_COLLECTION_FIELDS=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events","deferred_fields"],ITEM_UNION_DELIMITED_FIELDS=["acceptance_criteria"],ITEM_LATEST_TIMESTAMP_FIELDS=["updated_at"];function jsonEquals(left,right){return left===void 0||right===void 0?left===void 0&&right===void 0:stableStringify(left)===stableStringify(right)}function unionCollection(base,ours,theirs){const toEntries=value=>Array.isArray(value)?value:[],baseIds=new Set(toEntries(base).map(entry=>stableStringify(entry))),oursEntries=toEntries(ours),oursIds=new Set(oursEntries.map(entry=>stableStringify(entry))),theirsEntries=toEntries(theirs),theirsIds=new Set(theirsEntries.map(entry=>stableStringify(entry))),merged=oursEntries.filter(entry=>{const identity=stableStringify(entry);return!baseIds.has(identity)||theirsIds.has(identity)});for(const entry of theirsEntries){const identity=stableStringify(entry);!oursIds.has(identity)&&!baseIds.has(identity)&&merged.push(entry)}return merged}function linkedTestDefinitionIdentity(value){if(typeof value!="object"||value===null||Array.isArray(value))return stableStringify(value);const{provenance:_provenance,...definition}=value;return stableStringify(definition)}function markMergedLinkedTest(value){if(typeof value!="object"||value===null||Array.isArray(value))return value;const test=value;return test.provenance?{...test,provenance:{...test.provenance,source_kind:"merge_union"}}:{...test,provenance:{source_kind:"merge_union"}}}function unionLinkedTests(base,ours,theirs){const toEntries=value=>Array.isArray(value)?value:[],baseIds=new Set(toEntries(base).map(linkedTestDefinitionIdentity)),oursEntries=toEntries(ours),oursIds=new Set(oursEntries.map(linkedTestDefinitionIdentity)),theirsEntries=toEntries(theirs),theirsIds=new Set(theirsEntries.map(linkedTestDefinitionIdentity)),merged=oursEntries.filter(entry=>{const identity=linkedTestDefinitionIdentity(entry);return!baseIds.has(identity)||theirsIds.has(identity)});for(const entry of theirsEntries){const identity=linkedTestDefinitionIdentity(entry);!oursIds.has(identity)&&!baseIds.has(identity)&&merged.push(markMergedLinkedTest(entry))}return merged}function latestTimestamp(ours,theirs){return compareTimestampStrings(String(ours),String(theirs))>=0?ours:theirs}function mergeScalarThreeWay(base,ours,theirs,preferred){return jsonEquals(ours,theirs)?{value:ours,from_theirs:!1,conflict:!1}:jsonEquals(base,ours)?{value:theirs,from_theirs:!0,conflict:!1}:jsonEquals(base,theirs)?{value:ours,from_theirs:!1,conflict:!1}:{value:preferred==="theirs"?theirs:ours,from_theirs:preferred==="theirs",conflict:!0}}function mergeItemScalarThreeWay(base,ours,theirs,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt){const outcome=mergeScalarThreeWay(base,ours,theirs,preferred);if(!outcome.conflict)return{...outcome,conflict:!1};if(conflictResolution==="preferred_side")return{...outcome,resolution_basis:"requested_preference",retained_side:outcome.from_theirs?"theirs":"ours"};const timestampOrder=compareTimestampStrings(oursUpdatedAt,theirsUpdatedAt);if(conflictResolution==="latest_document_update"&&timestampOrder!==0){const retainTheirs2=timestampOrder<0;return{value:retainTheirs2?theirs:ours,from_theirs:retainTheirs2,conflict:!0,resolution_basis:"document_updated_at",retained_side:retainTheirs2?"theirs":"ours"}}const retainTheirs=stableStringify(encodeItemScalarDecisionValue(theirs)).localeCompare(stableStringify(encodeItemScalarDecisionValue(ours)))<0;return{value:retainTheirs?theirs:ours,from_theirs:retainTheirs,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:retainTheirs?"theirs":"ours"}}function toMetadataRecord(document){return{...document.metadata}}function parseItemMergeSide(raw,label,options){try{const document=canonicalDocument(parseItemDocument(raw,{...options,requireSupportedFormat:!0}),options),reservedField=Object.entries(document.metadata).find(([,value])=>isItemScalarMissingValue(value))?.[0];if(reservedField!==void 0)throw new TypeError(`metadata field ${reservedField} uses the reserved missing-scalar evidence marker`);return document}catch(error){throw error instanceof PmCliError&&error.context?.code==="item_format_version_unsupported"?error:new PmCliError(`Item merge input (${label}) is not a readable item document: ${String(error)}`,EXIT_CODE.GENERIC_FAILURE)}}function mergeUnionFieldValue(field,base,ours,theirs){return field==="tests"?unionLinkedTests(base,ours,theirs):field==="deferred_fields"?unionDeferredFields(base,ours,theirs):field==="acceptance_criteria"?unionCollection(splitAcceptanceCriteria(base),splitAcceptanceCriteria(ours),splitAcceptanceCriteria(theirs)).join("; "):unionCollection(base,ours,theirs)}function unionDeferredFields(base,ours,theirs){const byField=value=>new Map((Array.isArray(value)?value:[]).map(entry=>[String(entry.field),entry])),[baseEntries,oursEntries,theirsEntries]=[byField(base),byField(ours),byField(theirs)],merged=[];for(const field of[...new Set([...oursEntries.keys(),...theirsEntries.keys()])].sort()){const[baseEntry,oursEntry,theirsEntry]=[baseEntries.get(field),oursEntries.get(field),theirsEntries.get(field)];if(oursEntry===void 0||theirsEntry===void 0){merged.push(oursEntry??theirsEntry);continue}const outcome=mergeScalarThreeWay(baseEntry,oursEntry,theirsEntry,"ours");merged.push(outcome.conflict&&stableStringify(theirsEntry).localeCompare(stableStringify(oursEntry))<0?theirsEntry:outcome.value)}return merged}function mergeItemUnionField(params){if(!params.unionFieldSet.has(params.field))return!1;const union=mergeUnionFieldValue(params.field,params.baseValue,params.oursValue,params.theirsValue);return params.accumulator.merged[params.field]=union,jsonEquals(union,params.oursValue)||params.accumulator.unionFields.push(params.field),!0}function mergeItemScalarField(params){const outcome=mergeItemScalarThreeWay(params.baseValue,params.oursValue,params.theirsValue,params.preferred,params.conflictResolution,params.oursUpdatedAt,params.theirsUpdatedAt);outcome.value!==void 0&&(params.accumulator.merged[params.field]=outcome.value),outcome.conflict?(params.accumulator.conflictFields.push(params.field),params.accumulator.conflictDecisions.push({field:params.field,base:encodeItemScalarDecisionValue(params.baseValue),ours:encodeItemScalarDecisionValue(params.oursValue),theirs:encodeItemScalarDecisionValue(params.theirsValue),retained:encodeItemScalarDecisionValue(outcome.value),discarded:encodeItemScalarDecisionValue(outcome.from_theirs?params.oursValue:params.theirsValue),retained_side:outcome.retained_side,resolution_basis:outcome.resolution_basis})):outcome.from_theirs&&params.accumulator.fieldsFromTheirs.push(params.field)}function mergeItemMetadataRecords(baseRecord,oursRecord,theirsRecord,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt){const unionFieldSet=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]),latestFieldSet=new Set(ITEM_LATEST_TIMESTAMP_FIELDS),fieldNames=[...new Set([...Object.keys(oursRecord),...Object.keys(theirsRecord)])].sort((left,right)=>left.localeCompare(right)),accumulator={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(const field of fieldNames){const baseValue=baseRecord[field],oursValue=oursRecord[field],theirsValue=theirsRecord[field];if(!mergeItemUnionField({field,baseValue,oursValue,theirsValue,unionFieldSet,accumulator})){if(latestFieldSet.has(field)){accumulator.merged[field]=latestTimestamp(oursValue,theirsValue);continue}mergeItemScalarField({field,baseValue,oursValue,theirsValue,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt,accumulator})}}return reconcileMergedDeferrals(accumulator.merged),accumulator}function rebaseReplayDeferrals(replay,base,ours,theirs){const union=unionDeferredFields(base.deferred_fields,ours.deferred_fields,theirs.deferred_fields);replay.deferred_fields=union,reconcileMergedDeferrals(replay),replay.deferred_fields.length===0&&delete replay.deferred_fields}function reconcileMergedDeferrals(merged){Array.isArray(merged.deferred_fields)&&(merged.deferred_fields=merged.deferred_fields.filter(entry=>!hasConcreteItemFieldValue(merged,String(entry.field))))}function mergeItemDocuments(baseRaw,oursRaw,theirsRaw,options={}){const preferred=options.preferred??"ours",conflictResolution=options.conflictResolution??"preferred_side",ours=parseItemMergeSide(oursRaw,"ours",options),theirs=parseItemMergeSide(theirsRaw,"theirs",options);if(baseRaw.trim().length===0)throw new PmCliError("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:ours.metadata.id});const base=parseItemMergeSide(baseRaw,"base",options);if(base.metadata.id!==ours.metadata.id||base.metadata.id!==theirs.metadata.id)throw new PmCliError("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:base.metadata.id});const baseRecord=toMetadataRecord(base),oursRecord=toMetadataRecord(ours),theirsRecord=toMetadataRecord(theirs),{merged,conflictFields,fieldsFromTheirs,unionFields,conflictDecisions}=mergeItemMetadataRecords(baseRecord,oursRecord,theirsRecord,preferred,conflictResolution,ours.metadata.updated_at,theirs.metadata.updated_at),bodyOutcome=mergeItemScalarThreeWay(base.body,ours.body,theirs.body,preferred,conflictResolution,ours.metadata.updated_at,theirs.metadata.updated_at);bodyOutcome.conflict?(conflictFields.push("body"),conflictDecisions.push({field:"body",base:encodeItemScalarDecisionValue(base.body),ours:encodeItemScalarDecisionValue(ours.body),theirs:encodeItemScalarDecisionValue(theirs.body),retained:encodeItemScalarDecisionValue(bodyOutcome.value),discarded:encodeItemScalarDecisionValue(bodyOutcome.from_theirs?ours.body:theirs.body),retained_side:bodyOutcome.retained_side,resolution_basis:bodyOutcome.resolution_basis})):bodyOutcome.from_theirs&&fieldsFromTheirs.push("body");const mergedMetadata=merged;return mergedMetadata.pm_format_version=normalizeItemFormatVersion(Math.max(...[base.metadata,ours.metadata,theirs.metadata,mergedMetadata].map(requiredItemFormatVersion))),{merged:serializeItemDocument({metadata:mergedMetadata,body:bodyOutcome.value},options),conflict_fields:conflictFields,fields_from_theirs:fieldsFromTheirs,union_fields:unionFields,conflict_decisions:conflictDecisions,requested_preference:preferred,requested_preference_applied:conflictResolution==="preferred_side",conflict_resolution:conflictResolution}}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseJsonSide(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`JSON merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}.`,EXIT_CODE.GENERIC_FAILURE);if(raw.trim().length!==0)try{return JSON.parse(raw)}catch{throw new PmCliError(`JSON merge input (${label}) is not valid JSON.`,EXIT_CODE.GENERIC_FAILURE)}}function mergeAdditiveJsonArrays(base,ours,theirs){if(!Array.isArray(base)||!Array.isArray(ours)||!Array.isArray(theirs))return null;const countEntries=entries=>{const counts=new Map;for(const entry of entries){const identity=stableStringify(entry);counts.set(identity,(counts.get(identity)??0)+1)}return counts},baseCounts=countEntries(base),oursCounts=countEntries(ours),theirsCounts=countEntries(theirs);for(const[identity,baseCount]of baseCounts)if((oursCounts.get(identity)??0)<baseCount||(theirsCounts.get(identity)??0)<baseCount)return null;const unmatchedOursCounts=new Map(oursCounts),additionsFromTheirs=[];for(const entry of theirs){const identity=stableStringify(entry),unmatchedOursCount=unmatchedOursCounts.get(identity)??0;unmatchedOursCount>0?unmatchedOursCounts.set(identity,unmatchedOursCount-1):additionsFromTheirs.push(entry)}return{merged:[...ours,...additionsFromTheirs],acceptedTheirs:additionsFromTheirs.length>0}}function mergeJsonObjects(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs){if(!isPlainObject(ours)||!isPlainObject(theirs))return null;const baseObject=isPlainObject(base)?base:{},merged={},keys=[...new Set([...Object.keys(ours),...Object.keys(theirs)])].sort((left,right)=>left.localeCompare(right));for(const key of keys){const childPath=pathPrefix.length>0?`${pathPrefix}.${key}`:key,child=mergeJsonKey(baseObject,ours,theirs,key,preferred,childPath,conflictPaths,pathsFromTheirs);child!==void 0&&(merged[key]=child)}return merged}function mergeJsonValue(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs){if(jsonEquals(ours,theirs))return ours;const additiveArrayMerge=mergeAdditiveJsonArrays(base,ours,theirs);if(additiveArrayMerge!==null)return additiveArrayMerge.acceptedTheirs&&pathsFromTheirs.push(pathPrefix),additiveArrayMerge.merged;const mergedObject=mergeJsonObjects(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs);if(mergedObject!==null)return mergedObject;const outcome=mergeScalarThreeWay(base,ours,theirs,preferred);return outcome.conflict?conflictPaths.push(pathPrefix):outcome.from_theirs&&pathsFromTheirs.push(pathPrefix),outcome.value}function mergeJsonKey(base,ours,theirs,key,preferred,childPath,conflictPaths,pathsFromTheirs){const inOurs=Object.prototype.hasOwnProperty.call(ours,key),inTheirs=Object.prototype.hasOwnProperty.call(theirs,key),inBase=Object.prototype.hasOwnProperty.call(base,key);if(inOurs&&inTheirs)return mergeJsonValue(base[key],ours[key],theirs[key],preferred,childPath,conflictPaths,pathsFromTheirs);if(inOurs){if(inBase&&jsonEquals(base[key],ours[key])){pathsFromTheirs.push(childPath);return}return inBase?(conflictPaths.push(childPath),preferred==="theirs"?void 0:ours[key]):ours[key]}if(!(inBase&&jsonEquals(base[key],theirs[key])))return inBase?(conflictPaths.push(childPath),preferred==="theirs"?theirs[key]:void 0):(pathsFromTheirs.push(childPath),theirs[key])}function mergeJsonDocuments(baseRaw,oursRaw,theirsRaw,options={}){const preferred=options.preferred??"ours",base=parseJsonSide(baseRaw,"base"),ours=parseJsonSide(oursRaw,"ours"),theirs=parseJsonSide(theirsRaw,"theirs"),conflictPaths=[],pathsFromTheirs=[],merged=mergeJsonValue(base,ours,theirs,preferred,"",conflictPaths,pathsFromTheirs);return{merged:`${JSON.stringify(merged??null,null,2)}
4
- `,conflict_paths:conflictPaths,paths_from_theirs:pathsFromTheirs,preferred}}export{ITEM_LATEST_TIMESTAMP_FIELDS,ITEM_SCALAR_MISSING_VALUE,ITEM_UNION_COLLECTION_FIELDS,encodeItemScalarDecisionValue,hashItemScalarDecisionValue,isItemScalarMissingValue,mergeHistoryStreams,mergeItemDocuments,mergeJsonDocuments,mergeRelationshipEventStreams};
10
+ `,conflict_paths:conflictPaths,paths_from_theirs:pathsFromTheirs,preferred}}const _testOnly={collectUnionInexactIndexes,normalizationApplies,repairRecursAfterRuns};export{ITEM_LATEST_TIMESTAMP_FIELDS,ITEM_SCALAR_MISSING_VALUE,ITEM_UNION_COLLECTION_FIELDS,_testOnly,encodeItemScalarDecisionValue,hashItemScalarDecisionValue,isItemScalarMissingValue,mergeHistoryStreams,mergeItemDocuments,mergeJsonDocuments,mergeRelationshipEventStreams};
5
11
  //# sourceMappingURL=three-way.js.map
@@ -1,2 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f8f33f3d-854e-5cb4-b0bf-8d2d89da27e8")}catch{}})();import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{setTimeout as delay}from"node:timers/promises";const execFileAsync=promisify(execFile);async function writeMergeDriverGitConfig(cwd,args){const deadline=performance.now()+5e3;let backoff=25;for(;;)try{await execFileAsync("git",["config",...args],{cwd,env:{...gitWorkspaceEnvironment(),LC_ALL:"C"},timeout:1e4});return}catch(error){const remaining=deadline-performance.now();if(typeof error!="object"||error===null||!("stderr"in error)||typeof error.stderr!="string"||!/could not lock config file [^\r\n]+: File exists/u.test(error.stderr)||remaining<=0)throw error;await delay(Math.min(backoff,remaining)),backoff=Math.min(backoff*2,200)}}function gitWorkspaceEnvironment(){const env={...process.env};for(const key of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete env[key];return env}async function readLocalGitConfig(cwd,key){try{return(await execFileAsync("git",["config","--local",...key==="core.bare"||key==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",key],{cwd,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout.trim()}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&error.code===1)return;throw error}}async function resolveMergeDriverConfigScope(workspaceRoot){if(await readLocalGitConfig(workspaceRoot,"extensions.worktreeConfig")==="true")return"--worktree";const{stdout}=await execFileAsync("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4}),[gitDir,commonDir]=stdout.trim().split(/\r?\n/);if(gitDir===commonDir)return"--local";const mainConfig=path.join(commonDir,"config.worktree");for(const key of["core.bare","core.worktree"]){const value=await readLocalGitConfig(workspaceRoot,key);value===void 0||key==="core.bare"&&value!=="true"||(await writeMergeDriverGitConfig(workspaceRoot,["--file",mainConfig,key,value]),await writeMergeDriverGitConfig(workspaceRoot,["--local","--unset-all",key]))}for(const driver of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(const field of["name","driver"]){const key=`merge.${driver}.${field}`,value=await readLocalGitConfig(workspaceRoot,key);value!==void 0&&await writeMergeDriverGitConfig(workspaceRoot,["--file",mainConfig,key,value])}return await writeMergeDriverGitConfig(workspaceRoot,["--local","extensions.worktreeConfig","true"]),"--worktree"}export{gitWorkspaceEnvironment,resolveMergeDriverConfigScope,writeMergeDriverGitConfig};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f2a4f406-8400-50ac-a90a-f8498ab9b773")}catch{}})();import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{setTimeout as delay}from"node:timers/promises";const execFileAsync=promisify(execFile);async function writeMergeDriverGitConfig(cwd,args){const deadline=performance.now()+5e3;let backoff=25;for(;;)try{await execFileAsync("git",["config",...args],{cwd,env:{...gitWorkspaceEnvironment(),LC_ALL:"C"},timeout:1e4});return}catch(error){const remaining=deadline-performance.now();if(typeof error!="object"||error===null||!("stderr"in error)||typeof error.stderr!="string"||!/could not lock config file [^\r\n]+: File exists/u.test(error.stderr)||remaining<=0)throw error;await delay(Math.min(backoff,remaining)),backoff=Math.min(backoff*2,200)}}function stripGitPathTerminator(stdout,platform=process.platform){const line=stdout.endsWith(`
2
+ `)?stdout.slice(0,-1):stdout;return platform==="win32"&&line.endsWith("\r")?line.slice(0,-1):line}function gitWorkspaceEnvironment(){const env={...process.env};for(const key of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete env[key];return env}async function readLocalGitConfig(cwd,key){try{return(await execFileAsync("git",["config","--local",...key==="core.bare"||key==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",key],{cwd,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout.trim()}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&error.code===1)return;throw error}}async function resolveMergeDriverConfigScope(workspaceRoot){if(await readLocalGitConfig(workspaceRoot,"extensions.worktreeConfig")==="true")return"--worktree";const readGitPath=async flag=>stripGitPathTerminator((await execFileAsync("git",["rev-parse","--path-format=absolute",flag],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout),gitDir=await readGitPath("--git-dir"),commonDir=await readGitPath("--git-common-dir");if(gitDir===commonDir)return"--local";const mainConfig=path.join(commonDir,"config.worktree");for(const key of["core.bare","core.worktree"]){const value=await readLocalGitConfig(workspaceRoot,key);value===void 0||key==="core.bare"&&value!=="true"||(await writeMergeDriverGitConfig(workspaceRoot,["--file",mainConfig,key,value]),await writeMergeDriverGitConfig(workspaceRoot,["--local","--unset-all",key]))}for(const driver of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(const field of["name","driver"]){const key=`merge.${driver}.${field}`,value=await readLocalGitConfig(workspaceRoot,key);value!==void 0&&await writeMergeDriverGitConfig(workspaceRoot,["--file",mainConfig,key,value])}return await writeMergeDriverGitConfig(workspaceRoot,["--local","extensions.worktreeConfig","true"]),"--worktree"}export{gitWorkspaceEnvironment,resolveMergeDriverConfigScope,stripGitPathTerminator,writeMergeDriverGitConfig};
2
3
  //# sourceMappingURL=worktree-config.js.map