@unbrained/pm-cli 2026.11.22 → 2026.11.24

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 (912) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/after-command-context-usage.js +1 -1
  3. package/dist/cli/argv-utils.js +1 -1
  4. package/dist/cli/bootstrap-args.js +1 -1
  5. package/dist/cli/bundle-integrity.js +2 -2
  6. package/dist/cli/command-namespaces.js +1 -1
  7. package/dist/cli/commander-usage.js +11 -11
  8. package/dist/cli/commands/annotations/comments.js +1 -1
  9. package/dist/cli/commands/annotations/docs.js +1 -1
  10. package/dist/cli/commands/annotations/files.js +1 -1
  11. package/dist/cli/commands/annotations/learnings.js +1 -1
  12. package/dist/cli/commands/annotations/notes.js +1 -1
  13. package/dist/cli/commands/extension/describe.js +1 -1
  14. package/dist/cli/commands/extension/extension.js +1 -1
  15. package/dist/cli/commands/extension/scaffold.js +1 -1
  16. package/dist/cli/commands/extension/shared.js +1 -1
  17. package/dist/cli/commands/governance/gc.js +1 -1
  18. package/dist/cli/commands/governance/health.js +1 -1
  19. package/dist/cli/commands/governance/telemetry.js +1 -1
  20. package/dist/cli/commands/governance/validate.js +1 -1
  21. package/dist/cli/commands/history/activity.js +1 -1
  22. package/dist/cli/commands/history/history-compact.js +1 -1
  23. package/dist/cli/commands/history/history-redact.js +1 -1
  24. package/dist/cli/commands/history/history-repair.js +1 -1
  25. package/dist/cli/commands/history/history.js +1 -1
  26. package/dist/cli/commands/history/restore.js +1 -1
  27. package/dist/cli/commands/lifecycle/append.js +1 -1
  28. package/dist/cli/commands/lifecycle/claim.js +1 -1
  29. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  30. package/dist/cli/commands/lifecycle/close.js +1 -1
  31. package/dist/cli/commands/lifecycle/copy.js +1 -1
  32. package/dist/cli/commands/lifecycle/create.js +1 -1
  33. package/dist/cli/commands/lifecycle/delete.js +1 -1
  34. package/dist/cli/commands/lifecycle/focus.js +1 -1
  35. package/dist/cli/commands/lifecycle/plan.js +1 -1
  36. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  37. package/dist/cli/commands/lifecycle/update.js +1 -1
  38. package/dist/cli/commands/query/aggregate.js +1 -1
  39. package/dist/cli/commands/query/context.js +1 -1
  40. package/dist/cli/commands/query/deps.js +1 -1
  41. package/dist/cli/commands/query/duplicates.js +1 -1
  42. package/dist/cli/commands/query/eval.js +1 -1
  43. package/dist/cli/commands/query/get.js +1 -1
  44. package/dist/cli/commands/query/graph.js +1 -1
  45. package/dist/cli/commands/query/list.js +1 -1
  46. package/dist/cli/commands/query/next.js +1 -1
  47. package/dist/cli/commands/query/search.js +1 -1
  48. package/dist/cli/commands/query/stats.js +1 -1
  49. package/dist/cli/commands/test/test-all.js +1 -1
  50. package/dist/cli/commands/test/test-runs.js +1 -1
  51. package/dist/cli/commands/test/test.js +1 -1
  52. package/dist/cli/commands/workspace/config.js +1 -1
  53. package/dist/cli/commands/workspace/contracts.js +1 -1
  54. package/dist/cli/commands/workspace/init.js +1 -1
  55. package/dist/cli/commands/workspace/merge.js +1 -1
  56. package/dist/cli/commands/workspace/profile.js +1 -1
  57. package/dist/cli/commands/workspace/schema.js +1 -1
  58. package/dist/cli/commands/workspace/upgrade.js +1 -1
  59. package/dist/cli/context-intent-invocation.js +1 -1
  60. package/dist/cli/description-stdin.js +1 -1
  61. package/dist/cli/error-guidance.js +5 -5
  62. package/dist/cli/expected-revisions.js +1 -1
  63. package/dist/cli/extension-command-help.js +6 -6
  64. package/dist/cli/extension-recovery.js +1 -1
  65. package/dist/cli/help-content.js +5 -5
  66. package/dist/cli/help-json-payload.js +7 -7
  67. package/dist/cli/invocation-profile.js +2 -2
  68. package/dist/cli/main.js +5 -5
  69. package/dist/cli/migration-gates.js +1 -1
  70. package/dist/cli/option-values.js +1 -1
  71. package/dist/cli/preflight-warnings.js +3 -3
  72. package/dist/cli/public.js +1 -1
  73. package/dist/cli/register-annotations.js +1 -1
  74. package/dist/cli/register-assurance.js +1 -1
  75. package/dist/cli/register-files-lookup.js +1 -1
  76. package/dist/cli/register-history-activity.js +1 -1
  77. package/dist/cli/register-history-author.js +1 -1
  78. package/dist/cli/register-history-maintenance.js +2 -2
  79. package/dist/cli/register-list-query.js +10 -10
  80. package/dist/cli/register-mutation-options.js +0 -1
  81. package/dist/cli/register-mutation.js +6 -6
  82. package/dist/cli/register-operations.js +1 -1
  83. package/dist/cli/register-setup.js +1 -1
  84. package/dist/cli/register-structured-mutation.js +1 -1
  85. package/dist/cli/registration-helpers.js +1 -1
  86. package/dist/cli/runtime/activation.js +1 -1
  87. package/dist/cli/runtime/annotation-option-retry.js +1 -1
  88. package/dist/cli/runtime/close-fields-retry.js +1 -1
  89. package/dist/cli/runtime/field-route-retry.js +1 -1
  90. package/dist/cli/runtime/invocation-options.js +1 -1
  91. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  92. package/dist/cli/runtime/projection-retry.js +1 -1
  93. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  94. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  95. package/dist/cli/runtime/selection.js +1 -1
  96. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  97. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  98. package/dist/cli/schema/registration.js +15 -15
  99. package/dist/cli/schema-registration-helpers.js +1 -1
  100. package/dist/cli/search-refresh.js +1 -1
  101. package/dist/cli/stats-analytics-json.js +1 -1
  102. package/dist/cli/telemetry-flush.js +1 -1
  103. package/dist/cli-bundle/bundle-manifest.json +1 -1
  104. package/dist/cli-bundle/chunks/chunk-23K6DQQY.js +9 -0
  105. package/dist/cli-bundle/chunks/chunk-37UDIJ2K.js +3 -0
  106. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  107. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-7IROAPWI.js +3 -0
  109. package/dist/cli-bundle/chunks/chunk-7VRFEURZ.js +33 -0
  110. package/dist/cli-bundle/chunks/chunk-7X253M6Z.js +3 -0
  111. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  112. package/dist/cli-bundle/chunks/chunk-AWB5KBJS.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  114. package/dist/cli-bundle/chunks/chunk-DQDRA3SW.js +2 -0
  115. package/dist/cli-bundle/chunks/chunk-FXJYZBWV.js +113 -0
  116. package/dist/cli-bundle/chunks/chunk-HNKK2UG6.js +8 -0
  117. package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-I2OJ5B4A.js +2 -0
  119. package/dist/cli-bundle/chunks/chunk-I3BFCKZR.js +2 -0
  120. package/dist/cli-bundle/chunks/chunk-MXUSC5RS.js +31 -0
  121. package/dist/cli-bundle/chunks/chunk-PLIUU37C.js +3 -0
  122. package/dist/cli-bundle/chunks/chunk-PQUBVRV5.js +2 -0
  123. package/dist/cli-bundle/chunks/chunk-PW7U7WCE.js +3 -0
  124. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  125. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  126. package/dist/cli-bundle/chunks/chunk-SSALO4DB.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-STOOTHZZ.js +2 -0
  128. package/dist/cli-bundle/chunks/chunk-TKRY22SO.js +2 -0
  129. package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-TVIJ2VCU.js} +93 -93
  130. package/dist/cli-bundle/chunks/chunk-VJSGUXGU.js +3 -0
  131. package/dist/cli-bundle/chunks/chunk-WWTPNIC2.js +6 -0
  132. package/dist/cli-bundle/chunks/chunk-XFADNMGD.js +2 -0
  133. package/dist/cli-bundle/chunks/chunk-YOPTAIBD.js +125 -0
  134. package/dist/cli-bundle/chunks/chunk-YW2HBHRO.js +70 -0
  135. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  136. package/dist/cli-bundle/chunks/chunk-Z7MFVRDV.js +2 -0
  137. package/dist/cli-bundle/chunks/chunk-ZOX4SWRL.js +8 -0
  138. package/dist/cli-bundle/chunks/chunk-ZYCOM4MS.js +9 -0
  139. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  140. package/dist/cli-bundle/chunks/field-option-collisions-W66HSWMK.js +2 -0
  141. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  142. package/dist/cli-bundle/{focused-chunks/item-revision-2O6MLPEX.js → chunks/item-revision-D3LSBNIR.js} +2 -2
  143. package/dist/cli-bundle/chunks/item-transaction-M6NTBYH3.js +2 -0
  144. package/dist/cli-bundle/chunks/mutation-actor-OKL3CQVX.js +2 -0
  145. package/dist/cli-bundle/chunks/mutation-admission-EKPEOZMF.js +2 -0
  146. package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-3LBV6CS2.js} +11 -11
  147. package/dist/cli-bundle/chunks/register-mutation-72AGTMNE.js +21 -0
  148. package/dist/cli-bundle/chunks/register-operations-XERFG2SH.js +2 -0
  149. package/dist/cli-bundle/chunks/register-setup-W22L34Z4.js +2 -0
  150. package/dist/cli-bundle/chunks/runtime-schema-JP2KBHBY.js +2 -0
  151. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  152. package/dist/cli-bundle/chunks/stage-T2LKWN7C.js +2 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-24VRBNKE.js +26 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-3ELVASVA.js +2 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-3GT4A3ZN.js +44 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-3OCDKITJ.js +3 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-3Z7MCUJM.js +3 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-46MP7IZN.js +5 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-5LDBS6MS.js +91 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-B6BNHKUW.js +78 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-C7WHWI7K.js +3 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-EUQGZPGO.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-FDZPRJXJ.js +27 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-GXP7Q4XM.js +2 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-HL47UQZJ.js +8 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-LMFIAQ2V.js +2 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-LMU7DDOA.js +2 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-OZOCEB2Q.js +8 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-Q2HY44LV.js +13 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-REFMQY47.js +2 -0
  177. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  178. package/dist/cli-bundle/focused-chunks/chunk-RIQUIHYU.js +3 -0
  179. package/dist/cli-bundle/focused-chunks/chunk-RLO2HCZT.js +2 -0
  180. package/dist/cli-bundle/focused-chunks/chunk-SMMOZ3H3.js +100 -0
  181. package/dist/cli-bundle/focused-chunks/chunk-UVTUX54T.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/chunk-XDBHD4CY.js +8 -0
  184. package/dist/cli-bundle/focused-chunks/chunk-YD66IRSL.js +2 -0
  185. package/dist/cli-bundle/focused-chunks/chunk-Z7W2RQIB.js +2 -0
  186. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  187. package/dist/cli-bundle/focused-chunks/field-option-collisions-UODPSV6W.js +2 -0
  188. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  189. package/dist/cli-bundle/focused-chunks/item-revision-QH7RNBX4.js +2 -0
  190. package/dist/cli-bundle/focused-chunks/item-transaction-ZO72OINF.js +2 -0
  191. package/dist/cli-bundle/focused-chunks/mutation-actor-PHVLKG4I.js +2 -0
  192. package/dist/cli-bundle/focused-chunks/mutation-admission-ZSG5OECH.js +2 -0
  193. package/dist/cli-bundle/focused-chunks/runtime-schema-6RQMIDTN.js +2 -0
  194. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  195. package/dist/cli-bundle/focused-chunks/stage-AQMKRVX4.js +2 -0
  196. package/dist/cli-bundle/main.js +27 -27
  197. package/dist/cli-bundle/sdk-authoring.js +1 -1
  198. package/dist/cli-bundle/sdk-contracts.js +5 -5
  199. package/dist/cli-bundle/sdk-core.js +1 -1
  200. package/dist/cli-bundle/sdk-governance.js +1 -1
  201. package/dist/cli-bundle/sdk-graph.js +1 -1
  202. package/dist/cli-bundle/sdk-merge.js +66 -66
  203. package/dist/cli-bundle/sdk-query.js +1 -1
  204. package/dist/cli-bundle/sdk-runtime.js +1 -1
  205. package/dist/cli-bundle/sdk-testing.js +1 -1
  206. package/dist/cli-bundle/sdk.js +13 -13
  207. package/dist/cli.js +1 -1
  208. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  209. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  210. package/dist/core/checkpoint/mutation-context.js +1 -1
  211. package/dist/core/config/nested-settings.js +1 -1
  212. package/dist/core/config/positional-value.js +1 -1
  213. package/dist/core/diagnostics/remediation.js +1 -1
  214. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  215. package/dist/core/extensions/activation-summary.js +1 -1
  216. package/dist/core/extensions/activation-transaction.js +1 -1
  217. package/dist/core/extensions/capability-usage.js +1 -1
  218. package/dist/core/extensions/command-hook-context.js +1 -1
  219. package/dist/core/extensions/command-metadata-contract.js +1 -1
  220. package/dist/core/extensions/command-visibility-tier.js +1 -1
  221. package/dist/core/extensions/contribution-inventory.js +1 -1
  222. package/dist/core/extensions/exporter-output-contract.js +1 -1
  223. package/dist/core/extensions/extension-candidate.js +1 -1
  224. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  225. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  226. package/dist/core/extensions/extension-policy.js +1 -1
  227. package/dist/core/extensions/extension-registries.js +1 -1
  228. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  229. package/dist/core/extensions/extension-types.js +1 -1
  230. package/dist/core/extensions/flag-definition-validation.js +1 -1
  231. package/dist/core/extensions/flag-value-types.js +1 -1
  232. package/dist/core/extensions/index.js +1 -1
  233. package/dist/core/extensions/item-field-types.js +1 -1
  234. package/dist/core/extensions/item-fields.js +1 -1
  235. package/dist/core/extensions/loader.js +1 -1
  236. package/dist/core/extensions/manifest-parser.js +1 -1
  237. package/dist/core/extensions/manifest-schema.js +1 -1
  238. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  239. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  240. package/dist/core/extensions/mutation-actor.js +1 -1
  241. package/dist/core/extensions/preflight-ownership.js +1 -1
  242. package/dist/core/extensions/read-output-contract.js +1 -1
  243. package/dist/core/extensions/registration-contracts.js +1 -1
  244. package/dist/core/extensions/registration-validation.js +1 -1
  245. package/dist/core/extensions/registration-values.js +1 -1
  246. package/dist/core/extensions/reserved-host-flags.js +1 -1
  247. package/dist/core/extensions/runtime-registrations.js +1 -1
  248. package/dist/core/extensions/service-ownership.js +1 -1
  249. package/dist/core/extensions/version-compat.js +1 -1
  250. package/dist/core/extensions/version-diagnostics.js +1 -1
  251. package/dist/core/fs/atomic-create.js +1 -1
  252. package/dist/core/fs/file-glob.js +1 -1
  253. package/dist/core/fs/fs-utils.js +2 -2
  254. package/dist/core/fs/host-environment-errors.js +1 -1
  255. package/dist/core/fs/index.js +1 -1
  256. package/dist/core/fs/path-utils.js +1 -1
  257. package/dist/core/governance/content-fields.js +1 -1
  258. package/dist/core/governance/issue-codes.js +1 -1
  259. package/dist/core/governance/metadata-coverage.js +1 -1
  260. package/dist/core/history/bridge.js +1 -1
  261. package/dist/core/history/digest.js +1 -1
  262. package/dist/core/history/drift-cache.js +3 -3
  263. package/dist/core/history/drift-scan.js +1 -1
  264. package/dist/core/history/event-classification.js +1 -1
  265. package/dist/core/history/event-index.js +11 -11
  266. package/dist/core/history/history-compact-bulk.js +1 -1
  267. package/dist/core/history/history-diff.js +1 -1
  268. package/dist/core/history/history-rewrite.js +1 -1
  269. package/dist/core/history/history-storage-stats.js +1 -1
  270. package/dist/core/history/history-stream-policy.js +1 -1
  271. package/dist/core/history/history.js +2 -2
  272. package/dist/core/history/identity.js +1 -1
  273. package/dist/core/history/index.js +1 -1
  274. package/dist/core/history/operation-contract.js +1 -1
  275. package/dist/core/history/projection.js +1 -1
  276. package/dist/core/history/read.js +1 -1
  277. package/dist/core/history/replay.js +2 -2
  278. package/dist/core/history/stream-summary.js +2 -2
  279. package/dist/core/history/tombstone.js +1 -1
  280. package/dist/core/history/version-address.js +1 -1
  281. package/dist/core/history/workspace-history.js +2 -2
  282. package/dist/core/io/body-file.js +1 -1
  283. package/dist/core/io/bulk-ids-input.js +2 -2
  284. package/dist/core/item/actionability.js +1 -1
  285. package/dist/core/item/deferred-fields.js +1 -1
  286. package/dist/core/item/dependency-reference.js +1 -1
  287. package/dist/core/item/id.js +1 -1
  288. package/dist/core/item/index.js +1 -1
  289. package/dist/core/item/item-format-version.js +1 -1
  290. package/dist/core/item/item-format.js +7 -7
  291. package/dist/core/item/item-record.js +1 -1
  292. package/dist/core/item/item-type-definition.js +1 -1
  293. package/dist/core/item/literal-mutation-input.js +1 -1
  294. package/dist/core/item/parent-reference-policy.js +1 -1
  295. package/dist/core/item/parse.js +8 -8
  296. package/dist/core/item/plan-lifecycle.js +1 -1
  297. package/dist/core/item/priority.js +1 -1
  298. package/dist/core/item/sprint-release-format.js +1 -1
  299. package/dist/core/item/status-filter.js +1 -1
  300. package/dist/core/item/status.js +1 -1
  301. package/dist/core/item/toon-decode.js +1 -1
  302. package/dist/core/item/type-registry.js +1 -1
  303. package/dist/core/item/type-synonyms.js +1 -1
  304. package/dist/core/lock/index.js +1 -1
  305. package/dist/core/lock/lock-confinement.js +1 -1
  306. package/dist/core/lock/lock-gc.js +1 -1
  307. package/dist/core/lock/lock-owner.js +1 -1
  308. package/dist/core/lock/lock.js +4 -4
  309. package/dist/core/output/linked-test-projection.js +5 -5
  310. package/dist/core/output/mutation-projection.js +1 -1
  311. package/dist/core/output/output-control.js +1 -1
  312. package/dist/core/output/output.js +19 -19
  313. package/dist/core/output/query-summary.js +1 -1
  314. package/dist/core/output/tabular.js +3 -3
  315. package/dist/core/packages/manifest.js +1 -1
  316. package/dist/core/packages/root.js +1 -1
  317. package/dist/core/policy/workflow-policy-schema.js +1 -1
  318. package/dist/core/policy/workflow-policy-store.js +1 -1
  319. package/dist/core/policy/workflow-policy.js +1 -1
  320. package/dist/core/profile/profile-describe.js +1 -1
  321. package/dist/core/profile/profile-lint.d.ts +1 -1
  322. package/dist/core/profile/profile-lint.js +1 -1
  323. package/dist/core/profile/profile-plan.js +1 -1
  324. package/dist/core/profile/profile-presets.js +4 -4
  325. package/dist/core/reproducibility/context.js +1 -1
  326. package/dist/core/schema/fields-file.js +2 -2
  327. package/dist/core/schema/item-types-file.js +2 -2
  328. package/dist/core/schema/runtime-field-filters.js +1 -1
  329. package/dist/core/schema/runtime-field-values.js +1 -1
  330. package/dist/core/schema/runtime-schema.d.ts +2 -0
  331. package/dist/core/schema/runtime-schema.js +2 -2
  332. package/dist/core/schema/status-defs-file.js +2 -2
  333. package/dist/core/schema/status-token.js +1 -1
  334. package/dist/core/schema/type-inference.js +1 -1
  335. package/dist/core/schema/type-presets.js +1 -1
  336. package/dist/core/schema/type-workflows.js +1 -1
  337. package/dist/core/search/background-refresh.js +2 -2
  338. package/dist/core/search/bm25.js +1 -1
  339. package/dist/core/search/cache.js +2 -2
  340. package/dist/core/search/corpus.js +1 -1
  341. package/dist/core/search/embedding-batches.js +1 -1
  342. package/dist/core/search/eval-thresholds.js +1 -1
  343. package/dist/core/search/eval.js +1 -1
  344. package/dist/core/search/http-client.js +1 -1
  345. package/dist/core/search/providers.js +1 -1
  346. package/dist/core/search/relevance.js +1 -1
  347. package/dist/core/search/semantic-defaults.js +1 -1
  348. package/dist/core/search/staleness.js +1 -1
  349. package/dist/core/search/vector-stores.js +2 -2
  350. package/dist/core/search/vectorization-metadata.js +1 -1
  351. package/dist/core/sentry/helpers.js +1 -1
  352. package/dist/core/sentry/instrument.js +1 -1
  353. package/dist/core/sentry/sensitive-assignments.js +1 -1
  354. package/dist/core/session/session-state.js +1 -1
  355. package/dist/core/shared/agent-session-context.js +1 -1
  356. package/dist/core/shared/author.js +5 -5
  357. package/dist/core/shared/command-line.js +1 -1
  358. package/dist/core/shared/command-types.js +0 -1
  359. package/dist/core/shared/conflict-markers.js +1 -1
  360. package/dist/core/shared/constants.js +1 -1
  361. package/dist/core/shared/error-details.js +1 -1
  362. package/dist/core/shared/errors.js +1 -1
  363. package/dist/core/shared/html-entity-decode.js +1 -1
  364. package/dist/core/shared/index.js +1 -1
  365. package/dist/core/shared/item-metadata-contract.js +1 -1
  366. package/dist/core/shared/lazy-module.js +1 -1
  367. package/dist/core/shared/levenshtein.js +1 -1
  368. package/dist/core/shared/memo.js +1 -1
  369. package/dist/core/shared/numeric-parsers.js +1 -1
  370. package/dist/core/shared/option-alias-visibility.js +1 -1
  371. package/dist/core/shared/output-unicode.js +1 -1
  372. package/dist/core/shared/primitives.js +1 -1
  373. package/dist/core/shared/process-tree.js +2 -2
  374. package/dist/core/shared/secret-rules.js +5 -5
  375. package/dist/core/shared/serial-queue.js +1 -1
  376. package/dist/core/shared/serialization.js +1 -1
  377. package/dist/core/shared/split-comma-list.js +1 -1
  378. package/dist/core/shared/text-normalization.js +1 -1
  379. package/dist/core/shared/time.js +2 -2
  380. package/dist/core/shared/url-credentials.js +1 -1
  381. package/dist/core/store/index.js +1 -1
  382. package/dist/core/store/item-format-migration.js +1 -1
  383. package/dist/core/store/item-metadata-cache.js +1 -1
  384. package/dist/core/store/item-metadata-query-index.js +11 -11
  385. package/dist/core/store/item-metadata-read-work.js +1 -1
  386. package/dist/core/store/item-mutation-precondition.js +1 -1
  387. package/dist/core/store/item-store.js +1 -1
  388. package/dist/core/store/paths.js +1 -1
  389. package/dist/core/store/settings-concurrency.js +1 -1
  390. package/dist/core/store/settings-read-cache.js +1 -1
  391. package/dist/core/store/settings-sections.js +2 -2
  392. package/dist/core/store/settings-validator.js +1 -1
  393. package/dist/core/store/settings.d.ts +3 -1
  394. package/dist/core/store/settings.js +6 -6
  395. package/dist/core/store/sqlite-runtime.js +1 -1
  396. package/dist/core/store/tracker-preflight.js +1 -1
  397. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  398. package/dist/core/telemetry/consent.js +3 -3
  399. package/dist/core/telemetry/observability.js +1 -1
  400. package/dist/core/telemetry/policy.js +1 -1
  401. package/dist/core/telemetry/read-sampling.js +2 -2
  402. package/dist/core/telemetry/runtime.js +9 -9
  403. package/dist/core/test/background-runs.js +4 -4
  404. package/dist/core/test/item-test-run-tracking.js +1 -1
  405. package/dist/core/test/run-selectors.js +1 -1
  406. package/dist/core/validate/estimate-defaults.js +1 -1
  407. package/dist/core/validate/fix-planning.js +1 -1
  408. package/dist/core/validate/linked-artifact-reference.js +1 -1
  409. package/dist/core/validate/missing-by-type.js +1 -1
  410. package/dist/core/validate/missing-link-owners.js +1 -1
  411. package/dist/core/validate/stale-file-classification.js +1 -1
  412. package/dist/mcp/http-server.js +5 -5
  413. package/dist/mcp/legacy-adapter.js +1 -1
  414. package/dist/mcp/runtime-capabilities.js +1 -1
  415. package/dist/mcp/server.js +4 -4
  416. package/dist/mcp/tool-definitions.js +1 -1
  417. package/dist/sdk/actionability.js +1 -1
  418. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  419. package/dist/sdk/agent/command-recovery.js +1 -1
  420. package/dist/sdk/agent/command-suggestions.js +1 -1
  421. package/dist/sdk/agent/create-option-policy.js +1 -1
  422. package/dist/sdk/agent/identity-config.js +1 -1
  423. package/dist/sdk/agent/item-addressing.js +1 -1
  424. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  425. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  426. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  427. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  428. package/dist/sdk/agent-capability-contracts.js +3 -3
  429. package/dist/sdk/agent-session-context.js +1 -1
  430. package/dist/sdk/annotations.js +1 -1
  431. package/dist/sdk/author-attribution.js +1 -1
  432. package/dist/sdk/cli-bootstrap.js +1 -1
  433. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  434. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  435. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  436. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  437. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  438. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  439. package/dist/sdk/cli-contracts/completeness.js +1 -1
  440. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  441. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  442. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  443. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  444. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  445. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  446. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  447. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  448. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  449. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  450. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  451. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  452. package/dist/sdk/cli-contracts.js +1 -1
  453. package/dist/sdk/cli-program.js +1 -1
  454. package/dist/sdk/command-line.js +1 -1
  455. package/dist/sdk/comments.js +1 -1
  456. package/dist/sdk/compile-cache.js +1 -1
  457. package/dist/sdk/completion/bash.js +2 -2
  458. package/dist/sdk/completion/fish.js +72 -72
  459. package/dist/sdk/completion/shared.js +1 -1
  460. package/dist/sdk/completion/zsh.js +75 -75
  461. package/dist/sdk/completion.js +1 -1
  462. package/dist/sdk/config.js +1 -1
  463. package/dist/sdk/context/recency.js +1 -1
  464. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  465. package/dist/sdk/context/usage-egress.js +1 -1
  466. package/dist/sdk/context/usage-ledger.js +6 -6
  467. package/dist/sdk/context-intent-contracts.js +1 -1
  468. package/dist/sdk/context-intent-runtime.js +1 -1
  469. package/dist/sdk/context-packing.js +1 -1
  470. package/dist/sdk/context-relevance.js +1 -1
  471. package/dist/sdk/context-signal-store.js +2 -2
  472. package/dist/sdk/context-usage.js +1 -1
  473. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  474. package/dist/sdk/dependencies.js +1 -1
  475. package/dist/sdk/dependency-flag-validation.js +1 -1
  476. package/dist/sdk/dependency-provenance.js +1 -1
  477. package/dist/sdk/docs.js +1 -1
  478. package/dist/sdk/duplicates.js +1 -1
  479. package/dist/sdk/environment/host-environment-errors.js +1 -1
  480. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  481. package/dist/sdk/environment/source-context.js +1 -1
  482. package/dist/sdk/environment/tracker-preflight.js +1 -1
  483. package/dist/sdk/error-code-catalog.js +1 -1
  484. package/dist/sdk/error-runtime.js +1 -1
  485. package/dist/sdk/errors.js +1 -1
  486. package/dist/sdk/eval.js +1 -1
  487. package/dist/sdk/extension/author-manifest.js +1 -1
  488. package/dist/sdk/extension/bundled-catalog.js +1 -1
  489. package/dist/sdk/extension/command-options.d.ts +26 -1
  490. package/dist/sdk/extension/command-options.js +1 -1
  491. package/dist/sdk/extension/concurrency.js +1 -1
  492. package/dist/sdk/extension/copy-scope.js +1 -1
  493. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  494. package/dist/sdk/extension/describe.js +3 -3
  495. package/dist/sdk/extension/doctor.js +1 -1
  496. package/dist/sdk/extension/install-plan.js +1 -1
  497. package/dist/sdk/extension/install-receipts.js +1 -1
  498. package/dist/sdk/extension/install-runtime.js +3 -3
  499. package/dist/sdk/extension/install-snapshot.js +1 -1
  500. package/dist/sdk/extension/install-sources.js +5 -5
  501. package/dist/sdk/extension/managed-state.js +2 -2
  502. package/dist/sdk/extension/managed-update-status.js +1 -1
  503. package/dist/sdk/extension/migrations.js +2 -2
  504. package/dist/sdk/extension/native-command-options.js +1 -1
  505. package/dist/sdk/extension/output-ownership.js +1 -1
  506. package/dist/sdk/extension/runtime-summary.js +1 -1
  507. package/dist/sdk/extension/scaffold.js +11 -11
  508. package/dist/sdk/extension/shared.js +1 -1
  509. package/dist/sdk/extension/source-resolution.js +1 -1
  510. package/dist/sdk/extension/static-inventory.js +1 -1
  511. package/dist/sdk/extension/update-check.js +1 -1
  512. package/dist/sdk/extension-command-context.js +2 -2
  513. package/dist/sdk/extension-contracts.js +1 -1
  514. package/dist/sdk/extension.js +1 -1
  515. package/dist/sdk/files.js +1 -1
  516. package/dist/sdk/flag-invocation-contracts.js +1 -1
  517. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  518. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  519. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  520. package/dist/sdk/generated-error-code-catalog.js +1 -1
  521. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  522. package/dist/sdk/governance/assurance-action.js +1 -1
  523. package/dist/sdk/governance/assurance-limits.js +1 -1
  524. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  525. package/dist/sdk/governance/assurance-presets.js +1 -1
  526. package/dist/sdk/governance/assurance-runtime.js +1 -1
  527. package/dist/sdk/governance/assurance.js +4 -4
  528. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  529. package/dist/sdk/governance/closure-timestamps.js +1 -1
  530. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  531. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  532. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  533. package/dist/sdk/governance/defect-recurrence.js +2 -2
  534. package/dist/sdk/governance/extension-host-version.js +1 -1
  535. package/dist/sdk/governance/gc.js +1 -1
  536. package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
  537. package/dist/sdk/governance/health/projection.js +1 -1
  538. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  539. package/dist/sdk/governance/health.js +2 -2
  540. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  541. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  542. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  543. package/dist/sdk/governance/linked-file-report.js +1 -1
  544. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  545. package/dist/sdk/governance/provenance-health.js +4 -4
  546. package/dist/sdk/governance/reindex.js +5 -5
  547. package/dist/sdk/governance/stale-work.js +1 -1
  548. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  549. package/dist/sdk/governance/storage-integrity.js +1 -1
  550. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  551. package/dist/sdk/governance/upgrade.js +2 -2
  552. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  553. package/dist/sdk/governance/validate-history-drift.js +1 -1
  554. package/dist/sdk/governance/validate-item-reader.js +1 -1
  555. package/dist/sdk/governance/validate-normalization.js +1 -1
  556. package/dist/sdk/governance/validate.js +1 -1
  557. package/dist/sdk/governance/workflow-completeness.js +1 -1
  558. package/dist/sdk/governance/workflow-policy.js +3 -3
  559. package/dist/sdk/governance/workspace-position.js +2 -2
  560. package/dist/sdk/graph/analytics.js +1 -1
  561. package/dist/sdk/graph/assembly.js +1 -1
  562. package/dist/sdk/graph/cache.js +1 -1
  563. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  564. package/dist/sdk/graph/centrality.js +1 -1
  565. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  566. package/dist/sdk/graph/durable-cache.js +1 -1
  567. package/dist/sdk/graph/governance-contracts.js +1 -1
  568. package/dist/sdk/graph/governance.js +1 -1
  569. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  570. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  571. package/dist/sdk/graph/mutation-advisory.js +1 -1
  572. package/dist/sdk/graph/query-contracts.js +1 -1
  573. package/dist/sdk/graph/remediation.js +1 -1
  574. package/dist/sdk/graph/run.js +1 -1
  575. package/dist/sdk/graph/scheduling.js +1 -1
  576. package/dist/sdk/graph/traversal.js +1 -1
  577. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  578. package/dist/sdk/guide-topics.js +1 -1
  579. package/dist/sdk/guide.js +7 -7
  580. package/dist/sdk/history/append-only-repair.js +4 -4
  581. package/dist/sdk/history/attestation-command.js +2 -2
  582. package/dist/sdk/history/attestation-contract.js +1 -1
  583. package/dist/sdk/history/attestation-scan.js +1 -1
  584. package/dist/sdk/history/attestation.js +1 -1
  585. package/dist/sdk/history/maintenance.js +1 -1
  586. package/dist/sdk/history/reanchor-refusal.js +1 -1
  587. package/dist/sdk/history/reseed.js +1 -1
  588. package/dist/sdk/history/salvage.js +5 -5
  589. package/dist/sdk/history/subject.js +1 -1
  590. package/dist/sdk/history-analytics.js +1 -1
  591. package/dist/sdk/history-compact.js +1 -1
  592. package/dist/sdk/history-mcp.js +1 -1
  593. package/dist/sdk/history-provenance.js +1 -1
  594. package/dist/sdk/history-read.js +1 -1
  595. package/dist/sdk/history-redact.js +1 -1
  596. package/dist/sdk/history-repair.js +1 -1
  597. package/dist/sdk/improvement-ledger-validation.js +1 -1
  598. package/dist/sdk/improvement-ledger.js +2 -2
  599. package/dist/sdk/index.d.ts +1 -1
  600. package/dist/sdk/init-agent-guidance.js +10 -10
  601. package/dist/sdk/init.js +14 -14
  602. package/dist/sdk/invocation-author.js +1 -1
  603. package/dist/sdk/item-children.js +1 -1
  604. package/dist/sdk/item-metadata-index.js +1 -1
  605. package/dist/sdk/item-schedule.js +1 -1
  606. package/dist/sdk/item-transaction.js +1 -1
  607. package/dist/sdk/learnings.js +1 -1
  608. package/dist/sdk/lifecycle/append.js +3 -3
  609. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  610. package/dist/sdk/lifecycle/claim.js +1 -1
  611. package/dist/sdk/lifecycle/cli-input.js +1 -1
  612. package/dist/sdk/lifecycle/close-many.js +1 -1
  613. package/dist/sdk/lifecycle/close.js +1 -1
  614. package/dist/sdk/lifecycle/copy.js +1 -1
  615. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  616. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  617. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  618. package/dist/sdk/lifecycle/create.js +1 -1
  619. package/dist/sdk/lifecycle/delete.js +1 -1
  620. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  621. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  622. package/dist/sdk/lifecycle/focus.js +1 -1
  623. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  624. package/dist/sdk/lifecycle/item-revision.js +1 -1
  625. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  626. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  627. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  628. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  629. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  630. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  631. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  632. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  633. package/dist/sdk/lifecycle/plan.js +1 -1
  634. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  635. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  636. package/dist/sdk/lifecycle/reopen.js +1 -1
  637. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  638. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  639. package/dist/sdk/lifecycle/restore.js +1 -1
  640. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  641. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  642. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  643. package/dist/sdk/lifecycle/task-composition.js +1 -1
  644. package/dist/sdk/lifecycle/update-many.js +1 -1
  645. package/dist/sdk/lifecycle/update.js +2 -2
  646. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  647. package/dist/sdk/lifecycle-completion.js +1 -1
  648. package/dist/sdk/lifecycle-policy.js +1 -1
  649. package/dist/sdk/linked-artifacts.js +2 -2
  650. package/dist/sdk/mcp/apps.js +5 -5
  651. package/dist/sdk/mcp/authorization.js +1 -1
  652. package/dist/sdk/mcp/discovery.js +1 -1
  653. package/dist/sdk/mcp/executable.js +4 -4
  654. package/dist/sdk/mcp/interactions.js +1 -1
  655. package/dist/sdk/mcp/protocol.js +1 -1
  656. package/dist/sdk/mcp/skills.js +3 -3
  657. package/dist/sdk/mcp/subscriptions.js +1 -1
  658. package/dist/sdk/mcp/tasks.js +2 -2
  659. package/dist/sdk/mcp/transport.js +1 -1
  660. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  661. package/dist/sdk/merge/driver.js +7 -7
  662. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  663. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  664. package/dist/sdk/merge/index.js +1 -1
  665. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  666. package/dist/sdk/merge/install.js +6 -6
  667. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  668. package/dist/sdk/merge/receipt-operation.js +1 -1
  669. package/dist/sdk/merge/receipt-schema.js +1 -1
  670. package/dist/sdk/merge/receipts.js +4 -4
  671. package/dist/sdk/merge/reconcile.js +1 -1
  672. package/dist/sdk/merge/settlement-hook.js +4 -4
  673. package/dist/sdk/merge/stage.js +1 -1
  674. package/dist/sdk/merge/three-way.js +9 -9
  675. package/dist/sdk/merge/worktree-config.js +2 -2
  676. package/dist/sdk/merge.js +1 -1
  677. package/dist/sdk/mutation-events.js +1 -1
  678. package/dist/sdk/mutation-guard.js +1 -1
  679. package/dist/sdk/notes.js +1 -1
  680. package/dist/sdk/output/fit-envelope.js +1 -1
  681. package/dist/sdk/output/list-envelope.js +1 -1
  682. package/dist/sdk/output/table-rows.js +1 -1
  683. package/dist/sdk/output-contracts.js +1 -1
  684. package/dist/sdk/output-projection.js +1 -1
  685. package/dist/sdk/output-token-accounting.js +1 -1
  686. package/dist/sdk/output.js +2 -2
  687. package/dist/sdk/ownership-source.js +1 -1
  688. package/dist/sdk/package-import-adapters.js +1 -1
  689. package/dist/sdk/package-migrations.js +1 -1
  690. package/dist/sdk/package-runtime-options.js +1 -1
  691. package/dist/sdk/pagination.js +1 -1
  692. package/dist/sdk/profile.js +5 -5
  693. package/dist/sdk/provenance.js +1 -1
  694. package/dist/sdk/public-surface.json +1 -1
  695. package/dist/sdk/query/activity.js +1 -1
  696. package/dist/sdk/query/aggregate.js +1 -1
  697. package/dist/sdk/query/calendar.js +4 -4
  698. package/dist/sdk/query/complete-list.js +1 -1
  699. package/dist/sdk/query/context.js +2 -2
  700. package/dist/sdk/query/declared-blockers.js +1 -1
  701. package/dist/sdk/query/duplicate-candidates.js +1 -1
  702. package/dist/sdk/query/get-facet-roots.js +1 -1
  703. package/dist/sdk/query/get.js +1 -1
  704. package/dist/sdk/query/history.js +1 -1
  705. package/dist/sdk/query/item-filter-options.js +0 -1
  706. package/dist/sdk/query/light-metadata.js +1 -1
  707. package/dist/sdk/query/list-filter-shared.js +1 -1
  708. package/dist/sdk/query/list.js +1 -1
  709. package/dist/sdk/query/multi-value-filters.js +1 -1
  710. package/dist/sdk/query/next-ranking-policy.js +1 -1
  711. package/dist/sdk/query/next-ready-budget.js +1 -1
  712. package/dist/sdk/query/next.js +2 -2
  713. package/dist/sdk/query/parsers.js +1 -1
  714. package/dist/sdk/query/projection-contracts.js +1 -1
  715. package/dist/sdk/query/search/corpus.js +2 -2
  716. package/dist/sdk/query/search/filters.js +1 -1
  717. package/dist/sdk/query/search/input.js +1 -1
  718. package/dist/sdk/query/search/lexical.js +1 -1
  719. package/dist/sdk/query/search/response.js +1 -1
  720. package/dist/sdk/query/search/semantic.js +3 -3
  721. package/dist/sdk/query/search/types.js +0 -1
  722. package/dist/sdk/query/search-contracts.js +1 -1
  723. package/dist/sdk/query/search-pagination.js +1 -1
  724. package/dist/sdk/query/search-rendering.js +1 -1
  725. package/dist/sdk/query/search.js +1 -1
  726. package/dist/sdk/query/window-pagination.js +1 -1
  727. package/dist/sdk/query/workspace-contracts.js +1 -1
  728. package/dist/sdk/read-output/continuation.js +1 -1
  729. package/dist/sdk/read-output/extension.js +1 -1
  730. package/dist/sdk/read-output/options.js +1 -1
  731. package/dist/sdk/read-output/positional-rows.js +1 -1
  732. package/dist/sdk/read-output/provenance.js +1 -1
  733. package/dist/sdk/read-output/session-result.js +0 -1
  734. package/dist/sdk/read-output/surfaces.js +1 -1
  735. package/dist/sdk/read-output/tail-retention.js +1 -1
  736. package/dist/sdk/read-output-budget.js +1 -1
  737. package/dist/sdk/read-output-contracts.d.ts +11 -0
  738. package/dist/sdk/read-output-contracts.js +1 -1
  739. package/dist/sdk/read-output-rows.js +1 -1
  740. package/dist/sdk/read-output-session.js +1 -1
  741. package/dist/sdk/relationship-analytics.js +1 -1
  742. package/dist/sdk/relationship-context.js +1 -1
  743. package/dist/sdk/relationship-history.js +6 -6
  744. package/dist/sdk/relationship-kinds/contract.js +1 -1
  745. package/dist/sdk/relationships.js +1 -1
  746. package/dist/sdk/reproducibility/process.js +1 -1
  747. package/dist/sdk/runtime/actions.js +1 -1
  748. package/dist/sdk/runtime/context.js +1 -1
  749. package/dist/sdk/runtime/mutation-admission.js +1 -1
  750. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  751. package/dist/sdk/runtime/schema-preview.js +1 -1
  752. package/dist/sdk/runtime/schema.js +1 -1
  753. package/dist/sdk/runtime-action-aliases.js +1 -1
  754. package/dist/sdk/runtime-extended-actions.js +1 -1
  755. package/dist/sdk/runtime-input.d.ts +2 -0
  756. package/dist/sdk/runtime-input.js +1 -1
  757. package/dist/sdk/runtime-primitives.js +1 -1
  758. package/dist/sdk/runtime-public-contracts.js +0 -1
  759. package/dist/sdk/runtime-stats-options.js +1 -1
  760. package/dist/sdk/runtime.d.ts +5 -3
  761. package/dist/sdk/runtime.js +1 -1
  762. package/dist/sdk/scheduling-shortcuts.js +1 -1
  763. package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
  764. package/dist/sdk/schema/field-flag-spelling.js +2 -0
  765. package/dist/sdk/schema/field-option-collisions.js +2 -0
  766. package/dist/sdk/schema-migration.js +4 -4
  767. package/dist/sdk/schema.js +7 -7
  768. package/dist/sdk/search-refresh-worker.js +1 -1
  769. package/dist/sdk/similarity-scoring.js +1 -1
  770. package/dist/sdk/similarity.js +1 -1
  771. package/dist/sdk/start-task-status.js +1 -1
  772. package/dist/sdk/stats.js +1 -1
  773. package/dist/sdk/structured-mutations.js +1 -1
  774. package/dist/sdk/telemetry-flush.js +1 -1
  775. package/dist/sdk/telemetry.js +4 -4
  776. package/dist/sdk/templates.js +3 -3
  777. package/dist/sdk/test/batch.js +2 -2
  778. package/dist/sdk/test/command-args.js +1 -1
  779. package/dist/sdk/test/command-resolution.js +2 -2
  780. package/dist/sdk/test/entry.js +2 -2
  781. package/dist/sdk/test/execution-receipts.js +2 -2
  782. package/dist/sdk/test/execution.js +5 -5
  783. package/dist/sdk/test/json-path.js +1 -1
  784. package/dist/sdk/test/linked-command-detection.js +1 -1
  785. package/dist/sdk/test/measurements.js +1 -1
  786. package/dist/sdk/test/parsers.js +1 -1
  787. package/dist/sdk/test/prerequisites.js +1 -1
  788. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  789. package/dist/sdk/test/run-phases.js +1 -1
  790. package/dist/sdk/test/runs.js +1 -1
  791. package/dist/sdk/test/trust.js +2 -2
  792. package/dist/sdk/test/update.js +1 -1
  793. package/dist/sdk/test/workspace-snapshot.js +1 -1
  794. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  795. package/dist/sdk/traceability/source-traceability.js +2 -2
  796. package/dist/sdk/tracker-root-discovery.js +1 -1
  797. package/dist/sdk/transactions/item-finalization.js +1 -1
  798. package/dist/sdk/workspace-contracts-cache.js +1 -1
  799. package/dist/sdk/workspace-contracts.js +1 -1
  800. package/dist/sdk/workspace-memory.js +2 -2
  801. package/dist/sdk/workspace-snapshot.js +5 -5
  802. package/dist/sdk/workspace-transaction-gc.js +1 -1
  803. package/dist/sdk/workspace-transaction.js +2 -2
  804. package/dist/sdk/workspace.js +6 -6
  805. package/dist/types/index.js +1 -1
  806. package/dist/types.js +1 -1
  807. package/docs/COMMANDS.md +1 -1
  808. package/docs/EXTENSIONS.md +2 -2
  809. package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
  810. package/docs/SDK.md +94 -5
  811. package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
  812. package/marketplace.json +1 -1
  813. package/package.json +2 -1
  814. package/packages/pm-beads/package.json +1 -1
  815. package/packages/pm-calendar/package.json +1 -1
  816. package/packages/pm-command-kit/package.json +1 -1
  817. package/packages/pm-digital-twin/package.json +1 -1
  818. package/packages/pm-governance-audit/package.json +1 -1
  819. package/packages/pm-guide-shell/package.json +1 -1
  820. package/packages/pm-kanban/package.json +1 -1
  821. package/packages/pm-lifecycle-hooks/package.json +1 -1
  822. package/packages/pm-linked-test-adapters/package.json +1 -1
  823. package/packages/pm-search-advanced/package.json +1 -1
  824. package/packages/pm-templates/package.json +1 -1
  825. package/packages/pm-todos/package.json +1 -1
  826. package/packages/pm-vcs/package.json +1 -1
  827. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  828. package/plugins/pm-claude/package.json +1 -1
  829. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  830. package/plugins/pm-codex/package.json +1 -1
  831. package/plugins/pm-codex/plugin.json +1 -1
  832. package/runtime-dependencies.json +1 -1
  833. package/scripts/finalize-build.mjs +63 -24
  834. package/scripts/prepare-build-cache.mjs +28 -1
  835. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
  836. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
  837. package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
  838. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
  839. package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
  840. package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
  841. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
  842. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  843. package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
  844. package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
  845. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
  846. package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
  847. package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
  848. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
  849. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  850. package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
  851. package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
  852. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  853. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  854. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
  855. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  856. package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
  857. package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
  858. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
  859. package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
  860. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
  861. package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
  862. package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
  863. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  864. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  865. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  866. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  867. package/dist/cli-bundle/chunks/item-revision-4QBMZXKX.js +0 -2
  868. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
  869. package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
  870. package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
  871. package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
  872. package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
  873. package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
  874. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  875. package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
  876. package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
  877. package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
  878. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  879. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  880. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
  881. package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
  882. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
  883. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
  884. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
  885. package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
  886. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  888. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  892. package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
  893. package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
  894. package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
  895. package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
  896. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
  897. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
  898. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  899. package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
  900. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
  901. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
  902. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
  903. package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
  904. package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
  905. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
  906. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  907. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  908. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
  909. package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
  910. package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
  911. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  912. package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
