@unbrained/pm-cli 2026.11.13 → 2026.11.15

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 (289) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +1 -1
  3. package/dist/cli/extension-command-help.js +2 -2
  4. package/dist/cli/register-mutation.js +2 -2
  5. package/dist/cli/register-operations.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/chunk-6UTBX62V.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-GWVP23RZ.js → chunk-7AODVNHX.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-ASGAELBQ.js +9 -0
  10. package/dist/cli-bundle/chunks/{chunk-PUU5DXSV.js → chunk-DBUBX4DL.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5LG5YZYF.js → chunk-E4B2HWH7.js} +13 -13
  12. package/dist/cli-bundle/chunks/chunk-E74OMFBZ.js +6 -0
  13. package/dist/cli-bundle/chunks/chunk-FSE624WQ.js +2 -0
  14. package/dist/cli-bundle/chunks/chunk-FYOIH56R.js +20 -0
  15. package/dist/cli-bundle/chunks/chunk-GAFALSR2.js +8 -0
  16. package/dist/cli-bundle/chunks/{chunk-LKVFPQNY.js → chunk-GCSKHCYK.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-HMVZSXB4.js +8 -0
  18. package/dist/cli-bundle/chunks/chunk-IXV5UM4U.js +31 -0
  19. package/dist/cli-bundle/chunks/chunk-J6L3Q5J4.js +3 -0
  20. package/dist/cli-bundle/chunks/chunk-KLWGIEDC.js +114 -0
  21. package/dist/cli-bundle/chunks/chunk-KSLPRST2.js +10 -0
  22. package/dist/cli-bundle/chunks/chunk-LC6DL446.js +3 -0
  23. package/dist/cli-bundle/chunks/{chunk-UFZQPKQS.js → chunk-NAX554KY.js} +35 -35
  24. package/dist/cli-bundle/chunks/chunk-PMIGRSNZ.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-Q6GBRK27.js +3 -0
  26. package/dist/cli-bundle/chunks/chunk-QZNDEZYI.js +2 -0
  27. package/dist/cli-bundle/chunks/chunk-S5UXBECQ.js +2 -0
  28. package/dist/cli-bundle/chunks/{chunk-UJMQP2HP.js → chunk-TESRFVGF.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-GXGMMIZN.js → chunk-VWKLTHYQ.js} +80 -70
  30. package/dist/cli-bundle/chunks/chunk-YJNY5MKP.js +2 -0
  31. package/dist/cli-bundle/chunks/chunk-YLPZE2TK.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-RSAN2YUU.js → chunk-ZVDXGAYV.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-ZWUS65LN.js +2 -0
  34. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-I6RQGD6Y.js → indexed-receipt-blobs-42Y2CSEQ.js} +2 -2
  35. package/dist/cli-bundle/chunks/item-revision-JCEDTAVX.js +2 -0
  36. package/dist/cli-bundle/chunks/item-transaction-BSMGKZ4S.js +2 -0
  37. package/dist/cli-bundle/chunks/mutation-actor-IQHBRFAJ.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-admission-DF6BFGG6.js +2 -0
  39. package/dist/cli-bundle/chunks/{register-list-query-JNJY2D3N.js → register-list-query-DNKPQB76.js} +2 -2
  40. package/dist/cli-bundle/chunks/register-mutation-WVTDFLEF.js +20 -0
  41. package/dist/cli-bundle/chunks/register-operations-NR5MTT5T.js +2 -0
  42. package/dist/cli-bundle/chunks/register-setup-2RTG3LII.js +2 -0
  43. package/dist/cli-bundle/chunks/{settlement-hook-JHXLUBEN.js → settlement-hook-W5ULPKIE.js} +2 -2
  44. package/dist/cli-bundle/chunks/stage-YFNK7U26.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-Q3OA5OAK.js → chunk-2UQFFVQK.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/chunk-52H6AELE.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-J3LQQP3N.js → chunk-63FM3TIG.js} +7 -7
  48. package/dist/cli-bundle/focused-chunks/{chunk-VGFKTSGY.js → chunk-7GCAZJT4.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-BSY6FZ3Y.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-CZZKAGHE.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-DRBXOAGY.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-DXMQ32EH.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-EALGFJRP.js +78 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-FK2X6MJY.js +44 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-IDAYTYNN.js → chunk-JE3MFEQZ.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-JR75B6HU.js → chunk-JRRHN2PZ.js} +12 -12
  57. package/dist/cli-bundle/focused-chunks/chunk-JXA77YIV.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-LQZ5F6LE.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-LSWUTTE6.js +6 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-QXOFSZR6.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/chunk-RMCODWHZ.js +65 -0
  62. package/dist/cli-bundle/focused-chunks/chunk-S6GTALM4.js +24 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-UPUIDGNJ.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-TVJ2PHAK.js → chunk-W2KIQ7RF.js} +3 -3
  65. package/dist/cli-bundle/focused-chunks/chunk-WGYR3X6O.js +26 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-WVYXR3YX.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-ZJF6ZA7B.js → chunk-XQZKGTZV.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-4LFE3FQL.js → chunk-YTNUUEY6.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-YZUBG4W2.js +6 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-Z6HCQYSW.js +8 -0
  71. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-7XGVHYAO.js → indexed-receipt-blobs-LSBWMXKS.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/item-revision-YO7YGQYE.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/item-transaction-7A3Q4CAJ.js +2 -0
  74. package/dist/cli-bundle/focused-chunks/mutation-actor-UQHBNHOF.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/mutation-admission-G565NLPE.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/{settlement-hook-H56537UV.js → settlement-hook-UXN76GMA.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/stage-F3YJGNRK.js +2 -0
  78. package/dist/cli-bundle/main.js +7 -7
  79. package/dist/cli-bundle/sdk-authoring.js +1 -1
  80. package/dist/cli-bundle/sdk-contracts.js +3 -3
  81. package/dist/cli-bundle/sdk-core.js +1 -1
  82. package/dist/cli-bundle/sdk-governance.js +1 -1
  83. package/dist/cli-bundle/sdk-graph.js +1 -1
  84. package/dist/cli-bundle/sdk-merge.js +57 -57
  85. package/dist/cli-bundle/sdk-query.js +1 -1
  86. package/dist/cli-bundle/sdk-runtime.js +1 -1
  87. package/dist/cli-bundle/sdk-testing.js +1 -1
  88. package/dist/cli-bundle/sdk.js +11 -11
  89. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  90. package/dist/core/extensions/extension-types.d.ts +30 -0
  91. package/dist/core/extensions/extension-types.js +1 -1
  92. package/dist/core/extensions/index.d.ts +21 -1
  93. package/dist/core/extensions/index.js +1 -1
  94. package/dist/core/extensions/mutation-actor-snapshot.js +2 -0
  95. package/dist/core/extensions/mutation-actor.js +2 -0
  96. package/dist/core/item/deferred-fields.js +2 -0
  97. package/dist/core/item/item-format-version.d.ts +8 -6
  98. package/dist/core/item/item-format-version.js +1 -1
  99. package/dist/core/item/item-format.js +2 -2
  100. package/dist/core/lock/lock.js +3 -3
  101. package/dist/core/output/linked-test-projection.js +6 -0
  102. package/dist/core/output/output.d.ts +7 -0
  103. package/dist/core/output/output.js +9 -7
  104. package/dist/core/schema/runtime-field-values.d.ts +4 -0
  105. package/dist/core/schema/runtime-field-values.js +1 -1
  106. package/dist/core/session/session-state.js +1 -1
  107. package/dist/core/shared/item-metadata-contract.js +1 -1
  108. package/dist/core/shared/text-normalization.d.ts +24 -0
  109. package/dist/core/shared/text-normalization.js +1 -1
  110. package/dist/core/shared/url-credentials.js +1 -1
  111. package/dist/core/store/item-store.js +1 -1
  112. package/dist/core/test/run-selectors.d.ts +3 -1
  113. package/dist/core/test/run-selectors.js +1 -1
  114. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  115. package/dist/sdk/annotations.js +1 -1
  116. package/dist/sdk/authoring.d.ts +1 -1
  117. package/dist/sdk/authoring.js +1 -1
  118. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  119. package/dist/sdk/cli-contracts/completeness.js +1 -1
  120. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  121. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  122. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  123. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -1
  124. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  125. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +1 -1
  126. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  127. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  128. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  129. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  130. package/dist/sdk/completion/bash.js +1 -1
  131. package/dist/sdk/completion/fish.js +6 -1
  132. package/dist/sdk/completion/zsh.js +6 -1
  133. package/dist/sdk/context-intent-contracts.js +1 -1
  134. package/dist/sdk/docs.d.ts +3 -1
  135. package/dist/sdk/docs.js +1 -1
  136. package/dist/sdk/environment/project-runtime-compatibility.d.ts +8 -1
  137. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  138. package/dist/sdk/extension/command-options.d.ts +23 -4
  139. package/dist/sdk/extension/command-options.js +1 -1
  140. package/dist/sdk/extension/native-command-options.js +2 -0
  141. package/dist/sdk/files.d.ts +3 -1
  142. package/dist/sdk/files.js +1 -1
  143. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  144. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  145. package/dist/sdk/governance/health.js +1 -1
  146. package/dist/sdk/governance/lifecycle-dependency-cycles.d.ts +12 -0
  147. package/dist/sdk/governance/lifecycle-dependency-cycles.js +2 -0
  148. package/dist/sdk/governance/validate-deferred-fields.js +2 -0
  149. package/dist/sdk/governance/validate.d.ts +2 -2
  150. package/dist/sdk/governance/validate.js +1 -1
  151. package/dist/sdk/guide-topics.js +1 -1
  152. package/dist/sdk/index.d.ts +1 -1
  153. package/dist/sdk/index.js +1 -1
  154. package/dist/sdk/item-transaction.d.ts +2 -2
  155. package/dist/sdk/item-transaction.js +1 -1
  156. package/dist/sdk/lifecycle/claim.d.ts +5 -1
  157. package/dist/sdk/lifecycle/claim.js +1 -1
  158. package/dist/sdk/lifecycle/close.js +1 -1
  159. package/dist/sdk/lifecycle/copy.js +1 -1
  160. package/dist/sdk/lifecycle/create-deferrals.js +2 -0
  161. package/dist/sdk/lifecycle/create.d.ts +6 -2
  162. package/dist/sdk/lifecycle/create.js +1 -1
  163. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  164. package/dist/sdk/lifecycle/plan.js +1 -1
  165. package/dist/sdk/lifecycle/restore.js +1 -1
  166. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +7 -1
  167. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  168. package/dist/sdk/linked-artifacts.d.ts +45 -3
  169. package/dist/sdk/linked-artifacts.js +2 -2
  170. package/dist/sdk/merge/three-way.d.ts +1 -1
  171. package/dist/sdk/merge/three-way.js +2 -2
  172. package/dist/sdk/output/table-rows.d.ts +28 -4
  173. package/dist/sdk/output/table-rows.js +1 -1
  174. package/dist/sdk/output.d.ts +1 -1
  175. package/dist/sdk/output.js +1 -1
  176. package/dist/sdk/package-import-adapters.d.ts +9 -1
  177. package/dist/sdk/package-import-adapters.js +1 -1
  178. package/dist/sdk/pagination.js +1 -1
  179. package/dist/sdk/public-surface.json +1 -1
  180. package/dist/sdk/query/complete-list.d.ts +14 -5
  181. package/dist/sdk/query/complete-list.js +1 -1
  182. package/dist/sdk/query/list.js +1 -1
  183. package/dist/sdk/query/projection-contracts.d.ts +6 -0
  184. package/dist/sdk/query/projection-contracts.js +1 -1
  185. package/dist/sdk/read-output/continuation.js +1 -1
  186. package/dist/sdk/read-output/extension.js +1 -1
  187. package/dist/sdk/read-output-budget.js +1 -1
  188. package/dist/sdk/runtime-input.d.ts +6 -2
  189. package/dist/sdk/runtime-input.js +1 -1
  190. package/dist/sdk/runtime-primitives.d.ts +1 -1
  191. package/dist/sdk/runtime-primitives.js +1 -1
  192. package/dist/sdk/runtime.d.ts +2 -2
  193. package/dist/sdk/runtime.js +1 -1
  194. package/dist/sdk/structured-mutations.js +1 -1
  195. package/dist/sdk/test/batch.d.ts +5 -2
  196. package/dist/sdk/test/batch.js +2 -2
  197. package/dist/sdk/test/command-args.js +1 -1
  198. package/dist/sdk/test/entry.js +2 -2
  199. package/dist/sdk/test/execution.d.ts +10 -7
  200. package/dist/sdk/test/execution.js +2 -2
  201. package/dist/sdk/test/parsers.js +1 -1
  202. package/dist/sdk/test/prerequisites.d.ts +1 -1
  203. package/dist/sdk/test/prerequisites.js +1 -1
  204. package/dist/sdk/test/run-phases.d.ts +44 -0
  205. package/dist/sdk/test/run-phases.js +2 -0
  206. package/dist/sdk/testing.d.ts +15 -2
  207. package/dist/sdk/testing.js +1 -1
  208. package/dist/types.d.ts +11 -1
  209. package/dist/types.js +1 -1
  210. package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -4
  211. package/docs/COMMANDS.md +31 -4
  212. package/docs/EXTENSIONS.md +1 -1
  213. package/docs/LINKED_TEST_EDITS.md +2 -1
  214. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +6 -3
  215. package/docs/README.md +2 -2
  216. package/docs/READ_OUTPUT_CONTRACTS.md +23 -2
  217. package/docs/SDK.md +129 -6
  218. package/docs/TESTING.md +64 -1
  219. package/docs/WORKSPACE_CONCURRENCY.md +5 -1
  220. package/docs/generated/FLAG_LEXICON_BUDGETS.md +9 -9
  221. package/marketplace.json +1 -1
  222. package/package.json +6 -4
  223. package/packages/pm-beads/package.json +1 -1
  224. package/packages/pm-calendar/extensions/calendar/command-definitions.ts +2 -0
  225. package/packages/pm-calendar/package.json +1 -1
  226. package/packages/pm-command-kit/package.json +1 -1
  227. package/packages/pm-digital-twin/package.json +1 -1
  228. package/packages/pm-governance-audit/package.json +1 -1
  229. package/packages/pm-guide-shell/package.json +1 -1
  230. package/packages/pm-kanban/package.json +1 -1
  231. package/packages/pm-lifecycle-hooks/package.json +1 -1
  232. package/packages/pm-linked-test-adapters/package.json +1 -1
  233. package/packages/pm-search-advanced/package.json +1 -1
  234. package/packages/pm-templates/package.json +1 -1
  235. package/packages/pm-todos/extensions/todos/runtime.ts +3 -0
  236. package/packages/pm-todos/package.json +1 -1
  237. package/packages/pm-vcs/package.json +1 -1
  238. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  239. package/plugins/pm-claude/package.json +1 -1
  240. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  241. package/plugins/pm-codex/package.json +1 -1
  242. package/plugins/pm-codex/plugin.json +1 -1
  243. package/runtime-dependencies.json +1 -1
  244. package/CHANGELOG.md +0 -4793
  245. package/dist/cli-bundle/chunks/chunk-36E4L2R4.js +0 -2
  246. package/dist/cli-bundle/chunks/chunk-4WD4CHVH.js +0 -8
  247. package/dist/cli-bundle/chunks/chunk-6UXBWMEM.js +0 -2
  248. package/dist/cli-bundle/chunks/chunk-CO7RWLCM.js +0 -2
  249. package/dist/cli-bundle/chunks/chunk-COTC2QOR.js +0 -6
  250. package/dist/cli-bundle/chunks/chunk-FAYX6C7H.js +0 -2
  251. package/dist/cli-bundle/chunks/chunk-GIAJX2QJ.js +0 -9
  252. package/dist/cli-bundle/chunks/chunk-HQINCDF6.js +0 -116
  253. package/dist/cli-bundle/chunks/chunk-IYDIPXBO.js +0 -2
  254. package/dist/cli-bundle/chunks/chunk-L4F4ZHGR.js +0 -2
  255. package/dist/cli-bundle/chunks/chunk-O4ZLEN4T.js +0 -3
  256. package/dist/cli-bundle/chunks/chunk-O6PBQMD7.js +0 -2
  257. package/dist/cli-bundle/chunks/chunk-O6T24Z3M.js +0 -2
  258. package/dist/cli-bundle/chunks/chunk-OQCVU2SG.js +0 -8
  259. package/dist/cli-bundle/chunks/chunk-QSSENTXG.js +0 -20
  260. package/dist/cli-bundle/chunks/chunk-TCYIGAQG.js +0 -31
  261. package/dist/cli-bundle/chunks/chunk-URWNUZQZ.js +0 -3
  262. package/dist/cli-bundle/chunks/chunk-UYARS5XF.js +0 -3
  263. package/dist/cli-bundle/chunks/item-revision-G5OVYGZ5.js +0 -2
  264. package/dist/cli-bundle/chunks/item-transaction-I2X2P4TW.js +0 -2
  265. package/dist/cli-bundle/chunks/mutation-admission-SET4KY73.js +0 -2
  266. package/dist/cli-bundle/chunks/register-mutation-WTHZHPOP.js +0 -20
  267. package/dist/cli-bundle/chunks/register-operations-EZP3EG6A.js +0 -2
  268. package/dist/cli-bundle/chunks/register-setup-THFZP23A.js +0 -2
  269. package/dist/cli-bundle/chunks/stage-JXJILTYE.js +0 -2
  270. package/dist/cli-bundle/focused-chunks/chunk-2ZPGEGTB.js +0 -2
  271. package/dist/cli-bundle/focused-chunks/chunk-3MB47JLT.js +0 -2
  272. package/dist/cli-bundle/focused-chunks/chunk-5KTOMFLR.js +0 -44
  273. package/dist/cli-bundle/focused-chunks/chunk-5NTLNE54.js +0 -26
  274. package/dist/cli-bundle/focused-chunks/chunk-ADBFVDTG.js +0 -8
  275. package/dist/cli-bundle/focused-chunks/chunk-CSKDIMQP.js +0 -2
  276. package/dist/cli-bundle/focused-chunks/chunk-FNIX62V6.js +0 -3
  277. package/dist/cli-bundle/focused-chunks/chunk-G6ERMFJ5.js +0 -3
  278. package/dist/cli-bundle/focused-chunks/chunk-IYV3IPRF.js +0 -65
  279. package/dist/cli-bundle/focused-chunks/chunk-QGQJBQCH.js +0 -2
  280. package/dist/cli-bundle/focused-chunks/chunk-RIMNSVFA.js +0 -26
  281. package/dist/cli-bundle/focused-chunks/chunk-VGJDKDKA.js +0 -2
  282. package/dist/cli-bundle/focused-chunks/chunk-VGUQ4V47.js +0 -82
  283. package/dist/cli-bundle/focused-chunks/chunk-VTOTZ5UC.js +0 -91
  284. package/dist/cli-bundle/focused-chunks/chunk-WFVZ7GGR.js +0 -2
  285. package/dist/cli-bundle/focused-chunks/chunk-ZOGEQFGH.js +0 -2
  286. package/dist/cli-bundle/focused-chunks/item-revision-IF7E7BVY.js +0 -2
  287. package/dist/cli-bundle/focused-chunks/item-transaction-5TFWIOXI.js +0 -2
  288. package/dist/cli-bundle/focused-chunks/mutation-admission-KELM46JF.js +0 -2
  289. package/dist/cli-bundle/focused-chunks/stage-UAKMQTCI.js +0 -2
@@ -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]="b8f7423c-972b-57a6-b524-d7fbc36f6f58")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../environment/project-runtime-compatibility.js";import{enforceWorkflowMutation}from"../../core/policy/workflow-policy-store.js";import jsonPatch from"fast-json-patch";import fs from"node:fs/promises";import{readLocatedItemSnapshot}from"../../core/store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable}from"../../core/store/item-mutation-precondition.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{readHistorySnapshot}from"../../core/history/read.js";import{verifyHistoryRewriteNoDrift}from"../../core/history/history-rewrite.js";import{resolveHistorySubject}from"../history/subject.js";import{historyVersionOffset}from"../../core/history/version-address.js";import{writeFileAtomic,appendHistoryEntry,createHistoryEntry,replayToCanonicalItemDocument,replayToItemDocument,toReplayDocument,enforceHistoryStreamPolicyForItem,canonicalDocument,serializeItemDocument,resolveItemTypeRegistry,acquireLockLease,EXIT_CODE,PmCliError,nowIso,getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnWriteHooks,runActiveBeforeMutationHooks,createMutationGuardSdk,getItemPath,resolvePmRoot,resolveWorkspaceRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{applyHistoryPatch,ensureMaterializedHistoryTarget as ensureMaterializedRestoreTarget,extractPatchFailureContext,replayHistoryToTarget as replayToTarget,resolveHistoryTarget}from"../history-read.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../item-metadata-index.js";import{redactOptionalIdentityCredentials}from"../../core/shared/url-credentials.js";async function readRestoreItem(located,settings,history){const snapshot=await readLocatedItemSnapshot(located,{schema:settings.schema});return snapshot.error===null?{raw:snapshot.raw,document:snapshot.document}:{raw:snapshot.raw,document:replayCurrentDocument(history),recovered:!0}}function ensureReplayTarget(target,history){return resolveHistoryTarget(target,history,{errorSubject:"restore",allowFutureTimestamp:!0})}function replayCurrentDocument(history){const currentReplay=replayToTarget(history,history.length-1);return Object.keys(currentReplay.metadata).length===0?{metadata:{},body:currentReplay.body}:canonicalDocument(replayToItemDocument(currentReplay))}async function resolveRestoreSubject(pmRoot,id,settings,typeToFolder){const subject=await resolveHistorySubject(pmRoot,id,settings,typeToFolder),historyPolicy=subject.located?await enforceHistoryStreamPolicyForItem({pmRoot,settings,itemId:subject.id,commandLabel:"restore"}):{warnings:[]};return{...subject,historyPolicyWarnings:historyPolicy.warnings}}function changedFields(beforeDocument,afterDocument){const beforeReplay=toReplayDocument(beforeDocument),afterReplay=toReplayDocument(afterDocument),patch=jsonPatch.compare(beforeReplay,afterReplay),fields=new Set;for(const op of patch){if(op.path==="/body"||op.path.startsWith("/body/")){fields.add("body");continue}const segment=op.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];fields.add(segment.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(fields).sort((a,b)=>a.localeCompare(b))}async function loadRestoreStateUnderLock(params){const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:"restore",readItem:located=>readRestoreItem(located,params.settings,params.history)});return{loadedItemUnderLock:verified.loadedItemUnderLock,existingItemPath:verified.locatedUnderLock?.itemPath??null}}function resolveRestoreCurrentState(loadedItemUnderLock,history){return loadedItemUnderLock?{document:loadedItemUnderLock.document,originalRaw:loadedItemUnderLock.raw}:{document:replayCurrentDocument(history),originalRaw:null}}function collectRestoreOwnershipWarnings(params){const stored=params.document.metadata.assignee?.trim(),hasOwnershipConflict=stored&&stored!==params.author&&!params.force,assigned=redactOptionalIdentityCredentials(stored);if(!hasOwnershipConflict)return[];if(params.enforcement==="strict")throw new PmCliError(`Item ${params.resolvedId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return params.enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.resolvedId}:${assigned}`]:[]}async function restorePreviousItemAfterHistoryFailure(params){if(params.existingItemPath&&params.resolvedOriginalRaw!==null&&params.restoredItemPath!==params.existingItemPath){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw),await fs.rm(params.restoredItemPath,{force:!0});return}if(params.existingItemPath&&params.resolvedOriginalRaw!==null){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw);return}await fs.rm(params.restoredItemPath,{force:!0})}async function runRestoreWriteHooks(params){return[...await runActiveOnWriteHooks({path:params.restoredItemPath,scope:"project",op:"restore",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]}),...await runActiveOnWriteHooks({path:params.historyPath,scope:"project",op:"restore:history",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]})]}async function runRestore(id,target,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),subject=await resolveRestoreSubject(pmRoot,id,settings,typeRegistry.type_to_folder),resolvedId=subject.id,{raw:historyRawBeforeLock,entries:history}=await readHistorySnapshot(subject.historyPath,resolvedId);if(history.length===0)throw new PmCliError(`No history exists for ${resolvedId}; restore is unavailable.`,EXIT_CODE.NOT_FOUND);const resolvedTarget=ensureReplayTarget(target,history),replayDocument=ensureMaterializedRestoreTarget(replayToTarget(history,resolvedTarget.historyIndex),resolvedTarget),restoredDocument=replayToCanonicalItemDocument(replayDocument,{schema:settings.schema});if(restoredDocument.metadata.id!==resolvedId)throw new PmCliError(`Restore target resolved to item ${restoredDocument.metadata.id}, expected ${resolvedId}.`,EXIT_CODE.GENERIC_FAILURE);const currentItemRawBeforeLock=(subject.located?await readRestoreItem(subject.located,settings,history):null)?.raw??null,author=resolveAuthor(options.author,settings.author_default),lease=await acquireLockLease(pmRoot,resolvedId,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const{loadedItemUnderLock,existingItemPath}=await loadRestoreStateUnderLock({pmRoot,subject,settings,typeRegistry,historyRawBeforeLock,currentItemRawBeforeLock,history}),itemFormat="toon",currentState=resolveRestoreCurrentState(loadedItemUnderLock,history);loadedItemUnderLock?.recovered===!0&&assertItemRevisionExpectationsOnUnreadable(pmRoot,resolvedId,loadedItemUnderLock.raw),assertItemMutationPreconditions(pmRoot,loadedItemUnderLock?.document??EMPTY_CANONICAL_DOCUMENT,resolvedId),restoredDocument.metadata.pm_format_version=normalizeItemFormatVersion(Math.max(requiredItemFormatVersion(restoredDocument.metadata),requiredItemFormatVersion(currentState.document.metadata))),assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(pmRoot),requiredItemFormatVersion(restoredDocument.metadata));const ownershipWarnings=collectRestoreOwnershipWarnings({document:currentState.document,author,force:options.force,enforcement:settings.governance.ownership_enforcement,resolvedId}),restoreChangedFields=changedFields(currentState.document,restoredDocument),workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"restore",author,before:currentState.document,after:restoredDocument});await runActiveBeforeMutationHooks({pm_root:pmRoot,operation:"restore",before:currentState.document,after:restoredDocument,changed_fields:restoreChangedFields,sdk:createMutationGuardSdk({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder})});const serializedRestore=serializeItemDocument(restoredDocument,{format:itemFormat,schema:settings.schema}),restoredItemPath=getItemPath(pmRoot,restoredDocument.metadata.type,resolvedId,itemFormat,typeRegistry.type_to_folder),derivedIndexWarnings=await lease.fence(async()=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(pmRoot,author);let derivedIndexWarnings2;try{await writeFileAtomic(restoredItemPath,serializedRestore),existingItemPath&&restoredItemPath!==existingItemPath&&await fs.rm(existingItemPath);const historyEntry=createHistoryEntry({nowIso:nowIso(),author,op:"restore",before:currentState.document,after:restoredDocument,message:options.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(subject.historyPath,historyEntry)}catch(error){throw await restorePreviousItemAfterHistoryFailure({existingItemPath,resolvedOriginalRaw:currentState.originalRaw,restoredItemPath}),error}derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot,preferredFormat:settings.item_format,typeToFolder:typeRegistry.type_to_folder,schema:settings.schema,itemPath:restoredItemPath,previousItemPath:existingItemPath??void 0,document:restoredDocument})}finally{await releaseDerivedIndexLock()}return derivedIndexWarnings2});advanceItemMutationPreconditions(pmRoot,restoredDocument,resolvedId);const hookWarnings=await runRestoreWriteHooks({restoredItemPath,historyPath:subject.historyPath,before:currentState.document,after:restoredDocument});recordAfterCommandAffectedItem({id:restoredDocument.metadata.id,op:"restore",item_type:restoredDocument.metadata.type,previous_status:currentState.document.metadata.status,status:restoredDocument.metadata.status,previous:projectAfterCommandItemSnapshot(currentState.document.metadata,restoreChangedFields),current:projectAfterCommandItemSnapshot(restoredDocument.metadata,restoreChangedFields),changed_fields:restoreChangedFields});const targetEntry=history[resolvedTarget.historyIndex],offset=historyVersionOffset(history,!0);return{item:restoredDocument.metadata,restored_from:{kind:resolvedTarget.kind,target:resolvedTarget.raw,history_index:resolvedTarget.historyIndex+1,version:offset===null?null:offset+resolvedTarget.historyIndex+1,entry_ts:targetEntry.ts,entry_op:targetEntry.op},changed_fields:restoreChangedFields,warnings:[...workflowPolicy.warnings,...loadedItemUnderLock?.recovered?["restore_unreadable_item_recovered"]:[],...subject.historyPolicyWarnings,...ownershipWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}const _testOnlyRestoreCommand={applyHistoryPatch,changedFields,ensureMaterializedRestoreTarget,ensureReplayTarget,extractPatchFailureContext,replayCurrentDocument,replayToTarget,resolveRestoreSubject};export{_testOnlyRestoreCommand,runRestore};
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]="918ea579-30e4-59d4-9427-f0db30fd06cc")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../environment/project-runtime-compatibility.js";import{enforceWorkflowMutation}from"../../core/policy/workflow-policy-store.js";import jsonPatch from"fast-json-patch";import fs from"node:fs/promises";import{readLocatedItemSnapshot}from"../../core/store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable}from"../../core/store/item-mutation-precondition.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{readHistorySnapshot}from"../../core/history/read.js";import{verifyHistoryRewriteNoDrift}from"../../core/history/history-rewrite.js";import{resolveHistorySubject}from"../history/subject.js";import{historyVersionOffset}from"../../core/history/version-address.js";import{writeFileAtomic,appendHistoryEntry,createHistoryEntry,replayToCanonicalItemDocument,replayToItemDocument,toReplayDocument,enforceHistoryStreamPolicyForItem,canonicalDocument,serializeItemDocument,resolveItemTypeRegistry,acquireLockLease,EXIT_CODE,PmCliError,nowIso,getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnWriteHooks,runActiveBeforeMutationHooks,createMutationGuardSdk,getItemPath,resolvePmRoot,resolveWorkspaceRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{applyHistoryPatch,ensureMaterializedHistoryTarget as ensureMaterializedRestoreTarget,extractPatchFailureContext,replayHistoryToTarget as replayToTarget,resolveHistoryTarget}from"../history-read.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../item-metadata-index.js";import{redactOptionalIdentityCredentials}from"../../core/shared/url-credentials.js";async function readRestoreItem(located,settings,history){const snapshot=await readLocatedItemSnapshot(located,{schema:settings.schema});return snapshot.error===null?{raw:snapshot.raw,document:snapshot.document}:{raw:snapshot.raw,document:replayCurrentDocument(history),recovered:!0}}function ensureReplayTarget(target,history){return resolveHistoryTarget(target,history,{errorSubject:"restore",allowFutureTimestamp:!0})}function replayCurrentDocument(history){const currentReplay=replayToTarget(history,history.length-1);return Object.keys(currentReplay.metadata).length===0?{metadata:{},body:currentReplay.body}:canonicalDocument(replayToItemDocument(currentReplay))}async function resolveRestoreSubject(pmRoot,id,settings,typeToFolder){const subject=await resolveHistorySubject(pmRoot,id,settings,typeToFolder),historyPolicy=subject.located?await enforceHistoryStreamPolicyForItem({pmRoot,settings,itemId:subject.id,commandLabel:"restore"}):{warnings:[]};return{...subject,historyPolicyWarnings:historyPolicy.warnings}}function changedFields(beforeDocument,afterDocument){const beforeReplay=toReplayDocument(beforeDocument),afterReplay=toReplayDocument(afterDocument),patch=jsonPatch.compare(beforeReplay,afterReplay),fields=new Set;for(const op of patch){if(op.path==="/body"||op.path.startsWith("/body/")){fields.add("body");continue}const segment=op.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];fields.add(segment.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(fields).sort((a,b)=>a.localeCompare(b))}async function loadRestoreStateUnderLock(params){const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:"restore",readItem:located=>readRestoreItem(located,params.settings,params.history)});return{loadedItemUnderLock:verified.loadedItemUnderLock,existingItemPath:verified.locatedUnderLock?.itemPath??null}}function resolveRestoreCurrentState(loadedItemUnderLock,history){return loadedItemUnderLock?{document:loadedItemUnderLock.document,originalRaw:loadedItemUnderLock.raw}:{document:replayCurrentDocument(history),originalRaw:null}}function collectRestoreOwnershipWarnings(params){const stored=params.document.metadata.assignee?.trim(),hasOwnershipConflict=stored&&stored!==params.author&&!params.force,assigned=redactOptionalIdentityCredentials(stored);if(!hasOwnershipConflict)return[];if(params.enforcement==="strict")throw new PmCliError(`Item ${params.resolvedId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return params.enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.resolvedId}:${assigned}`]:[]}async function restorePreviousItemAfterHistoryFailure(params){if(params.existingItemPath&&params.resolvedOriginalRaw!==null&&params.restoredItemPath!==params.existingItemPath){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw),await fs.rm(params.restoredItemPath,{force:!0});return}if(params.existingItemPath&&params.resolvedOriginalRaw!==null){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw);return}await fs.rm(params.restoredItemPath,{force:!0})}async function runRestoreWriteHooks(params){return[...await runActiveOnWriteHooks({path:params.restoredItemPath,scope:"project",op:"restore",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]}),...await runActiveOnWriteHooks({path:params.historyPath,scope:"project",op:"restore:history",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]})]}async function runRestore(id,target,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),subject=await resolveRestoreSubject(pmRoot,id,settings,typeRegistry.type_to_folder),resolvedId=subject.id,{raw:historyRawBeforeLock,entries:history}=await readHistorySnapshot(subject.historyPath,resolvedId);if(history.length===0)throw new PmCliError(`No history exists for ${resolvedId}; restore is unavailable.`,EXIT_CODE.NOT_FOUND);const resolvedTarget=ensureReplayTarget(target,history),replayDocument=ensureMaterializedRestoreTarget(replayToTarget(history,resolvedTarget.historyIndex),resolvedTarget),restoredDocument=replayToCanonicalItemDocument(replayDocument,{schema:settings.schema});if(restoredDocument.metadata.id!==resolvedId)throw new PmCliError(`Restore target resolved to item ${restoredDocument.metadata.id}, expected ${resolvedId}.`,EXIT_CODE.GENERIC_FAILURE);const currentItemRawBeforeLock=(subject.located?await readRestoreItem(subject.located,settings,history):null)?.raw??null,author=resolveAuthor(options.author,settings.author_default),lease=await acquireLockLease(pmRoot,resolvedId,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const{loadedItemUnderLock,existingItemPath}=await loadRestoreStateUnderLock({pmRoot,subject,settings,typeRegistry,historyRawBeforeLock,currentItemRawBeforeLock,history}),itemFormat="toon",currentState=resolveRestoreCurrentState(loadedItemUnderLock,history);loadedItemUnderLock?.recovered===!0&&assertItemRevisionExpectationsOnUnreadable(pmRoot,resolvedId,loadedItemUnderLock.raw),assertItemMutationPreconditions(pmRoot,loadedItemUnderLock?.document??EMPTY_CANONICAL_DOCUMENT,resolvedId),restoredDocument.metadata.pm_format_version=normalizeItemFormatVersion(Math.max(requiredItemFormatVersion(restoredDocument.metadata),requiredItemFormatVersion(currentState.document.metadata))),assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(pmRoot),requiredItemFormatVersion(restoredDocument.metadata));const ownershipWarnings=collectRestoreOwnershipWarnings({document:currentState.document,author,force:options.force,enforcement:settings.governance.ownership_enforcement,resolvedId}),restoreChangedFields=changedFields(currentState.document,restoredDocument),workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"restore",author,before:currentState.document,after:restoredDocument});await runActiveBeforeMutationHooks({pm_root:pmRoot,operation:"restore",before:currentState.document,after:restoredDocument,changed_fields:restoreChangedFields,author,sdk:createMutationGuardSdk({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder})});const serializedRestore=serializeItemDocument(restoredDocument,{format:itemFormat,schema:settings.schema}),restoredItemPath=getItemPath(pmRoot,restoredDocument.metadata.type,resolvedId,itemFormat,typeRegistry.type_to_folder),derivedIndexWarnings=await lease.fence(async()=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(pmRoot,author);let derivedIndexWarnings2;try{await writeFileAtomic(restoredItemPath,serializedRestore),existingItemPath&&restoredItemPath!==existingItemPath&&await fs.rm(existingItemPath);const historyEntry=createHistoryEntry({nowIso:nowIso(),author,op:"restore",before:currentState.document,after:restoredDocument,message:options.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(subject.historyPath,historyEntry)}catch(error){throw await restorePreviousItemAfterHistoryFailure({existingItemPath,resolvedOriginalRaw:currentState.originalRaw,restoredItemPath}),error}derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot,preferredFormat:settings.item_format,typeToFolder:typeRegistry.type_to_folder,schema:settings.schema,itemPath:restoredItemPath,previousItemPath:existingItemPath??void 0,document:restoredDocument})}finally{await releaseDerivedIndexLock()}return derivedIndexWarnings2});advanceItemMutationPreconditions(pmRoot,restoredDocument,resolvedId);const hookWarnings=await runRestoreWriteHooks({restoredItemPath,historyPath:subject.historyPath,before:currentState.document,after:restoredDocument});recordAfterCommandAffectedItem({id:restoredDocument.metadata.id,op:"restore",item_type:restoredDocument.metadata.type,previous_status:currentState.document.metadata.status,status:restoredDocument.metadata.status,previous:projectAfterCommandItemSnapshot(currentState.document.metadata,restoreChangedFields),current:projectAfterCommandItemSnapshot(restoredDocument.metadata,restoreChangedFields),changed_fields:restoreChangedFields});const targetEntry=history[resolvedTarget.historyIndex],offset=historyVersionOffset(history,!0);return{item:restoredDocument.metadata,restored_from:{kind:resolvedTarget.kind,target:resolvedTarget.raw,history_index:resolvedTarget.historyIndex+1,version:offset===null?null:offset+resolvedTarget.historyIndex+1,entry_ts:targetEntry.ts,entry_op:targetEntry.op},changed_fields:restoreChangedFields,warnings:[...workflowPolicy.warnings,...loadedItemUnderLock?.recovered?["restore_unreadable_item_recovered"]:[],...subject.historyPolicyWarnings,...ownershipWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}const _testOnlyRestoreCommand={applyHistoryPatch,changedFields,ensureMaterializedRestoreTarget,ensureReplayTarget,extractPatchFailureContext,replayCurrentDocument,replayToTarget,resolveRestoreSubject};export{_testOnlyRestoreCommand,runRestore};
2
2
  //# sourceMappingURL=restore.js.map
