@unbrained/pm-cli 2026.11.20 → 2026.11.21

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 (168) hide show
  1. package/.agents/skills/pm-sdk/SKILL.md +1 -1
  2. package/.agents/skills/pm-test-audit/SKILL.md +1 -1
  3. package/.claude-plugin/marketplace.json +1 -1
  4. package/CONTRIBUTING.md +2 -1
  5. package/dist/cli/error-guidance.js +2 -2
  6. package/dist/cli/register-list-query.js +2 -2
  7. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  8. package/dist/cli-bundle/bundle-manifest.json +1 -1
  9. package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +21 -0
  10. package/dist/cli-bundle/chunks/{chunk-XK25TAJZ.js → chunk-5647LU3A.js} +4 -4
  11. package/dist/cli-bundle/chunks/{chunk-OXG5XPC7.js → chunk-6QLEXRUG.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-MGYAJONE.js → chunk-AHQB7W2H.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-3BOR22MC.js → chunk-BKSVHOWI.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-KQSPKWFH.js → chunk-CASX6SFI.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-ZVEHACE6.js → chunk-CIKGG34F.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-KDDIHGAO.js → chunk-D6ILFXZY.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-M5D3CEMY.js → chunk-IUIOTAF6.js} +4 -4
  18. package/dist/cli-bundle/chunks/{chunk-GXGW6KHB.js → chunk-JVGRFU5H.js} +2 -2
  19. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +3 -0
  20. package/dist/cli-bundle/chunks/{chunk-2IZGNOGT.js → chunk-KVBIMFUG.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +3 -0
  22. package/dist/cli-bundle/chunks/{chunk-5LF5QZT3.js → chunk-NCFCBKIP.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-HJQ3XPS3.js → chunk-NT5AKFE5.js} +30 -30
  24. package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +125 -0
  25. package/dist/cli-bundle/chunks/{chunk-KEBLUTC3.js → chunk-RMIRNYRG.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-6HRPGEBF.js → chunk-RULHZRFN.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-FF4TXJDH.js → chunk-S6HB3WL2.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-4QQPM3IY.js → chunk-SA4BNP3Q.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-DG2EOOFX.js → chunk-SRVTCYAU.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-4TZW4NLM.js → chunk-WELSVDPU.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-6X2AGUOT.js → chunk-XHJ3H5PL.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-ZAO7VGX3.js → chunk-XWHJIRNV.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +8 -0
  34. package/dist/cli-bundle/chunks/{chunk-FOYRE23V.js → chunk-YKJKQ7DM.js} +43 -43
  35. package/dist/cli-bundle/chunks/{chunk-Y4LXVPA5.js → chunk-YMUSRWV4.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-HQYIKAC6.js → chunk-YR2KEBHP.js} +2 -2
  37. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-ELEMA7IW.js → indexed-receipt-blobs-ITTXIN4K.js} +2 -2
  38. package/dist/cli-bundle/chunks/{item-revision-GE2CQECR.js → item-revision-R5SZPJZ5.js} +2 -2
  39. package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +2 -0
  40. package/dist/cli-bundle/chunks/{mutation-actor-5GYX7LP3.js → mutation-actor-3TG636XG.js} +2 -2
  41. package/dist/cli-bundle/chunks/{mutation-admission-72TYKPGU.js → mutation-admission-LICSDNNO.js} +2 -2
  42. package/dist/cli-bundle/chunks/{register-list-query-OQZZEWEB.js → register-list-query-SPGPS3OS.js} +10 -10
  43. package/dist/cli-bundle/chunks/{register-mutation-YZEUZ6XT.js → register-mutation-WWVECKFQ.js} +2 -2
  44. package/dist/cli-bundle/chunks/{register-operations-JNVCF7EW.js → register-operations-L6HFJNWD.js} +2 -2
  45. package/dist/cli-bundle/chunks/{register-setup-LDKULZSD.js → register-setup-K7UFG5TD.js} +2 -2
  46. package/dist/cli-bundle/chunks/{settlement-hook-E5LHZ4RD.js → settlement-hook-BXN5LEQD.js} +2 -2
  47. package/dist/cli-bundle/chunks/{stage-Q2QZ2IBG.js → stage-57KH3KAC.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-IXYBN6D2.js → chunk-3IRCYJI5.js} +3 -3
  49. package/dist/cli-bundle/focused-chunks/{chunk-DH4DHL6V.js → chunk-3V53UBHN.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-7SB6VKEI.js → chunk-532WZV65.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-KQJNJZKP.js → chunk-7A4QWNZX.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +3 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-MJP3TFVW.js → chunk-CWWKRI5P.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-FPKVHC3Q.js → chunk-HGFNL5XI.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +13 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-UATP3RK3.js → chunk-J63D6QST.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-ZKGGGU2K.js → chunk-JMQJBZQ5.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-O25KFLLA.js → chunk-LNHUE4VV.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-BZCLW5V7.js → chunk-MKM5NKD7.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-5VSXKA35.js → chunk-NP72ZDXE.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-PZSTRYTA.js → chunk-OSLQD5VH.js} +37 -37
  63. package/dist/cli-bundle/focused-chunks/{chunk-V55XZFOP.js → chunk-QGKLRXP7.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{chunk-TNKI6WKG.js → chunk-QSJW6NSQ.js} +53 -53
  65. package/dist/cli-bundle/focused-chunks/{chunk-PKMDWIP3.js → chunk-RPE6IX26.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +91 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-PQXTZLK3.js → chunk-UOC6257J.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-SJE3PYPI.js → chunk-URJ2E6AS.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +8 -0
  70. package/dist/cli-bundle/focused-chunks/{chunk-PRFEOCNZ.js → chunk-XCJSHNXK.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{chunk-QNJQPJWO.js → chunk-XQQSSKJI.js} +5 -5
  72. package/dist/cli-bundle/focused-chunks/{chunk-JUYJ7NXL.js → chunk-YOAYY3HE.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ZTRFCPH7.js → indexed-receipt-blobs-AF4U3F3D.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{item-revision-OXDZHMJ7.js → item-revision-3V3UIP5X.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{item-transaction-54VSTT6L.js → item-transaction-HLBW7B3J.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/{mutation-actor-6DYIF6NH.js → mutation-actor-62HKR5IO.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/{mutation-admission-2BYXANVJ.js → mutation-admission-X4PF2SG3.js} +2 -2
  78. package/dist/cli-bundle/focused-chunks/{settlement-hook-OUBUN45C.js → settlement-hook-ARYCZQY4.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/{stage-FGHSB3QX.js → stage-O7T7CXBB.js} +2 -2
  80. package/dist/cli-bundle/main.js +25 -25
  81. package/dist/cli-bundle/sdk-authoring.js +1 -1
  82. package/dist/cli-bundle/sdk-contracts.js +1 -1
  83. package/dist/cli-bundle/sdk-core.js +1 -1
  84. package/dist/cli-bundle/sdk-governance.js +1 -1
  85. package/dist/cli-bundle/sdk-graph.js +1 -1
  86. package/dist/cli-bundle/sdk-merge.js +58 -57
  87. package/dist/cli-bundle/sdk-query.js +1 -1
  88. package/dist/cli-bundle/sdk-runtime.js +1 -1
  89. package/dist/cli-bundle/sdk-testing.js +1 -1
  90. package/dist/cli-bundle/sdk.js +11 -11
  91. package/dist/core/extensions/index.d.ts +2 -0
  92. package/dist/core/extensions/index.js +1 -1
  93. package/dist/core/fs/fs-utils.d.ts +3 -1
  94. package/dist/core/fs/fs-utils.js +1 -1
  95. package/dist/core/history/history-stream-policy.js +1 -1
  96. package/dist/core/history/read.d.ts +11 -1
  97. package/dist/core/history/read.js +1 -1
  98. package/dist/core/history/stream-summary.d.ts +129 -0
  99. package/dist/core/history/stream-summary.js +3 -0
  100. package/dist/core/shared/errors.d.ts +8 -0
  101. package/dist/core/shared/errors.js +1 -1
  102. package/dist/core/shared/url-credentials.js +1 -1
  103. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  104. package/dist/sdk/governance/gc.js +1 -1
  105. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  106. package/dist/sdk/governance/validate.js +1 -1
  107. package/dist/sdk/governance/workspace-position.js +1 -1
  108. package/dist/sdk/history-provenance.js +1 -1
  109. package/dist/sdk/index.d.ts +1 -1
  110. package/dist/sdk/index.js +1 -1
  111. package/dist/sdk/merge/index.d.ts +1 -1
  112. package/dist/sdk/merge/index.js +1 -1
  113. package/dist/sdk/merge/install.d.ts +20 -6
  114. package/dist/sdk/merge/install.js +3 -3
  115. package/dist/sdk/merge/worktree-config.js +2 -1
  116. package/dist/sdk/public-surface.json +1 -1
  117. package/dist/sdk/query/activity.d.ts +67 -5
  118. package/dist/sdk/query/activity.js +1 -1
  119. package/dist/sdk/query/context.d.ts +13 -3
  120. package/dist/sdk/query/context.js +2 -2
  121. package/dist/sdk/query.d.ts +1 -1
  122. package/dist/sdk/query.js +1 -1
  123. package/docs/COMMANDS.md +56 -2
  124. package/docs/MERGE_SAFETY.md +8 -0
  125. package/docs/MUTATION_INTEGRITY.md +3 -1
  126. package/docs/PERFORMANCE.md +17 -2
  127. package/docs/README.md +6 -4
  128. package/docs/SDK.md +25 -1
  129. package/docs/TESTING.md +8 -697
  130. package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +1 -1
  131. package/marketplace.json +1 -1
  132. package/package.json +6 -2
  133. package/packages/pm-beads/package.json +1 -1
  134. package/packages/pm-calendar/package.json +1 -1
  135. package/packages/pm-command-kit/package.json +1 -1
  136. package/packages/pm-digital-twin/package.json +1 -1
  137. package/packages/pm-governance-audit/package.json +1 -1
  138. package/packages/pm-guide-shell/package.json +1 -1
  139. package/packages/pm-kanban/package.json +1 -1
  140. package/packages/pm-lifecycle-hooks/package.json +1 -1
  141. package/packages/pm-linked-test-adapters/package.json +1 -1
  142. package/packages/pm-search-advanced/package.json +1 -1
  143. package/packages/pm-templates/package.json +1 -1
  144. package/packages/pm-todos/package.json +1 -1
  145. package/packages/pm-vcs/package.json +1 -1
  146. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  147. package/plugins/pm-claude/package.json +1 -1
  148. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  149. package/plugins/pm-codex/package.json +1 -1
  150. package/plugins/pm-codex/plugin.json +1 -1
  151. package/runtime-dependencies.json +1 -1
  152. package/dist/cli-bundle/chunks/chunk-5OFMWP3Q.js +0 -3
  153. package/dist/cli-bundle/chunks/chunk-7ESF676D.js +0 -125
  154. package/dist/cli-bundle/chunks/chunk-7EZZ4W7O.js +0 -20
  155. package/dist/cli-bundle/chunks/chunk-VS565KBX.js +0 -2
  156. package/dist/cli-bundle/chunks/chunk-W4TLA5H3.js +0 -8
  157. package/dist/cli-bundle/chunks/item-transaction-YSAWJRA2.js +0 -2
  158. package/dist/cli-bundle/focused-chunks/chunk-3LRSQXCN.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +0 -2
  160. package/dist/cli-bundle/focused-chunks/chunk-I7XBR2RM.js +0 -91
  161. package/dist/cli-bundle/focused-chunks/chunk-SIPDQBJI.js +0 -8
  162. package/dist/cli-bundle/focused-chunks/chunk-TRCXANRR.js +0 -12
  163. package/docs/MCP_2026_07_28_CONFORMANCE.md +0 -41
  164. package/docs/QUALITY_EVIDENCE.md +0 -130
  165. package/docs/generated/FLAG_LEXICON_BUDGETS.md +0 -117
  166. package/docs/performance/cli-transport-overhead.md +0 -51
  167. package/docs/performance/runner-qualification.md +0 -36
  168. 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,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