@@ -1,3 +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]="f3e94896-b2a0-561c-902b-71c28ddde2a1")}catch{}})();import{randomUUID}from"node:crypto";import{readFile}from"node:fs/promises";import path from"node:path";import{acquireLock,isFileMissingError,writeFileAtomic}from"../runtime-primitives.js";import{PM_MCP_ERROR_CODES,PmMcpProtocolError,isMcpRecord}from"./protocol.js";import{parseMcpInputRequests,parseMcpInputResponses}from"./interactions.js";const PM_MCP_TASKS_EXTENSION="io.modelcontextprotocol/tasks",PM_MCP_TASK_STATUSES=["working","input_required","completed","failed","cancelled"],TASK_ID_PATTERN=/^mcp-task-[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,DEFAULT_TASK_TTL_MS=3600*1e3,DEFAULT_TASK_POLL_INTERVAL_MS=1e3,MAX_STATUS_MESSAGE_LENGTH=1024,TASK_LOCK_TTL_SECONDS=30,TASK_LOCK_WAIT_MS=2e3;function taskProtocolError(message){return new PmMcpProtocolError(message,PM_MCP_ERROR_CODES.invalidParams,{code:"mcp_task_not_found_or_not_authorized"})}function validateTaskId(taskId){const normalized=taskId.trim();if(!TASK_ID_PATTERN.test(normalized))throw taskProtocolError("Unknown MCP task");return normalized}function parseTimestamp(value,field){if(typeof value!="string"||!Number.isFinite(Date.parse(value)))throw new PmMcpProtocolError("Corrupt MCP task record",PM_MCP_ERROR_CODES.invalidParams,{field});return value}function parseTaskError(value){if(!isMcpRecord(value)||typeof value.code!="number"||!Number.isFinite(value.code)||typeof value.message!="string")throw new PmMcpProtocolError("Corrupt MCP task error",PM_MCP_ERROR_CODES.invalidParams);return{code:value.code,message:value.message.slice(0,MAX_STATUS_MESSAGE_LENGTH),...isMcpRecord(value.data)?{data:structuredClone(value.data)}:{}}}function parseTaskStatus(value){if(!PM_MCP_TASK_STATUSES.includes(value))throw new PmMcpProtocolError("Corrupt MCP task record",PM_MCP_ERROR_CODES.invalidParams);return value}function parseTaskPrincipal(value){if(typeof value!="string"||value.length===0)throw new PmMcpProtocolError("Corrupt MCP task record",PM_MCP_ERROR_CODES.invalidParams);return value}function parseTaskWorkerPid(value){if(typeof value!="number"||!Number.isSafeInteger(value)||value<1)throw new PmMcpProtocolError("Corrupt MCP task record",PM_MCP_ERROR_CODES.invalidParams);return value}function parseTaskTtl(value){if(value!==null&&(typeof value!="number"||!Number.isSafeInteger(value)||value<0))throw new PmMcpProtocolError("Corrupt MCP task record",PM_MCP_ERROR_CODES.invalidParams);return value}function parseTaskPollInterval(value){if(value!==void 0){if(typeof value!="number"||!Number.isSafeInteger(value)||value<0)throw new PmMcpProtocolError("Corrupt MCP task record",PM_MCP_ERROR_CODES.invalidParams);return value}}function parseConsumedInputKeys(value){if(!Array.isArray(value)||value.some(entry=>typeof entry!="string"))throw new PmMcpProtocolError("Corrupt MCP task record",PM_MCP_ERROR_CODES.invalidParams);return[...value]}function parseStoredTask(value){if(!isMcpRecord(value)||value.version!==1)throw new PmMcpProtocolError("Corrupt MCP task record",PM_MCP_ERROR_CODES.invalidParams);const taskId=typeof value.taskId=="string"?validateTaskId(value.taskId):"",status=parseTaskStatus(value.status),principal=parseTaskPrincipal(value.principal),workerPid=parseTaskWorkerPid(value.workerPid),ttlMs=parseTaskTtl(value.ttlMs),pollIntervalMs=parseTaskPollInterval(value.pollIntervalMs),parsed={version:1,taskId,status,principal,workerPid,createdAt:parseTimestamp(value.createdAt,"createdAt"),lastUpdatedAt:parseTimestamp(value.lastUpdatedAt,"lastUpdatedAt"),ttlMs,consumedInputKeys:parseConsumedInputKeys(value.consumedInputKeys),...typeof value.statusMessage=="string"?{statusMessage:value.statusMessage.slice(0,MAX_STATUS_MESSAGE_LENGTH)}:{},...typeof pollIntervalMs=="number"?{pollIntervalMs}:{}};if(isMcpRecord(value.inputRequests)&&(parsed.inputRequests=structuredClone(value.inputRequests)),isMcpRecord(value.inputResponses)&&(parsed.inputResponses=structuredClone(value.inputResponses)),isMcpRecord(value.result)&&(parsed.result=structuredClone(value.result)),value.error!==void 0&&(parsed.error=parseTaskError(value.error)),parsed.status==="input_required"&&!parsed.inputRequests||parsed.status==="completed"&&!parsed.result||parsed.status==="failed"&&!parsed.error)throw new PmMcpProtocolError("Corrupt MCP task status payload",PM_MCP_ERROR_CODES.invalidParams,{status:parsed.status});return parsed}function publicTask(record){const base={taskId:record.taskId,status:record.status,createdAt:record.createdAt,lastUpdatedAt:record.lastUpdatedAt,ttlMs:record.ttlMs,...record.statusMessage?{statusMessage:record.statusMessage}:{},...record.pollIntervalMs===void 0?{}:{pollIntervalMs:record.pollIntervalMs}};return record.status==="input_required"?{...base,status:"input_required",inputRequests:structuredClone(record.inputRequests)}:record.status==="completed"?{...base,status:"completed",result:structuredClone(record.result)}:record.status==="failed"?{...base,status:"failed",error:structuredClone(record.error)}:record.status==="cancelled"?{...base,status:"cancelled"}:{...base,status:"working"}}function isTerminalTask(status){return status==="completed"||status==="failed"||status==="cancelled"}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return!(typeof error=="object"&&error!==null&&"code"in error&&error.code==="ESRCH")}}class PmMcpTaskStore{#pmRoot;#owner;#now;#taskIdFactory;#workerPid;constructor(options){this.#pmRoot=path.resolve(options.pmRoot),this.#owner=options.owner?.trim()||"pm-mcp",this.#now=options.now??(()=>new Date),this.#taskIdFactory=options.taskIdFactory??(()=>`mcp-task-${randomUUID()}`),this.#workerPid=options.workerPid??process.pid}#taskPath(taskId){return path.join(this.#pmRoot,"runtime","mcp-tasks","records",`${validateTaskId(taskId)}.json`)}async#read(taskId){try{return parseStoredTask(JSON.parse(await readFile(this.#taskPath(taskId),"utf8")))}catch(error){throw isFileMissingError(error)||error instanceof SyntaxError?taskProtocolError("Unknown MCP task"):error}}async#write(record){await writeFileAtomic(this.#taskPath(record.taskId),`${JSON.stringify(record,null,2)}
2
- `)}async#mutate(taskId,principal,mutation){const normalizedId=validateTaskId(taskId),release=await acquireLock(this.#pmRoot,normalizedId,TASK_LOCK_TTL_SECONDS,this.#owner,!1,!1,TASK_LOCK_WAIT_MS);try{const current=await this.#read(normalizedId);if(current.principal!==principal)throw taskProtocolError("Unknown MCP task");const next=mutation(current);return await this.#write(next),next}finally{await release()}}async create(input){const taskId=validateTaskId(this.#taskIdFactory()),principal=input.principal.trim(),ttlMs=input.ttlMs===void 0?DEFAULT_TASK_TTL_MS:input.ttlMs,pollIntervalMs=input.pollIntervalMs??DEFAULT_TASK_POLL_INTERVAL_MS;if(principal.length===0||ttlMs!==null&&(!Number.isSafeInteger(ttlMs)||ttlMs<0)||!Number.isSafeInteger(pollIntervalMs)||pollIntervalMs<0)throw new PmMcpProtocolError("Invalid MCP task creation options",PM_MCP_ERROR_CODES.invalidParams);const timestamp=this.#now().toISOString(),record={version:1,taskId,status:"working",createdAt:timestamp,lastUpdatedAt:timestamp,ttlMs,pollIntervalMs,principal,workerPid:this.#workerPid,consumedInputKeys:[],...input.statusMessage?.trim()?{statusMessage:input.statusMessage.trim().slice(0,MAX_STATUS_MESSAGE_LENGTH)}:{}};return await this.#write(record),{...publicTask(record),resultType:"task"}}async get(taskId,principal){return publicTask(await this.#mutate(taskId,principal,record=>{if(isTerminalTask(record.status))return record;const nowMs=this.#now().getTime(),expired=record.ttlMs!==null&&Date.parse(record.createdAt)+record.ttlMs<=nowMs,unavailableWorker=record.workerPid!==this.#workerPid&&!isProcessAlive(record.workerPid);return!expired&&!unavailableWorker?record:{...record,status:"failed",statusMessage:expired?"Task retention expired before completion.":"Task worker ended before recording a terminal result.",lastUpdatedAt:this.#now().toISOString(),error:{code:-32603,message:expired?"MCP task expired":"MCP task worker unavailable after restart",data:{recoverable:!1,createNewTask:!0}},inputRequests:void 0}}))}async requireInput(input){const requests=parseMcpInputRequests(input.inputRequests,input.requestContext);return publicTask(await this.#mutate(input.taskId,input.principal,record=>{if(isTerminalTask(record.status))return record;const reused=Object.keys(requests).filter(key=>record.consumedInputKeys.includes(key));if(reused.length>0)throw new PmMcpProtocolError("MCP task input request keys must be unique for the task lifetime",PM_MCP_ERROR_CODES.invalidParams,{reused});return{...record,status:"input_required",statusMessage:input.statusMessage?.trim().slice(0,MAX_STATUS_MESSAGE_LENGTH),lastUpdatedAt:this.#now().toISOString(),inputRequests:requests}}))}async update(taskId,principal,inputResponses){const responses=parseMcpInputResponses(inputResponses),acceptedKeys=[];let remainingKeys=[];return await this.#mutate(taskId,principal,record=>{if(record.status!=="input_required"||!record.inputRequests)return record;const outstanding={...record.inputRequests},accepted=record.inputResponses?{...record.inputResponses}:{};for(const[key,response]of Object.entries(responses))Object.prototype.hasOwnProperty.call(outstanding,key)&&(accepted[key]=response,delete outstanding[key],acceptedKeys.push(key));return remainingKeys=Object.keys(outstanding).sort(),acceptedKeys.length===0?record:{...record,status:remainingKeys.length===0?"working":"input_required",lastUpdatedAt:this.#now().toISOString(),inputRequests:remainingKeys.length===0?void 0:outstanding,inputResponses:accepted,consumedInputKeys:[...new Set([...record.consumedInputKeys,...acceptedKeys])].sort()}}),{acceptedKeys:acceptedKeys.sort(),remainingKeys}}async takeInputResponses(taskId,principal){let responses={};return await this.#mutate(taskId,principal,record=>(responses=structuredClone(record.inputResponses??{}),Object.keys(responses).length===0?record:{...record,inputResponses:void 0})),responses}async complete(taskId,principal,result){return publicTask(await this.#mutate(taskId,principal,record=>isTerminalTask(record.status)?record:{...record,status:"completed",statusMessage:"Task completed.",lastUpdatedAt:this.#now().toISOString(),result:structuredClone(result),inputRequests:void 0,error:void 0}))}async fail(taskId,principal,error){const boundedError=parseTaskError(error);return publicTask(await this.#mutate(taskId,principal,record=>isTerminalTask(record.status)?record:{...record,status:"failed",statusMessage:boundedError.message,lastUpdatedAt:this.#now().toISOString(),error:boundedError,inputRequests:void 0,result:void 0}))}async cancel(taskId,principal){return publicTask(await this.#mutate(taskId,principal,record=>isTerminalTask(record.status)?record:{...record,status:"cancelled",statusMessage:"Task cancelled by the client.",lastUpdatedAt:this.#now().toISOString(),inputRequests:void 0,result:void 0,error:void 0}))}}function createMcpTaskStore(options){return new PmMcpTaskStore(options)}export{PM_MCP_TASKS_EXTENSION,PM_MCP_TASK_STATUSES,PmMcpTaskStore,createMcpTaskStore};
1
+ import{randomUUID as I}from"node:crypto";import{readFile as C}from"node:fs/promises";import g from"node:path";import{acquireLock as T,isFileMissingError as _,writeFileAtomic as A}from"../runtime-primitives.js";import{PM_MCP_ERROR_CODES as u,PmMcpProtocolError as p,isMcpRecord as c}from"./protocol.js";import{parseMcpInputRequests as R,parseMcpInputResponses as b}from"./interactions.js";const Y="io.modelcontextprotocol/tasks",q=["working","input_required","completed","failed","cancelled"],O=/^mcp-task-[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,U=3600*1e3,E=1e3,k=1024,K=30,N=2e3;function M(t){return new p(t,u.invalidParams,{code:"mcp_task_not_found_or_not_authorized"})}function w(t){const s=t.trim();if(!O.test(s))throw M("Unknown MCP task");return s}function P(t,s){if(typeof t!="string"||!Number.isFinite(Date.parse(t)))throw new p("Corrupt MCP task record",u.invalidParams,{field:s});return t}function y(t){if(!c(t)||typeof t.code!="number"||!Number.isFinite(t.code)||typeof t.message!="string")throw new p("Corrupt MCP task error",u.invalidParams);return{code:t.code,message:t.message.slice(0,k),...c(t.data)?{data:structuredClone(t.data)}:{}}}function x(t){if(!q.includes(t))throw new p("Corrupt MCP task record",u.invalidParams);return t}function L(t){if(typeof t!="string"||t.length===0)throw new p("Corrupt MCP task record",u.invalidParams);return t}function D(t){if(typeof t!="number"||!Number.isSafeInteger(t)||t<1)throw new p("Corrupt MCP task record",u.invalidParams);return t}function F(t){if(t!==null&&(typeof t!="number"||!Number.isSafeInteger(t)||t<0))throw new p("Corrupt MCP task record",u.invalidParams);return t}function j(t){if(t!==void 0){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw new p("Corrupt MCP task record",u.invalidParams);return t}}function $(t){if(!Array.isArray(t)||t.some(s=>typeof s!="string"))throw new p("Corrupt MCP task record",u.invalidParams);return[...t]}function z(t){if(!c(t)||t.version!==1)throw new p("Corrupt MCP task record",u.invalidParams);const s=typeof t.taskId=="string"?w(t.taskId):"",a=x(t.status),e=L(t.principal),r=D(t.workerPid),i=F(t.ttlMs),o=j(t.pollIntervalMs),n={version:1,taskId:s,status:a,principal:e,workerPid:r,createdAt:P(t.createdAt,"createdAt"),lastUpdatedAt:P(t.lastUpdatedAt,"lastUpdatedAt"),ttlMs:i,consumedInputKeys:$(t.consumedInputKeys),...typeof t.statusMessage=="string"?{statusMessage:t.statusMessage.slice(0,k)}:{},...typeof o=="number"?{pollIntervalMs:o}:{}};if(c(t.inputRequests)&&(n.inputRequests=structuredClone(t.inputRequests)),c(t.inputResponses)&&(n.inputResponses=structuredClone(t.inputResponses)),c(t.result)&&(n.result=structuredClone(t.result)),t.error!==void 0&&(n.error=y(t.error)),n.status==="input_required"&&!n.inputRequests||n.status==="completed"&&!n.result||n.status==="failed"&&!n.error)throw new p("Corrupt MCP task status payload",u.invalidParams,{status:n.status});return n}function d(t){const s={taskId:t.taskId,status:t.status,createdAt:t.createdAt,lastUpdatedAt:t.lastUpdatedAt,ttlMs:t.ttlMs,...t.statusMessage?{statusMessage:t.statusMessage}:{},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs}};return t.status==="input_required"?{...s,status:"input_required",inputRequests:structuredClone(t.inputRequests)}:t.status==="completed"?{...s,status:"completed",result:structuredClone(t.result)}:t.status==="failed"?{...s,status:"failed",error:structuredClone(t.error)}:t.status==="cancelled"?{...s,status:"cancelled"}:{...s,status:"working"}}function l(t){return t==="completed"||t==="failed"||t==="cancelled"}function W(t){try{return process.kill(t,0),!0}catch(s){return!(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ESRCH")}}class G{#e;#r;#t;#a;#n;constructor(s){this.#e=g.resolve(s.pmRoot),this.#r=s.owner?.trim()||"pm-mcp",this.#t=s.now??(()=>new Date),this.#a=s.taskIdFactory??(()=>`mcp-task-${I()}`),this.#n=s.workerPid??process.pid}#i(s){return g.join(this.#e,"runtime","mcp-tasks","records",`${w(s)}.json`)}async#u(s){try{return z(JSON.parse(await C(this.#i(s),"utf8")))}catch(a){throw _(a)||a instanceof SyntaxError?M("Unknown MCP task"):a}}async#o(s){await A(this.#i(s.taskId),`${JSON.stringify(s,null,2)}
2
+ `)}async#s(s,a,e){const r=w(s),i=await T(this.#e,r,K,this.#r,!1,!1,N);try{const o=await this.#u(r);if(o.principal!==a)throw M("Unknown MCP task");const n=e(o);return await this.#o(n),n}finally{await i()}}async create(s){const a=w(this.#a()),e=s.principal.trim(),r=s.ttlMs===void 0?U:s.ttlMs,i=s.pollIntervalMs??E;if(e.length===0||r!==null&&(!Number.isSafeInteger(r)||r<0)||!Number.isSafeInteger(i)||i<0)throw new p("Invalid MCP task creation options",u.invalidParams);const o=this.#t().toISOString(),n={version:1,taskId:a,status:"working",createdAt:o,lastUpdatedAt:o,ttlMs:r,pollIntervalMs:i,principal:e,workerPid:this.#n,consumedInputKeys:[],...s.statusMessage?.trim()?{statusMessage:s.statusMessage.trim().slice(0,k)}:{}};return await this.#o(n),{...d(n),resultType:"task"}}async get(s,a){return d(await this.#s(s,a,e=>{if(l(e.status))return e;const r=this.#t().getTime(),i=e.ttlMs!==null&&Date.parse(e.createdAt)+e.ttlMs<=r,o=e.workerPid!==this.#n&&!W(e.workerPid);return!i&&!o?e:{...e,status:"failed",statusMessage:i?"Task retention expired before completion.":"Task worker ended before recording a terminal result.",lastUpdatedAt:this.#t().toISOString(),error:{code:-32603,message:i?"MCP task expired":"MCP task worker unavailable after restart",data:{recoverable:!1,createNewTask:!0}},inputRequests:void 0}}))}async requireInput(s){const a=R(s.inputRequests,s.requestContext);return d(await this.#s(s.taskId,s.principal,e=>{if(l(e.status))return e;const r=Object.keys(a).filter(i=>e.consumedInputKeys.includes(i));if(r.length>0)throw new p("MCP task input request keys must be unique for the task lifetime",u.invalidParams,{reused:r});return{...e,status:"input_required",statusMessage:s.statusMessage?.trim().slice(0,k),lastUpdatedAt:this.#t().toISOString(),inputRequests:a}}))}async update(s,a,e){const r=b(e),i=[];let o=[];return await this.#s(s,a,n=>{if(n.status!=="input_required"||!n.inputRequests)return n;const f={...n.inputRequests},h=n.inputResponses?{...n.inputResponses}:{};for(const[m,S]of Object.entries(r))Object.prototype.hasOwnProperty.call(f,m)&&(h[m]=S,delete f[m],i.push(m));return o=Object.keys(f).sort(),i.length===0?n:{...n,status:o.length===0?"working":"input_required",lastUpdatedAt:this.#t().toISOString(),inputRequests:o.length===0?void 0:f,inputResponses:h,consumedInputKeys:[...new Set([...n.consumedInputKeys,...i])].sort()}}),{acceptedKeys:i.sort(),remainingKeys:o}}async takeInputResponses(s,a){let e={};return await this.#s(s,a,r=>(e=structuredClone(r.inputResponses??{}),Object.keys(e).length===0?r:{...r,inputResponses:void 0})),e}async complete(s,a,e){return d(await this.#s(s,a,r=>l(r.status)?r:{...r,status:"completed",statusMessage:"Task completed.",lastUpdatedAt:this.#t().toISOString(),result:structuredClone(e),inputRequests:void 0,error:void 0}))}async fail(s,a,e){const r=y(e);return d(await this.#s(s,a,i=>l(i.status)?i:{...i,status:"failed",statusMessage:r.message,lastUpdatedAt:this.#t().toISOString(),error:r,inputRequests:void 0,result:void 0}))}async cancel(s,a){return d(await this.#s(s,a,e=>l(e.status)?e:{...e,status:"cancelled",statusMessage:"Task cancelled by the client.",lastUpdatedAt:this.#t().toISOString(),inputRequests:void 0,result:void 0,error:void 0}))}}function Z(t){return new G(t)}export{Y as PM_MCP_TASKS_EXTENSION,q as PM_MCP_TASK_STATUSES,G as PmMcpTaskStore,Z as createMcpTaskStore};
3
3
  //# sourceMappingURL=tasks.js.map
@@ -1,2 +1,2 @@
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]="3681273a-e101-57a0-9446-982c450e7183")}catch{}})();import{PM_MCP_ERROR_CODES,PM_MCP_PROTOCOL_VERSION,PmMcpProtocolError,isMcpRecord,resolveMcpRequestContext}from"./protocol.js";const BASE64_SENTINEL_PATTERN=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/u,HEADER_NAME_TOKEN_PATTERN=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,PLAIN_HEADER_VALUE_PATTERN=/^[\t\x20-\x7E]*$/u,REQUIRED_NAME_METHODS=new Set(["prompts/get","resources/read","tools/call"]);function normalizedHeaders(headers){const normalized=new Map;for(const[name,value]of Object.entries(headers)){if(value===void 0)continue;const entry=typeof value=="string"?value:value.join(", ");normalized.set(name.toLowerCase(),entry)}return normalized}function failHeader(message,header){throw new PmMcpProtocolError(message,PM_MCP_ERROR_CODES.headerMismatch,{header})}function encodeMcpHttpHeaderValue(value){const serialized=typeof value=="boolean"?String(value).toLowerCase():String(value);return serialized.length>0&&serialized.trim()===serialized&&PLAIN_HEADER_VALUE_PATTERN.test(serialized)&&!BASE64_SENTINEL_PATTERN.test(serialized)?serialized:`=?base64?${Buffer.from(serialized,"utf8").toString("base64")}?=`}function decodeMcpHttpHeaderValue(value,header){const sentinel=BASE64_SENTINEL_PATTERN.exec(value);if(sentinel){const encoded=sentinel[1],decoded=Buffer.from(encoded,"base64");return decoded.toString("base64")!==encoded||decoded.length===0?failHeader("Malformed MCP Base64 header value",header):decoded.toString("utf8")}return value.length===0||value.trim()!==value||!PLAIN_HEADER_VALUE_PATTERN.test(value)?failHeader("Malformed MCP header value",header):value}function containsHeaderAnnotation(value){return Array.isArray(value)?value.some(containsHeaderAnnotation):isMcpRecord(value)?Object.prototype.hasOwnProperty.call(value,"x-mcp-header")||Object.values(value).some(containsHeaderAnnotation):!1}function parseMcpHeaderAnnotation(propertySchema,propertyPath,names){const annotation=propertySchema["x-mcp-header"];if(annotation===void 0)return;const type=propertySchema.type;if(typeof annotation!="string"||!HEADER_NAME_TOKEN_PATTERN.test(annotation)||!["boolean","integer","string"].includes(String(type))||names.has(annotation.toLowerCase()))throw new PmMcpProtocolError("Invalid MCP x-mcp-header annotation",PM_MCP_ERROR_CODES.invalidParams,{field:propertyPath.join("."),annotation});return names.add(annotation.toLowerCase()),{name:annotation,path:propertyPath,type}}function collectMcpHeaderAnnotations(schema){if(!isMcpRecord(schema))throw new PmMcpProtocolError("Invalid MCP tool schema",PM_MCP_ERROR_CODES.invalidParams,{field:"inputSchema",expected:"object"});const annotations=[],names=new Set,visitProperties=(node,path)=>{const properties=node.properties;if(properties!==void 0){if(!isMcpRecord(properties))throw new PmMcpProtocolError("Invalid MCP tool schema properties",PM_MCP_ERROR_CODES.invalidParams,{field:"inputSchema.properties"});for(const[property,propertySchema]of Object.entries(properties)){if(!isMcpRecord(propertySchema))continue;const propertyPath=[...path,property],annotation=parseMcpHeaderAnnotation(propertySchema,propertyPath,names);annotation&&annotations.push(annotation);for(const[keyword,nested]of Object.entries(propertySchema))if(keyword!=="properties"&&keyword!=="x-mcp-header"&&containsHeaderAnnotation(nested))throw new PmMcpProtocolError("MCP x-mcp-header is not statically reachable",PM_MCP_ERROR_CODES.invalidParams,{field:propertyPath.join("."),keyword});visitProperties(propertySchema,propertyPath)}}};for(const[keyword,nested]of Object.entries(schema))if(keyword!=="properties"&&containsHeaderAnnotation(nested))throw new PmMcpProtocolError("MCP x-mcp-header is not statically reachable",PM_MCP_ERROR_CODES.invalidParams,{field:"inputSchema",keyword});return visitProperties(schema,[]),annotations}function valueAtPath(value,path){let current=value;for(const part of path){if(!isMcpRecord(current))return;current=current[part]}return current}function mirroredName(method,params){const value=method==="resources/read"?params.uri:params.name;return typeof value=="string"?value:void 0}function buildMcpCustomRequestHeaders(params,toolSchema){const argumentsValue=isMcpRecord(params.arguments)?params.arguments:{},headers={};for(const annotation of collectMcpHeaderAnnotations(toolSchema)){const value=valueAtPath(argumentsValue,annotation.path);if(value!=null){if(!(annotation.type==="integer"&&typeof value=="number"&&Number.isSafeInteger(value)||annotation.type==="boolean"&&typeof value=="boolean"||annotation.type==="string"&&typeof value=="string"))throw new PmMcpProtocolError("Invalid MCP custom header argument",PM_MCP_ERROR_CODES.invalidParams,{field:annotation.path.join("."),expected:annotation.type});headers[`Mcp-Param-${annotation.name}`]=encodeMcpHttpHeaderValue(value)}}return headers}function buildMcpHttpRequestHeaders(input){const params=isMcpRecord(input.request.params)?input.request.params:void 0,context=resolveMcpRequestContext(params),method=input.request.method;if(typeof method!="string"||method.length===0)return failHeader("Missing MCP request method","Mcp-Method");const headers={Accept:"application/json, text/event-stream","Content-Type":"application/json","MCP-Protocol-Version":context.protocolVersion,"Mcp-Method":method},name=mirroredName(method,params);if(REQUIRED_NAME_METHODS.has(method)){if(name===void 0)return failHeader("Missing MCP request name","Mcp-Name");headers["Mcp-Name"]=encodeMcpHttpHeaderValue(name)}return method==="tools/call"&&input.toolSchema!==void 0&&Object.assign(headers,buildMcpCustomRequestHeaders(params,input.toolSchema)),headers}function validateMcpRequiredRequestHeaders(headers,request){const method=request.method;(typeof method!="string"||method.length===0)&&failHeader("Missing MCP request method","Mcp-Method");const params=isMcpRecord(request.params)?request.params:void 0,expectedProtocol=resolveMcpRequestContext(params).protocolVersion;if(headers.get("mcp-protocol-version")!==expectedProtocol&&failHeader("MCP protocol header does not match request metadata","MCP-Protocol-Version"),headers.get("mcp-method")!==method&&failHeader("MCP method header does not match request body","Mcp-Method"),REQUIRED_NAME_METHODS.has(method)){const headerName=headers.get("mcp-name"),name=mirroredName(method,params);(headerName===void 0||name===void 0||decodeMcpHttpHeaderValue(headerName,"Mcp-Name")!==name)&&failHeader("MCP name header does not match request body","Mcp-Name")}headers.has("last-event-id")&&failHeader("MCP SSE resumability is not supported","Last-Event-ID")}function customHeaderMatches(annotation,value,decoded){return annotation.type==="integer"?typeof value=="number"&&Number.isSafeInteger(value)&&Number(decoded)===value:annotation.type==="boolean"?typeof value=="boolean"&&decoded===String(value):typeof value=="string"&&decoded===value}function validateMcpCustomRequestHeaders(input){const argumentsValue=isMcpRecord(input.params.arguments)?input.params.arguments:{};for(const annotation of collectMcpHeaderAnnotations(input.toolSchema)){const value=valueAtPath(argumentsValue,annotation.path),header=`Mcp-Param-${annotation.name}`,mirrored=input.headers.get(header.toLowerCase());if(value==null){mirrored!==void 0&&failHeader("Unexpected MCP parameter header",header);continue}mirrored===void 0&&failHeader("Missing MCP parameter header",header),customHeaderMatches(annotation,value,decodeMcpHttpHeaderValue(mirrored,header))||failHeader("MCP parameter header does not match request body",header)}}function validateMcpHttpRequestHeaders(input){const headers=normalizedHeaders(input.headers),method=typeof input.request.method=="string"?input.request.method:"";validateMcpRequiredRequestHeaders(headers,input.request),!(method!=="tools/call"||input.toolSchema===void 0)&&validateMcpCustomRequestHeaders({headers,params:input.request.params,toolSchema:input.toolSchema})}const PM_MCP_HTTP_PROTOCOL_VERSION=PM_MCP_PROTOCOL_VERSION;export{PM_MCP_HTTP_PROTOCOL_VERSION,buildMcpHttpRequestHeaders,collectMcpHeaderAnnotations,decodeMcpHttpHeaderValue,encodeMcpHttpHeaderValue,validateMcpHttpRequestHeaders};
1
+ import{PM_MCP_ERROR_CODES as d,PM_MCP_PROTOCOL_VERSION as H,PmMcpProtocolError as f,isMcpRecord as i,resolveMcpRequestContext as M}from"./protocol.js";const P=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/u,_=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,g=/^[\t\x20-\x7E]*$/u,y=new Set(["prompts/get","resources/read","tools/call"]);function N(e){const t=new Map;for(const[n,o]of Object.entries(e)){if(o===void 0)continue;const r=typeof o=="string"?o:o.join(", ");t.set(n.toLowerCase(),r)}return t}function s(e,t){throw new f(e,d.headerMismatch,{header:t})}function C(e){const t=typeof e=="boolean"?String(e).toLowerCase():String(e);return t.length>0&&t.trim()===t&&g.test(t)&&!P.test(t)?t:`=?base64?${Buffer.from(t,"utf8").toString("base64")}?=`}function b(e,t){const n=P.exec(e);if(n){const o=n[1],r=Buffer.from(o,"base64");return r.toString("base64")!==o||r.length===0?s("Malformed MCP Base64 header value",t):r.toString("utf8")}return e.length===0||e.trim()!==e||!g.test(e)?s("Malformed MCP header value",t):e}function m(e){return Array.isArray(e)?e.some(m):i(e)?Object.prototype.hasOwnProperty.call(e,"x-mcp-header")||Object.values(e).some(m):!1}function O(e,t,n){const o=e["x-mcp-header"];if(o===void 0)return;const r=e.type;if(typeof o!="string"||!_.test(o)||!["boolean","integer","string"].includes(String(r))||n.has(o.toLowerCase()))throw new f("Invalid MCP x-mcp-header annotation",d.invalidParams,{field:t.join("."),annotation:o});return n.add(o.toLowerCase()),{name:o,path:t,type:r}}function S(e){if(!i(e))throw new f("Invalid MCP tool schema",d.invalidParams,{field:"inputSchema",expected:"object"});const t=[],n=new Set,o=(r,a)=>{const c=r.properties;if(c!==void 0){if(!i(c))throw new f("Invalid MCP tool schema properties",d.invalidParams,{field:"inputSchema.properties"});for(const[x,p]of Object.entries(c)){if(!i(p))continue;const u=[...a,x],h=O(p,u,n);h&&t.push(h);for(const[l,R]of Object.entries(p))if(l!=="properties"&&l!=="x-mcp-header"&&m(R))throw new f("MCP x-mcp-header is not statically reachable",d.invalidParams,{field:u.join("."),keyword:l});o(p,u)}}};for(const[r,a]of Object.entries(e))if(r!=="properties"&&m(a))throw new f("MCP x-mcp-header is not statically reachable",d.invalidParams,{field:"inputSchema",keyword:r});return o(e,[]),t}function w(e,t){let n=e;for(const o of t){if(!i(n))return;n=n[o]}return n}function E(e,t){const n=e==="resources/read"?t.uri:t.name;return typeof n=="string"?n:void 0}function q(e,t){const n=i(e.arguments)?e.arguments:{},o={};for(const r of S(t)){const a=w(n,r.path);if(a==null)continue;if(!(r.type==="integer"&&typeof a=="number"&&Number.isSafeInteger(a)||r.type==="boolean"&&typeof a=="boolean"||r.type==="string"&&typeof a=="string"))throw new f("Invalid MCP custom header argument",d.invalidParams,{field:r.path.join("."),expected:r.type});o[`Mcp-Param-${r.name}`]=C(a)}return o}function I(e){const t=i(e.request.params)?e.request.params:void 0,n=M(t),o=e.request.method;if(typeof o!="string"||o.length===0)return s("Missing MCP request method","Mcp-Method");const r={Accept:"application/json, text/event-stream","Content-Type":"application/json","MCP-Protocol-Version":n.protocolVersion,"Mcp-Method":o},a=E(o,t);if(y.has(o)){if(a===void 0)return s("Missing MCP request name","Mcp-Name");r["Mcp-Name"]=C(a)}return o==="tools/call"&&e.toolSchema!==void 0&&Object.assign(r,q(t,e.toolSchema)),r}function A(e,t){const n=t.method;(typeof n!="string"||n.length===0)&&s("Missing MCP request method","Mcp-Method");const o=i(t.params)?t.params:void 0,r=M(o).protocolVersion;if(e.get("mcp-protocol-version")!==r&&s("MCP protocol header does not match request metadata","MCP-Protocol-Version"),e.get("mcp-method")!==n&&s("MCP method header does not match request body","Mcp-Method"),y.has(n)){const a=e.get("mcp-name"),c=E(n,o);(a===void 0||c===void 0||b(a,"Mcp-Name")!==c)&&s("MCP name header does not match request body","Mcp-Name")}e.has("last-event-id")&&s("MCP SSE resumability is not supported","Last-Event-ID")}function j(e,t,n){return e.type==="integer"?typeof t=="number"&&Number.isSafeInteger(t)&&Number(n)===t:e.type==="boolean"?typeof t=="boolean"&&n===String(t):typeof t=="string"&&n===t}function T(e){const t=i(e.params.arguments)?e.params.arguments:{};for(const n of S(e.toolSchema)){const o=w(t,n.path),r=`Mcp-Param-${n.name}`,a=e.headers.get(r.toLowerCase());if(o==null){a!==void 0&&s("Unexpected MCP parameter header",r);continue}a===void 0&&s("Missing MCP parameter header",r),j(n,o,b(a,r))||s("MCP parameter header does not match request body",r)}}function L(e){const t=N(e.headers),n=typeof e.request.method=="string"?e.request.method:"";A(t,e.request),!(n!=="tools/call"||e.toolSchema===void 0)&&T({headers:t,params:e.request.params,toolSchema:e.toolSchema})}const V=H;export{V as PM_MCP_HTTP_PROTOCOL_VERSION,I as buildMcpHttpRequestHeaders,S as collectMcpHeaderAnnotations,b as decodeMcpHttpHeaderValue,C as encodeMcpHttpHeaderValue,L as validateMcpHttpRequestHeaders};
2
2
  //# sourceMappingURL=transport.js.map
@@ -1,2 +1,2 @@
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]="3fe6f853-6742-5305-b722-0cc74547f367")}catch{}})();import{runHistoryRepair}from"../history-repair.js";import{isOriginalGitStateRestored}from"./receipt-operation.js";import{markMergeReceiptReconciled,summarizeMergeReceipt}from"./receipts.js";async function settleAbandonedMergeReceipts(params){if(params.cwd===null)return[];const settled=[];for(const receipt of params.receipts){if(receipt.operation===void 0||!await isOriginalGitStateRestored(params.cwd,receipt.item_path,receipt.operation))continue;const mergeAbandonmentProof={gitWorkspaceRoot:params.cwd,receipt};await runHistoryRepair(receipt.item_id,{dryRun:!0,mergeAbandonmentProof},params.global),params.dryRun||(await runHistoryRepair(receipt.item_id,{author:params.author??params.global.author,mergeAbandonmentProof,message:params.message??`Settle ${receipt.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...summarizeMergeReceipt(receipt),reason:"original_git_state_restored",operation:receipt.operation}]}}},params.global),await markMergeReceiptReconciled(params.cwd,receipt,{requireExisting:!0,settlement:"original_git_state_restored"})),settled.push(receipt.id)}return settled}export{settleAbandonedMergeReceipts};
1
+ import{runHistoryRepair as r}from"../history-repair.js";import{isOriginalGitStateRestored as n}from"./receipt-operation.js";import{markMergeReceiptReconciled as a,summarizeMergeReceipt as d}from"./receipts.js";async function l(e){if(e.cwd===null)return[];const i=[];for(const t of e.receipts){if(t.operation===void 0||!await n(e.cwd,t.item_path,t.operation))continue;const o={gitWorkspaceRoot:e.cwd,receipt:t};await r(t.item_id,{dryRun:!0,mergeAbandonmentProof:o},e.global),e.dryRun||(await r(t.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:o,message:e.message??`Settle ${t.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...d(t),reason:"original_git_state_restored",operation:t.operation}]}}},e.global),await a(e.cwd,t,{requireExisting:!0,settlement:"original_git_state_restored"})),i.push(t.id)}return i}export{l as settleAbandonedMergeReceipts};
2
2
  //# sourceMappingURL=abandoned-receipts.js.map
@@ -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]="74f8a3ee-f0dc-568d-86d1-8c0b9649e2e2")}catch{}})();import{readFile,writeFile}from"node:fs/promises";import path from"node:path";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{pathExists}from"../../core/fs/fs-utils.js";import{parseItemDocument}from"../../core/item/item-format.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{nowIso}from"../../core/shared/time.js";import{getSettingsPath,resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{hashItemScalarDecisionValue,mergeHistoryStreams,mergeItemDocuments,mergeJsonDocuments,mergeRelationshipEventStreams}from"./three-way.js";import{captureMergeReceiptOperation}from"./receipt-operation.js";import{summarizeMergeReceipt,writeMergeReceipt}from"./receipts.js";const MERGE_DRIVER_ARTIFACT_VALUES=["item","history","relationship","json"];function resolveArtifact(value){const normalized=value.trim().toLowerCase();if(MERGE_DRIVER_ARTIFACT_VALUES.includes(normalized))return normalized;throw new PmCliError(`Unknown merge artifact "${value}". Supported values: ${MERGE_DRIVER_ARTIFACT_VALUES.join(", ")}.`,EXIT_CODE.USAGE)}function resolvePreferredSide(value){if(value===void 0)return"ours";const normalized=value.trim().toLowerCase();if(normalized==="ours"||normalized==="theirs")return normalized;throw new PmCliError(`Unknown --prefer value "${value}". Supported values: ours, theirs.`,EXIT_CODE.USAGE)}async function readSideFile(filePath,label){try{return await readFile(filePath,"utf8")}catch{throw new PmCliError(`Cannot read merge ${label} file at ${filePath}.`,EXIT_CODE.NOT_FOUND)}}async function loadOptionalSettings(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);return await pathExists(getSettingsPath(pmRoot))?readSettings(pmRoot):null}function itemFormatForPath(filePath,settings){return filePath.endsWith(".md")?"json_markdown":filePath.endsWith(".toon")?"toon":settings?.item_format??"toon"}async function preserveIdentityRefusal(merge,sides){try{return merge()}catch(error){if(error instanceof PmCliError&&error.context?.code==="item_identity_conflict"){const line=raw=>raw.endsWith(`
2
- `)?raw:`${raw}
3
- `;throw await writeFile(sides.outputPath,`<<<<<<< pm ours
4
- ${line(sides.oursRaw)}||||||| pm base
5
- ${line(sides.baseRaw)}=======
6
- ${line(sides.theirsRaw)}>>>>>>> pm theirs
7
- `,"utf8"),new PmCliError(`Unresolved identity for ${sides.itemPath}: both snapshots remain in conflict markers. ${error.message}`,error.exitCode,{...error.context,recovery:{suggested_retry:"git status --short"},nextSteps:["Preserve both source snapshots and establish item identity before resolving. Do not stage conflict markers as a completed merge; pm health and storage validation reject them."]})}throw error}}async function runMergeDriver(options,global2){const artifact=resolveArtifact(options.artifact),preferred=resolvePreferredSide(options.prefer),outputPath=path.resolve(options.outputPath??options.oursPath),[baseRaw,oursRaw,theirsRaw]=await Promise.all([readSideFile(options.basePath,"base"),readSideFile(options.oursPath,"ours"),readSideFile(options.theirsPath,"theirs")]);let merged,receiptInput;const conflicts=[],result={},refusalSides={baseRaw,oursRaw,theirsRaw,outputPath,itemPath:options.itemPath??outputPath};if(artifact==="history"){const historyMerge=await preserveIdentityRefusal(()=>mergeHistoryStreams(baseRaw,oursRaw,theirsRaw),refusalSides);merged=historyMerge.merged,result.history={strategy:historyMerge.strategy,common_entries:historyMerge.common_entries,entries_from_ours:historyMerge.entries_from_ours,entries_from_theirs:historyMerge.entries_from_theirs,entries_total:historyMerge.entries_total,reanchored:historyMerge.reanchored}}else if(artifact==="relationship"){const relationshipMerge=mergeRelationshipEventStreams(baseRaw,oursRaw,theirsRaw);merged=relationshipMerge.merged,result.relationship={strategy:relationshipMerge.strategy,common_entries:relationshipMerge.common_entries,entries_from_ours:relationshipMerge.entries_from_ours,entries_from_theirs:relationshipMerge.entries_from_theirs,entries_total:relationshipMerge.entries_total,reanchored:relationshipMerge.reanchored}}else if(artifact==="item"){const settings=await loadOptionalSettings(global2),itemFormat=itemFormatForPath(options.itemPath??outputPath,settings),extensionFieldNames=collectRegisteredItemFieldNames(getActiveExtensionRegistrations()),itemMerge=await preserveIdentityRefusal(()=>mergeItemDocuments(baseRaw,oursRaw,theirsRaw,{format:itemFormat,schema:settings?.schema,extensionFieldNames,preferred,conflictResolution:"latest_document_update"}),refusalSides);if(merged=itemMerge.merged,conflicts.push(...itemMerge.conflict_fields),result.item={fields_from_theirs:itemMerge.fields_from_theirs,union_fields:itemMerge.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},options.itemPath!==void 0){const mergedDocument=parseItemDocument(merged,{format:itemFormat,schema:settings?.schema,extensionFieldNames}),mergedMetadata=mergedDocument.metadata,receiptFields=[...new Set([...itemMerge.fields_from_theirs,...itemMerge.union_fields,...itemMerge.conflict_decisions.map(decision=>decision.field)])];receiptInput={cwd:process.cwd(),itemPath:options.itemPath,preferred,conflictResolution:"latest_document_update",fieldsFromTheirs:itemMerge.fields_from_theirs,unionFields:itemMerge.union_fields,mergedFieldHashes:Object.fromEntries(receiptFields.map(field=>[field,hashItemScalarDecisionValue(field==="body"?mergedDocument.body:mergedMetadata[field])])),decisions:itemMerge.conflict_decisions,operation:await captureMergeReceiptOperation(process.cwd(),options.itemPath,oursRaw)}}}else{const jsonMerge=mergeJsonDocuments(baseRaw,oursRaw,theirsRaw,{preferred});merged=jsonMerge.merged,conflicts.push(...jsonMerge.conflict_paths),result.json={paths_from_theirs:jsonMerge.paths_from_theirs}}if(await writeFile(outputPath,merged,"utf8"),receiptInput!==void 0){const receipt=await writeMergeReceipt(receiptInput);receipt!==null&&(result.receipt=summarizeMergeReceipt(receipt))}const guidance=[];if(conflicts.length>0){const receiptGuidance=result.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${result.receipt.receipt_id} with item ${result.receipt.item_id}; clone-local discarded values are never copied into this result.`;guidance.push(`Both branches changed ${conflicts.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${receiptGuidance} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return artifact==="history"&&result.history?.reanchored&&guidance.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:conflicts.length===0,artifact,output_path:outputPath,requested_preference:preferred,conflicts,...result,guidance,generated_at:nowIso()}}export{MERGE_DRIVER_ARTIFACT_VALUES,runMergeDriver};
1
+ import{readFile as x,writeFile as S}from"node:fs/promises";import D from"node:path";import{getActiveExtensionRegistrations as I}from"../../core/extensions/index.js";import{collectRegisteredItemFieldNames as M}from"../../core/extensions/item-fields.js";import{pathExists as j}from"../../core/fs/fs-utils.js";import{parseItemDocument as k}from"../../core/item/item-format.js";import{EXIT_CODE as g}from"../../core/shared/constants.js";import{PmCliError as u}from"../../core/shared/errors.js";import{nowIso as A}from"../../core/shared/time.js";import{getSettingsPath as C,resolvePmRoot as U}from"../../core/store/paths.js";import{readSettings as O}from"../../core/store/settings.js";import{hashItemScalarDecisionValue as T,mergeHistoryStreams as G,mergeItemDocuments as N,mergeJsonDocuments as q,mergeRelationshipEventStreams as z}from"./three-way.js";import{captureMergeReceiptOperation as L}from"./receipt-operation.js";import{summarizeMergeReceipt as V,writeMergeReceipt as W}from"./receipts.js";const b=["item","history","relationship","json"];function H(e){const r=e.trim().toLowerCase();if(b.includes(r))return r;throw new u(`Unknown merge artifact "${e}". Supported values: ${b.join(", ")}.`,g.USAGE)}function B(e){if(e===void 0)return"ours";const r=e.trim().toLowerCase();if(r==="ours"||r==="theirs")return r;throw new u(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,g.USAGE)}async function w(e,r){try{return await x(e,"utf8")}catch{throw new u(`Cannot read merge ${r} file at ${e}.`,g.NOT_FOUND)}}async function J(e){const r=U(process.cwd(),e.path);return await j(C(r))?O(r):null}function X(e,r){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":r?.item_format??"toon"}async function $(e,r){try{return e()}catch(i){if(i instanceof u&&i.context?.code==="item_identity_conflict"){const a=s=>s.endsWith(`
2
+ `)?s:`${s}
3
+ `;throw await S(r.outputPath,`<<<<<<< pm ours
4
+ ${a(r.oursRaw)}||||||| pm base
5
+ ${a(r.baseRaw)}=======
6
+ ${a(r.theirsRaw)}>>>>>>> pm theirs
7
+ `,"utf8"),new u(`Unresolved identity for ${r.itemPath}: both snapshots remain in conflict markers. ${i.message}`,i.exitCode,{...i.context,recovery:{suggested_retry:"git status --short"},nextSteps:["Preserve both source snapshots and establish item identity before resolving. Do not stage conflict markers as a completed merge; pm health and storage validation reject them."]})}throw i}}async function de(e,r){const i=H(e.artifact),a=B(e.prefer),s=D.resolve(e.outputPath??e.oursPath),[l,c,h]=await Promise.all([w(e.basePath,"base"),w(e.oursPath,"ours"),w(e.theirsPath,"theirs")]);let m,p;const d=[],o={},y={baseRaw:l,oursRaw:c,theirsRaw:h,outputPath:s,itemPath:e.itemPath??s};if(i==="history"){const t=await $(()=>G(l,c,h),y);m=t.merged,o.history={strategy:t.strategy,common_entries:t.common_entries,entries_from_ours:t.entries_from_ours,entries_from_theirs:t.entries_from_theirs,entries_total:t.entries_total,reanchored:t.reanchored}}else if(i==="relationship"){const t=z(l,c,h);m=t.merged,o.relationship={strategy:t.strategy,common_entries:t.common_entries,entries_from_ours:t.entries_from_ours,entries_from_theirs:t.entries_from_theirs,entries_total:t.entries_total,reanchored:t.reanchored}}else if(i==="item"){const t=await J(r),R=X(e.itemPath??s,t),v=M(I()),n=await $(()=>N(l,c,h,{format:R,schema:t?.schema,extensionFieldNames:v,preferred:a,conflictResolution:"latest_document_update"}),y);if(m=n.merged,d.push(...n.conflict_fields),o.item={fields_from_theirs:n.fields_from_theirs,union_fields:n.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){const P=k(m,{format:R,schema:t?.schema,extensionFieldNames:v}),F=P.metadata,E=[...new Set([...n.fields_from_theirs,...n.union_fields,...n.conflict_decisions.map(f=>f.field)])];p={cwd:process.cwd(),itemPath:e.itemPath,preferred:a,conflictResolution:"latest_document_update",fieldsFromTheirs:n.fields_from_theirs,unionFields:n.union_fields,mergedFieldHashes:Object.fromEntries(E.map(f=>[f,T(f==="body"?P.body:F[f])])),decisions:n.conflict_decisions,operation:await L(process.cwd(),e.itemPath,c)}}}else{const t=q(l,c,h,{preferred:a});m=t.merged,d.push(...t.conflict_paths),o.json={paths_from_theirs:t.paths_from_theirs}}if(await S(s,m,"utf8"),p!==void 0){const t=await W(p);t!==null&&(o.receipt=V(t))}const _=[];if(d.length>0){const t=o.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${o.receipt.receipt_id} with item ${o.receipt.item_id}; clone-local discarded values are never copied into this result.`;_.push(`Both branches changed ${d.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${t} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return i==="history"&&o.history?.reanchored&&_.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:d.length===0,artifact:i,output_path:s,requested_preference:a,conflicts:d,...o,guidance:_,generated_at:A()}}export{b as MERGE_DRIVER_ARTIFACT_VALUES,de as runMergeDriver};
8
8
  //# sourceMappingURL=driver.js.map
@@ -1,2 +1,2 @@
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]="b3ef9db1-1d20-5d88-927e-a08edf563cd5")}catch{}})();import{tryApplyReplayPatch}from"../../core/history/replay.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";function rebaseHistoryScalarPatch(current,patch,coordinate){const direct=tryApplyReplayPatch(current,patch);if(direct.ok)return direct.document;let next=structuredClone(current);for(const[index,operation]of patch.entries()){const field=/^\/metadata\/([^/]*)$/u.exec(operation.path)?.[1],missingField=field!==void 0&&!Object.hasOwn(next.metadata,field.replaceAll("~1","/").replaceAll("~0","~"));if(missingField&&operation.op==="remove")continue;const projected=missingField&&operation.op==="replace"?{...operation,op:"add"}:operation,applied=tryApplyReplayPatch(next,[projected]);if(!applied.ok)throw new PmCliError(`History union cannot rebase a scalar patch at ${coordinate.branch} line ${coordinate.line} (${coordinate.op}), operation ${index+1} ${operation.op} ${operation.path}; preserve the source histories for manual recovery.`,EXIT_CODE.CONFLICT,{code:"history_union_rebase_conflict",field:operation.path,history_merge:{...coordinate,patch_index:index,patch_path:operation.path},nextSteps:["Preserve all three history inputs and both item snapshots. Review the named branch event against the merged replay state; do not drop the event or concatenate unchecked patches. After resolving the history and item deliberately, run pm history <id> --verify and pm merge reconcile --dry-run before committing."]});next=applied.document}return next}export{rebaseHistoryScalarPatch};
1
+ import{tryApplyReplayPatch as h}from"../../core/history/replay.js";import{EXIT_CODE as d}from"../../core/shared/constants.js";import{PmCliError as m}from"../../core/shared/errors.js";function b(o,n,t){const a=h(o,n);if(a.ok)return a.document;let r=structuredClone(o);for(const[i,e]of n.entries()){const c=/^\/metadata\/([^/]*)$/u.exec(e.path)?.[1],p=c!==void 0&&!Object.hasOwn(r.metadata,c.replaceAll("~1","/").replaceAll("~0","~"));if(p&&e.op==="remove")continue;const l=p&&e.op==="replace"?{...e,op:"add"}:e,s=h(r,[l]);if(!s.ok)throw new m(`History union cannot rebase a scalar patch at ${t.branch} line ${t.line} (${t.op}), operation ${i+1} ${e.op} ${e.path}; preserve the source histories for manual recovery.`,d.CONFLICT,{code:"history_union_rebase_conflict",field:e.path,history_merge:{...t,patch_index:i,patch_path:e.path},nextSteps:["Preserve all three history inputs and both item snapshots. Review the named branch event against the merged replay state; do not drop the event or concatenate unchecked patches. After resolving the history and item deliberately, run pm history <id> --verify and pm merge reconcile --dry-run before committing."]});r=s.document}return r}export{b as rebaseHistoryScalarPatch};
2
2
  //# sourceMappingURL=history-scalar-rebase.js.map
@@ -1,2 +1,2 @@
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]="e57ef62f-fd40-5a33-9816-e24d8dba4d1d")}catch{}})();import{execFile}from"node:child_process";import{promisify}from"node:util";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{gitWorkspaceEnvironment}from"./worktree-config.js";const execFileAsync=promisify(execFile);async function inspectIgnoredMergeArtifacts(workspaceRoot,paths){if(paths.length===0)return[];let stdout;try{const pending=execFileAsync("git",["check-ignore","--verbose","-z","--stdin"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4}),input=pending.child.stdin;input!==null&&(input.on("error",()=>{pending.child.kill()}),input.end(`${paths.join("\0")}\0`)),{stdout}=await pending}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&error.code===1)return[];throw new PmCliError("Git could not verify ignore rules for merge artifacts; no automatic settlement is safe until that check succeeds.",EXIT_CODE.CONFLICT,{code:"merge_settlement_review_required",reason:"ignore_check_unavailable",nextSteps:["Check Git configuration and ignore-file readability, then retry pm merge reconcile --stage --dry-run."]})}const fields=stdout.split("\0"),ignored=[];for(let index=0;index+3<fields.length;index+=4){const[source,line,pattern,target]=fields.slice(index,index+4);pattern.startsWith("!")||ignored.push({path:target,source,line:Number(line),pattern})}return ignored}export{inspectIgnoredMergeArtifacts};
1
+ import{execFile as m}from"node:child_process";import{promisify as d}from"node:util";import{EXIT_CODE as f}from"../../core/shared/constants.js";import{PmCliError as u}from"../../core/shared/errors.js";import{gitWorkspaceEnvironment as g}from"./worktree-config.js";const p=d(m);async function b(s,r){if(r.length===0)return[];let i;try{const e=p("git",["check-ignore","--verbose","-z","--stdin"],{cwd:s,env:g(),timeout:1e4}),t=e.child.stdin;t!==null&&(t.on("error",()=>{e.child.kill()}),t.end(`${r.join("\0")}\0`)),{stdout:i}=await e}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code===1)return[];throw new u("Git could not verify ignore rules for merge artifacts; no automatic settlement is safe until that check succeeds.",f.CONFLICT,{code:"merge_settlement_review_required",reason:"ignore_check_unavailable",nextSteps:["Check Git configuration and ignore-file readability, then retry pm merge reconcile --stage --dry-run."]})}const n=i.split("\0"),o=[];for(let e=0;e+3<n.length;e+=4){const[t,l,c,a]=n.slice(e,e+4);c.startsWith("!")||o.push({path:a,source:t,line:Number(l),pattern:c})}return o}export{b as inspectIgnoredMergeArtifacts};
2
2
  //# sourceMappingURL=ignored-artifacts.js.map
@@ -1,2 +1,2 @@
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]="5f13a638-252b-53e3-9b65-c38ced133a9d")}catch{}})();import{ITEM_SCALAR_MISSING_VALUE,ITEM_LATEST_TIMESTAMP_FIELDS,ITEM_UNION_COLLECTION_FIELDS,encodeItemScalarDecisionValue,hashItemScalarDecisionValue,isItemScalarMissingValue,mergeHistoryStreams,mergeItemDocuments,mergeJsonDocuments,mergeRelationshipEventStreams}from"./three-way.js";import{inspectMergeReceiptEvidence,listMergeReceipts,markMergeReceiptReconciled,runMergeReceiptEvidenceReport,runMergeReceiptReport,summarizeMergeReceipt}from"./receipts.js";import{MERGE_DRIVER_ARTIFACT_VALUES,runMergeDriver}from"./driver.js";import{auditMergeAttributeFence,auditMergeDriverConfiguration,buildMergeAttributePatterns,findGitWorkspaceRoot,PM_GITATTRIBUTES_END,PM_GITATTRIBUTES_START,PM_GITATTRIBUTES_V2_END,PM_GITATTRIBUTES_V2_START,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,runMergeInstall}from"./install.js";import{runMergeReconcile}from"./reconcile.js";export{ITEM_LATEST_TIMESTAMP_FIELDS,ITEM_SCALAR_MISSING_VALUE,ITEM_UNION_COLLECTION_FIELDS,MERGE_DRIVER_ARTIFACT_VALUES,PM_GITATTRIBUTES_END,PM_GITATTRIBUTES_START,PM_GITATTRIBUTES_V2_END,PM_GITATTRIBUTES_V2_START,auditMergeAttributeFence,auditMergeDriverConfiguration,buildMergeAttributePatterns,encodeItemScalarDecisionValue,findGitWorkspaceRoot,hashItemScalarDecisionValue,inspectMergeReceiptEvidence,isItemScalarMissingValue,listMergeReceipts,markMergeReceiptReconciled,mergeHistoryStreams,mergeItemDocuments,mergeJsonDocuments,mergeRelationshipEventStreams,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,runMergeDriver,runMergeInstall,runMergeReceiptEvidenceReport,runMergeReceiptReport,runMergeReconcile,summarizeMergeReceipt};
1
+ import{ITEM_SCALAR_MISSING_VALUE as t,ITEM_LATEST_TIMESTAMP_FIELDS as i,ITEM_UNION_COLLECTION_FIELDS as T,encodeItemScalarDecisionValue as n,hashItemScalarDecisionValue as o,isItemScalarMissingValue as I,mergeHistoryStreams as M,mergeItemDocuments as c,mergeJsonDocuments as s,mergeRelationshipEventStreams as a}from"./three-way.js";import{inspectMergeReceiptEvidence as E,listMergeReceipts as _,markMergeReceiptReconciled as g,runMergeReceiptEvidenceReport as m,runMergeReceiptReport as S,summarizeMergeReceipt as l}from"./receipts.js";import{MERGE_DRIVER_ARTIFACT_VALUES as A,runMergeDriver as p}from"./driver.js";import{auditMergeAttributeFence as d,auditMergeDriverConfiguration as f,buildMergeAttributePatterns as L,findGitWorkspaceRoot as V,PM_GITATTRIBUTES_END as G,PM_GITATTRIBUTES_START as U,PM_GITATTRIBUTES_V2_END as v,PM_GITATTRIBUTES_V2_START as x,refreshMergeAttributeFenceIfInstalled as C,resolveMergeInstallContext as N,runMergeInstall as P}from"./install.js";import{runMergeReconcile as b}from"./reconcile.js";export{i as ITEM_LATEST_TIMESTAMP_FIELDS,t as ITEM_SCALAR_MISSING_VALUE,T as ITEM_UNION_COLLECTION_FIELDS,A as MERGE_DRIVER_ARTIFACT_VALUES,G as PM_GITATTRIBUTES_END,U as PM_GITATTRIBUTES_START,v as PM_GITATTRIBUTES_V2_END,x as PM_GITATTRIBUTES_V2_START,d as auditMergeAttributeFence,f as auditMergeDriverConfiguration,L as buildMergeAttributePatterns,n as encodeItemScalarDecisionValue,V as findGitWorkspaceRoot,o as hashItemScalarDecisionValue,E as inspectMergeReceiptEvidence,I as isItemScalarMissingValue,_ as listMergeReceipts,g as markMergeReceiptReconciled,M as mergeHistoryStreams,c as mergeItemDocuments,s as mergeJsonDocuments,a as mergeRelationshipEventStreams,C as refreshMergeAttributeFenceIfInstalled,N as resolveMergeInstallContext,p as runMergeDriver,P as runMergeInstall,m as runMergeReceiptEvidenceReport,S as runMergeReceiptReport,b as runMergeReconcile,l as summarizeMergeReceipt};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
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]="5d2c2c37-5ff2-5dab-84f1-55a7fa8d5a27")}catch{}})();import{execFile}from"node:child_process";import{realpath}from"node:fs/promises";import path from"node:path";import{promisify}from"node:util";import{isPathOutsideRoot}from"../workspace.js";import{gitWorkspaceEnvironment}from"./worktree-config.js";const execFileAsync=promisify(execFile),OBJECT_ID="[a-f0-9]{40}(?:[a-f0-9]{24})?",INDEX_ENTRY=new RegExp(`^100(?:644|755) (${OBJECT_ID}) 0$`,"u"),BLOB_METADATA=new RegExp(`^(${OBJECT_ID}) blob (\\d+)$`,"u");async function gitBatch(args,ids,options){const pending=execFileAsync("git",args,{...options,encoding:"buffer"}),input=pending.child.stdin;return input!==null&&(input.on("error",()=>{pending.child.kill()}),input.end(`${ids.join(`
1
+ import{execFile as O}from"node:child_process";import{realpath as E}from"node:fs/promises";import w from"node:path";import{promisify as T}from"node:util";import{isPathOutsideRoot as M}from"../workspace.js";import{gitWorkspaceEnvironment as N}from"./worktree-config.js";const b=T(O),I="[a-f0-9]{40}(?:[a-f0-9]{24})?",R=new RegExp(`^100(?:644|755) (${I}) 0$`,"u"),B=new RegExp(`^(${I}) blob (\\d+)$`,"u");async function x(o,a,r){const t=b("git",o,{...r,encoding:"buffer"}),e=t.child.stdin;return e!==null&&(e.on("error",()=>{t.child.kill()}),e.end(`${a.join(`
2
2
  `)}
3
- `)),(await pending).stdout}function indexedFiles(listing,requested){const files=new Map;for(const record of listing.split("\0")){const separator=record.indexOf(" "),file=record.slice(separator+1),metadata=INDEX_ENTRY.exec(record.slice(0,separator));metadata!==null&&requested.has(file)&&files.set(file,metadata[1])}return files}function blobBatches(metadata,requested,maximumBytes){const batches=[];let batch=[],bytes=0;for(const line of metadata.trimEnd().split(/\r?\n/u)){const match=BLOB_METADATA.exec(line);if(match===null||!requested.has(match[1]))continue;const size=Number(match[2]);!Number.isSafeInteger(size)||size>maximumBytes||(batch.length>0&&bytes+size+128>maximumBytes&&(batches.push(batch),batch=[],bytes=0),batch.push({id:match[1],size}),bytes+=size+128)}return batch.length>0&&batches.push(batch),batches}function decodeBlobs(output,entries,blobs){let offset=0;for(const{id,size}of entries){const start=output.indexOf(10,offset)+1;if(start===0||output.subarray(offset,start-1).toString("ascii")!==`${id} blob ${size}`||output[start+size]!==10)throw new Error("Invalid indexed receipt batch framing");blobs.set(id,output.subarray(start,start+size).toString("utf8")),offset=start+size+1}if(offset!==output.length)throw new Error("Unexpected indexed receipt batch data")}async function readIndexedReceiptBlobs(cwd,directory,fileNames,maximumBytes,linkedDirectory,policy={}){const env=gitWorkspaceEnvironment();env.GIT_NO_REPLACE_OBJECTS="1",linkedDirectory===void 0&&process.env.GIT_INDEX_FILE!==void 0&&(env.GIT_INDEX_FILE=path.resolve(process.env.GIT_INDEX_FILE));const options={cwd,env,windowsHide:!0,timeout:1e4,maxBuffer:maximumBytes+256};try{const root=(await execFileAsync("git",["rev-parse","--show-toplevel"],{...options,encoding:"utf8"})).stdout.trim(),[workspace,physicalDirectory]=await Promise.all([realpath(root),realpath(linkedDirectory??directory)]),relative=path.relative(workspace,linkedDirectory===void 0?physicalDirectory:path.resolve(linkedDirectory)).replaceAll("\\","/");if(isPathOutsideRoot(relative))return new Map;options.cwd=workspace;const names=new Map(fileNames.map(file=>[`${relative}/${file}`,file])),listing=(await execFileAsync("git",["ls-files","--stage","-z","--",`:(literal)${relative}/`],{...options,encoding:"utf8"})).stdout,files=indexedFiles(listing,new Set(names.keys()));if(files.size===0)return new Map;const ids=new Set(files.values()),metadata=(await gitBatch(["cat-file","--batch-check"],[...ids],options)).toString("utf8"),blobs=new Map;for(const batch of blobBatches(metadata,ids,maximumBytes))decodeBlobs(await gitBatch(["cat-file","--batch"],batch.map(entry=>entry.id),options),batch,blobs);if(policy.failOnReadError&&blobs.size!==ids.size)throw new Error("Unable to read every indexed receipt blob");return new Map([...files].filter(([,id])=>blobs.has(id)).map(([file,id])=>[names.get(file),blobs.get(id)]))}catch(error){if(policy.failOnReadError)throw error;return new Map}}export{readIndexedReceiptBlobs};
3
+ `)),(await t).stdout}function S(o,a){const r=new Map;for(const t of o.split("\0")){const e=t.indexOf(" "),i=t.slice(e+1),n=R.exec(t.slice(0,e));n!==null&&a.has(i)&&r.set(i,n[1])}return r}function y(o,a,r){const t=[];let e=[],i=0;for(const n of o.trimEnd().split(/\r?\n/u)){const s=B.exec(n);if(s===null||!a.has(s[1]))continue;const c=Number(s[2]);!Number.isSafeInteger(c)||c>r||(e.length>0&&i+c+128>r&&(t.push(e),e=[],i=0),e.push({id:s[1],size:c}),i+=c+128)}return e.length>0&&t.push(e),t}function z(o,a,r){let t=0;for(const{id:e,size:i}of a){const n=o.indexOf(10,t)+1;if(n===0||o.subarray(t,n-1).toString("ascii")!==`${e} blob ${i}`||o[n+i]!==10)throw new Error("Invalid indexed receipt batch framing");r.set(e,o.subarray(n,n+i).toString("utf8")),t=n+i+1}if(t!==o.length)throw new Error("Unexpected indexed receipt batch data")}async function C(o,a,r,t,e,i={}){const n=N();n.GIT_NO_REPLACE_OBJECTS="1",e===void 0&&process.env.GIT_INDEX_FILE!==void 0&&(n.GIT_INDEX_FILE=w.resolve(process.env.GIT_INDEX_FILE));const s={cwd:o,env:n,windowsHide:!0,timeout:1e4,maxBuffer:t+256};try{const c=(await b("git",["rev-parse","--show-toplevel"],{...s,encoding:"utf8"})).stdout.trim(),[g,v]=await Promise.all([E(c),E(e??a)]),d=w.relative(g,e===void 0?v:w.resolve(e)).replaceAll("\\","/");if(M(d))return new Map;s.cwd=g;const m=new Map(r.map(f=>[`${d}/${f}`,f])),_=(await b("git",["ls-files","--stage","-z","--",`:(literal)${d}/`],{...s,encoding:"utf8"})).stdout,p=S(_,new Set(m.keys()));if(p.size===0)return new Map;const u=new Set(p.values()),$=(await x(["cat-file","--batch-check"],[...u],s)).toString("utf8"),l=new Map;for(const f of y($,u,t))z(await x(["cat-file","--batch"],f.map(h=>h.id),s),f,l);if(i.failOnReadError&&l.size!==u.size)throw new Error("Unable to read every indexed receipt blob");return new Map([...p].filter(([,f])=>l.has(f)).map(([f,h])=>[m.get(f),l.get(h)]))}catch(c){if(i.failOnReadError)throw c;return new Map}}export{C as readIndexedReceiptBlobs};
4
4
  //# sourceMappingURL=indexed-receipt-blobs.js.map
@@ -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]="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
- `),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}
1
+ import{assertInitializedTracker as J}from"../environment/tracker-preflight.js";import{isFileMissingError as z,readFileIfExists as X,writeFileAtomic as Y}from"../../core/fs/fs-utils.js";import{access as Q,lstat as D,readFile as $,realpath as h}from"node:fs/promises";import{constants as Z}from"node:fs";import{execFile as ee}from"node:child_process";import a from"node:path";import{promisify as te}from"node:util";import{pathExists as I}from"../../core/fs/fs-utils.js";import{resolveItemTypeRegistry as re}from"../../core/item/type-registry.js";import{acquireLock as E}from"../../core/lock/lock.js";import{resolvePmPackageRootFromModule as ne}from"../../core/packages/root.js";import{EXIT_CODE as b}from"../../core/shared/constants.js";import{PmCliError as k}from"../../core/shared/errors.js";import{resolveAuthor as oe}from"../../core/shared/author.js";import{nowIso as ie}from"../../core/shared/time.js";import{resolvePmRoot as A}from"../../core/store/paths.js";import{readSettings as R,resolveGovernanceKnobs as se}from"../../core/store/settings.js";import{isPathOutsideRoot as ae}from"../workspace.js";import{resolveSourceContextWritePolicy as ce}from"../environment/source-context.js";import{gitWorkspaceEnvironment as _,resolveMergeDriverConfigScope as le,stripGitPathTerminator as F,writeMergeDriverGitConfig as ue}from"./worktree-config.js";import{discoverProjectRuntimeVersionPins as me}from"../environment/project-runtime-compatibility.js";const v=te(ee),P="# pm-cli:merge-drivers:start",pe="# pm-cli:merge-drivers:end",x="# pm-cli:merge-drivers:v2:start",G="# pm-cli:merge-drivers:v2:end",de="merge-fence",fe="merge-attributes";function T(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function ge(e,o){const r=await h(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(r))return;const{stdout:t}=await v(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()===o?r:void 0}async function he(){const e=ne(import.meta.url,["../../.."]);let o=process.execPath,r=!1;const t=await h(process.execPath),n=process.versions.bun,i=(process.env.PATH??"").split(a.delimiter).filter(s=>a.isAbsolute(s)).map(s=>a.join(s,n===void 0?a.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),c=n===void 0?i:[process.env.npm_execpath??"",...i,t].filter(s=>a.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(a.basename(s)));for(const s of c)try{if(await Q(s,Z.X_OK),n!==void 0){const p=await ge(s,n);if(p!==void 0){o=p,r=!0;break}continue}if(s!==t&&await h(s)===t){o=s;break}}catch{}if(n!==void 0&&!r)throw new k("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",b.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`${T(o)} ${T(a.join(e,"dist","cli.js"))}`}const B=[{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 we(e){const o=e.explicitPath?.trim(),r=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),t=e.environment.PM_SOURCE_PM_PATH?.trim(),n=ce(e.environment),i=!!(r&&t),c=o===void 0&&i&&(e.dryRun||n.source_writes_allowed);if(o!==void 0){const s=A(e.cwd,o);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:n}}return c?{pm_root:a.resolve(t),workspace_start:a.resolve(r),source_coordinates_available:!0,source_context_selected:!0,source_policy:n}:{pm_root:i?A(e.cwd,".agents/pm"):A(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:n}}async function M(e){try{const{stdout:o}=await v("git",["rev-parse","--show-toplevel"],{cwd:e,env:_(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await h(F(o))}catch{return null}}async function L(e){const o=await M(e);if(o===null)throw new k("pm merge install requires a git repository (merge drivers are git configuration).",b.USAGE);return o}function S(e,o){return a.relative(e,o).split(a.sep).join("/")}function N(e){return e.replace(/[\\*?[\]!]/gu,"\\$&")}function g(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function W(e,o){if(e[o]!=="'")return null;let r="";for(let t=o+1;t<e.length;t+=1){if(e.startsWith(`'"'"'`,t)){r+="'",t+=4;continue}if(e[t]==="'")return{value:r,nextOffset:t+1};r+=e[t]}return null}async function ye(e,o,r){if(me(o).filter(i=>i.constraint==="exact").some(i=>i.version!==r))return!1;const n=await M(e);if(n!==null&&n!==await h(o)){const i=await Promise.all([n,o].map(async c=>{const s=await v("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:c,env:_(),timeout:1e4});return h(s.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function ve(e,o,r){const t=W(e,0);if(t===null||e[t.nextOffset]!==" ")return!1;const n=W(e,t.nextOffset+1);if(n===null||e.slice(n.nextOffset)!==o||!/^(?:node|bun)(?:\.exe)?$/iu.test(a.basename(t.value))||a.basename(n.value)!=="cli.js"||a.basename(a.dirname(n.value))!=="dist"||!await I(t.value)||!await I(n.value))return!1;try{const i=a.dirname(a.dirname(n.value)),c=JSON.parse(await $(a.join(i,"package.json"),"utf8")),s=typeof c.bin=="string"?c.bin:c.bin?.pm;return await ye(i,r,c.version)?c.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function C(e,o){const r=e.length>0?`${N(e)}/`:"",t=[`${g(`${r}**/*.toon`)} merge=pm-item-toon`,`${g(`${r}**/*.md`)} merge=pm-item-markdown`];for(const n of o){const i=N(n);t.push(`${g(`${r}${i}/*.toon`)} merge=pm-item-toon`),t.push(`${g(`${r}${i}/*.md`)} merge=pm-item-markdown`)}return t.push(`${g(`${r}**/*.jsonl`)} merge=pm-relationship`),t.push(`${g(`${r}history/*.jsonl`)} merge=pm-history`),t.push(`${g(`${r}settings.json`)} merge=pm-json`),t.push(`${g(`${r}**/*.json`)} merge=pm-json`),t.push(`${g(`${r}extensions/**`)} merge=text`),t.push(`${g(`${r}extensions/.managed-extensions.json`)} merge=pm-json`),t}function H(e){const o=[];let r=0;for(;r<e.length;){const t=e.indexOf(P,r),n=e.indexOf(x,r),i=t===-1?n:n===-1?t:Math.min(t,n);if(i===-1)break;const c=i===n,s=c?x:P,p=c?G:pe,d=e.indexOf(p,i+s.length),u=d===-1?e.length:d+p.length;o.push({start:i,end:u,closed:d!==-1,lines:e.slice(i+s.length,d===-1?u:d).split(`
2
+ `).map(l=>l.trim()).filter(Boolean)}),r=u}return o}function U(e,o,r){const t=new Set(o),n=g(r.length>0?`${r}/`:"").slice(0,-1);return e.some(i=>t.has(i)||i.startsWith(n)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(i.slice(n.length)))}async function K(e,o,r,t){const n=a.join(e,".gitattributes"),i=t?null:F((await v("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:_(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout),c=i===null?null:await E(i,fe,120,"merge-fence",!1,!0,5e3);try{const s=await X(n)??"",p=[x,...r,G].join(`
3
+ `),d=H(s),u=d.filter(m=>U(m.lines,r,o));u.length===0&&o===".agents/pm"&&d.length===1&&d[0].lines.every(m=>!m.includes("/"))&&u.push(d[0]);let l;if(u.length>0){const m=u[0];l=s;for(const y of u.slice(1).reverse())l=`${l.slice(0,y.start)}${l.slice(y.end)}`;l=`${l.slice(0,m.start)}${p}${l.slice(m.end)}`}else{const m=s.trimEnd();l=`${m.length>0?`${m}
4
4
 
5
- `:""}${block}
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
- `);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};
5
+ `:""}${p}
6
+ `}return l===s&&!(await D(n)).isSymbolicLink()?{path:n,changed:!1}:(t||await Y(n,l),{path:n,changed:!0})}finally{await c?.()}}function q(e){const o=re(e,null);return[...new Set(Object.values(o.type_to_folder))].sort((r,t)=>r.localeCompare(t))}async function V(e){try{return await h(e)}catch{return null}}function _e(e,o){const r=a.relative(e,o);return r===""||!a.isAbsolute(r)&&r.split(a.sep)[0]!==".."}async function be(e){try{return(await D(e)).isFile()?await $(e,"utf8"):null}catch{return null}}async function ke(e){try{return await $(e,"utf8")}catch{return null}}async function xe(e,o){const r=o===void 0?await M(e):o;if(r===null)return{trackerRoot:e,topLevel:null};const[t,n]=await Promise.all([V(e),V(r)]);return t===null||n===null||!_e(n,t)?null:{trackerRoot:t,topLevel:n}}async function $e(e){const o=e.topLevel===null?ke:be;let r=e.trackerRoot;for(let t=0;e.topLevel!==null||t<8;t+=1){const n=await o(a.join(r,".gitattributes"));if(n!==null&&(n.includes(x)||n.includes(P)))return{directory:r,content:n};const i=a.dirname(r);if(i===r||e.topLevel!==null&&a.relative(e.topLevel,r)==="")return null;r=i}return null}async function Je(e,o,r={}){const t=await xe(a.resolve(e),r.gitWorkspaceRoot),n=t===null?null:await $e(t);if(t===null||n===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};const i=n.directory,c=n.content,s=a.join(i,".gitattributes"),p=S(i,t.trackerRoot),d=H(c),u=C(p,o),l=d.filter(w=>U(w.lines,u,p)),m=l.flatMap(w=>w.closed?w.lines:[]),y=new Set(m),f=new Set(u),j=u.filter(w=>!y.has(w)),O=m.filter(w=>!f.has(w));return{status:l.length!==1||!l[0].closed||j.length>0||O.length>0?"drift":"ok",path:s,missing_patterns:j,stale_patterns:O,schema_scope:"project"}}async function ze(e){const o=[],r=[];for(const t of B){const n=`merge.${t.key}.driver`,i=` merge driver ${t.artifact} "%O" "%A" "%B"${t.itemPath===void 0?"":` --item-path ${t.itemPath}`}`;try{const{stdout:c}=await v("git",["config","--get",n],{cwd:e,env:_(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=c.trim();await ve(s,i,e)||r.push(n)}catch{o.push(n)}}return{status:o.length>0?"missing":r.length>0?"drift":"ok",missing_keys:o,drifted_keys:r}}async function Xe(e){let o;try{o=await L(a.resolve(e))}catch{return{status:"no_git"}}const r=S(o,a.resolve(e)),t=await R(e),n=oe(void 0,t.author_default),i=await E(e,de,t.locks.ttl_seconds,n,!1,se(t).force_required_for_stale_lock,t.locks.wait_ms);try{const c=a.join(o,".gitattributes");let s;try{s=await $(c,"utf8")}catch(l){if(l instanceof Error&&"code"in l&&z(l))return{status:"not_installed",path:c};throw l}if(!s.includes(x)&&!s.includes(P))return{status:"not_installed",path:c};const p=await R(e),d=q(p),u=await K(o,r,C(r,d),!1);return{status:u.changed?"refreshed":"unchanged",path:u.path}}finally{await i()}}async function Ye(e,o){const r=we({cwd:process.cwd(),explicitPath:o.path,dryRun:e.dryRun===!0,environment:process.env}),t=r.pm_root;await J(t);const n=await L(r.workspace_start);return Ee({pmRoot:t,workspaceRoot:n,dryRun:e.dryRun===!0,preCommitHook:e.preCommitHook===!0})}async function Pe(e,o){const r=(await v("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:_(),timeout:1e4})).stdout.trim(),t=await E(r,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{const n=await le(e);let i;try{i=(await v("git",["config",n,"--null","--get-regexp","."],{cwd:e,env:_(),timeout:1e4})).stdout}catch(s){if(typeof s!="object"||s===null||!("code"in s)||s.code!==1)throw s;i=""}const c=new Map(i.split("\0").filter(Boolean).map(s=>{const p=s.indexOf(`
7
+ `);return[s.slice(0,p),s.slice(p+1)]}));for(const s of o)c.get(s.key)!==s.value&&await ue(e,[n,s.key,s.value])}finally{await t()}}async function Ee(e){const o=a.resolve(e.pmRoot),r=a.resolve(e.workspaceRoot),t=e.dryRun===!0;let n,i;try{[n,i]=await Promise.all([h(o),h(r)])}catch(f){throw new k(`Cannot resolve tracker root ${o} or workspace root ${r}: ${String(f)}`,b.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 c=S(i,n);if(ae(c))throw new k(`Tracker root ${o} is outside the git repository ${r}; there is nothing to configure for this repository.`,b.USAGE);const s=await R(n),p=q(s),d=C(c,p),u=[],l=await he(),m=e.preCommitHook===!0?await import("./settlement-hook.js").then(async f=>({plan:await f.prepareMergeSettlementHook(i,`${l} --pm-path ${T(c||".")}`),write:f.writeMergeSettlementHook})):void 0;for(const f of B)u.push({key:`merge.${f.key}.name`,value:f.name}),u.push({key:`merge.${f.key}.driver`,value:`${l} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!t)try{await Pe(i,u)}catch{throw new k(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,b.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 y=await K(i,c,d,t);return m!==void 0&&!t&&await m.write(m.plan),{ok:!0,dry_run:t,workspace_root:i,pm_root:n,gitattributes:{path:y.path,changed:y.changed,patterns:d,schema_scope:"project"},git_config:u,...m===void 0?{}:{settlement_hook:{path:m.plan.path,changed:m.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:ie()}}export{pe as PM_GITATTRIBUTES_END,P as PM_GITATTRIBUTES_START,G as PM_GITATTRIBUTES_V2_END,x as PM_GITATTRIBUTES_V2_START,Je as auditMergeAttributeFence,ze as auditMergeDriverConfiguration,C as buildMergeAttributePatterns,M as findGitWorkspaceRoot,Ee as installMergeFence,Xe as refreshMergeAttributeFenceIfInstalled,we as resolveMergeInstallContext,q as resolveProjectMergeTypeFolders,Ye as runMergeInstall};
8
8
  //# sourceMappingURL=install.js.map
@@ -1,2 +1,2 @@
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]="1439aa83-2e99-5713-891d-92846e62a302")}catch{}})();import{constants as fsConstants}from"node:fs";import{lstat,open}from"node:fs/promises";const MERGE_RECEIPT_FILE_MAX_BYTES=16*1024*1024,NODE_RECEIPT_FILE_BOUNDARY={lstat,open};function resolveReceiptNoFollowFlag(constants){return constants.O_NOFOLLOW??0}async function readBoundedRegularFile(receiptPath,maximumBytes,boundary=NODE_RECEIPT_FILE_BOUNDARY){const pathStats=await boundary.lstat(receiptPath);if(pathStats.isSymbolicLink()||!pathStats.isFile()||pathStats.size>maximumBytes)return null;const handle=await boundary.open(receiptPath,fsConstants.O_RDONLY|resolveReceiptNoFollowFlag(fsConstants));try{const openedStats=await handle.stat();if(!openedStats.isFile()||openedStats.size>maximumBytes)return null;const buffer=Buffer.alloc(openedStats.size);let offset=0;for(;offset<buffer.length;){const{bytesRead}=await handle.read(buffer,offset,buffer.length-offset,offset);if(bytesRead===0)break;offset+=bytesRead}return(await handle.stat()).size===openedStats.size&&offset===openedStats.size?buffer.toString("utf8",0,offset):null}finally{await handle.close()}}export{MERGE_RECEIPT_FILE_MAX_BYTES,readBoundedRegularFile,resolveReceiptNoFollowFlag};
1
+ import{constants as f}from"node:fs";import{lstat as c,open as u}from"node:fs/promises";const O=16*1024*1024,E={lstat:c,open:u};function p(n){return n.O_NOFOLLOW??0}async function R(n,o,l=E){const i=await l.lstat(n);if(i.isSymbolicLink()||!i.isFile()||i.size>o)return null;const s=await l.open(n,f.O_RDONLY|p(f));try{const e=await s.stat();if(!e.isFile()||e.size>o)return null;const a=Buffer.alloc(e.size);let t=0;for(;t<a.length;){const{bytesRead:r}=await s.read(a,t,a.length-t,t);if(r===0)break;t+=r}return(await s.stat()).size===e.size&&t===e.size?a.toString("utf8",0,t):null}finally{await s.close()}}export{O as MERGE_RECEIPT_FILE_MAX_BYTES,R as readBoundedRegularFile,p as resolveReceiptNoFollowFlag};
2
2
  //# sourceMappingURL=receipt-file-boundary.js.map
@@ -1,2 +1,2 @@
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]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();import{execFile}from"node:child_process";import{createHash}from"node:crypto";import{readdir}from"node:fs/promises";import path from"node:path";import{promisify}from"node:util";import{readBoundedRegularFile}from"./receipt-file-boundary.js";const execFileAsync=promisify(execFile),GIT_OBJECT_ID=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function captureMergeReceiptOperation(cwd,itemPath,originalItemRaw){const trimmedItemPath=itemPath.trim(),normalizedItemPath=/^(['"])(.*)\1$/su.exec(trimmedItemPath)?.[2]??trimmedItemPath;for(const backend of["rebase-merge","rebase-apply"])try{const{stdout:marker}=await execFileAsync("git",["rev-parse","--path-format=absolute","--git-path",`${backend}/orig-head`],{cwd,timeout:1e4}),originalHead=(await readBoundedRegularFile(marker.trim(),128))?.trim();if(originalHead===void 0||!GIT_OBJECT_ID.test(originalHead))continue;const{stdout}=await execFileAsync("git",["rev-parse","--verify",`${originalHead}:${normalizedItemPath}`],{cwd,timeout:1e4}),originalBlob=stdout.trim();return{kind:"rebase",original_head:originalHead,original_blob:originalBlob}}catch{}if(originalItemRaw!==void 0&&Object.keys(process.env).some(key=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(key)))try{const{stdout:heads}=await execFileAsync("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd,timeout:1e4}),[head,originalHead]=heads.trim().split(/\r?\n/u);if(head!==originalHead||!GIT_OBJECT_ID.test(head))return;const{stdout}=await execFileAsync("git",["rev-parse","--verify",`${head}:${normalizedItemPath}`],{cwd,timeout:1e4}),originalBlob=stdout.trim(),oursBlob=createHash(originalBlob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(originalItemRaw)}\0`).update(originalItemRaw).digest("hex");return originalBlob!==oursBlob?void 0:{kind:"merge",original_head:head,original_blob:originalBlob}}catch{}}function isMergeReceiptOperation(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const record=value;return Object.keys(record).length===3&&(record.kind==="rebase"||record.kind==="merge")&&typeof record.original_head=="string"&&GIT_OBJECT_ID.test(record.original_head)&&typeof record.original_blob=="string"&&GIT_OBJECT_ID.test(record.original_blob)}async function isOriginalGitStateRestored(cwd,itemPath,operation,expectedItemRaw){if(expectedItemRaw!==void 0&&createHash(operation.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(expectedItemRaw)}\0`).update(expectedItemRaw).digest("hex")!==operation.original_blob)return!1;try{const{stdout:gitDirectory}=await execFileAsync("git",["rev-parse","--absolute-git-dir"],{cwd,timeout:1e4}),activeMarkers=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await readdir(gitDirectory.trim())).some(entry=>activeMarkers.has(entry)))return!1;const{stdout:head}=await execFileAsync("git",["rev-parse","HEAD"],{cwd,timeout:1e4});if(head.trim()!==operation.original_head)return!1;const{stdout:originalBlob}=await execFileAsync("git",["rev-parse","--verify",`HEAD:${itemPath}`],{cwd,timeout:1e4});if(originalBlob.trim()!==operation.original_blob)return!1;const{stdout:blob}=await execFileAsync("git",["hash-object","--",path.resolve(cwd,itemPath)],{cwd,timeout:1e4});return blob.trim()!==operation.original_blob?!1:(await execFileAsync("git",["diff","--cached","--quiet","HEAD","--",itemPath],{cwd,timeout:1e4}),!0)}catch{return!1}}export{captureMergeReceiptOperation,isMergeReceiptOperation,isOriginalGitStateRestored};
1
+ import{execFile as c}from"node:child_process";import{createHash as d}from"node:crypto";import{readdir as m}from"node:fs/promises";import p from"node:path";import{promisify as h}from"node:util";import{readBoundedRegularFile as _}from"./receipt-file-boundary.js";const i=h(c),g=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function v(t,e,r){const u=e.trim(),l=/^(['"])(.*)\1$/su.exec(u)?.[2]??u;for(const n of["rebase-merge","rebase-apply"])try{const{stdout:o}=await i("git",["rev-parse","--path-format=absolute","--git-path",`${n}/orig-head`],{cwd:t,timeout:1e4}),a=(await _(o.trim(),128))?.trim();if(a===void 0||!g.test(a))continue;const{stdout:f}=await i("git",["rev-parse","--verify",`${a}:${l}`],{cwd:t,timeout:1e4}),s=f.trim();return{kind:"rebase",original_head:a,original_blob:s}}catch{}if(r!==void 0&&Object.keys(process.env).some(n=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(n)))try{const{stdout:n}=await i("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:t,timeout:1e4}),[o,a]=n.trim().split(/\r?\n/u);if(o!==a||!g.test(o))return;const{stdout:f}=await i("git",["rev-parse","--verify",`${o}:${l}`],{cwd:t,timeout:1e4}),s=f.trim(),b=d(s.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex");return s!==b?void 0:{kind:"merge",original_head:o,original_blob:s}}catch{}}function B(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return Object.keys(e).length===3&&(e.kind==="rebase"||e.kind==="merge")&&typeof e.original_head=="string"&&g.test(e.original_head)&&typeof e.original_blob=="string"&&g.test(e.original_blob)}async function k(t,e,r,u){if(u!==void 0&&d(r.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(u)}\0`).update(u).digest("hex")!==r.original_blob)return!1;try{const{stdout:l}=await i("git",["rev-parse","--absolute-git-dir"],{cwd:t,timeout:1e4}),n=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await m(l.trim())).some(s=>n.has(s)))return!1;const{stdout:o}=await i("git",["rev-parse","HEAD"],{cwd:t,timeout:1e4});if(o.trim()!==r.original_head)return!1;const{stdout:a}=await i("git",["rev-parse","--verify",`HEAD:${e}`],{cwd:t,timeout:1e4});if(a.trim()!==r.original_blob)return!1;const{stdout:f}=await i("git",["hash-object","--",p.resolve(t,e)],{cwd:t,timeout:1e4});return f.trim()!==r.original_blob?!1:(await i("git",["diff","--cached","--quiet","HEAD","--",e],{cwd:t,timeout:1e4}),!0)}catch{return!1}}export{v as captureMergeReceiptOperation,B as isMergeReceiptOperation,k as isOriginalGitStateRestored};
2
2
  //# sourceMappingURL=receipt-operation.js.map
@@ -1,2 +1,2 @@
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]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();import path from"node:path";import{stableStringify}from"../../core/shared/serialization.js";import{isRfc3339DateTime}from"../../core/shared/time.js";import{encodeItemScalarDecisionValue,hashItemScalarDecisionValue,isItemScalarMissingValue}from"./three-way.js";import{isMergeReceiptOperation}from"./receipt-operation.js";const RECEIPT_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,RECEIPT_ITEM_ID_PATTERN=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,RECEIPT_FIELD_MAX=2048,RECEIPT_VALUE_MAX_DEPTH=64,RECEIPT_VALUE_MAX_NODES=1e5,RECEIPT_KEYS=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function isSafeReceiptId(value){return RECEIPT_ID_PATTERN.test(value)}const RECEIPT_DECISION_KEYS=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),DURABLE_VALUE_POLICY="bounded_non_sensitive_scalars_v1",REVIEWABLE_BUILTIN_STATUSES=new Set(["open","in_progress","blocked","closed","canceled"]),REVIEWABLE_ORDINAL_FIELDS=new Set(["risk","confidence","severity"]),REVIEWABLE_ORDINAL_VALUES=new Set(["low","medium","high","critical"]),REVIEWABLE_DURABLE_VALUES_BY_FIELD=new Map([["priority",new Set([0,1,2,3,4].map(stableStringify))],["status",new Set([...REVIEWABLE_BUILTIN_STATUSES].map(stableStringify))],...[...REVIEWABLE_ORDINAL_FIELDS].map(field=>[field,new Set([...REVIEWABLE_ORDINAL_VALUES].map(stableStringify))])]);function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function hasOnlyKeys(value,allowed){return Object.keys(value).every(key=>allowed.has(key))}function isStringArray(value){return Array.isArray(value)&&value.length<=RECEIPT_FIELD_MAX&&value.every(entry=>typeof entry=="string"&&entry.length>0&&entry.length<=256)}function hasBoundedJsonStructure(value){const pending=[{value,depth:0}];let nodes=0;for(;pending.length>0;){const current=pending.pop();if(nodes+=1,nodes>RECEIPT_VALUE_MAX_NODES||current.depth>RECEIPT_VALUE_MAX_DEPTH)return!1;if(Array.isArray(current.value))for(const entry of current.value)pending.push({value:entry,depth:current.depth+1});else if(isRecord(current.value))for(const entry of Object.values(current.value))pending.push({value:entry,depth:current.depth+1})}return!0}function isMergeDecision(value){if(!isRecord(value))return!1;const retainedSides=[void 0,"ours","theirs"],resolutionBases=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[hasOnlyKeys(value,RECEIPT_DECISION_KEYS),typeof value.field=="string",typeof value.field=="string"&&value.field.length>0,typeof value.field=="string"&&value.field.length<=256,Object.hasOwn(value,"base"),Object.hasOwn(value,"ours"),Object.hasOwn(value,"theirs"),Object.hasOwn(value,"retained"),Object.hasOwn(value,"discarded"),hasBoundedJsonStructure(value.base),hasBoundedJsonStructure(value.ours),hasBoundedJsonStructure(value.theirs),hasBoundedJsonStructure(value.retained),hasBoundedJsonStructure(value.discarded),retainedSides.includes(value.retained_side),resolutionBases.includes(value.resolution_basis)].every(Boolean)}function isMergedFieldHashes(value){if(!isRecord(value))return!1;const entries=Object.entries(value);return entries.length<=RECEIPT_FIELD_MAX&&entries.every(([field,hash])=>field.length>0&&field.length<=256&&typeof hash=="string"&&/^[a-f0-9]{64}$/u.test(hash))}function isSafeReceiptItemPath(value,itemId){if(typeof value!="string"||value.length===0||value.length>4096||value.includes("\0")||value.includes("\\")||path.posix.isAbsolute(value))return!1;const normalized=path.posix.normalize(value);return normalized!==".."&&!normalized.startsWith("../")&&path.posix.basename(normalized,path.posix.extname(normalized))===itemId}function hasValidReceiptCollections(value){return!isStringArray(value.fields_from_theirs)||!isStringArray(value.union_fields)||!Array.isArray(value.decisions)||value.decisions.length>RECEIPT_FIELD_MAX||!value.decisions.every(isMergeDecision)?!1:value.merged_field_hashes===void 0||isMergedFieldHashes(value.merged_field_hashes)}function hasValidReceiptEnums(value){const preferences=[void 0,"ours","theirs"],resolutions=[void 0,"preferred_side","stable_value_order","latest_document_update"],availabilities=[void 0,"clone_local","hash_only","bounded_inline","mixed"],sources=[void 0,"clone_local","durable"];return preferences.includes(value.requested_preference)&&preferences.includes(value.preferred)&&(value.requested_preference_applied===void 0||typeof value.requested_preference_applied=="boolean")&&resolutions.includes(value.conflict_resolution)&&(value.state==="pending"||value.state==="reconciled")&&availabilities.includes(value.value_availability)&&(value.value_policy===void 0||value.value_policy===DURABLE_VALUE_POLICY)&&sources.includes(value.evidence_source)}function hasValidReceiptTimestamps(value){return typeof value.created_at=="string"&&isRfc3339DateTime(value.created_at)&&(value.reconciled_at===void 0||typeof value.reconciled_at=="string"&&isRfc3339DateTime(value.reconciled_at))}function hasDurableDecisionValue(field,value){if(!isRecord(value)||isPrehashedValue(value)===void 0)return!1;const keys=Object.keys(value);if(!keys.every(key=>key==="pm_value_hash"||key==="pm_value"))return!1;if(!Object.hasOwn(value,"pm_value"))return keys.length===1;const preview=value.pm_value;return(preview===null||REVIEWABLE_DURABLE_VALUES_BY_FIELD.get(field)?.has(stableStringify(preview))===!0)&&hashItemScalarDecisionValue(preview)===value.pm_value_hash}function hasValidDurableDecisions(receipt){if(!receipt.decisions.every(decision=>decision.base===null&&decision.ours===null&&decision.theirs===null&&hasDurableDecisionValue(decision.field,decision.retained)&&hasDurableDecisionValue(decision.field,decision.discarded)))return!1;const inlineValueCount=receipt.decisions.reduce((count,decision)=>count+(isRecord(decision.retained)&&Object.hasOwn(decision.retained,"pm_value")?1:0)+(isRecord(decision.discarded)&&Object.hasOwn(decision.discarded,"pm_value")?1:0),0),expectedAvailability=inlineValueCount===0?"hash_only":inlineValueCount===receipt.decisions.length*2?"bounded_inline":"mixed";return receipt.value_availability===expectedAvailability&&(inlineValueCount===0||receipt.value_policy===DURABLE_VALUE_POLICY)}function hasValidReceiptOperation(value){return value.operation!==void 0&&!isMergeReceiptOperation(value.operation)?!1:value.settlement===void 0||value.settlement==="original_git_state_restored"&&value.state==="reconciled"&&value.operation!==void 0}function receiptIdentityValidationError(value){for(const key of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(value,key))return"required_fields";return value.version!==1||!hasOnlyKeys(value,RECEIPT_KEYS)?"required_fields":typeof value.id!="string"||!isSafeReceiptId(value.id)?"receipt_id":typeof value.item_id!="string"||!RECEIPT_ITEM_ID_PATTERN.test(value.item_id)?"item_id":isSafeReceiptItemPath(value.item_path,value.item_id)?null:"item_path"}function receiptValidationError(value,evidenceSource){if(!isRecord(value))return"required_fields";const identityError=receiptIdentityValidationError(value);return identityError!==null?identityError:hasValidReceiptOperation(value)?hasValidReceiptCollections(value)?hasValidReceiptEnums(value)?hasValidReceiptTimestamps(value)?evidenceSource==="durable"&&!hasValidDurableDecisions(value)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function normalizeLegacyReceipt(value){if(!isRecord(value)||value.version!==1||value.value_policy!==void 0||!Array.isArray(value.decisions))return value;const preferredEra=(value.preferred==="ours"||value.preferred==="theirs")&&value.requested_preference===void 0,requestedPreferenceEra=(value.requested_preference==="ours"||value.requested_preference==="theirs")&&value.value_availability==="clone_local";return!preferredEra&&!requestedPreferenceEra?value:{...value,decisions:value.decisions.map(decision=>!isRecord(decision)||!Object.hasOwn(decision,"retained")||!Object.hasOwn(decision,"discarded")?decision:{base:encodeItemScalarDecisionValue(void 0),ours:encodeItemScalarDecisionValue(void 0),theirs:encodeItemScalarDecisionValue(void 0),...decision})}}function receiptCollectionValidationPath(value){if(!isRecord(value))return;if(!isStringArray(value.fields_from_theirs))return"fields_from_theirs";if(!isStringArray(value.union_fields))return"union_fields";if(!Array.isArray(value.decisions)||value.decisions.length>RECEIPT_FIELD_MAX)return"decisions";const index=value.decisions.findIndex(decision=>!isMergeDecision(decision));return index>=0?`decisions[${index}]`:"merged_field_hashes"}function isMergeDecisionReceipt(value,evidenceSource){return receiptValidationError(value,evidenceSource)===null}function isPrehashedValue(value){if(typeof value!="object"||value===null||Array.isArray(value)||!("pm_value_hash"in value))return;const hash=value.pm_value_hash;return typeof hash=="string"&&/^[a-f0-9]{64}$/u.test(hash)?hash:void 0}function durableValueEvidence(field,value){const missing=isItemScalarMissingValue(value),pmValueHash=hashItemScalarDecisionValue(missing?void 0:value);return!missing&&(value===null||REVIEWABLE_DURABLE_VALUES_BY_FIELD.get(field)?.has(stableStringify(value))===!0)?{pm_value_hash:pmValueHash,pm_value:value}:{pm_value_hash:pmValueHash}}export{DURABLE_VALUE_POLICY,durableValueEvidence,isMergeDecisionReceipt,isPrehashedValue,isSafeReceiptId,normalizeLegacyReceipt,receiptCollectionValidationPath,receiptValidationError};
1
+ import c from"node:path";import{stableStringify as o}from"../../core/shared/serialization.js";import{isRfc3339DateTime as l}from"../../core/shared/time.js";import{encodeItemScalarDecisionValue as _,hashItemScalarDecisionValue as p,isItemScalarMissingValue as g}from"./three-way.js";import{isMergeReceiptOperation as A}from"./receipt-operation.js";const O=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,I=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,f=2048,R=64,w=1e5,S=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function V(e){return O.test(e)}const D=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),h="bounded_non_sensitive_scalars_v1",L=new Set(["open","in_progress","blocked","closed","canceled"]),x=new Set(["risk","confidence","severity"]),T=new Set(["low","medium","high","critical"]),m=new Map([["priority",new Set([0,1,2,3,4].map(o))],["status",new Set([...L].map(o))],...[...x].map(e=>[e,new Set([...T].map(o))])]);function s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function y(e,n){return Object.keys(e).every(r=>n.has(r))}function a(e){return Array.isArray(e)&&e.length<=f&&e.every(n=>typeof n=="string"&&n.length>0&&n.length<=256)}function d(e){const n=[{value:e,depth:0}];let r=0;for(;n.length>0;){const t=n.pop();if(r+=1,r>w||t.depth>R)return!1;if(Array.isArray(t.value))for(const i of t.value)n.push({value:i,depth:t.depth+1});else if(s(t.value))for(const i of Object.values(t.value))n.push({value:i,depth:t.depth+1})}return!0}function E(e){if(!s(e))return!1;const n=[void 0,"ours","theirs"],r=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[y(e,D),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),d(e.base),d(e.ours),d(e.theirs),d(e.retained),d(e.discarded),n.includes(e.retained_side),r.includes(e.resolution_basis)].every(Boolean)}function j(e){if(!s(e))return!1;const n=Object.entries(e);return n.length<=f&&n.every(([r,t])=>r.length>0&&r.length<=256&&typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t))}function P(e,n){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||c.posix.isAbsolute(e))return!1;const r=c.posix.normalize(e);return r!==".."&&!r.startsWith("../")&&c.posix.basename(r,c.posix.extname(r))===n}function q(e){return!a(e.fields_from_theirs)||!a(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>f||!e.decisions.every(E)?!1:e.merged_field_hashes===void 0||j(e.merged_field_hashes)}function C(e){const n=[void 0,"ours","theirs"],r=[void 0,"preferred_side","stable_value_order","latest_document_update"],t=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return n.includes(e.requested_preference)&&n.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&r.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&t.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===h)&&i.includes(e.evidence_source)}function B(e){return typeof e.created_at=="string"&&l(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&l(e.reconciled_at))}function b(e,n){if(!s(n)||k(n)===void 0)return!1;const r=Object.keys(n);if(!r.every(u=>u==="pm_value_hash"||u==="pm_value"))return!1;if(!Object.hasOwn(n,"pm_value"))return r.length===1;const t=n.pm_value;return(t===null||m.get(e)?.has(o(t))===!0)&&p(t)===n.pm_value_hash}function M(e){if(!e.decisions.every(t=>t.base===null&&t.ours===null&&t.theirs===null&&b(t.field,t.retained)&&b(t.field,t.discarded)))return!1;const n=e.decisions.reduce((t,i)=>t+(s(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(s(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),r=n===0?"hash_only":n===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===r&&(n===0||e.value_policy===h)}function U(e){return e.operation!==void 0&&!A(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function z(e){for(const n of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,n))return"required_fields";return e.version!==1||!y(e,S)?"required_fields":typeof e.id!="string"||!V(e.id)?"receipt_id":typeof e.item_id!="string"||!I.test(e.item_id)?"item_id":P(e.item_path,e.item_id)?null:"item_path"}function N(e,n){if(!s(e))return"required_fields";const r=z(e);return r!==null?r:U(e)?q(e)?C(e)?B(e)?n==="durable"&&!M(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function K(e){if(!s(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;const n=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,r=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!n&&!r?e:{...e,decisions:e.decisions.map(t=>!s(t)||!Object.hasOwn(t,"retained")||!Object.hasOwn(t,"discarded")?t:{base:_(void 0),ours:_(void 0),theirs:_(void 0),...t})}}function X(e){if(!s(e))return;if(!a(e.fields_from_theirs))return"fields_from_theirs";if(!a(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>f)return"decisions";const n=e.decisions.findIndex(r=>!E(r));return n>=0?`decisions[${n}]`:"merged_field_hashes"}function Z(e,n){return N(e,n)===null}function k(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;const n=e.pm_value_hash;return typeof n=="string"&&/^[a-f0-9]{64}$/u.test(n)?n:void 0}function J(e,n){const r=g(n),t=p(r?void 0:n);return!r&&(n===null||m.get(e)?.has(o(n))===!0)?{pm_value_hash:t,pm_value:n}:{pm_value_hash:t}}export{h as DURABLE_VALUE_POLICY,J as durableValueEvidence,Z as isMergeDecisionReceipt,k as isPrehashedValue,V as isSafeReceiptId,K as normalizeLegacyReceipt,X as receiptCollectionValidationPath,N as receiptValidationError};
2
2
  //# sourceMappingURL=receipt-schema.js.map