@@ -88,4 +88,10 @@ export declare function expandUnsetFieldTokens(raw:readonly string[],resolvesWho
88
88
  /** Parse and validate common command `--unset` tokens while preserving command-specific field resolution. */
89
89
  export declare function parseCommandUnsetTargets(options:{readonly raw:readonly string[]|undefined;readonly resolveDefinition:CommandUnsetTargetResolver;readonly supportedFields:string;}):ParsedCommandUnsetTargets;
90
90
  /** Resolve a runtime-schema field definition from a command `--unset` token. */
91
- export declare function resolveRuntimeUnsetFieldDefinition(token:string,command:RuntimeFieldCommand,runtimeFieldRegistry:RuntimeFieldRegistry|undefined):RuntimeUnsetFieldDefinition|undefined;
91
+ export declare function resolveRuntimeUnsetFieldDefinition(token:string,command:RuntimeFieldCommand,runtimeFieldRegistry:RuntimeFieldRegistry|undefined):RuntimeUnsetFieldDefinition|undefined;
92
+ /**
93
+ * Parse create `--unset` tokens exactly as create resolves them: core aliases
94
+ * first, then schema fields, with whole-token expansion. Shared by create and
95
+ * the stdin-json document adapter, so both agree on what an unset names.
96
+ */
97
+ export declare function parseCreateUnsetTargets(raw:readonly string[]|undefined,runtimeFieldRegistry?:RuntimeFieldRegistry):{metadataKeys:Set<string>;optionKeys:Set<string>;};
@@ -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]="cfab194a-06fd-5536-9572-d33a34b94065")}catch{}})();import{EXIT_CODE,PmCliError}from"../runtime-primitives.js";import{isLegacyNoneToken}from"./legacy-none-tokens.js";const CLOSE_REASON_UNSET_ALIASES=["close_reason","close-reason"],COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_CLOSE_REASON=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],COMMON_UNSET_FIELD_DEFINITIONS_AFTER_CLOSE_REASON_BEFORE_AUTHOR=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_AUTHOR=[...COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_CLOSE_REASON,...COMMON_UNSET_FIELD_DEFINITIONS_AFTER_CLOSE_REASON_BEFORE_AUTHOR],COMMON_UNSET_FIELD_DEFINITIONS_AFTER_AUTHOR=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}],CREATE_UNSET_FIELD_DEFINITIONS=[...COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_AUTHOR,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...COMMON_UNSET_FIELD_DEFINITIONS_AFTER_AUTHOR],UPDATE_UNSET_FIELD_DEFINITIONS=[...COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_CLOSE_REASON,{canonical:"close-reason",aliases:CLOSE_REASON_UNSET_ALIASES,optionKey:"closeReason",metadataKey:"close_reason"},...COMMON_UNSET_FIELD_DEFINITIONS_AFTER_CLOSE_REASON_BEFORE_AUTHOR,...COMMON_UNSET_FIELD_DEFINITIONS_AFTER_AUTHOR],FORMER_CLEAR_SENTINELS=new Set(["none","null","-"]);function unsetDefinitionsFor(action){return action==="create"?CREATE_UNSET_FIELD_DEFINITIONS:UPDATE_UNSET_FIELD_DEFINITIONS}function foldNullClearsIntoUnset(action,options){const current=options.unset;if(current!==void 0&&typeof current!="string"&&!Array.isArray(current))return;const tokens=[];for(const definition of unsetDefinitionsFor(action))definition.optionKey==="author"||!Object.hasOwn(options,definition.optionKey)||options[definition.optionKey]!==null||(Reflect.deleteProperty(options,definition.optionKey),tokens.push(definition.canonical));tokens.length!==0&&(options.unset=[...current===void 0?[]:typeof current=="string"?[current]:current,...tokens])}function isFormerClearSentinel(value){return typeof value=="string"&&FORMER_CLEAR_SENTINELS.has(value.trim().toLowerCase())}function literalSentinelAdvisories(action,options,literal,stored){return literal?unsetDefinitionsFor(action).flatMap(definition=>{const value=options[definition.optionKey],kept=stored[definition.metadataKey];return isFormerClearSentinel(value)&&(isFormerClearSentinel(kept)||Array.isArray(kept)&&kept.some(isFormerClearSentinel))?[`literal_sentinel_stored:${definition.canonical}:${value.trim()}`]:[]}):[]}function expandUnsetFieldTokens(raw,resolvesWhole){return raw.flatMap(entry=>entry.includes(",")&&resolvesWhole(entry)?[entry]:entry.split(","))}function parseCommandUnsetTargets(options){const metadataKeys=new Set,optionKeys=new Set;if(!options.raw||options.raw.length===0)return{metadataKeys,optionKeys};const tokens=expandUnsetFieldTokens(options.raw,entry=>options.resolveDefinition(entry.trim().toLowerCase())!==void 0);for(const entry of tokens){const trimmed=entry.trim().toLowerCase();if(!trimmed)throw new PmCliError("--unset values must not be empty; name each field once, for example --unset parent,release",EXIT_CODE.USAGE);if(isLegacyNoneToken(trimmed))throw new PmCliError('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',EXIT_CODE.USAGE);const definition=options.resolveDefinition(trimmed);if(!definition)throw new PmCliError(`Unsupported --unset field "${entry}". Supported fields: ${options.supportedFields}`,EXIT_CODE.USAGE);metadataKeys.add(definition.metadataKey),optionKeys.add(definition.optionKey)}return{metadataKeys,optionKeys}}function resolveRuntimeUnsetFieldDefinition(token,command,runtimeFieldRegistry){const normalizedToken=token.trim().toLowerCase();if(!runtimeFieldRegistry)return;const definitions=runtimeFieldRegistry.command_to_fields?.get(command)??[];for(const definition of definitions){if(definition.allow_unset===!1)continue;const candidates=new Set;if(typeof definition.key=="string"&&definition.key.length>0&&candidates.add(definition.key.toLowerCase()),typeof definition.metadata_key=="string"&&definition.metadata_key.length>0&&candidates.add(definition.metadata_key.toLowerCase()),typeof definition.cli_flag=="string"&&definition.cli_flag.length>0&&(candidates.add(definition.cli_flag.replaceAll("-","_").toLowerCase()),candidates.add(definition.cli_flag.toLowerCase())),Array.isArray(definition.cli_aliases))for(const alias of definition.cli_aliases)typeof alias!="string"||alias.length===0||(candidates.add(alias.replaceAll("-","_").toLowerCase()),candidates.add(alias.toLowerCase()));if(candidates.has(normalizedToken))return{optionKey:definition.key,metadataKey:definition.metadata_key}}}export{CLOSE_REASON_UNSET_ALIASES,COMMON_UNSET_FIELD_DEFINITIONS_AFTER_AUTHOR,COMMON_UNSET_FIELD_DEFINITIONS_AFTER_CLOSE_REASON_BEFORE_AUTHOR,COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_AUTHOR,COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_CLOSE_REASON,CREATE_UNSET_FIELD_DEFINITIONS,UPDATE_UNSET_FIELD_DEFINITIONS,expandUnsetFieldTokens,foldNullClearsIntoUnset,literalSentinelAdvisories,parseCommandUnsetTargets,resolveRuntimeUnsetFieldDefinition};
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]="5146346c-df7b-5011-9d55-c59a7ff88f29")}catch{}})();import{EXIT_CODE,PmCliError}from"../runtime-primitives.js";import{isLegacyNoneToken}from"./legacy-none-tokens.js";const CLOSE_REASON_UNSET_ALIASES=["close_reason","close-reason"],COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_CLOSE_REASON=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],COMMON_UNSET_FIELD_DEFINITIONS_AFTER_CLOSE_REASON_BEFORE_AUTHOR=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_AUTHOR=[...COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_CLOSE_REASON,...COMMON_UNSET_FIELD_DEFINITIONS_AFTER_CLOSE_REASON_BEFORE_AUTHOR],COMMON_UNSET_FIELD_DEFINITIONS_AFTER_AUTHOR=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}],CREATE_UNSET_FIELD_DEFINITIONS=[...COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_AUTHOR,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...COMMON_UNSET_FIELD_DEFINITIONS_AFTER_AUTHOR],UPDATE_UNSET_FIELD_DEFINITIONS=[...COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_CLOSE_REASON,{canonical:"close-reason",aliases:CLOSE_REASON_UNSET_ALIASES,optionKey:"closeReason",metadataKey:"close_reason"},...COMMON_UNSET_FIELD_DEFINITIONS_AFTER_CLOSE_REASON_BEFORE_AUTHOR,...COMMON_UNSET_FIELD_DEFINITIONS_AFTER_AUTHOR],FORMER_CLEAR_SENTINELS=new Set(["none","null","-"]);function unsetDefinitionsFor(action){return action==="create"?CREATE_UNSET_FIELD_DEFINITIONS:UPDATE_UNSET_FIELD_DEFINITIONS}function foldNullClearsIntoUnset(action,options){const current=options.unset;if(current!==void 0&&typeof current!="string"&&!Array.isArray(current))return;const tokens=[];for(const definition of unsetDefinitionsFor(action))definition.optionKey==="author"||!Object.hasOwn(options,definition.optionKey)||options[definition.optionKey]!==null||(Reflect.deleteProperty(options,definition.optionKey),tokens.push(definition.canonical));tokens.length!==0&&(options.unset=[...current===void 0?[]:typeof current=="string"?[current]:current,...tokens])}function isFormerClearSentinel(value){return typeof value=="string"&&FORMER_CLEAR_SENTINELS.has(value.trim().toLowerCase())}function literalSentinelAdvisories(action,options,literal,stored){return literal?unsetDefinitionsFor(action).flatMap(definition=>{const value=options[definition.optionKey],kept=stored[definition.metadataKey];return isFormerClearSentinel(value)&&(isFormerClearSentinel(kept)||Array.isArray(kept)&&kept.some(isFormerClearSentinel))?[`literal_sentinel_stored:${definition.canonical}:${value.trim()}`]:[]}):[]}function expandUnsetFieldTokens(raw,resolvesWhole){return raw.flatMap(entry=>entry.includes(",")&&resolvesWhole(entry)?[entry]:entry.split(","))}function parseCommandUnsetTargets(options){const metadataKeys=new Set,optionKeys=new Set;if(!options.raw||options.raw.length===0)return{metadataKeys,optionKeys};const tokens=expandUnsetFieldTokens(options.raw,entry=>options.resolveDefinition(entry.trim().toLowerCase())!==void 0);for(const entry of tokens){const trimmed=entry.trim().toLowerCase();if(!trimmed)throw new PmCliError("--unset values must not be empty; name each field once, for example --unset parent,release",EXIT_CODE.USAGE);if(isLegacyNoneToken(trimmed))throw new PmCliError('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',EXIT_CODE.USAGE);const definition=options.resolveDefinition(trimmed);if(!definition)throw new PmCliError(`Unsupported --unset field "${entry}". Supported fields: ${options.supportedFields}`,EXIT_CODE.USAGE);metadataKeys.add(definition.metadataKey),optionKeys.add(definition.optionKey)}return{metadataKeys,optionKeys}}function resolveRuntimeUnsetFieldDefinition(token,command,runtimeFieldRegistry){const normalizedToken=token.trim().toLowerCase();if(!runtimeFieldRegistry)return;const definitions=runtimeFieldRegistry.command_to_fields?.get(command)??[];for(const definition of definitions){if(definition.allow_unset===!1)continue;const candidates=new Set;if(typeof definition.key=="string"&&definition.key.length>0&&candidates.add(definition.key.toLowerCase()),typeof definition.metadata_key=="string"&&definition.metadata_key.length>0&&candidates.add(definition.metadata_key.toLowerCase()),typeof definition.cli_flag=="string"&&definition.cli_flag.length>0&&(candidates.add(definition.cli_flag.replaceAll("-","_").toLowerCase()),candidates.add(definition.cli_flag.toLowerCase())),Array.isArray(definition.cli_aliases))for(const alias of definition.cli_aliases)typeof alias!="string"||alias.length===0||(candidates.add(alias.replaceAll("-","_").toLowerCase()),candidates.add(alias.toLowerCase()));if(candidates.has(normalizedToken))return{optionKey:definition.key,metadataKey:definition.metadata_key}}}const CREATE_UNSET_ALIAS_MAP=(()=>{const map=new Map;for(const definition of CREATE_UNSET_FIELD_DEFINITIONS)for(const alias of definition.aliases)map.set(alias,{optionKey:definition.optionKey,metadataKey:definition.metadataKey});return map})(),CREATE_UNSET_SUPPORTED_CANONICAL_FIELDS=CREATE_UNSET_FIELD_DEFINITIONS.map(definition=>definition.canonical).sort((left,right)=>left.localeCompare(right)).join(", ");function parseCreateUnsetTargets(raw,runtimeFieldRegistry){return parseCommandUnsetTargets({raw,supportedFields:CREATE_UNSET_SUPPORTED_CANONICAL_FIELDS,resolveDefinition:trimmed=>CREATE_UNSET_ALIAS_MAP.get(trimmed)??resolveRuntimeUnsetFieldDefinition(trimmed,"create",runtimeFieldRegistry)})}export{CLOSE_REASON_UNSET_ALIASES,COMMON_UNSET_FIELD_DEFINITIONS_AFTER_AUTHOR,COMMON_UNSET_FIELD_DEFINITIONS_AFTER_CLOSE_REASON_BEFORE_AUTHOR,COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_AUTHOR,COMMON_UNSET_FIELD_DEFINITIONS_BEFORE_CLOSE_REASON,CREATE_UNSET_FIELD_DEFINITIONS,UPDATE_UNSET_FIELD_DEFINITIONS,expandUnsetFieldTokens,foldNullClearsIntoUnset,literalSentinelAdvisories,parseCommandUnsetTargets,parseCreateUnsetTargets,resolveRuntimeUnsetFieldDefinition};
2
2
  //# sourceMappingURL=shared-unset-fields.js.map
@@ -1,4 +1,42 @@
1
- import type{GlobalOptions}from "../core/shared/command-types.js";import type{LinkScope}from "../types/index.js";import type{AnnotationOmissionReceipt}from "./annotations.js";
1
+ import type{GlobalOptions}from "../core/shared/command-types.js";import{PmCliError}from "../core/shared/errors.js";import type{LinkScope}from "../types/index.js";import type{AnnotationOmissionReceipt}from "./annotations.js";
2
+ /** How an add treats a stored link whose note differs from the requested one. */
3
+ export declare const LINKED_ARTIFACT_NOTE_CONFLICT_MODES:readonly["refuse","replace","append"];
4
+ /** One of {@link LINKED_ARTIFACT_NOTE_CONFLICT_MODES}; `refuse` is the default. */
5
+ export type LinkedArtifactNoteConflictMode=(typeof LINKED_ARTIFACT_NOTE_CONFLICT_MODES)[number];
6
+ /** What one requested link became in storage. */
7
+ export type LinkedArtifactLinkOutcome="added"|"note_added"|"note_replaced"|"note_appended"|"unchanged";
8
+ /** Per-link outcome a files or docs write reports in its mutation receipt. */
9
+ export interface LinkedArtifactLinkOutcomeEntry{
10
+ /** Linked path after anchoring and any path migration. */
11
+ path:string;
12
+ /** Scope of the requested link. */
13
+ scope:LinkScope;
14
+ /** What the write did to this link. */
15
+ outcome:LinkedArtifactLinkOutcome;}
16
+ /** A requested note that would overwrite a different stored note. */
17
+ export interface LinkedArtifactNoteConflict{
18
+ /** Linked path the conflict is on. */
19
+ path:string;
20
+ /** Scope of the stored link. */
21
+ scope:LinkScope;
22
+ /** The note already stored, which a refusal keeps. */
23
+ existing_note:string;
24
+ /** The note the add asked for. */
25
+ requested_note:string;
26
+ /** Whether the existing note was stored before this write or set by an earlier entry of the same write. */
27
+ source:"stored"|"this_write";}
28
+ /** Separator `append` places between the stored note and the requested one. */
29
+ export declare const LINKED_ARTIFACT_NOTE_JOINER="; ";
30
+ /** Parse the conflict mode, refusing a value outside the closed set and a mode with nothing to add. */
31
+ export declare function parseNoteConflictMode(raw:string|undefined,hasAddFlags:boolean):LinkedArtifactNoteConflictMode;
32
+ /**
33
+ * The note a stored link keeps after an add requests `requested`, and the
34
+ * outcome to report. A missing or identical requested note, and an append
35
+ * whose text is already one of the joined segments, leave the link unchanged.
36
+ */
37
+ export declare function reviseLinkedNote(existing:string|undefined,requested:string|undefined,mode:LinkedArtifactNoteConflictMode):{note:string|undefined;outcome:LinkedArtifactLinkOutcome;conflict:boolean;};
38
+ /** Refuse a write whose adds would overwrite stored notes; nothing has been written when this throws. */
39
+ export declare function buildNoteConflictError(params:{itemId:string;noun:"file"|"doc";conflicts:readonly LinkedArtifactNoteConflict[];retryArgs:(mode:Exclude<LinkedArtifactNoteConflictMode,"refuse">)=> string[]|undefined;render:(args:string[])=> string;}):PmCliError;
2
40
  /** Restricts linked artifact values accepted by command, SDK, and storage contracts. */
3
41
  export type LinkedArtifact={
4
42
  /** Filesystem path used for path resolution. */
@@ -27,6 +65,8 @@ remove?:string[];
27
65
  migrate?:string[];
28
66
  /** GH-170 (pm-pfnx): standalone note applied to every link added by --add / --add-glob in the same invocation. A per-entry embedded note (the `path=...,note=...` pair syntax) takes precedence over this flag. Requires at least one --add/--add-glob; rejected otherwise. */
29
67
  note?:string;
68
+ /** How an add treats a stored link with a different note: refuse (default), replace or append (GH-1716). Requires --add or --add-glob. */
69
+ noteConflict?:LinkedArtifactNoteConflictMode|(string&{});
30
70
  /** Value that configures or reports list for this contract. */
31
71
  list?:boolean;
32
72
  /** Value that configures or reports append stable for this contract. */
@@ -48,7 +88,9 @@ changed_count:number;
48
88
  /** Stored entries this mutation removed. */
49
89
  removed_count:number;
50
90
  /** Whether the response includes the complete post-mutation collection. */
51
- full_history_included:boolean;}
91
+ full_history_included:boolean;
92
+ /** Files and docs writes: what each requested link became, so a note overwrite never reads as an add (GH-1716). */
93
+ link_outcomes?:LinkedArtifactLinkOutcomeEntry[];}
52
94
  /** Counts and receipts a linked-collection mutation response carries beside its entries. */
53
95
  export interface LinkedCollectionMutationProjection<TEntry>{
54
96
  /** The written entries, or the whole collection when full history was requested. */
@@ -72,7 +114,7 @@ export declare function writtenLinkedEntries<TEntry>(before:readonly TEntry[],af
72
114
  * MCP `full`) returns the whole collection, and the omission receipt names
73
115
  * that selector whenever stored entries were withheld.
74
116
  */
75
- export declare function projectLinkedCollectionMutation<TEntry>(params:{collectionKey:"files"|"docs"|"tests";stored:readonly TEntry[];written:readonly TEntry[];removedCount:number;fullHistory:boolean;}):LinkedCollectionMutationProjection<TEntry>;
117
+ export declare function projectLinkedCollectionMutation<TEntry>(params:{collectionKey:"files"|"docs"|"tests";stored:readonly TEntry[];written:readonly TEntry[];removedCount:number;fullHistory:boolean;linkOutcomes?:readonly LinkedArtifactLinkOutcomeEntry[];}):LinkedCollectionMutationProjection<TEntry>;
76
118
  /** Documents the path migration payload exchanged by command, SDK, and package integrations. */
77
119
  export interface PathMigration{
78
120
  /** Value that configures or reports from for this contract. */
@@ -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]="ac5ce7de-2997-5af1-a414-19f1783f8f05")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{glob}from"tinyglobby";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,createStdinTokenResolver,looksLikeGenericKeyValueEntry,parseCsvKv,splitStructuredEntrySegments}from"../core/item/parse.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isRemoteLinkedArtifactReference}from"../core/validate/linked-artifact-reference.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{stableValueEquals}from"../core/shared/serialization.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{SCOPE_VALUES}from"../types/index.js";import{resolveAuthor}from"../core/shared/author.js";import{renderPmCommand,resolvePmCommandScopeArgs}from"./command-line.js";import{activeItemRevisionExpectations}from"../core/store/item-mutation-precondition.js";const LINKED_ARTIFACT_ADD_KEYS=["path","scope","note"],LINKED_ARTIFACT_ADD_GLOB_KEYS=["pattern","glob","path","scope","note"],LINKED_ARTIFACT_REMOVE_KEYS=["path"],LINKED_ARTIFACT_MIGRATE_KEYS=["from","to"],LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS=new Set(["note","scope"]);function persistedLinkedForm(entry){return JSON.parse(JSON.stringify(entry))}function writtenLinkedEntries(before,after){const unmatched=before.map(persistedLinkedForm);return after.filter(entry=>{const persisted=persistedLinkedForm(entry),index=unmatched.findIndex(candidate=>stableValueEquals(candidate,persisted));return index>=0&&unmatched.splice(index,1),index<0})}function projectLinkedCollectionMutation(params){const entries=params.fullHistory?[...params.stored]:[...params.written],withheld=entries.length<params.stored.length;return{entries,total_count:params.stored.length,returned_count:entries.length,has_more:withheld,mutation_receipt:{changed_count:params.written.length,removed_count:params.removedCount,full_history_included:!withheld},omission_receipt:{has_omissions:withheld,omitted_field_group_count:withheld?1:0,omitted_field_groups:withheld?[{name:`${params.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value))throw new PmCliError(`Invalid scope "${raw}". Valid scopes: ${SCOPE_VALUES.join(", ")} (default: project).`,EXIT_CODE.USAGE);return value}function looksLikeStructuredPathEntry(raw){if(raw.startsWith("```")||raw.includes(`
2
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw))return!0;const firstCommaIndex=raw.indexOf(","),leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length),equalsIndex=leadingSegment.indexOf("=");return equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))?!1:leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value)if(character==="("&&(depth+=1),character===")"&&(depth-=1),depth<0)return!1;return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed))return{path:trimmed,scope:"project",note:void 0};const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2))return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return;const label=trimmed.slice(0,delimiterIndex).trim(),destination=trimmed.slice(delimiterIndex+1).trim();if(!(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)))return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){return raw?raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};if(assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS),!kv.path)throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE);return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]}):[]}function parseAddGlobEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern)throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE);return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}}):[]}function parseRemoveEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove"),unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0)throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE);if(assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS),!kv.path)throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE);return kv.path}return trimmed}):[]}function parseMigrateEntries(raw){return raw?raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim(),to=kv.to?.trim();if(!from||!to)throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE);return{from,to}}):[]}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations)next.startsWith(migration.from)&&(next=`${migration.to}${next.slice(migration.from.length)}`);return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0)return;const addedPaths=new Set(adds.map(entry=>applyPathMigrations(entry.path,migrations))),conflicts=[...new Set(removes.map(entry=>applyPathMigrations(entry,migrations)).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length!==0)throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed))return trimmed;if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed))return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep));const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);return invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)?normalizeLinkedPath(path.normalize(trimmed)):normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){if(path.resolve(invocationRoot,entry.pattern)===path.resolve(invocationRoot))continue;const absolutePattern=path.isAbsolute(entry.pattern),matches=await glob(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches)expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0)return adds;if(!hasAddFlags)throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE);const trimmed=note.trim();return trimmed.length===0?adds:adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);return byPath!==0?byPath:left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right)),existingFiles=[],missingPaths=[],nonFilePaths=[],remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{(await fs.stat(resolvedPath)).isFile()?existingFiles.push(relativePath):nonFilePaths.push(relativePath)}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);migratedPath!==current[index].path&&(current[index]={...current[index],path:migratedPath},count+=1)}return{adds:adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);return migratedPath!==entry.path&&(count+=1),{...entry,path:migratedPath}}),removes:removes.map(entry=>applyPathMigrations(entry,migrations)),count}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable){const merged=dedupeLinkedArtifacts(current);for(const add of adds){const index=merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope);index<0?merged.push(add):add.note!==void 0&&(merged[index]={...merged[index],note:add.note})}if(removes.length>0)for(let index=merged.length-1;index>=0;index-=1)removes.includes(merged[index].path)&&merged.splice(index,1);return appendStable?merged:sortLinkedArtifacts(merged)}async function buildLinkedArtifactResult(params){const returned=params.mutation?.entries??params.artifacts,validated=params.options.validatePaths?params.artifacts:returned,{counts,receipts}=linkedCollectionMutationFields(params.mutation);return{id:params.id,artifacts:returned,changed:params.changed,count:returned.length,...counts,migrations_applied:params.migrationsApplied&&params.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed&&validated.length>0?await validateLinkedPaths(validated.map(entry=>entry.path),params.workspaceRoot):void 0,...receipts}}function countRemovedLinkedArtifacts(before,after,migrations){const remaining=new Map;for(const entry of after){const key=artifactKey(entry);remaining.set(key,(remaining.get(key)??0)+1)}let removed=0;for(const entry of before){const key=artifactKey({...entry,path:applyPathMigrations(entry.path,migrations)}),left=remaining.get(key)??0;left>0?remaining.set(key,left-1):removed+=1}return removed}function findMisreadNoteSegment(entry,bareNoun){const segments=/[\n\r]|^\s*[-*+`]/u.test(entry)?[]:splitStructuredEntrySegments(entry),noteIndex=segments.findIndex(segment=>segment.key?.toLowerCase()==="note");if(noteIndex<0)return;const fields=segments.slice(0,noteIndex).map(segment=>segment.raw.trim()),keys=new Set(segments.slice(0,noteIndex).map(segment=>segment.key?.toLowerCase())),prose=[segments[noteIndex].value];let misread;for(const segment of segments.slice(noteIndex+1)){const key=segment.key?.toLowerCase();if((key==="path"||key==="scope")&&!keys.has(key)){fields.push(segment.raw.trim()),keys.add(key);continue}misread??=segment.key===void 0?void 0:{segment:segment.text.trim(),key:segment.key},prose.push(segment.text)}if(misread===void 0)return;const note=prose.join(",").trim(),rewritten=[...fields,`note=${JSON.stringify(note)}`].join(",");try{parseAddEntries([rewritten],bareNoun)}catch{return}return{entry:rewritten,note,...misread}}function firstRefusedAddEntry(entries,bareNoun){return entries.findIndex(entry=>{try{return parseAddEntries([entry],bareNoun),!1}catch{return!0}})+1}function repeatFlag(flag,values){return(values??[]).flatMap(value=>[flag,value])}function noteRecoveryRetryArgs(params){const{options}=params;return[...resolvePmCommandScopeArgs(params.global),...params.guards.map(guard=>`--expect-hash=${guard}`),params.config.metadataKey,params.id,...repeatFlag("--add",params.entries.map((entry,index)=>index===params.position-1?params.rewritten:entry)),...repeatFlag("--add-glob",params.resolved.addGlob),...repeatFlag("--remove",params.resolved.remove),...repeatFlag("--migrate",params.resolved.migrate),...options.note===void 0?[]:["--note",options.note],...params.config.supportsAppendStable&&options.appendStable===!0?["--append-stable"]:[],...options.validatePaths===!0?["--validate-paths"]:[],...options.fullHistory===!0?["--full-history"]:[],...options.author?["--author",options.author]:[],...options.message?["--message",options.message]:[],...options.force===!0?["--force"]:[]]}function misreadKeyHint(key){return LINKED_ARTIFACT_ADD_KEYS.some(allowed=>allowed===key.toLowerCase())?`If "${key}" was meant as a key, give it once per entry.`:`If "${key}" was meant as a key, it is not one of: ${LINKED_ARTIFACT_ADD_KEYS.join(", ")}.`}function parseAddEntriesWithNoteRecovery(params){try{return parseAddEntries(params.entries,params.config.bareNoun)}catch(error){const entries=params.entries,cause=error,position=firstRefusedAddEntry(entries,params.config.bareNoun),misread=findMisreadNoteSegment(entries[position-1],params.config.bareNoun);if(misread===void 0)throw error;const guards=activeItemRevisionExpectations(params.pmRoot),retryArgs=guards===void 0?void 0:noteRecoveryRetryArgs({...params,entries,position,rewritten:misread.entry,guards});throw new PmCliError(`--add read the note segment "${misread.segment}" as a new key "${misread.key}", so the ${params.config.bareNoun} link was refused (${cause.message})`,EXIT_CODE.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:entries[position-1],required:`Retry with the note quoted so its commas stay prose (${retryArgs===void 0?`as ${misread.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${misreadKeyHint(misread.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...retryArgs===void 0?{}:{nextSteps:[renderPmCommand(retryArgs)]},details:{entry_index:position,misread_segment:misread.segment,misread_key:misread.key,note:misread.note,rewritten_entry:misread.entry,cause:cause.context.code??"invalid_argument_value"},...retryArgs===void 0?{}:{recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}}})}}function linkedCollectionMutationFields(mutation){return mutation===void 0?{counts:{},receipts:{}}:{counts:{total_count:mutation.total_count,returned_count:mutation.returned_count,has_more:mutation.has_more},receipts:{mutation_receipt:mutation.mutation_receipt,omission_receipt:mutation.omission_receipt}}}async function readLinkedArtifacts(params){const{settings,config}=params,located=await locateItem(params.pmRoot,params.id,settings.id_prefix,settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Item ${params.id} not found`,EXIT_CODE.NOT_FOUND);const artifacts=(await readLocatedItem(located,{schema:settings.schema})).document.metadata[config.metadataKey]??[],mutation=params.writeRequested?projectLinkedCollectionMutation({collectionKey:config.metadataKey,stored:artifacts,written:[],removedCount:0,fullHistory:params.options.fullHistory===!0}):void 0;return buildLinkedArtifactResult({id:located.id,artifacts,changed:!1,options:params.options,workspaceRoot:params.workspaceRoot,mutation})}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config,stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot),invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate"),parsedAdds=parseAddEntriesWithNoteRecovery({id,pmRoot,entries:resolvedAdds,resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config}).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)})),addGlobs=parseAddGlobEntries(resolvedAddGlobs),expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot),adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,parsedAdds.length>0||addGlobs.length>0),removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot)),migrations=parseMigrateEntries(resolvedMigrations);if(assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations),!(adds.length>0||removes.length>0||migrations.length>0))return readLinkedArtifacts({id,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,options,workspaceRoot,config,writeRequested:addGlobs.length>0});const author=resolveAuthor(options.author,settings.author_default);let before=[],removedCount=0;const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:!0,mutate(document){const metadata=document.metadata,current=metadata[metadataKey]??[],next=[...current],migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations),normalized=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===!0);normalized.length>0?metadata[metadataKey]=normalized:delete metadata[metadataKey];const changed=!stableValueEquals(current,normalized);return before=current,removedCount=countRemovedLinkedArtifacts(current,normalized,migrations),{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}}),artifacts=result.item[metadataKey]??[],migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:")),migrationCount=migrationWarning?Number(migrationWarning.slice(24)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot,mutation:projectLinkedCollectionMutation({collectionKey:metadataKey,stored:artifacts,written:writtenLinkedEntries(before,artifacts),removedCount,fullHistory:options.fullHistory===!0})})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result))out[field==="artifacts"?key:field]=value;return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,findMisreadNoteSegment,linkedCollectionMutationFields,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,projectLinkedCollectionMutation,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,writtenLinkedEntries};
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]="6c72ddef-c0fa-5d0b-9e35-20e3ba3c8d73")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{glob}from"tinyglobby";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,createStdinTokenResolver,looksLikeGenericKeyValueEntry,parseCsvKv,splitStructuredEntrySegments}from"../core/item/parse.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isRemoteLinkedArtifactReference}from"../core/validate/linked-artifact-reference.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{stableValueEquals}from"../core/shared/serialization.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{SCOPE_VALUES}from"../types/index.js";import{resolveAuthor}from"../core/shared/author.js";import{renderPmCommand,resolvePmCommandScopeArgs}from"./command-line.js";import{activeItemRevisionExpectations}from"../core/store/item-mutation-precondition.js";const LINKED_ARTIFACT_NOTE_CONFLICT_MODES=["refuse","replace","append"],LINKED_ARTIFACT_NOTE_JOINER="; ";function parseNoteConflictMode(raw,hasAddFlags){if(raw===void 0)return"refuse";const mode=raw.trim().toLowerCase();if(!LINKED_ARTIFACT_NOTE_CONFLICT_MODES.some(allowed=>allowed===mode))throw new PmCliError(`--note-conflict must be one of ${LINKED_ARTIFACT_NOTE_CONFLICT_MODES.join(", ")}; got "${raw}"`,EXIT_CODE.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:raw,required:`Pass --note-conflict ${LINKED_ARTIFACT_NOTE_CONFLICT_MODES.join("|")}.`});if(!hasAddFlags)throw new PmCliError("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",EXIT_CODE.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return mode}function reviseLinkedNote(existing,requested,mode){if(requested===void 0||requested===existing)return{note:existing,outcome:"unchanged",conflict:!1};if(existing===void 0)return{note:requested,outcome:"note_added",conflict:!1};if(mode==="replace")return{note:requested,outcome:"note_replaced",conflict:!1};if(mode==="append"){const joiner=LINKED_ARTIFACT_NOTE_JOINER;return`${joiner}${existing}${joiner}`.includes(`${joiner}${requested}${joiner}`)?{note:existing,outcome:"unchanged",conflict:!1}:{note:`${existing}${LINKED_ARTIFACT_NOTE_JOINER}${requested}`,outcome:"note_appended",conflict:!1}}return{note:existing,outcome:"unchanged",conflict:!0}}function buildNoteConflictError(params){const first=params.conflicts[0],more=params.conflicts.length>1?` and ${params.conflicts.length-1} more`:"",append=params.retryArgs("append"),replace=params.retryArgs("replace"),message=first.source==="stored"?`${params.itemId} already links ${params.noun} ${first.path} with the note "${first.existing_note}"${more}; the add was refused so that note is kept`:`The add names ${params.noun} ${first.path} on ${params.itemId} with two notes, "${first.existing_note}" and then "${first.requested_note}"${more}; the add was refused because they disagree`;return new PmCliError(message,EXIT_CODE.CONFLICT,{code:"linked_artifact_note_conflict",item_id:params.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...append===void 0||replace===void 0?{}:{nextSteps:[params.render(append),params.render(replace)],recovery:{suggested_retry:params.render(append),suggested_retry_args:append}},details:{conflicts:params.conflicts.map(conflict=>({...conflict}))}})}const LINKED_ARTIFACT_ADD_KEYS=["path","scope","note"],LINKED_ARTIFACT_ADD_GLOB_KEYS=["pattern","glob","path","scope","note"],LINKED_ARTIFACT_REMOVE_KEYS=["path"],LINKED_ARTIFACT_MIGRATE_KEYS=["from","to"],LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS=new Set(["note","scope"]);function persistedLinkedForm(entry){return JSON.parse(JSON.stringify(entry))}function writtenLinkedEntries(before,after){const unmatched=before.map(persistedLinkedForm);return after.filter(entry=>{const persisted=persistedLinkedForm(entry),index=unmatched.findIndex(candidate=>stableValueEquals(candidate,persisted));return index>=0&&unmatched.splice(index,1),index<0})}function projectLinkedCollectionMutation(params){const entries=params.fullHistory?[...params.stored]:[...params.written],withheld=entries.length<params.stored.length;return{entries,total_count:params.stored.length,returned_count:entries.length,has_more:withheld,mutation_receipt:{changed_count:params.written.length,removed_count:params.removedCount,full_history_included:!withheld,...params.linkOutcomes&&params.linkOutcomes.length>0?{link_outcomes:[...params.linkOutcomes]}:{}},omission_receipt:{has_omissions:withheld,omitted_field_group_count:withheld?1:0,omitted_field_groups:withheld?[{name:`${params.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value))throw new PmCliError(`Invalid scope "${raw}". Valid scopes: ${SCOPE_VALUES.join(", ")} (default: project).`,EXIT_CODE.USAGE);return value}function looksLikeStructuredPathEntry(raw){if(raw.startsWith("```")||raw.includes(`
2
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw))return!0;const firstCommaIndex=raw.indexOf(","),leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length),equalsIndex=leadingSegment.indexOf("=");return equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))?!1:leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value)if(character==="("&&(depth+=1),character===")"&&(depth-=1),depth<0)return!1;return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed))return{path:trimmed,scope:"project",note:void 0};const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2))return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return;const label=trimmed.slice(0,delimiterIndex).trim(),destination=trimmed.slice(delimiterIndex+1).trim();if(!(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)))return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){return raw?raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};if(assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS),!kv.path)throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE);return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]}):[]}function parseAddGlobEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern)throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE);return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}}):[]}function parseRemoveEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove"),unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0)throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE);if(assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS),!kv.path)throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE);return kv.path}return trimmed}):[]}function parseMigrateEntries(raw){return raw?raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim(),to=kv.to?.trim();if(!from||!to)throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE);return{from,to}}):[]}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations)next.startsWith(migration.from)&&(next=`${migration.to}${next.slice(migration.from.length)}`);return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0)return;const addedPaths=new Set(adds.map(entry=>storedLinkedPath(applyPathMigrations(entry.path,migrations)))),conflicts=[...new Set(removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length!==0)throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed))return trimmed;if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed))return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep));const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);return invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)?normalizeLinkedPath(path.normalize(trimmed)):normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){if(path.resolve(invocationRoot,entry.pattern)===path.resolve(invocationRoot))continue;const absolutePattern=path.isAbsolute(entry.pattern),matches=await glob(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches)expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0)return adds;if(!hasAddFlags)throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE);const trimmed=note.trim();return trimmed.length===0?adds:adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);return byPath!==0?byPath:left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right)),existingFiles=[],missingPaths=[],nonFilePaths=[],remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{(await fs.stat(resolvedPath)).isFile()?existingFiles.push(relativePath):nonFilePaths.push(relativePath)}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);migratedPath!==current[index].path&&(count+=1);const storedPath=storedLinkedPath(migratedPath);storedPath!==current[index].path&&(current[index]={...current[index],path:storedPath})}return{adds:adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);return migratedPath!==entry.path&&(count+=1),{...entry,path:storedLinkedPath(migratedPath)}}),removes:removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))),count}}function storedLinkedPath(value){return value.replaceAll("\\","/")}function storedLinkKey(entry){return`${entry.scope}\0${storedLinkedPath(entry.path)}`}function linkedArtifactOutcomes(baseline,merged,adds){const before=new Map(baseline.map(entry=>[storedLinkKey(entry),entry.note])),after=new Map(merged.map(entry=>[storedLinkKey(entry),entry.note])),outcomes=new Map;for(const add of adds){const key=storedLinkKey(add);outcomes.has(key)||outcomes.set(key,{path:storedLinkedPath(add.path),scope:add.scope,outcome:classifyLinkOutcome(before.has(key),before.get(key),after.get(key))})}return[...outcomes.values()]}function classifyLinkOutcome(existed,prior,final){return existed?final===prior?"unchanged":prior===void 0?"note_added":final?.startsWith(`${prior}${LINKED_ARTIFACT_NOTE_JOINER}`)?"note_appended":"note_replaced":"added"}function applyLinkedArtifactAdd(state,add,noteConflict){const index=state.merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope),stored=state.merged[index];if(stored===void 0){state.merged.push(add),add.note!==void 0&&state.notedHere.add(add);return}const revision=reviseLinkedNote(stored.note,add.note,noteConflict);if(revision.conflict)state.conflicts.push({path:add.path,scope:add.scope,existing_note:stored.note,requested_note:add.note,source:state.notedHere.has(stored)?"this_write":"stored"});else if(revision.note!==stored.note){const revised={...stored,note:revision.note};state.merged[index]=revised,state.notedHere.add(revised)}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable,noteConflict){const baseline=dedupeLinkedArtifacts(current),state={merged:[...baseline],notedHere:new Set,conflicts:[]};for(const add of adds)applyLinkedArtifactAdd(state,add,noteConflict);const{merged}=state,outcomes=linkedArtifactOutcomes(baseline,merged,adds);if(removes.length>0)for(let index=merged.length-1;index>=0;index-=1)removes.includes(merged[index].path)&&merged.splice(index,1);return{entries:appendStable?merged:sortLinkedArtifacts(merged),outcomes,conflicts:state.conflicts}}async function buildLinkedArtifactResult(params){const returned=params.mutation?.entries??params.artifacts,validated=params.options.validatePaths?params.artifacts:returned,{counts,receipts}=linkedCollectionMutationFields(params.mutation);return{id:params.id,artifacts:returned,changed:params.changed,count:returned.length,...counts,migrations_applied:params.migrationsApplied&&params.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed&&validated.length>0?await validateLinkedPaths(validated.map(entry=>entry.path),params.workspaceRoot):void 0,...receipts}}function countRemovedLinkedArtifacts(before,after,migrations){const remaining=new Map;for(const entry of after){const key=artifactKey(entry);remaining.set(key,(remaining.get(key)??0)+1)}let removed=0;for(const entry of before){const key=artifactKey({...entry,path:storedLinkedPath(applyPathMigrations(entry.path,migrations))}),left=remaining.get(key)??0;left>0?remaining.set(key,left-1):removed+=1}return removed}function findMisreadNoteSegment(entry,bareNoun){const segments=/[\n\r]|^\s*[-*+`]/u.test(entry)?[]:splitStructuredEntrySegments(entry),noteIndex=segments.findIndex(segment=>segment.key?.toLowerCase()==="note");if(noteIndex<0)return;const fields=segments.slice(0,noteIndex).map(segment=>segment.raw.trim()),keys=new Set(segments.slice(0,noteIndex).map(segment=>segment.key?.toLowerCase())),prose=[segments[noteIndex].value];let misread;for(const segment of segments.slice(noteIndex+1)){const key=segment.key?.toLowerCase();if((key==="path"||key==="scope")&&!keys.has(key)){fields.push(segment.raw.trim()),keys.add(key);continue}misread??=segment.key===void 0?void 0:{segment:segment.text.trim(),key:segment.key},prose.push(segment.text)}if(misread===void 0)return;const note=prose.join(",").trim(),rewritten=[...fields,`note=${JSON.stringify(note)}`].join(",");try{parseAddEntries([rewritten],bareNoun)}catch{return}return{entry:rewritten,note,...misread}}function firstRefusedAddEntry(entries,bareNoun){return entries.findIndex(entry=>{try{return parseAddEntries([entry],bareNoun),!1}catch{return!0}})+1}function repeatFlag(flag,values,literalKey){return(values??[]).flatMap(value=>[flag,literalKey!==void 0&&value.trim()==="-"?`${literalKey}=-`:value])}function noteRecoveryRetryArgs(params){const{options}=params,noteConflict=params.noteConflict??options.noteConflict;return[...resolvePmCommandScopeArgs(params.global),...params.guards.map(guard=>`--expect-hash=${guard}`),params.config.metadataKey,params.id,...repeatFlag("--add",params.entries.map((entry,index)=>index===params.position-1?params.rewritten:entry),"path"),...repeatFlag("--add-glob",params.resolved.addGlob,"pattern"),...repeatFlag("--remove",params.resolved.remove,"path"),...repeatFlag("--migrate",params.resolved.migrate),...options.note===void 0?[]:["--note",options.note],...noteConflict===void 0?[]:["--note-conflict",noteConflict],...params.config.supportsAppendStable&&options.appendStable===!0?["--append-stable"]:[],...options.validatePaths===!0?["--validate-paths"]:[],...options.fullHistory===!0?["--full-history"]:[],...options.author?["--author",options.author]:[],...options.message?["--message",options.message]:[],...options.force===!0?["--force"]:[]]}function misreadKeyHint(key){return LINKED_ARTIFACT_ADD_KEYS.some(allowed=>allowed===key.toLowerCase())?`If "${key}" was meant as a key, give it once per entry.`:`If "${key}" was meant as a key, it is not one of: ${LINKED_ARTIFACT_ADD_KEYS.join(", ")}.`}function parseAddEntriesWithNoteRecovery(params){try{return parseAddEntries(params.entries,params.config.bareNoun)}catch(error){const entries=params.entries,cause=error,position=firstRefusedAddEntry(entries,params.config.bareNoun),misread=findMisreadNoteSegment(entries[position-1],params.config.bareNoun);if(misread===void 0)throw error;const guards=activeItemRevisionExpectations(params.pmRoot),retryArgs=guards===void 0?void 0:noteRecoveryRetryArgs({...params,entries,position,rewritten:misread.entry,guards});throw new PmCliError(`--add read the note segment "${misread.segment}" as a new key "${misread.key}", so the ${params.config.bareNoun} link was refused (${cause.message})`,EXIT_CODE.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:entries[position-1],required:`Retry with the note quoted so its commas stay prose (${retryArgs===void 0?`as ${misread.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${misreadKeyHint(misread.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...retryArgs===void 0?{}:{nextSteps:[renderPmCommand(retryArgs)]},details:{entry_index:position,misread_segment:misread.segment,misread_key:misread.key,note:misread.note,rewritten_entry:misread.entry,cause:cause.context.code??"invalid_argument_value"},...retryArgs===void 0?{}:{recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}}})}}function linkedCollectionMutationFields(mutation){return mutation===void 0?{counts:{},receipts:{}}:{counts:{total_count:mutation.total_count,returned_count:mutation.returned_count,has_more:mutation.has_more},receipts:{mutation_receipt:mutation.mutation_receipt,omission_receipt:mutation.omission_receipt}}}async function readLinkedArtifacts(params){const{settings,config}=params,located=await locateItem(params.pmRoot,params.id,settings.id_prefix,settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Item ${params.id} not found`,EXIT_CODE.NOT_FOUND);const artifacts=(await readLocatedItem(located,{schema:settings.schema})).document.metadata[config.metadataKey]??[],mutation=params.writeRequested?projectLinkedCollectionMutation({collectionKey:config.metadataKey,stored:artifacts,written:[],removedCount:0,fullHistory:params.options.fullHistory===!0}):void 0;return buildLinkedArtifactResult({id:located.id,artifacts,changed:!1,options:params.options,workspaceRoot:params.workspaceRoot,mutation})}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config,stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot),invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate"),parsedAdds=parseAddEntriesWithNoteRecovery({id,pmRoot,entries:resolvedAdds,resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config}).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)})),addGlobs=parseAddGlobEntries(resolvedAddGlobs),expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot),hasAddFlags=parsedAdds.length>0||addGlobs.length>0,adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,hasAddFlags),noteConflict=parseNoteConflictMode(options.noteConflict,hasAddFlags),removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot)),migrations=parseMigrateEntries(resolvedMigrations);if(assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations),!(adds.length>0||removes.length>0||migrations.length>0))return readLinkedArtifacts({id,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,options,workspaceRoot,config,writeRequested:addGlobs.length>0});const author=resolveAuthor(options.author,settings.author_default);let before=[],removedCount=0,linkOutcomes=[];const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:!0,mutate(document){const metadata=document.metadata,current=metadata[metadataKey]??[],next=[...current],migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations),merge=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===!0,noteConflict);if(merge.conflicts.length>0){const guards=activeItemRevisionExpectations(pmRoot);throw buildNoteConflictError({itemId:document.metadata.id,noun:config.bareNoun,conflicts:merge.conflicts,retryArgs:mode=>guards===void 0?void 0:noteRecoveryRetryArgs({id:document.metadata.id,entries:resolvedAdds??[],position:0,rewritten:"",resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config,guards,noteConflict:mode}),render:renderPmCommand})}const normalized=merge.entries;linkOutcomes=merge.outcomes,normalized.length>0?metadata[metadataKey]=normalized:delete metadata[metadataKey];const changed=!stableValueEquals(current,normalized);return before=current,removedCount=countRemovedLinkedArtifacts(current,normalized,migrations),{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}}),artifacts=result.item[metadataKey]??[],migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:")),migrationCount=migrationWarning?Number(migrationWarning.slice(24)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot,mutation:projectLinkedCollectionMutation({collectionKey:metadataKey,stored:artifacts,written:writtenLinkedEntries(before,artifacts),removedCount,fullHistory:options.fullHistory===!0,linkOutcomes})})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result))out[field==="artifacts"?key:field]=value;return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_NOTE_CONFLICT_MODES,LINKED_ARTIFACT_NOTE_JOINER,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,buildNoteConflictError,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,findMisreadNoteSegment,linkedCollectionMutationFields,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseNoteConflictMode,parseRemoveEntries,projectLinkedCollectionMutation,renameArtifactsResultKey,reviseLinkedNote,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,writtenLinkedEntries};
3
3
  //# sourceMappingURL=linked-artifacts.js.map
@@ -81,7 +81,7 @@ export declare function mergeRelationshipEventStreams(baseRaw:string,oursRaw:str
81
81
  * steps carry cross-element ordering invariants that set-union would corrupt,
82
82
  * so they stay under scalar three-way semantics with explicit conflicts.
83
83
  */
84
- export declare const ITEM_UNION_COLLECTION_FIELDS:readonly["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"];
84
+ export declare const ITEM_UNION_COLLECTION_FIELDS:readonly["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events","deferred_fields"];
85
85
  /** Item metadata fields resolved by deterministic latest-timestamp-wins instead of three-way conflict, so disjoint-field edits never conflict on the shared freshness scalar every mutation rewrites. */
86
86
  export declare const ITEM_LATEST_TIMESTAMP_FIELDS:readonly["updated_at"];
87
87
  /** Documents one recoverable scalar decision made during an item merge. */
@@ -1,5 +1,5 @@
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]="425ef2aa-56fa-5d06-b8d0-316373ad2433")}catch{}})();import{cloneEmptyReplayDocument,historyEntriesToRaw,normalizeReplayPatchOps,reanchorHistoryEntries,toReplayDocument,tryApplyReplayPatch}from"../../core/history/replay.js";import jsonPatch from"fast-json-patch";import{rebaseHistoryScalarPatch}from"./history-scalar-rebase.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../../core/item/item-format.js";import{splitAcceptanceCriteria}from"../../core/item/parse.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{PmCliError}from"../../core/shared/errors.js";import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{compareTimestampStrings}from"../../core/shared/time.js";const ITEM_SCALAR_MISSING_VALUE=Object.freeze({pm_item_scalar_missing:!0});function isItemScalarMissingValue(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length===1&&value.pm_item_scalar_missing===!0}function encodeItemScalarDecisionValue(value){return value===void 0?ITEM_SCALAR_MISSING_VALUE:value}function hashItemScalarDecisionValue(value){return sha256Hex(stableStringify(value===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value}))}function parseHistoryJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{const parsed=JSON.parse(line);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new TypeError("history entry must be an object");entries.push(parsed)}catch{throw new PmCliError(`History merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}}return entries}function historyEntryIdentity(entry){return stableStringify({ts:entry.ts,author:entry.author,op:entry.op,patch:entry.patch,message:entry.message??null})}function commonHistoryPrefixLength(ours,theirs){const limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&historyEntryIdentity(ours[shared])===historyEntryIdentity(theirs[shared]);)shared+=1;return shared}function orderHistoryUnionSuffix(ours,theirs,incoming,oursIdentities){const entries=[...ours,...incoming],positions=new Map(entries.map((entry,index)=>[entry,index])),aliases=new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),successors=entries.map(()=>new Set);for(const branch of[ours,theirs]){const coordinates=branch.map(entry=>positions.get(entry)??aliases.get(historyEntryIdentity(entry)));for(let index=1;index<coordinates.length;index+=1)coordinates[index-1]!==coordinates[index]&&successors[coordinates[index-1]].add(coordinates[index])}const predecessors=entries.map(()=>0);for(const targets of successors)for(const target of targets)predecessors[target]+=1;const ready=entries.map((_,index)=>index).filter(index=>predecessors[index]===0),result=[];for(;ready.length>0;){ready.sort((leftIndex,rightIndex)=>{const left=entries[leftIndex],right=entries[rightIndex],byTs=compareTimestampStrings(left.ts,right.ts),leftIdentity=historyEntryIdentity(left),rightIdentity=historyEntryIdentity(right);return byTs||Number(oursIdentities.has(rightIdentity))-Number(oursIdentities.has(leftIdentity))});const index=ready.shift();result.push(entries[index]);for(const target of successors[index])predecessors[target]-=1,predecessors[target]===0&&ready.push(target)}if(result.length!==entries.length)throw new PmCliError("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return result}function createHistoryBranchProjection(entries){return{entries,positions:new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),index:-1,document:cloneEmptyReplayDocument()}}function advanceHistoryBranch(state,target){const end=target??state.index;for(;state.index<end;){const applied=tryApplyReplayPatch(state.document,state.entries[state.index+1].patch);if(!applied.ok)throw new PmCliError("History union cannot preserve a patch that does not apply in its original branch.",EXIT_CODE.GENERIC_FAILURE);state.document=applied.document,state.index+=1}return state.document}function advanceOrderedHistoryBranch(state,target){if(target!==void 0&&target>state.index+1)throw new PmCliError("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return advanceHistoryBranch(state,target)}function historyUnionPatchProjection(ours,theirs,shared){if(shared===0)return;const oursBranch=createHistoryBranchProjection(ours),theirsBranch=createHistoryBranchProjection(theirs),prefix=advanceHistoryBranch(oursBranch,shared-1);advanceHistoryBranch(theirsBranch,shared-1);let position=0;const unionFields=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]);return(entry,current)=>{if(position++<shared)return entry.patch;const identity=historyEntryIdentity(entry),oursState=advanceOrderedHistoryBranch(oursBranch,oursBranch.positions.get(identity)),theirsState=advanceOrderedHistoryBranch(theirsBranch,theirsBranch.positions.get(identity)),scalarPatch=normalizeReplayPatchOps(entry.patch).filter(operation=>{const[root,field]=operation.path.slice(1).split("/");return root!=="metadata"||!unionFields.has(field)}),oursPosition=oursBranch.positions.get(identity),next=rebaseHistoryScalarPatch(current,scalarPatch,{branch:oursPosition===void 0?"theirs":"ours",line:(oursPosition??theirsBranch.positions.get(identity))+1,op:entry.op}),merged=mergeItemMetadataRecords(prefix.metadata,oursState.metadata,theirsState.metadata,"ours","latest_document_update",String(oursState.metadata.updated_at),String(theirsState.metadata.updated_at));for(const field of unionFields)Object.hasOwn(merged.merged,field)?next.metadata[field]=merged.merged[field]:delete next.metadata[field];const canonical=toReplayDocument({metadata:next.metadata,body:next.body});return jsonPatch.compare(current,canonical)}}function mergeHistoryStreams(baseRaw,oursRaw,theirsRaw){const base=parseHistoryJsonl(baseRaw,"base"),ours=parseHistoryJsonl(oursRaw,"ours"),theirs=parseHistoryJsonl(theirsRaw,"theirs"),creates=[base,ours,theirs].map(entries=>entries.filter(entry=>entry.op==="create"));if(creates[0].length===0&&creates.slice(1).every(entries=>entries.length>0)||creates.some(entries=>entries.length>1)||new Set(creates.flat().map(historyEntryIdentity)).size>1)throw new PmCliError("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict"});const shared=commonHistoryPrefixLength(ours,theirs);if(shared===ours.length&&shared===theirs.length)return{merged:historyEntriesToRaw(ours),strategy:"identical",common_entries:shared,entries_from_ours:0,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===theirs.length)return{merged:historyEntriesToRaw(ours),strategy:"fast_forward_ours",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===ours.length)return{merged:historyEntriesToRaw(theirs),strategy:"fast_forward_theirs",common_entries:shared,entries_from_ours:0,entries_from_theirs:theirs.length-shared,entries_total:theirs.length,reanchored:!1};const oursSuffix=ours.slice(shared),seenIdentities=new Set(oursSuffix.map(historyEntryIdentity)),theirsSuffix=theirs.slice(shared).filter(entry=>!seenIdentities.has(historyEntryIdentity(entry))),mergedSuffix=orderHistoryUnionSuffix(oursSuffix,theirs.slice(shared),theirsSuffix,seenIdentities),reanchored=reanchorHistoryEntries([...ours.slice(0,shared),...mergedSuffix],void 0,{continuousHashSurface:!0,projectPatch:historyUnionPatchProjection(ours,theirs,shared)});if(reanchored.skippedOps>0)throw new PmCliError(`History union cannot preserve ${reanchored.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,EXIT_CODE.GENERIC_FAILURE);return{merged:historyEntriesToRaw(reanchored.entries),strategy:"union_reanchor",common_entries:shared,entries_from_ours:oursSuffix.length,entries_from_theirs:theirsSuffix.length,entries_total:reanchored.entries.length,reanchored:!0}}function parseRelationshipJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`Relationship merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const events=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(!line)continue;let parsed;try{parsed=JSON.parse(line)}catch{throw new PmCliError(`Relationship merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)||typeof parsed.eventId!="string"||typeof parsed.sequence!="number")throw new PmCliError(`Relationship merge input (${label}) line ${index+1} is not a relationship event (eventId + sequence required).`,EXIT_CODE.GENERIC_FAILURE);events.push(parsed)}return events}function relationshipEventsToRaw(events){return events.length===0?"":`${events.map(event=>JSON.stringify(event)).join(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0f1f1c8e-c7be-5615-82b8-458d6d2d7812")}catch{}})();import{cloneEmptyReplayDocument,historyEntriesToRaw,normalizeReplayPatchOps,reanchorHistoryEntries,toReplayDocument,tryApplyReplayPatch}from"../../core/history/replay.js";import jsonPatch from"fast-json-patch";import{rebaseHistoryScalarPatch}from"./history-scalar-rebase.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../../core/item/item-format.js";import{splitAcceptanceCriteria}from"../../core/item/parse.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{PmCliError}from"../../core/shared/errors.js";import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{compareTimestampStrings}from"../../core/shared/time.js";import{hasConcreteItemFieldValue}from"../../core/item/deferred-fields.js";const ITEM_SCALAR_MISSING_VALUE=Object.freeze({pm_item_scalar_missing:!0});function isItemScalarMissingValue(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length===1&&value.pm_item_scalar_missing===!0}function encodeItemScalarDecisionValue(value){return value===void 0?ITEM_SCALAR_MISSING_VALUE:value}function hashItemScalarDecisionValue(value){return sha256Hex(stableStringify(value===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value}))}function parseHistoryJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{const parsed=JSON.parse(line);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new TypeError("history entry must be an object");entries.push(parsed)}catch{throw new PmCliError(`History merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}}return entries}function historyEntryIdentity(entry){return stableStringify({ts:entry.ts,author:entry.author,op:entry.op,patch:entry.patch,message:entry.message??null})}function commonHistoryPrefixLength(ours,theirs){const limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&historyEntryIdentity(ours[shared])===historyEntryIdentity(theirs[shared]);)shared+=1;return shared}function orderHistoryUnionSuffix(ours,theirs,incoming,oursIdentities){const entries=[...ours,...incoming],positions=new Map(entries.map((entry,index)=>[entry,index])),aliases=new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),successors=entries.map(()=>new Set);for(const branch of[ours,theirs]){const coordinates=branch.map(entry=>positions.get(entry)??aliases.get(historyEntryIdentity(entry)));for(let index=1;index<coordinates.length;index+=1)coordinates[index-1]!==coordinates[index]&&successors[coordinates[index-1]].add(coordinates[index])}const predecessors=entries.map(()=>0);for(const targets of successors)for(const target of targets)predecessors[target]+=1;const ready=entries.map((_,index)=>index).filter(index=>predecessors[index]===0),result=[];for(;ready.length>0;){ready.sort((leftIndex,rightIndex)=>{const left=entries[leftIndex],right=entries[rightIndex],byTs=compareTimestampStrings(left.ts,right.ts),leftIdentity=historyEntryIdentity(left),rightIdentity=historyEntryIdentity(right);return byTs||Number(oursIdentities.has(rightIdentity))-Number(oursIdentities.has(leftIdentity))});const index=ready.shift();result.push(entries[index]);for(const target of successors[index])predecessors[target]-=1,predecessors[target]===0&&ready.push(target)}if(result.length!==entries.length)throw new PmCliError("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return result}function createHistoryBranchProjection(entries){return{entries,positions:new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),index:-1,document:cloneEmptyReplayDocument()}}function advanceHistoryBranch(state,target){const end=target??state.index;for(;state.index<end;){const applied=tryApplyReplayPatch(state.document,state.entries[state.index+1].patch);if(!applied.ok)throw new PmCliError("History union cannot preserve a patch that does not apply in its original branch.",EXIT_CODE.GENERIC_FAILURE);state.document=applied.document,state.index+=1}return state.document}function advanceOrderedHistoryBranch(state,target){if(target!==void 0&&target>state.index+1)throw new PmCliError("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return advanceHistoryBranch(state,target)}function historyUnionPatchProjection(ours,theirs,shared){if(shared===0)return;const oursBranch=createHistoryBranchProjection(ours),theirsBranch=createHistoryBranchProjection(theirs),prefix=advanceHistoryBranch(oursBranch,shared-1);advanceHistoryBranch(theirsBranch,shared-1);let position=0;const unionFields=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]);return(entry,current)=>{if(position++<shared)return entry.patch;const identity=historyEntryIdentity(entry),oursState=advanceOrderedHistoryBranch(oursBranch,oursBranch.positions.get(identity)),theirsState=advanceOrderedHistoryBranch(theirsBranch,theirsBranch.positions.get(identity)),scalarPatch=normalizeReplayPatchOps(entry.patch).filter(operation=>{const[root,field]=operation.path.slice(1).split("/");return root!=="metadata"||!unionFields.has(field)}),oursPosition=oursBranch.positions.get(identity),next=rebaseHistoryScalarPatch(current,scalarPatch,{branch:oursPosition===void 0?"theirs":"ours",line:(oursPosition??theirsBranch.positions.get(identity))+1,op:entry.op}),merged=mergeItemMetadataRecords(prefix.metadata,oursState.metadata,theirsState.metadata,"ours","latest_document_update",String(oursState.metadata.updated_at),String(theirsState.metadata.updated_at));for(const field of unionFields)Object.hasOwn(merged.merged,field)?next.metadata[field]=merged.merged[field]:delete next.metadata[field];rebaseReplayDeferrals(next.metadata,prefix.metadata,oursState.metadata,theirsState.metadata);const canonical=toReplayDocument({metadata:next.metadata,body:next.body});return jsonPatch.compare(current,canonical)}}function mergeHistoryStreams(baseRaw,oursRaw,theirsRaw){const base=parseHistoryJsonl(baseRaw,"base"),ours=parseHistoryJsonl(oursRaw,"ours"),theirs=parseHistoryJsonl(theirsRaw,"theirs"),creates=[base,ours,theirs].map(entries=>entries.filter(entry=>entry.op==="create"));if(creates[0].length===0&&creates.slice(1).every(entries=>entries.length>0)||creates.some(entries=>entries.length>1)||new Set(creates.flat().map(historyEntryIdentity)).size>1)throw new PmCliError("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict"});const shared=commonHistoryPrefixLength(ours,theirs);if(shared===ours.length&&shared===theirs.length)return{merged:historyEntriesToRaw(ours),strategy:"identical",common_entries:shared,entries_from_ours:0,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===theirs.length)return{merged:historyEntriesToRaw(ours),strategy:"fast_forward_ours",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===ours.length)return{merged:historyEntriesToRaw(theirs),strategy:"fast_forward_theirs",common_entries:shared,entries_from_ours:0,entries_from_theirs:theirs.length-shared,entries_total:theirs.length,reanchored:!1};const oursSuffix=ours.slice(shared),seenIdentities=new Set(oursSuffix.map(historyEntryIdentity)),theirsSuffix=theirs.slice(shared).filter(entry=>!seenIdentities.has(historyEntryIdentity(entry))),mergedSuffix=orderHistoryUnionSuffix(oursSuffix,theirs.slice(shared),theirsSuffix,seenIdentities),reanchored=reanchorHistoryEntries([...ours.slice(0,shared),...mergedSuffix],void 0,{continuousHashSurface:!0,projectPatch:historyUnionPatchProjection(ours,theirs,shared)});if(reanchored.skippedOps>0)throw new PmCliError(`History union cannot preserve ${reanchored.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,EXIT_CODE.GENERIC_FAILURE);return{merged:historyEntriesToRaw(reanchored.entries),strategy:"union_reanchor",common_entries:shared,entries_from_ours:oursSuffix.length,entries_from_theirs:theirsSuffix.length,entries_total:reanchored.entries.length,reanchored:!0}}function parseRelationshipJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`Relationship merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const events=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(!line)continue;let parsed;try{parsed=JSON.parse(line)}catch{throw new PmCliError(`Relationship merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)||typeof parsed.eventId!="string"||typeof parsed.sequence!="number")throw new PmCliError(`Relationship merge input (${label}) line ${index+1} is not a relationship event (eventId + sequence required).`,EXIT_CODE.GENERIC_FAILURE);events.push(parsed)}return events}function relationshipEventsToRaw(events){return events.length===0?"":`${events.map(event=>JSON.stringify(event)).join(`
2
2
  `)}
3
- `}function renumberRelationshipEvents(events){return events.map((event,index)=>({...event,sequence:index+1}))}function mergeRelationshipEventStreams(baseRaw,oursRaw,theirsRaw){parseRelationshipJsonl(baseRaw,"base");const ours=parseRelationshipJsonl(oursRaw,"ours"),theirs=parseRelationshipJsonl(theirsRaw,"theirs"),limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&ours[shared].eventId===theirs[shared].eventId;)shared+=1;if(shared===ours.length&&shared===theirs.length)return{merged:relationshipEventsToRaw(ours),strategy:"identical",common_entries:shared,entries_from_ours:0,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===theirs.length)return{merged:relationshipEventsToRaw(ours),strategy:"fast_forward_ours",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===ours.length)return{merged:relationshipEventsToRaw(theirs),strategy:"fast_forward_theirs",common_entries:shared,entries_from_ours:0,entries_from_theirs:theirs.length-shared,entries_total:theirs.length,reanchored:!1};const oursSuffix=ours.slice(shared),oursEventIds=new Set(oursSuffix.map(event=>event.eventId)),theirsSuffix=theirs.slice(shared).filter(event=>!oursEventIds.has(event.eventId)),mergedSuffix=[...oursSuffix,...theirsSuffix].sort((left,right)=>{if(left.timestamp!==void 0&&right.timestamp!==void 0){const byTs=compareTimestampStrings(left.timestamp,right.timestamp);if(byTs!==0)return byTs}else{if(left.timestamp===void 0&&right.timestamp!==void 0)return 1;if(left.timestamp!==void 0)return-1}const leftFromOurs=oursEventIds.has(left.eventId),rightFromOurs=oursEventIds.has(right.eventId);return leftFromOurs!==rightFromOurs?Number(rightFromOurs)-Number(leftFromOurs):0}),merged=renumberRelationshipEvents([...ours.slice(0,shared),...mergedSuffix]);return{merged:relationshipEventsToRaw(merged),strategy:"union_reanchor",common_entries:shared,entries_from_ours:oursSuffix.length,entries_from_theirs:theirsSuffix.length,entries_total:merged.length,reanchored:!0}}const ITEM_UNION_COLLECTION_FIELDS=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],ITEM_UNION_DELIMITED_FIELDS=["acceptance_criteria"],ITEM_LATEST_TIMESTAMP_FIELDS=["updated_at"];function jsonEquals(left,right){return left===void 0||right===void 0?left===void 0&&right===void 0:stableStringify(left)===stableStringify(right)}function unionCollection(base,ours,theirs){const toEntries=value=>Array.isArray(value)?value:[],baseIds=new Set(toEntries(base).map(entry=>stableStringify(entry))),oursEntries=toEntries(ours),oursIds=new Set(oursEntries.map(entry=>stableStringify(entry))),theirsEntries=toEntries(theirs),theirsIds=new Set(theirsEntries.map(entry=>stableStringify(entry))),merged=oursEntries.filter(entry=>{const identity=stableStringify(entry);return!baseIds.has(identity)||theirsIds.has(identity)});for(const entry of theirsEntries){const identity=stableStringify(entry);!oursIds.has(identity)&&!baseIds.has(identity)&&merged.push(entry)}return merged}function linkedTestDefinitionIdentity(value){if(typeof value!="object"||value===null||Array.isArray(value))return stableStringify(value);const{provenance:_provenance,...definition}=value;return stableStringify(definition)}function markMergedLinkedTest(value){if(typeof value!="object"||value===null||Array.isArray(value))return value;const test=value;return test.provenance?{...test,provenance:{...test.provenance,source_kind:"merge_union"}}:{...test,provenance:{source_kind:"merge_union"}}}function unionLinkedTests(base,ours,theirs){const toEntries=value=>Array.isArray(value)?value:[],baseIds=new Set(toEntries(base).map(linkedTestDefinitionIdentity)),oursEntries=toEntries(ours),oursIds=new Set(oursEntries.map(linkedTestDefinitionIdentity)),theirsEntries=toEntries(theirs),theirsIds=new Set(theirsEntries.map(linkedTestDefinitionIdentity)),merged=oursEntries.filter(entry=>{const identity=linkedTestDefinitionIdentity(entry);return!baseIds.has(identity)||theirsIds.has(identity)});for(const entry of theirsEntries){const identity=linkedTestDefinitionIdentity(entry);!oursIds.has(identity)&&!baseIds.has(identity)&&merged.push(markMergedLinkedTest(entry))}return merged}function latestTimestamp(ours,theirs){return compareTimestampStrings(String(ours),String(theirs))>=0?ours:theirs}function mergeScalarThreeWay(base,ours,theirs,preferred){return jsonEquals(ours,theirs)?{value:ours,from_theirs:!1,conflict:!1}:jsonEquals(base,ours)?{value:theirs,from_theirs:!0,conflict:!1}:jsonEquals(base,theirs)?{value:ours,from_theirs:!1,conflict:!1}:{value:preferred==="theirs"?theirs:ours,from_theirs:preferred==="theirs",conflict:!0}}function mergeItemScalarThreeWay(base,ours,theirs,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt){const outcome=mergeScalarThreeWay(base,ours,theirs,preferred);if(!outcome.conflict)return{...outcome,conflict:!1};if(conflictResolution==="preferred_side")return{...outcome,resolution_basis:"requested_preference",retained_side:outcome.from_theirs?"theirs":"ours"};const timestampOrder=compareTimestampStrings(oursUpdatedAt,theirsUpdatedAt);if(conflictResolution==="latest_document_update"&&timestampOrder!==0){const retainTheirs2=timestampOrder<0;return{value:retainTheirs2?theirs:ours,from_theirs:retainTheirs2,conflict:!0,resolution_basis:"document_updated_at",retained_side:retainTheirs2?"theirs":"ours"}}const retainTheirs=stableStringify(encodeItemScalarDecisionValue(theirs)).localeCompare(stableStringify(encodeItemScalarDecisionValue(ours)))<0;return{value:retainTheirs?theirs:ours,from_theirs:retainTheirs,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:retainTheirs?"theirs":"ours"}}function toMetadataRecord(document){return{...document.metadata}}function parseItemMergeSide(raw,label,options){try{const document=canonicalDocument(parseItemDocument(raw,{...options,requireSupportedFormat:!0}),options),reservedField=Object.entries(document.metadata).find(([,value])=>isItemScalarMissingValue(value))?.[0];if(reservedField!==void 0)throw new TypeError(`metadata field ${reservedField} uses the reserved missing-scalar evidence marker`);return document}catch(error){throw error instanceof PmCliError&&error.context?.code==="item_format_version_unsupported"?error:new PmCliError(`Item merge input (${label}) is not a readable item document: ${String(error)}`,EXIT_CODE.GENERIC_FAILURE)}}function mergeItemUnionField(params){if(!params.unionFieldSet.has(params.field))return!1;const union=params.field==="tests"?unionLinkedTests(params.baseValue,params.oursValue,params.theirsValue):params.field==="acceptance_criteria"?unionCollection(splitAcceptanceCriteria(params.baseValue),splitAcceptanceCriteria(params.oursValue),splitAcceptanceCriteria(params.theirsValue)).join("; "):unionCollection(params.baseValue,params.oursValue,params.theirsValue);return params.accumulator.merged[params.field]=union,jsonEquals(union,params.oursValue)||params.accumulator.unionFields.push(params.field),!0}function mergeItemScalarField(params){const outcome=mergeItemScalarThreeWay(params.baseValue,params.oursValue,params.theirsValue,params.preferred,params.conflictResolution,params.oursUpdatedAt,params.theirsUpdatedAt);outcome.value!==void 0&&(params.accumulator.merged[params.field]=outcome.value),outcome.conflict?(params.accumulator.conflictFields.push(params.field),params.accumulator.conflictDecisions.push({field:params.field,base:encodeItemScalarDecisionValue(params.baseValue),ours:encodeItemScalarDecisionValue(params.oursValue),theirs:encodeItemScalarDecisionValue(params.theirsValue),retained:encodeItemScalarDecisionValue(outcome.value),discarded:encodeItemScalarDecisionValue(outcome.from_theirs?params.oursValue:params.theirsValue),retained_side:outcome.retained_side,resolution_basis:outcome.resolution_basis})):outcome.from_theirs&&params.accumulator.fieldsFromTheirs.push(params.field)}function mergeItemMetadataRecords(baseRecord,oursRecord,theirsRecord,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt){const unionFieldSet=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]),latestFieldSet=new Set(ITEM_LATEST_TIMESTAMP_FIELDS),fieldNames=[...new Set([...Object.keys(oursRecord),...Object.keys(theirsRecord)])].sort((left,right)=>left.localeCompare(right)),accumulator={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(const field of fieldNames){const baseValue=baseRecord[field],oursValue=oursRecord[field],theirsValue=theirsRecord[field];if(!mergeItemUnionField({field,baseValue,oursValue,theirsValue,unionFieldSet,accumulator})){if(latestFieldSet.has(field)){accumulator.merged[field]=latestTimestamp(oursValue,theirsValue);continue}mergeItemScalarField({field,baseValue,oursValue,theirsValue,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt,accumulator})}}return accumulator}function mergeItemDocuments(baseRaw,oursRaw,theirsRaw,options={}){const preferred=options.preferred??"ours",conflictResolution=options.conflictResolution??"preferred_side",ours=parseItemMergeSide(oursRaw,"ours",options),theirs=parseItemMergeSide(theirsRaw,"theirs",options);if(baseRaw.trim().length===0)throw new PmCliError("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:ours.metadata.id});const base=parseItemMergeSide(baseRaw,"base",options);if(base.metadata.id!==ours.metadata.id||base.metadata.id!==theirs.metadata.id)throw new PmCliError("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:base.metadata.id});const baseRecord=toMetadataRecord(base),oursRecord=toMetadataRecord(ours),theirsRecord=toMetadataRecord(theirs),{merged,conflictFields,fieldsFromTheirs,unionFields,conflictDecisions}=mergeItemMetadataRecords(baseRecord,oursRecord,theirsRecord,preferred,conflictResolution,ours.metadata.updated_at,theirs.metadata.updated_at),bodyOutcome=mergeItemScalarThreeWay(base.body,ours.body,theirs.body,preferred,conflictResolution,ours.metadata.updated_at,theirs.metadata.updated_at);bodyOutcome.conflict?(conflictFields.push("body"),conflictDecisions.push({field:"body",base:encodeItemScalarDecisionValue(base.body),ours:encodeItemScalarDecisionValue(ours.body),theirs:encodeItemScalarDecisionValue(theirs.body),retained:encodeItemScalarDecisionValue(bodyOutcome.value),discarded:encodeItemScalarDecisionValue(bodyOutcome.from_theirs?ours.body:theirs.body),retained_side:bodyOutcome.retained_side,resolution_basis:bodyOutcome.resolution_basis})):bodyOutcome.from_theirs&&fieldsFromTheirs.push("body");const mergedMetadata=merged;return mergedMetadata.pm_format_version=normalizeItemFormatVersion(Math.max(...[base.metadata,ours.metadata,theirs.metadata,mergedMetadata].map(requiredItemFormatVersion))),{merged:serializeItemDocument({metadata:mergedMetadata,body:bodyOutcome.value},options),conflict_fields:conflictFields,fields_from_theirs:fieldsFromTheirs,union_fields:unionFields,conflict_decisions:conflictDecisions,requested_preference:preferred,requested_preference_applied:conflictResolution==="preferred_side",conflict_resolution:conflictResolution}}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseJsonSide(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`JSON merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}.`,EXIT_CODE.GENERIC_FAILURE);if(raw.trim().length!==0)try{return JSON.parse(raw)}catch{throw new PmCliError(`JSON merge input (${label}) is not valid JSON.`,EXIT_CODE.GENERIC_FAILURE)}}function mergeAdditiveJsonArrays(base,ours,theirs){if(!Array.isArray(base)||!Array.isArray(ours)||!Array.isArray(theirs))return null;const countEntries=entries=>{const counts=new Map;for(const entry of entries){const identity=stableStringify(entry);counts.set(identity,(counts.get(identity)??0)+1)}return counts},baseCounts=countEntries(base),oursCounts=countEntries(ours),theirsCounts=countEntries(theirs);for(const[identity,baseCount]of baseCounts)if((oursCounts.get(identity)??0)<baseCount||(theirsCounts.get(identity)??0)<baseCount)return null;const unmatchedOursCounts=new Map(oursCounts),additionsFromTheirs=[];for(const entry of theirs){const identity=stableStringify(entry),unmatchedOursCount=unmatchedOursCounts.get(identity)??0;unmatchedOursCount>0?unmatchedOursCounts.set(identity,unmatchedOursCount-1):additionsFromTheirs.push(entry)}return{merged:[...ours,...additionsFromTheirs],acceptedTheirs:additionsFromTheirs.length>0}}function mergeJsonObjects(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs){if(!isPlainObject(ours)||!isPlainObject(theirs))return null;const baseObject=isPlainObject(base)?base:{},merged={},keys=[...new Set([...Object.keys(ours),...Object.keys(theirs)])].sort((left,right)=>left.localeCompare(right));for(const key of keys){const childPath=pathPrefix.length>0?`${pathPrefix}.${key}`:key,child=mergeJsonKey(baseObject,ours,theirs,key,preferred,childPath,conflictPaths,pathsFromTheirs);child!==void 0&&(merged[key]=child)}return merged}function mergeJsonValue(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs){if(jsonEquals(ours,theirs))return ours;const additiveArrayMerge=mergeAdditiveJsonArrays(base,ours,theirs);if(additiveArrayMerge!==null)return additiveArrayMerge.acceptedTheirs&&pathsFromTheirs.push(pathPrefix),additiveArrayMerge.merged;const mergedObject=mergeJsonObjects(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs);if(mergedObject!==null)return mergedObject;const outcome=mergeScalarThreeWay(base,ours,theirs,preferred);return outcome.conflict?conflictPaths.push(pathPrefix):outcome.from_theirs&&pathsFromTheirs.push(pathPrefix),outcome.value}function mergeJsonKey(base,ours,theirs,key,preferred,childPath,conflictPaths,pathsFromTheirs){const inOurs=Object.prototype.hasOwnProperty.call(ours,key),inTheirs=Object.prototype.hasOwnProperty.call(theirs,key),inBase=Object.prototype.hasOwnProperty.call(base,key);if(inOurs&&inTheirs)return mergeJsonValue(base[key],ours[key],theirs[key],preferred,childPath,conflictPaths,pathsFromTheirs);if(inOurs){if(inBase&&jsonEquals(base[key],ours[key])){pathsFromTheirs.push(childPath);return}return inBase?(conflictPaths.push(childPath),preferred==="theirs"?void 0:ours[key]):ours[key]}if(!(inBase&&jsonEquals(base[key],theirs[key])))return inBase?(conflictPaths.push(childPath),preferred==="theirs"?theirs[key]:void 0):(pathsFromTheirs.push(childPath),theirs[key])}function mergeJsonDocuments(baseRaw,oursRaw,theirsRaw,options={}){const preferred=options.preferred??"ours",base=parseJsonSide(baseRaw,"base"),ours=parseJsonSide(oursRaw,"ours"),theirs=parseJsonSide(theirsRaw,"theirs"),conflictPaths=[],pathsFromTheirs=[],merged=mergeJsonValue(base,ours,theirs,preferred,"",conflictPaths,pathsFromTheirs);return{merged:`${JSON.stringify(merged??null,null,2)}
3
+ `}function renumberRelationshipEvents(events){return events.map((event,index)=>({...event,sequence:index+1}))}function mergeRelationshipEventStreams(baseRaw,oursRaw,theirsRaw){parseRelationshipJsonl(baseRaw,"base");const ours=parseRelationshipJsonl(oursRaw,"ours"),theirs=parseRelationshipJsonl(theirsRaw,"theirs"),limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&ours[shared].eventId===theirs[shared].eventId;)shared+=1;if(shared===ours.length&&shared===theirs.length)return{merged:relationshipEventsToRaw(ours),strategy:"identical",common_entries:shared,entries_from_ours:0,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===theirs.length)return{merged:relationshipEventsToRaw(ours),strategy:"fast_forward_ours",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===ours.length)return{merged:relationshipEventsToRaw(theirs),strategy:"fast_forward_theirs",common_entries:shared,entries_from_ours:0,entries_from_theirs:theirs.length-shared,entries_total:theirs.length,reanchored:!1};const oursSuffix=ours.slice(shared),oursEventIds=new Set(oursSuffix.map(event=>event.eventId)),theirsSuffix=theirs.slice(shared).filter(event=>!oursEventIds.has(event.eventId)),mergedSuffix=[...oursSuffix,...theirsSuffix].sort((left,right)=>{if(left.timestamp!==void 0&&right.timestamp!==void 0){const byTs=compareTimestampStrings(left.timestamp,right.timestamp);if(byTs!==0)return byTs}else{if(left.timestamp===void 0&&right.timestamp!==void 0)return 1;if(left.timestamp!==void 0)return-1}const leftFromOurs=oursEventIds.has(left.eventId),rightFromOurs=oursEventIds.has(right.eventId);return leftFromOurs!==rightFromOurs?Number(rightFromOurs)-Number(leftFromOurs):0}),merged=renumberRelationshipEvents([...ours.slice(0,shared),...mergedSuffix]);return{merged:relationshipEventsToRaw(merged),strategy:"union_reanchor",common_entries:shared,entries_from_ours:oursSuffix.length,entries_from_theirs:theirsSuffix.length,entries_total:merged.length,reanchored:!0}}const ITEM_UNION_COLLECTION_FIELDS=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events","deferred_fields"],ITEM_UNION_DELIMITED_FIELDS=["acceptance_criteria"],ITEM_LATEST_TIMESTAMP_FIELDS=["updated_at"];function jsonEquals(left,right){return left===void 0||right===void 0?left===void 0&&right===void 0:stableStringify(left)===stableStringify(right)}function unionCollection(base,ours,theirs){const toEntries=value=>Array.isArray(value)?value:[],baseIds=new Set(toEntries(base).map(entry=>stableStringify(entry))),oursEntries=toEntries(ours),oursIds=new Set(oursEntries.map(entry=>stableStringify(entry))),theirsEntries=toEntries(theirs),theirsIds=new Set(theirsEntries.map(entry=>stableStringify(entry))),merged=oursEntries.filter(entry=>{const identity=stableStringify(entry);return!baseIds.has(identity)||theirsIds.has(identity)});for(const entry of theirsEntries){const identity=stableStringify(entry);!oursIds.has(identity)&&!baseIds.has(identity)&&merged.push(entry)}return merged}function linkedTestDefinitionIdentity(value){if(typeof value!="object"||value===null||Array.isArray(value))return stableStringify(value);const{provenance:_provenance,...definition}=value;return stableStringify(definition)}function markMergedLinkedTest(value){if(typeof value!="object"||value===null||Array.isArray(value))return value;const test=value;return test.provenance?{...test,provenance:{...test.provenance,source_kind:"merge_union"}}:{...test,provenance:{source_kind:"merge_union"}}}function unionLinkedTests(base,ours,theirs){const toEntries=value=>Array.isArray(value)?value:[],baseIds=new Set(toEntries(base).map(linkedTestDefinitionIdentity)),oursEntries=toEntries(ours),oursIds=new Set(oursEntries.map(linkedTestDefinitionIdentity)),theirsEntries=toEntries(theirs),theirsIds=new Set(theirsEntries.map(linkedTestDefinitionIdentity)),merged=oursEntries.filter(entry=>{const identity=linkedTestDefinitionIdentity(entry);return!baseIds.has(identity)||theirsIds.has(identity)});for(const entry of theirsEntries){const identity=linkedTestDefinitionIdentity(entry);!oursIds.has(identity)&&!baseIds.has(identity)&&merged.push(markMergedLinkedTest(entry))}return merged}function latestTimestamp(ours,theirs){return compareTimestampStrings(String(ours),String(theirs))>=0?ours:theirs}function mergeScalarThreeWay(base,ours,theirs,preferred){return jsonEquals(ours,theirs)?{value:ours,from_theirs:!1,conflict:!1}:jsonEquals(base,ours)?{value:theirs,from_theirs:!0,conflict:!1}:jsonEquals(base,theirs)?{value:ours,from_theirs:!1,conflict:!1}:{value:preferred==="theirs"?theirs:ours,from_theirs:preferred==="theirs",conflict:!0}}function mergeItemScalarThreeWay(base,ours,theirs,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt){const outcome=mergeScalarThreeWay(base,ours,theirs,preferred);if(!outcome.conflict)return{...outcome,conflict:!1};if(conflictResolution==="preferred_side")return{...outcome,resolution_basis:"requested_preference",retained_side:outcome.from_theirs?"theirs":"ours"};const timestampOrder=compareTimestampStrings(oursUpdatedAt,theirsUpdatedAt);if(conflictResolution==="latest_document_update"&&timestampOrder!==0){const retainTheirs2=timestampOrder<0;return{value:retainTheirs2?theirs:ours,from_theirs:retainTheirs2,conflict:!0,resolution_basis:"document_updated_at",retained_side:retainTheirs2?"theirs":"ours"}}const retainTheirs=stableStringify(encodeItemScalarDecisionValue(theirs)).localeCompare(stableStringify(encodeItemScalarDecisionValue(ours)))<0;return{value:retainTheirs?theirs:ours,from_theirs:retainTheirs,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:retainTheirs?"theirs":"ours"}}function toMetadataRecord(document){return{...document.metadata}}function parseItemMergeSide(raw,label,options){try{const document=canonicalDocument(parseItemDocument(raw,{...options,requireSupportedFormat:!0}),options),reservedField=Object.entries(document.metadata).find(([,value])=>isItemScalarMissingValue(value))?.[0];if(reservedField!==void 0)throw new TypeError(`metadata field ${reservedField} uses the reserved missing-scalar evidence marker`);return document}catch(error){throw error instanceof PmCliError&&error.context?.code==="item_format_version_unsupported"?error:new PmCliError(`Item merge input (${label}) is not a readable item document: ${String(error)}`,EXIT_CODE.GENERIC_FAILURE)}}function mergeUnionFieldValue(field,base,ours,theirs){return field==="tests"?unionLinkedTests(base,ours,theirs):field==="deferred_fields"?unionDeferredFields(base,ours,theirs):field==="acceptance_criteria"?unionCollection(splitAcceptanceCriteria(base),splitAcceptanceCriteria(ours),splitAcceptanceCriteria(theirs)).join("; "):unionCollection(base,ours,theirs)}function unionDeferredFields(base,ours,theirs){const byField=value=>new Map((Array.isArray(value)?value:[]).map(entry=>[String(entry.field),entry])),[baseEntries,oursEntries,theirsEntries]=[byField(base),byField(ours),byField(theirs)],merged=[];for(const field of[...new Set([...oursEntries.keys(),...theirsEntries.keys()])].sort()){const[baseEntry,oursEntry,theirsEntry]=[baseEntries.get(field),oursEntries.get(field),theirsEntries.get(field)];if(oursEntry===void 0||theirsEntry===void 0){merged.push(oursEntry??theirsEntry);continue}const outcome=mergeScalarThreeWay(baseEntry,oursEntry,theirsEntry,"ours");merged.push(outcome.conflict&&stableStringify(theirsEntry).localeCompare(stableStringify(oursEntry))<0?theirsEntry:outcome.value)}return merged}function mergeItemUnionField(params){if(!params.unionFieldSet.has(params.field))return!1;const union=mergeUnionFieldValue(params.field,params.baseValue,params.oursValue,params.theirsValue);return params.accumulator.merged[params.field]=union,jsonEquals(union,params.oursValue)||params.accumulator.unionFields.push(params.field),!0}function mergeItemScalarField(params){const outcome=mergeItemScalarThreeWay(params.baseValue,params.oursValue,params.theirsValue,params.preferred,params.conflictResolution,params.oursUpdatedAt,params.theirsUpdatedAt);outcome.value!==void 0&&(params.accumulator.merged[params.field]=outcome.value),outcome.conflict?(params.accumulator.conflictFields.push(params.field),params.accumulator.conflictDecisions.push({field:params.field,base:encodeItemScalarDecisionValue(params.baseValue),ours:encodeItemScalarDecisionValue(params.oursValue),theirs:encodeItemScalarDecisionValue(params.theirsValue),retained:encodeItemScalarDecisionValue(outcome.value),discarded:encodeItemScalarDecisionValue(outcome.from_theirs?params.oursValue:params.theirsValue),retained_side:outcome.retained_side,resolution_basis:outcome.resolution_basis})):outcome.from_theirs&&params.accumulator.fieldsFromTheirs.push(params.field)}function mergeItemMetadataRecords(baseRecord,oursRecord,theirsRecord,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt){const unionFieldSet=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]),latestFieldSet=new Set(ITEM_LATEST_TIMESTAMP_FIELDS),fieldNames=[...new Set([...Object.keys(oursRecord),...Object.keys(theirsRecord)])].sort((left,right)=>left.localeCompare(right)),accumulator={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(const field of fieldNames){const baseValue=baseRecord[field],oursValue=oursRecord[field],theirsValue=theirsRecord[field];if(!mergeItemUnionField({field,baseValue,oursValue,theirsValue,unionFieldSet,accumulator})){if(latestFieldSet.has(field)){accumulator.merged[field]=latestTimestamp(oursValue,theirsValue);continue}mergeItemScalarField({field,baseValue,oursValue,theirsValue,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt,accumulator})}}return reconcileMergedDeferrals(accumulator.merged),accumulator}function rebaseReplayDeferrals(replay,base,ours,theirs){const union=unionDeferredFields(base.deferred_fields,ours.deferred_fields,theirs.deferred_fields);replay.deferred_fields=union,reconcileMergedDeferrals(replay),replay.deferred_fields.length===0&&delete replay.deferred_fields}function reconcileMergedDeferrals(merged){Array.isArray(merged.deferred_fields)&&(merged.deferred_fields=merged.deferred_fields.filter(entry=>!hasConcreteItemFieldValue(merged,String(entry.field))))}function mergeItemDocuments(baseRaw,oursRaw,theirsRaw,options={}){const preferred=options.preferred??"ours",conflictResolution=options.conflictResolution??"preferred_side",ours=parseItemMergeSide(oursRaw,"ours",options),theirs=parseItemMergeSide(theirsRaw,"theirs",options);if(baseRaw.trim().length===0)throw new PmCliError("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:ours.metadata.id});const base=parseItemMergeSide(baseRaw,"base",options);if(base.metadata.id!==ours.metadata.id||base.metadata.id!==theirs.metadata.id)throw new PmCliError("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:base.metadata.id});const baseRecord=toMetadataRecord(base),oursRecord=toMetadataRecord(ours),theirsRecord=toMetadataRecord(theirs),{merged,conflictFields,fieldsFromTheirs,unionFields,conflictDecisions}=mergeItemMetadataRecords(baseRecord,oursRecord,theirsRecord,preferred,conflictResolution,ours.metadata.updated_at,theirs.metadata.updated_at),bodyOutcome=mergeItemScalarThreeWay(base.body,ours.body,theirs.body,preferred,conflictResolution,ours.metadata.updated_at,theirs.metadata.updated_at);bodyOutcome.conflict?(conflictFields.push("body"),conflictDecisions.push({field:"body",base:encodeItemScalarDecisionValue(base.body),ours:encodeItemScalarDecisionValue(ours.body),theirs:encodeItemScalarDecisionValue(theirs.body),retained:encodeItemScalarDecisionValue(bodyOutcome.value),discarded:encodeItemScalarDecisionValue(bodyOutcome.from_theirs?ours.body:theirs.body),retained_side:bodyOutcome.retained_side,resolution_basis:bodyOutcome.resolution_basis})):bodyOutcome.from_theirs&&fieldsFromTheirs.push("body");const mergedMetadata=merged;return mergedMetadata.pm_format_version=normalizeItemFormatVersion(Math.max(...[base.metadata,ours.metadata,theirs.metadata,mergedMetadata].map(requiredItemFormatVersion))),{merged:serializeItemDocument({metadata:mergedMetadata,body:bodyOutcome.value},options),conflict_fields:conflictFields,fields_from_theirs:fieldsFromTheirs,union_fields:unionFields,conflict_decisions:conflictDecisions,requested_preference:preferred,requested_preference_applied:conflictResolution==="preferred_side",conflict_resolution:conflictResolution}}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseJsonSide(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`JSON merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}.`,EXIT_CODE.GENERIC_FAILURE);if(raw.trim().length!==0)try{return JSON.parse(raw)}catch{throw new PmCliError(`JSON merge input (${label}) is not valid JSON.`,EXIT_CODE.GENERIC_FAILURE)}}function mergeAdditiveJsonArrays(base,ours,theirs){if(!Array.isArray(base)||!Array.isArray(ours)||!Array.isArray(theirs))return null;const countEntries=entries=>{const counts=new Map;for(const entry of entries){const identity=stableStringify(entry);counts.set(identity,(counts.get(identity)??0)+1)}return counts},baseCounts=countEntries(base),oursCounts=countEntries(ours),theirsCounts=countEntries(theirs);for(const[identity,baseCount]of baseCounts)if((oursCounts.get(identity)??0)<baseCount||(theirsCounts.get(identity)??0)<baseCount)return null;const unmatchedOursCounts=new Map(oursCounts),additionsFromTheirs=[];for(const entry of theirs){const identity=stableStringify(entry),unmatchedOursCount=unmatchedOursCounts.get(identity)??0;unmatchedOursCount>0?unmatchedOursCounts.set(identity,unmatchedOursCount-1):additionsFromTheirs.push(entry)}return{merged:[...ours,...additionsFromTheirs],acceptedTheirs:additionsFromTheirs.length>0}}function mergeJsonObjects(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs){if(!isPlainObject(ours)||!isPlainObject(theirs))return null;const baseObject=isPlainObject(base)?base:{},merged={},keys=[...new Set([...Object.keys(ours),...Object.keys(theirs)])].sort((left,right)=>left.localeCompare(right));for(const key of keys){const childPath=pathPrefix.length>0?`${pathPrefix}.${key}`:key,child=mergeJsonKey(baseObject,ours,theirs,key,preferred,childPath,conflictPaths,pathsFromTheirs);child!==void 0&&(merged[key]=child)}return merged}function mergeJsonValue(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs){if(jsonEquals(ours,theirs))return ours;const additiveArrayMerge=mergeAdditiveJsonArrays(base,ours,theirs);if(additiveArrayMerge!==null)return additiveArrayMerge.acceptedTheirs&&pathsFromTheirs.push(pathPrefix),additiveArrayMerge.merged;const mergedObject=mergeJsonObjects(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs);if(mergedObject!==null)return mergedObject;const outcome=mergeScalarThreeWay(base,ours,theirs,preferred);return outcome.conflict?conflictPaths.push(pathPrefix):outcome.from_theirs&&pathsFromTheirs.push(pathPrefix),outcome.value}function mergeJsonKey(base,ours,theirs,key,preferred,childPath,conflictPaths,pathsFromTheirs){const inOurs=Object.prototype.hasOwnProperty.call(ours,key),inTheirs=Object.prototype.hasOwnProperty.call(theirs,key),inBase=Object.prototype.hasOwnProperty.call(base,key);if(inOurs&&inTheirs)return mergeJsonValue(base[key],ours[key],theirs[key],preferred,childPath,conflictPaths,pathsFromTheirs);if(inOurs){if(inBase&&jsonEquals(base[key],ours[key])){pathsFromTheirs.push(childPath);return}return inBase?(conflictPaths.push(childPath),preferred==="theirs"?void 0:ours[key]):ours[key]}if(!(inBase&&jsonEquals(base[key],theirs[key])))return inBase?(conflictPaths.push(childPath),preferred==="theirs"?theirs[key]:void 0):(pathsFromTheirs.push(childPath),theirs[key])}function mergeJsonDocuments(baseRaw,oursRaw,theirsRaw,options={}){const preferred=options.preferred??"ours",base=parseJsonSide(baseRaw,"base"),ours=parseJsonSide(oursRaw,"ours"),theirs=parseJsonSide(theirsRaw,"theirs"),conflictPaths=[],pathsFromTheirs=[],merged=mergeJsonValue(base,ours,theirs,preferred,"",conflictPaths,pathsFromTheirs);return{merged:`${JSON.stringify(merged??null,null,2)}
4
4
  `,conflict_paths:conflictPaths,paths_from_theirs:pathsFromTheirs,preferred}}export{ITEM_LATEST_TIMESTAMP_FIELDS,ITEM_SCALAR_MISSING_VALUE,ITEM_UNION_COLLECTION_FIELDS,encodeItemScalarDecisionValue,hashItemScalarDecisionValue,isItemScalarMissingValue,mergeHistoryStreams,mergeItemDocuments,mergeJsonDocuments,mergeRelationshipEventStreams};
5
5
  //# sourceMappingURL=three-way.js.map
@@ -24,6 +24,20 @@ null_column_index?:number[];
24
24
  column_order?:string[];
25
25
  /** Missing field coordinates, expressed as [zero-based row, column name]. */
26
26
  absent:Array<[number,string]>;}
27
+ /**
28
+ * An encoding block in the form the TOON host renders it (GH-1684). Empty
29
+ * `json_columns` and `absent` arrays are left out, and missing cells are
30
+ * grouped by column in `absent_rows`, so consumers recognize the block by its
31
+ * reserved `<collection>_encoding` key rather than by the arrays it carries.
32
+ * {@link decodePmTableRows} accepts this form and every earlier one.
33
+ */
34
+ export interface PmRenderedTableCellEncoding extends Omit<PmTableCellEncoding,"json_columns"|"absent">{
35
+ /** Columns whose every present cell contains a JSON-serialized value; omitted when none. */
36
+ json_columns?:string[];
37
+ /** Missing field coordinates as [zero-based row, column name] pairs, as earlier releases rendered them. */
38
+ absent?:Array<[number,string]>;
39
+ /** Missing field coordinates grouped by column: column name to its zero-based row indexes. */
40
+ absent_rows?:Record<string,number[]>;}
27
41
  /** Primitive rows accepted by the standard TOON tabular encoder. */
28
42
  export interface PmEncodedTableRows{
29
43
  /** Key-hoisted rows with primitive cells and null padding for absent keys. */
@@ -40,8 +54,18 @@ encoding:PmTableCellEncoding;}
40
54
  */
41
55
  export declare function encodePmTableRows(rows:readonly Record<string,JsonValue>[],options?:{compact?:boolean;}):PmEncodedTableRows;
42
56
  /**
43
- * Restore rows emitted by {@link encodePmTableRows}. Metadata is explicit, so
44
- * strings resembling JSON stay strings unless their column declares JSON.
45
- * Malformed JSON cells throw instead of silently changing their meaning.
57
+ * Project an encoding for TOON delivery without losing a fact: empty
58
+ * `json_columns` and `absent` arrays are dropped, and absent coordinates are
59
+ * grouped by column. Grouping writes each column name once, so it is smaller
60
+ * whenever a column misses more than one cell, which is the shape of sparse
61
+ * focus rows such as unblocked `pm context` rows.
62
+ */
63
+ export declare function projectPmTableEncodingForToon(encoding:PmTableCellEncoding):PmRenderedTableCellEncoding;
64
+ /**
65
+ * Restore rows emitted by {@link encodePmTableRows}, including the TOON form
66
+ * that omits empty metadata and groups absent cells by column. Metadata is
67
+ * explicit, so strings resembling JSON stay strings unless their column
68
+ * declares JSON. Malformed JSON cells throw instead of silently changing their
69
+ * meaning.
46
70
  */
47
- export declare function decodePmTableRows(table:PmEncodedTableRows):Record<string,JsonValue>[];
71
+ export declare function decodePmTableRows(table:{rows:PmEncodedTableRows["rows"];encoding:PmRenderedTableCellEncoding;}):Record<string,JsonValue>[];
@@ -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]="d3d21124-3c8a-5049-803d-00c63c0c2b61")}catch{}})();function encodePmTableRows(rows,options={}){const columns=[...new Set(rows.flatMap(row=>Object.keys(row)))],nullColumns=options.compact?columns.filter(column=>rows.every(row=>Object.hasOwn(row,column)&&row[column]===null)):[],listColumns=options.compact?columns.filter(column=>rows.every(row=>{if(!Object.hasOwn(row,column))return!0;const cell=row[column];return Array.isArray(cell)&&cell.every(value=>typeof value=="string"&&value!==""&&!value.includes(";"))})):[],lists=new Set(listColumns),nulls=new Set(nullColumns),jsonColumns=columns.filter(column=>!lists.has(column)&&rows.some(row=>{const cell=row[column];return cell!==null&&typeof cell=="object"})),nested=new Set(jsonColumns),absent=[];return{rows:rows.map((row,index)=>Object.fromEntries(columns.filter(column=>!nulls.has(column)).map(column=>{if(!Object.hasOwn(row,column))return absent.push([index,column]),[column,null];const cell=row[column];return lists.has(column)?[column,cell.join(";")]:[column,nested.has(column)?JSON.stringify(cell):cell]}))),encoding:{json_columns:jsonColumns,absent,...listColumns.length?{list_columns:Object.fromEntries(listColumns.map(column=>[column,";"]))}:{},...nullColumns.length?{null_columns:nullColumns,null_column_index:nullColumns.map(column=>columns.indexOf(column))}:{}}}}function restoreColumnOrder(encodedColumns,encoding){const nullColumns=encoding.null_columns??[],positions=encoding.null_column_index??[],columns=[...encodedColumns],insertions=nullColumns.map((column,index)=>({column,position:positions[index]})).filter(entry=>typeof entry.position=="number").sort((left,right)=>left.position-right.position);for(const{column,position}of insertions)columns.splice(Math.min(position,columns.length),0,column);for(const column of nullColumns)columns.includes(column)||columns.push(column);return columns}function decodePmTableRows(table){const nested=new Set(table.encoding.json_columns),delimiters=new Map(Object.entries(table.encoding.list_columns??{})),absent=new Set(table.encoding.absent.map(([row,column])=>JSON.stringify([row,column])));return table.rows.map((row,index)=>{const cells=new Map(Object.entries(row).flatMap(([column,cell])=>{if(absent.has(JSON.stringify([index,column])))return[];const delimiter=delimiters.get(column),value=delimiter!==void 0?cell===""?[]:String(cell).split(delimiter):nested.has(column)?JSON.parse(String(cell)):cell;return[[column,value]]}));for(const column of table.encoding.null_columns??[])cells.set(column,null);const columns=table.encoding.column_order??restoreColumnOrder(Object.keys(row),table.encoding);return Object.fromEntries(columns.filter(column=>cells.has(column)).map(column=>[column,cells.get(column)]))})}export{decodePmTableRows,encodePmTableRows};
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]="bafcd4e4-ec0f-5340-89ce-b85d822b2323")}catch{}})();function encodePmTableRows(rows,options={}){const columns=[...new Set(rows.flatMap(row=>Object.keys(row)))],nullColumns=options.compact?columns.filter(column=>rows.every(row=>Object.hasOwn(row,column)&&row[column]===null)):[],listColumns=options.compact?columns.filter(column=>rows.every(row=>{if(!Object.hasOwn(row,column))return!0;const cell=row[column];return Array.isArray(cell)&&cell.every(value=>typeof value=="string"&&value!==""&&!value.includes(";"))})):[],lists=new Set(listColumns),nulls=new Set(nullColumns),jsonColumns=columns.filter(column=>!lists.has(column)&&rows.some(row=>{const cell=row[column];return cell!==null&&typeof cell=="object"})),nested=new Set(jsonColumns),absent=[];return{rows:rows.map((row,index)=>Object.fromEntries(columns.filter(column=>!nulls.has(column)).map(column=>{if(!Object.hasOwn(row,column))return absent.push([index,column]),[column,null];const cell=row[column];return lists.has(column)?[column,cell.join(";")]:[column,nested.has(column)?JSON.stringify(cell):cell]}))),encoding:{json_columns:jsonColumns,absent,...listColumns.length?{list_columns:Object.fromEntries(listColumns.map(column=>[column,";"]))}:{},...nullColumns.length?{null_columns:nullColumns,null_column_index:nullColumns.map(column=>columns.indexOf(column))}:{}}}}function projectPmTableEncodingForToon(encoding){const{json_columns:jsonColumns,absent,...declarations}=encoding,absentRows=new Map;for(const[row,column]of absent){const rows=absentRows.get(column)??[];rows.push(row),absentRows.set(column,rows)}return{...jsonColumns.length>0?{json_columns:jsonColumns}:{},...absentRows.size>0?{absent_rows:Object.fromEntries(absentRows)}:{},...declarations}}function restoreColumnOrder(encodedColumns,encoding){const nullColumns=encoding.null_columns??[],positions=encoding.null_column_index??[],columns=[...encodedColumns],insertions=nullColumns.map((column,index)=>({column,position:positions[index]})).filter(entry=>typeof entry.position=="number").sort((left,right)=>left.position-right.position);for(const{column,position}of insertions)columns.splice(Math.min(position,columns.length),0,column);for(const column of nullColumns)columns.includes(column)||columns.push(column);return columns}function decodePmTableRows(table){const nested=new Set(table.encoding.json_columns??[]),delimiters=new Map(Object.entries(table.encoding.list_columns??{})),absent=new Set([...(table.encoding.absent??[]).map(([row,column])=>JSON.stringify([row,column])),...Object.entries(table.encoding.absent_rows??{}).flatMap(([column,rows])=>rows.map(row=>JSON.stringify([row,column])))]);return table.rows.map((row,index)=>{const cells=new Map(Object.entries(row).flatMap(([column,cell])=>{if(absent.has(JSON.stringify([index,column])))return[];const delimiter=delimiters.get(column),value=delimiter!==void 0?cell===""?[]:String(cell).split(delimiter):nested.has(column)?JSON.parse(String(cell)):cell;return[[column,value]]}));for(const column of table.encoding.null_columns??[])cells.set(column,null);const columns=table.encoding.column_order??restoreColumnOrder(Object.keys(row),table.encoding);return Object.fromEntries(columns.filter(column=>cells.has(column)).map(column=>[column,cells.get(column)]))})}export{decodePmTableRows,encodePmTableRows,projectPmTableEncodingForToon};
2
2
  //# sourceMappingURL=table-rows.js.map
@@ -4,7 +4,7 @@
4
4
  * Defines public output-control primitives for extension commands, exporters,
5
5
  * renderers, and custom SDK-built hosts.
6
6
  */
7
- export{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput,type SuppressedHostOutput,}from "../core/output/output-control.js";export{encodePmTableRows,decodePmTableRows,type PmTableCellEncoding,type PmEncodedTableRows,}from "./output/table-rows.js";export{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,}from "./output/list-envelope.js";export{assertWellFormedOutputText,toWellFormedText}from "../core/shared/output-unicode.js";
7
+ export{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput,type SuppressedHostOutput,}from "../core/output/output-control.js";export{encodePmTableRows,decodePmTableRows,type PmTableCellEncoding,type PmRenderedTableCellEncoding,type PmEncodedTableRows,}from "./output/table-rows.js";export{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,}from "./output/list-envelope.js";export{assertWellFormedOutputText,toWellFormedText}from "../core/shared/output-unicode.js";
8
8
  /**
9
9
  * Serialize object rows as newline-delimited JSON without adding a trailing
10
10
  * newline. CLI hosts can append their final newline while SDK consumers can
@@ -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]="9febe44f-931d-5442-95e6-2793cb571972")}catch{}})();import{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput}from"../core/output/output-control.js";import{encodePmTableRows,decodePmTableRows}from"./output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"./output/list-envelope.js";import{assertWellFormedOutputText,toWellFormedText}from"../core/shared/output-unicode.js";function serializeNdjsonRows(rows){return rows.map((row,index)=>{if(typeof row!="object"||row===null||Array.isArray(row))throw new TypeError(`NDJSON row ${index} must be a non-null object.`);const serialized=JSON.stringify(row);if(serialized===void 0)throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);const projected=JSON.parse(serialized);if(typeof projected!="object"||projected===null||Array.isArray(projected))throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);return serialized}).join(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e6c590de-c83e-59ca-9fdb-9a68cc88d545")}catch{}})();import{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput}from"../core/output/output-control.js";import{encodePmTableRows,decodePmTableRows}from"./output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"./output/list-envelope.js";import{assertWellFormedOutputText,toWellFormedText}from"../core/shared/output-unicode.js";function serializeNdjsonRows(rows){return rows.map((row,index)=>{if(typeof row!="object"||row===null||Array.isArray(row))throw new TypeError(`NDJSON row ${index} must be a non-null object.`);const serialized=JSON.stringify(row);if(serialized===void 0)throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);const projected=JSON.parse(serialized);if(typeof projected!="object"||projected===null||Array.isArray(projected))throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);return serialized}).join(`
2
2
  `)}function serializeNdjsonStream(rows,trailer){if(trailer.count!==rows.length)throw new TypeError(`NDJSON trailer count ${trailer.count} does not match ${rows.length} ${rows.length===1?"row":"rows"}.`);for(const[index,row]of rows.entries())if(typeof row=="object"&&row!==null&&!Array.isArray(row)&&Reflect.get(row,"record_type")==="pm.stream.trailer")throw new TypeError(`NDJSON row ${index} uses reserved record_type pm.stream.trailer`);return serializeNdjsonRows([...rows,{...trailer,record_type:"pm.stream.trailer"}])}export{SUPPRESS_HOST_OUTPUT_MARKER,assertWellFormedOutputText,decodePmTableRows,encodePmTableRows,isHostOutputSuppressed,projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,serializeNdjsonRows,serializeNdjsonStream,suppressHostOutput,toWellFormedText};
3
3
  //# sourceMappingURL=output.js.map
@@ -12,7 +12,7 @@
12
12
  * at runtime via `PM_CLI_PACKAGE_ROOT`). Centralizing them here removes copy-pasted
13
13
  * helper bodies while keeping each package's explicit field mapping in the package.
14
14
  */
15
- import type{ConfidenceTextLevel,ItemDocument,ItemMetadata,ItemStatus,LinkedDoc,LinkedFile,LinkedTest,LogNote,PmSettings}from "../types/index.js";
15
+ import type{ConfidenceTextLevel,ItemDocument,ItemDeferredField,ItemMetadata,ItemStatus,LinkedDoc,LinkedFile,LinkedTest,LogNote,PmSettings}from "../types/index.js";
16
16
  /** Restricts shared import priority values accepted by import adapters. */
17
17
  export type ImportPriorityValue=0|1|2|3|4;
18
18
  /** Restricts import linked-artifact scopes accepted by bundled package adapters. */
@@ -89,6 +89,14 @@ export declare function toImportLogEntries(value:unknown,options:ToImportLogEntr
89
89
  export declare function toImportLinkedFiles(value:unknown,options?:ToImportLinkedArtifactsOptions):LinkedFile[]|undefined;
90
90
  /** Converts source doc artifacts into pm linked docs. */
91
91
  export declare function toImportLinkedDocs(value:unknown,options?:ToImportLinkedArtifactsOptions):LinkedDoc[]|undefined;
92
+ /**
93
+ * Converts source deferral entries into pm `deferred_fields` (GH-1713): one
94
+ * entry per deferrable field, with a non-empty reason. An importer passes the
95
+ * result straight into item metadata, and `commitImportedItem` stamps the
96
+ * format the deferral needs, so a round trip keeps the audit trail and the
97
+ * strict-close protection.
98
+ */
99
+ export declare function toImportDeferredFields(value:unknown):ItemDeferredField[]|undefined;
92
100
  /** Converts source test artifacts into pm linked tests. */
93
101
  export declare function toImportLinkedTests(value:unknown,options?:ToImportLinkedTestsOptions):LinkedTest[]|undefined;
94
102
  /** Resolves the effective import author through the canonical CLI and SDK precedence contract. */