@unbrained/pm-cli 2026.5.29 → 2026.5.31

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 (274) hide show
  1. package/CHANGELOG.md +54 -12
  2. package/dist/cli/bootstrap-args.d.ts +1 -1
  3. package/dist/cli/bootstrap-args.js +59 -9
  4. package/dist/cli/bootstrap-args.js.map +1 -1
  5. package/dist/cli/commands/activity.js +4 -4
  6. package/dist/cli/commands/activity.js.map +1 -1
  7. package/dist/cli/commands/calendar.js +83 -11
  8. package/dist/cli/commands/calendar.js.map +1 -1
  9. package/dist/cli/commands/close.js +4 -4
  10. package/dist/cli/commands/close.js.map +1 -1
  11. package/dist/cli/commands/completion.js +4 -4
  12. package/dist/cli/commands/completion.js.map +1 -1
  13. package/dist/cli/commands/create.js +50 -7
  14. package/dist/cli/commands/create.js.map +1 -1
  15. package/dist/cli/commands/deps.js +4 -4
  16. package/dist/cli/commands/deps.js.map +1 -1
  17. package/dist/cli/commands/extension/install-sources.d.ts +3 -0
  18. package/dist/cli/commands/extension/install-sources.js +29 -4
  19. package/dist/cli/commands/extension/install-sources.js.map +1 -1
  20. package/dist/cli/commands/extension.js +26 -5
  21. package/dist/cli/commands/extension.js.map +1 -1
  22. package/dist/cli/commands/get.js +6 -3
  23. package/dist/cli/commands/get.js.map +1 -1
  24. package/dist/cli/commands/list.js +25 -6
  25. package/dist/cli/commands/list.js.map +1 -1
  26. package/dist/cli/commands/reindex.js +3 -3
  27. package/dist/cli/commands/reindex.js.map +1 -1
  28. package/dist/cli/commands/search.d.ts +17 -0
  29. package/dist/cli/commands/search.js +40 -10
  30. package/dist/cli/commands/search.js.map +1 -1
  31. package/dist/cli/commands/stats.js +4 -4
  32. package/dist/cli/commands/stats.js.map +1 -1
  33. package/dist/cli/commands/test-all.js +4 -4
  34. package/dist/cli/commands/test-all.js.map +1 -1
  35. package/dist/cli/main.d.ts +2 -0
  36. package/dist/cli/main.js +39 -11
  37. package/dist/cli/main.js.map +1 -1
  38. package/dist/cli/register-list-query.js +10 -12
  39. package/dist/cli/register-list-query.js.map +1 -1
  40. package/dist/cli/register-mutation.js +20 -22
  41. package/dist/cli/register-mutation.js.map +1 -1
  42. package/dist/cli/register-operations.js +32 -25
  43. package/dist/cli/register-operations.js.map +1 -1
  44. package/dist/cli/register-setup.js +7 -9
  45. package/dist/cli/register-setup.js.map +1 -1
  46. package/dist/cli/registration-helpers.js +6 -3
  47. package/dist/cli/registration-helpers.js.map +1 -1
  48. package/dist/cli/search-refresh.d.ts +2 -0
  49. package/dist/cli/search-refresh.js +13 -0
  50. package/dist/cli/search-refresh.js.map +1 -0
  51. package/dist/cli-bundle/chunks/activity-OWYSUZOY.js +17 -0
  52. package/dist/cli-bundle/chunks/activity-OWYSUZOY.js.map +7 -0
  53. package/dist/cli-bundle/chunks/aggregate-ADUOSFRO.js +209 -0
  54. package/dist/cli-bundle/chunks/aggregate-ADUOSFRO.js.map +7 -0
  55. package/dist/cli-bundle/chunks/append-JD2DETU7.js +73 -0
  56. package/dist/cli-bundle/chunks/append-JD2DETU7.js.map +7 -0
  57. package/dist/cli-bundle/chunks/chunk-3HUE7XOF.js +27 -0
  58. package/dist/cli-bundle/chunks/chunk-3HUE7XOF.js.map +7 -0
  59. package/dist/cli-bundle/chunks/chunk-3M73P3G6.js +1636 -0
  60. package/dist/cli-bundle/chunks/chunk-3M73P3G6.js.map +7 -0
  61. package/dist/cli-bundle/chunks/chunk-4AEZR5EJ.js +189 -0
  62. package/dist/cli-bundle/chunks/chunk-4AEZR5EJ.js.map +7 -0
  63. package/dist/cli-bundle/chunks/chunk-5HSEP75M.js +330 -0
  64. package/dist/cli-bundle/chunks/chunk-5HSEP75M.js.map +7 -0
  65. package/dist/cli-bundle/chunks/chunk-6HT2F4TK.js +1770 -0
  66. package/dist/cli-bundle/chunks/chunk-6HT2F4TK.js.map +7 -0
  67. package/dist/cli-bundle/chunks/chunk-6YCV7WSL.js +552 -0
  68. package/dist/cli-bundle/chunks/chunk-6YCV7WSL.js.map +7 -0
  69. package/dist/cli-bundle/chunks/chunk-7Y53ZJIQ.js +202 -0
  70. package/dist/cli-bundle/chunks/chunk-7Y53ZJIQ.js.map +7 -0
  71. package/dist/cli-bundle/chunks/chunk-A7E7PUVX.js +157 -0
  72. package/dist/cli-bundle/chunks/chunk-A7E7PUVX.js.map +7 -0
  73. package/dist/cli-bundle/chunks/chunk-AKOOMO3T.js +90 -0
  74. package/dist/cli-bundle/chunks/chunk-AKOOMO3T.js.map +7 -0
  75. package/dist/cli-bundle/chunks/chunk-BUPWJ3IJ.js +950 -0
  76. package/dist/cli-bundle/chunks/chunk-BUPWJ3IJ.js.map +7 -0
  77. package/dist/cli-bundle/chunks/chunk-CEFIVZPG.js +79 -0
  78. package/dist/cli-bundle/chunks/chunk-CEFIVZPG.js.map +7 -0
  79. package/dist/cli-bundle/chunks/chunk-D7AOMPRH.js +349 -0
  80. package/dist/cli-bundle/chunks/chunk-D7AOMPRH.js.map +7 -0
  81. package/dist/cli-bundle/chunks/chunk-EAOG77HM.js +56 -0
  82. package/dist/cli-bundle/chunks/chunk-EAOG77HM.js.map +7 -0
  83. package/dist/cli-bundle/chunks/chunk-EGUGFSNX.js +47 -0
  84. package/dist/cli-bundle/chunks/chunk-EGUGFSNX.js.map +7 -0
  85. package/dist/cli-bundle/chunks/chunk-FM26RGSU.js +56 -0
  86. package/dist/cli-bundle/chunks/chunk-FM26RGSU.js.map +7 -0
  87. package/dist/cli-bundle/chunks/chunk-FQE6XZDB.js +435 -0
  88. package/dist/cli-bundle/chunks/chunk-FQE6XZDB.js.map +7 -0
  89. package/dist/cli-bundle/chunks/chunk-G57E5D7T.js +185 -0
  90. package/dist/cli-bundle/chunks/chunk-G57E5D7T.js.map +7 -0
  91. package/dist/cli-bundle/chunks/chunk-GN7IJPCD.js +3621 -0
  92. package/dist/cli-bundle/chunks/chunk-GN7IJPCD.js.map +7 -0
  93. package/dist/cli-bundle/chunks/chunk-JFWUHHS2.js +233 -0
  94. package/dist/cli-bundle/chunks/chunk-JFWUHHS2.js.map +7 -0
  95. package/dist/cli-bundle/chunks/chunk-JTWRXG4B.js +1861 -0
  96. package/dist/cli-bundle/chunks/chunk-JTWRXG4B.js.map +7 -0
  97. package/dist/cli-bundle/chunks/chunk-JULRTHJQ.js +648 -0
  98. package/dist/cli-bundle/chunks/chunk-JULRTHJQ.js.map +7 -0
  99. package/dist/cli-bundle/chunks/chunk-KBQY3YG5.js +122 -0
  100. package/dist/cli-bundle/chunks/chunk-KBQY3YG5.js.map +7 -0
  101. package/dist/cli-bundle/chunks/chunk-L2FXEKDB.js +185 -0
  102. package/dist/cli-bundle/chunks/chunk-L2FXEKDB.js.map +7 -0
  103. package/dist/cli-bundle/chunks/chunk-LRBOHPUE.js +189 -0
  104. package/dist/cli-bundle/chunks/chunk-LRBOHPUE.js.map +7 -0
  105. package/dist/cli-bundle/chunks/chunk-LSXGH6NE.js +5153 -0
  106. package/dist/cli-bundle/chunks/chunk-LSXGH6NE.js.map +7 -0
  107. package/dist/cli-bundle/chunks/chunk-MD7K4JYF.js +1345 -0
  108. package/dist/cli-bundle/chunks/chunk-MD7K4JYF.js.map +7 -0
  109. package/dist/cli-bundle/chunks/chunk-NGN7UV5K.js +341 -0
  110. package/dist/cli-bundle/chunks/chunk-NGN7UV5K.js.map +7 -0
  111. package/dist/cli-bundle/chunks/chunk-O7IWB35H.js +18 -0
  112. package/dist/cli-bundle/chunks/chunk-O7IWB35H.js.map +7 -0
  113. package/dist/cli-bundle/chunks/chunk-OGZEG5TT.js +2929 -0
  114. package/dist/cli-bundle/chunks/chunk-OGZEG5TT.js.map +7 -0
  115. package/dist/cli-bundle/chunks/chunk-P53TN6IA.js +674 -0
  116. package/dist/cli-bundle/chunks/chunk-P53TN6IA.js.map +7 -0
  117. package/dist/cli-bundle/chunks/chunk-PVNQLCIS.js +176 -0
  118. package/dist/cli-bundle/chunks/chunk-PVNQLCIS.js.map +7 -0
  119. package/dist/cli-bundle/chunks/chunk-PXUAZUUY.js +1680 -0
  120. package/dist/cli-bundle/chunks/chunk-PXUAZUUY.js.map +7 -0
  121. package/dist/cli-bundle/chunks/chunk-QAJBIGRA.js +20 -0
  122. package/dist/cli-bundle/chunks/chunk-QAJBIGRA.js.map +7 -0
  123. package/dist/cli-bundle/chunks/chunk-SEXQN4KL.js +60 -0
  124. package/dist/cli-bundle/chunks/chunk-SEXQN4KL.js.map +7 -0
  125. package/dist/cli-bundle/chunks/chunk-U7FMKRXH.js +362 -0
  126. package/dist/cli-bundle/chunks/chunk-U7FMKRXH.js.map +7 -0
  127. package/dist/cli-bundle/chunks/chunk-VGICHR7D.js +141 -0
  128. package/dist/cli-bundle/chunks/chunk-VGICHR7D.js.map +7 -0
  129. package/dist/cli-bundle/chunks/chunk-WDPXDQFG.js +632 -0
  130. package/dist/cli-bundle/chunks/chunk-WDPXDQFG.js.map +7 -0
  131. package/dist/cli-bundle/chunks/chunk-WJ2NAC37.js +252 -0
  132. package/dist/cli-bundle/chunks/chunk-WJ2NAC37.js.map +7 -0
  133. package/dist/cli-bundle/chunks/claim-EE4TKKCV.js +133 -0
  134. package/dist/cli-bundle/chunks/claim-EE4TKKCV.js.map +7 -0
  135. package/dist/cli-bundle/chunks/close-XY4CSAYF.js +14 -0
  136. package/dist/cli-bundle/chunks/close-XY4CSAYF.js.map +7 -0
  137. package/dist/cli-bundle/chunks/comments-AAKJQ6LW.js +104 -0
  138. package/dist/cli-bundle/chunks/comments-AAKJQ6LW.js.map +7 -0
  139. package/dist/cli-bundle/chunks/config-V3FZOKLI.js +1577 -0
  140. package/dist/cli-bundle/chunks/config-V3FZOKLI.js.map +7 -0
  141. package/dist/cli-bundle/chunks/context-RZ5QPNJB.js +1458 -0
  142. package/dist/cli-bundle/chunks/context-RZ5QPNJB.js.map +7 -0
  143. package/dist/cli-bundle/chunks/contracts-YLMH33VU.js +1245 -0
  144. package/dist/cli-bundle/chunks/contracts-YLMH33VU.js.map +7 -0
  145. package/dist/cli-bundle/chunks/create-PZVHRIZQ.js +28 -0
  146. package/dist/cli-bundle/chunks/create-PZVHRIZQ.js.map +7 -0
  147. package/dist/cli-bundle/chunks/delete-RHCTEORS.js +59 -0
  148. package/dist/cli-bundle/chunks/delete-RHCTEORS.js.map +7 -0
  149. package/dist/cli-bundle/chunks/deps-MZYCMLAO.js +229 -0
  150. package/dist/cli-bundle/chunks/deps-MZYCMLAO.js.map +7 -0
  151. package/dist/cli-bundle/chunks/docs-FXXUCZYU.js +35 -0
  152. package/dist/cli-bundle/chunks/docs-FXXUCZYU.js.map +7 -0
  153. package/dist/cli-bundle/chunks/extension-B4WL7BQU.js +25 -0
  154. package/dist/cli-bundle/chunks/extension-B4WL7BQU.js.map +7 -0
  155. package/dist/cli-bundle/chunks/files-WVOX67PE.js +286 -0
  156. package/dist/cli-bundle/chunks/files-WVOX67PE.js.map +7 -0
  157. package/dist/cli-bundle/chunks/gc-JWNF66EC.js +181 -0
  158. package/dist/cli-bundle/chunks/gc-JWNF66EC.js.map +7 -0
  159. package/dist/cli-bundle/chunks/get-LTK3HOCQ.js +198 -0
  160. package/dist/cli-bundle/chunks/get-LTK3HOCQ.js.map +7 -0
  161. package/dist/cli-bundle/chunks/health-TCWL55KM.js +1233 -0
  162. package/dist/cli-bundle/chunks/health-TCWL55KM.js.map +7 -0
  163. package/dist/cli-bundle/chunks/history-A2JUDXUE.js +21 -0
  164. package/dist/cli-bundle/chunks/history-A2JUDXUE.js.map +7 -0
  165. package/dist/cli-bundle/chunks/history-redact-ED6RFCPL.js +20 -0
  166. package/dist/cli-bundle/chunks/history-redact-ED6RFCPL.js.map +7 -0
  167. package/dist/cli-bundle/chunks/history-repair-ZWSTDRH2.js +198 -0
  168. package/dist/cli-bundle/chunks/history-repair-ZWSTDRH2.js.map +7 -0
  169. package/dist/cli-bundle/chunks/init-M2WUB4YH.js +16 -0
  170. package/dist/cli-bundle/chunks/init-M2WUB4YH.js.map +7 -0
  171. package/dist/cli-bundle/chunks/learnings-NXTWE3FR.js +48 -0
  172. package/dist/cli-bundle/chunks/learnings-NXTWE3FR.js.map +7 -0
  173. package/dist/cli-bundle/chunks/list-OGWQPC26.js +20 -0
  174. package/dist/cli-bundle/chunks/list-OGWQPC26.js.map +7 -0
  175. package/dist/cli-bundle/chunks/notes-DFS5ZGOO.js +48 -0
  176. package/dist/cli-bundle/chunks/notes-DFS5ZGOO.js.map +7 -0
  177. package/dist/cli-bundle/chunks/plan-67AB2PLM.js +1175 -0
  178. package/dist/cli-bundle/chunks/plan-67AB2PLM.js.map +7 -0
  179. package/dist/cli-bundle/chunks/register-list-query-UP3VRUFS.js +232 -0
  180. package/dist/cli-bundle/chunks/register-list-query-UP3VRUFS.js.map +7 -0
  181. package/dist/cli-bundle/chunks/register-mutation-YWSBF545.js +712 -0
  182. package/dist/cli-bundle/chunks/register-mutation-YWSBF545.js.map +7 -0
  183. package/dist/cli-bundle/chunks/register-operations-3BDTGSDH.js +374 -0
  184. package/dist/cli-bundle/chunks/register-operations-3BDTGSDH.js.map +7 -0
  185. package/dist/cli-bundle/chunks/register-setup-V56GDRUS.js +246 -0
  186. package/dist/cli-bundle/chunks/register-setup-V56GDRUS.js.map +7 -0
  187. package/dist/cli-bundle/chunks/restore-MB2ISME7.js +18 -0
  188. package/dist/cli-bundle/chunks/restore-MB2ISME7.js.map +7 -0
  189. package/dist/cli-bundle/chunks/schema-Q622KC46.js +119 -0
  190. package/dist/cli-bundle/chunks/schema-Q622KC46.js.map +7 -0
  191. package/dist/cli-bundle/chunks/search-HENBL456.js +1135 -0
  192. package/dist/cli-bundle/chunks/search-HENBL456.js.map +7 -0
  193. package/dist/cli-bundle/chunks/stats-N6H3YP2F.js +124 -0
  194. package/dist/cli-bundle/chunks/stats-N6H3YP2F.js.map +7 -0
  195. package/dist/cli-bundle/chunks/test-VNBDRJ4Z.js +32 -0
  196. package/dist/cli-bundle/chunks/test-VNBDRJ4Z.js.map +7 -0
  197. package/dist/cli-bundle/chunks/test-all-G2AZOHXI.js +332 -0
  198. package/dist/cli-bundle/chunks/test-all-G2AZOHXI.js.map +7 -0
  199. package/dist/cli-bundle/chunks/test-runs-GX5HTPSF.js +939 -0
  200. package/dist/cli-bundle/chunks/test-runs-GX5HTPSF.js.map +7 -0
  201. package/dist/cli-bundle/chunks/update-H6SCWNMA.js +22 -0
  202. package/dist/cli-bundle/chunks/update-H6SCWNMA.js.map +7 -0
  203. package/dist/cli-bundle/chunks/update-many-46HRSP2Q.js +676 -0
  204. package/dist/cli-bundle/chunks/update-many-46HRSP2Q.js.map +7 -0
  205. package/dist/cli-bundle/chunks/upgrade-H5HHM5UV.js +271 -0
  206. package/dist/cli-bundle/chunks/upgrade-H5HHM5UV.js.map +7 -0
  207. package/dist/cli-bundle/chunks/validate-TMCVKIGZ.js +1110 -0
  208. package/dist/cli-bundle/chunks/validate-TMCVKIGZ.js.map +7 -0
  209. package/dist/cli-bundle/main.js +6952 -0
  210. package/dist/cli-bundle/main.js.map +7 -0
  211. package/dist/cli.js +1 -1
  212. package/dist/core/config/nested-settings.d.ts +2 -0
  213. package/dist/core/config/nested-settings.js +17 -2
  214. package/dist/core/config/nested-settings.js.map +1 -1
  215. package/dist/core/item/item-type-definition.js +6 -2
  216. package/dist/core/item/item-type-definition.js.map +1 -1
  217. package/dist/core/item/type-registry.d.ts +4 -0
  218. package/dist/core/item/type-registry.js +10 -2
  219. package/dist/core/item/type-registry.js.map +1 -1
  220. package/dist/core/item/type-synonyms.d.ts +20 -0
  221. package/dist/core/item/type-synonyms.js +42 -0
  222. package/dist/core/item/type-synonyms.js.map +1 -0
  223. package/dist/core/search/background-refresh.d.ts +53 -0
  224. package/dist/core/search/background-refresh.js +286 -0
  225. package/dist/core/search/background-refresh.js.map +1 -0
  226. package/dist/core/search/cache.d.ts +20 -1
  227. package/dist/core/search/cache.js +76 -5
  228. package/dist/core/search/cache.js.map +1 -1
  229. package/dist/core/search/semantic-defaults.js +73 -32
  230. package/dist/core/search/semantic-defaults.js.map +1 -1
  231. package/dist/core/search/vector-stores.js +7 -3
  232. package/dist/core/search/vector-stores.js.map +1 -1
  233. package/dist/core/sentry/helpers.d.ts +1 -1
  234. package/dist/core/sentry/helpers.js +4 -4
  235. package/dist/core/sentry/helpers.js.map +1 -1
  236. package/dist/core/shared/constants.d.ts +2 -2
  237. package/dist/core/shared/constants.js +3 -3
  238. package/dist/core/shared/constants.js.map +1 -1
  239. package/dist/core/shared/html-entity-decode.d.ts +2 -1
  240. package/dist/core/shared/html-entity-decode.js +14 -9
  241. package/dist/core/shared/html-entity-decode.js.map +1 -1
  242. package/dist/core/shared/time.js +52 -2
  243. package/dist/core/shared/time.js.map +1 -1
  244. package/dist/core/store/front-matter-cache.d.ts +24 -0
  245. package/dist/core/store/front-matter-cache.js +119 -8
  246. package/dist/core/store/front-matter-cache.js.map +1 -1
  247. package/dist/core/store/item-format-migration.js +25 -15
  248. package/dist/core/store/item-format-migration.js.map +1 -1
  249. package/dist/core/store/item-store.d.ts +7 -0
  250. package/dist/core/store/item-store.js +13 -3
  251. package/dist/core/store/item-store.js.map +1 -1
  252. package/dist/core/store/settings-validator.d.ts +1 -0
  253. package/dist/core/store/settings-validator.js +7 -2
  254. package/dist/core/store/settings-validator.js.map +1 -1
  255. package/dist/core/store/settings.js +19 -3
  256. package/dist/core/store/settings.js.map +1 -1
  257. package/dist/core/telemetry/runtime.d.ts +10 -0
  258. package/dist/core/telemetry/runtime.js +86 -2
  259. package/dist/core/telemetry/runtime.js.map +1 -1
  260. package/dist/mcp/server.js +3 -3
  261. package/dist/mcp/server.js.map +1 -1
  262. package/dist/sdk/cli-contracts/tool-parameter-tables.js +4 -4
  263. package/dist/sdk/cli-contracts/tool-parameter-tables.js.map +1 -1
  264. package/dist/sdk/cli-contracts.js +29 -8
  265. package/dist/sdk/cli-contracts.js.map +1 -1
  266. package/dist/types.d.ts +9 -1
  267. package/dist/types.js +2 -2
  268. package/dist/types.js.map +1 -1
  269. package/docs/CONFIGURATION.md +11 -0
  270. package/docs/RELEASING.md +1 -1
  271. package/package.json +7 -5
  272. package/packages/pm-calendar/extensions/calendar/index.js +27 -2
  273. package/packages/pm-calendar/extensions/calendar/index.ts +28 -2
  274. package/scripts/bundle-cli.mjs +39 -0
@@ -0,0 +1,950 @@
1
+ import {
2
+ acquireLock
3
+ } from "./chunk-4AEZR5EJ.js";
4
+ import {
5
+ normalizeItemId,
6
+ normalizeRawItemId
7
+ } from "./chunk-CEFIVZPG.js";
8
+ import {
9
+ canonicalDocument,
10
+ parseItemDocument,
11
+ serializeItemDocument
12
+ } from "./chunk-MD7K4JYF.js";
13
+ import {
14
+ resolveItemTypeRegistry
15
+ } from "./chunk-WDPXDQFG.js";
16
+ import {
17
+ nowIso
18
+ } from "./chunk-PVNQLCIS.js";
19
+ import {
20
+ EMPTY_CANONICAL_DOCUMENT,
21
+ EXIT_CODE,
22
+ FRONT_MATTER_KEY_ORDER,
23
+ ITEM_FILE_EXTENSIONS,
24
+ PmCliError,
25
+ TYPE_TO_FOLDER,
26
+ appendLineAtomic,
27
+ ensureDir,
28
+ getActiveExtensionRegistrations,
29
+ getHistoryPath,
30
+ getItemFormatFromPath,
31
+ getItemPath,
32
+ hasActiveOnReadHooks,
33
+ orderObject,
34
+ pathExists,
35
+ resolveGovernanceKnobs,
36
+ runActiveOnReadHooks,
37
+ runActiveOnWriteHooks,
38
+ runActiveServiceOverride,
39
+ sha256Hex,
40
+ stableStringify,
41
+ writeFileAtomic
42
+ } from "./chunk-LSXGH6NE.js";
43
+
44
+ // dist/core/item/item-record.js
45
+ !(function() {
46
+ try {
47
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
48
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "104fe68e-6cf6-52c7-86ab-063e6535ac0e");
49
+ } catch (e2) {
50
+ }
51
+ })();
52
+ function toItemRecord(item) {
53
+ return item;
54
+ }
55
+
56
+ // dist/core/history/history.js
57
+ import jsonPatch from "fast-json-patch";
58
+ !(function() {
59
+ try {
60
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
61
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "9a356560-3dec-5529-a2b5-1b4224116c14");
62
+ } catch (e2) {
63
+ }
64
+ })();
65
+ var EMPTY_LEGACY_HASH_DOCUMENT = {
66
+ front_matter: {},
67
+ body: ""
68
+ };
69
+ function decodeJsonPointer(path4) {
70
+ if (!path4 || path4 === "/") {
71
+ return [];
72
+ }
73
+ if (!path4.startsWith("/")) {
74
+ return [];
75
+ }
76
+ return path4.slice(1).split("/").map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~"));
77
+ }
78
+ function isDefinedPointerPath(document, path4) {
79
+ const segments = decodeJsonPointer(path4);
80
+ if (segments.length === 0) {
81
+ return true;
82
+ }
83
+ let cursor = document;
84
+ for (const segment of segments) {
85
+ if (Array.isArray(cursor)) {
86
+ if (segment === "-" || !/^(0|[1-9]\d*)$/.test(segment)) {
87
+ return false;
88
+ }
89
+ const index = Number(segment);
90
+ if (!Number.isInteger(index) || index < 0 || index >= cursor.length) {
91
+ return false;
92
+ }
93
+ const next2 = cursor[index];
94
+ if (next2 === void 0) {
95
+ return false;
96
+ }
97
+ cursor = next2;
98
+ continue;
99
+ }
100
+ if (typeof cursor !== "object" || cursor === null) {
101
+ return false;
102
+ }
103
+ if (!Object.prototype.hasOwnProperty.call(cursor, segment)) {
104
+ return false;
105
+ }
106
+ const next = cursor[segment];
107
+ if (next === void 0) {
108
+ return false;
109
+ }
110
+ cursor = next;
111
+ }
112
+ return true;
113
+ }
114
+ function normalizeHistoryPatchOps(beforeDocument, patch) {
115
+ const normalized = [];
116
+ let replayCursor = structuredClone(beforeDocument);
117
+ for (const operation of patch) {
118
+ const normalizedOperation = operation.op === "replace" && !isDefinedPointerPath(replayCursor, operation.path) ? { ...operation, op: "add" } : operation;
119
+ normalized.push(normalizedOperation);
120
+ replayCursor = jsonPatch.applyPatch(replayCursor, [normalizedOperation], true, true).newDocument;
121
+ }
122
+ return normalized;
123
+ }
124
+ function canonicalHashDocument(document) {
125
+ const hasMetadata = document.metadata && Object.keys(document.metadata).length > 0;
126
+ if (!hasMetadata) {
127
+ return {
128
+ front_matter: {},
129
+ body: document.body ?? ""
130
+ };
131
+ }
132
+ const canonical = canonicalDocument(document);
133
+ const orderedFrontMatter = orderObject(toItemRecord(canonical.metadata), FRONT_MATTER_KEY_ORDER);
134
+ return {
135
+ front_matter: orderedFrontMatter,
136
+ body: canonical.body
137
+ };
138
+ }
139
+ function canonicalPatchDocument(document) {
140
+ const hasMetadata = document.metadata && Object.keys(document.metadata).length > 0;
141
+ if (!hasMetadata) {
142
+ return {
143
+ metadata: {},
144
+ body: document.body ?? ""
145
+ };
146
+ }
147
+ const canonical = canonicalDocument(document);
148
+ const orderedMetadata = orderObject(toItemRecord(canonical.metadata), FRONT_MATTER_KEY_ORDER);
149
+ return {
150
+ metadata: orderedMetadata,
151
+ body: canonical.body
152
+ };
153
+ }
154
+ function hashDocument(document) {
155
+ return sha256Hex(stableStringify(canonicalHashDocument(document)));
156
+ }
157
+ function hashEmptyDocument() {
158
+ return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT));
159
+ }
160
+ function createHistoryEntry(params) {
161
+ const beforeHashCanonical = canonicalHashDocument(params.before);
162
+ const afterHashCanonical = canonicalHashDocument(params.after);
163
+ const beforePatchCanonical = canonicalPatchDocument(params.before);
164
+ const afterPatchCanonical = canonicalPatchDocument(params.after);
165
+ const rawPatch = jsonPatch.compare(beforePatchCanonical, afterPatchCanonical);
166
+ const patch = normalizeHistoryPatchOps(beforePatchCanonical, rawPatch);
167
+ return {
168
+ ts: params.nowIso,
169
+ author: params.author,
170
+ op: params.op,
171
+ patch,
172
+ before_hash: sha256Hex(stableStringify(beforeHashCanonical)),
173
+ after_hash: sha256Hex(stableStringify(afterHashCanonical)),
174
+ message: params.message === void 0 ? void 0 : params.message
175
+ };
176
+ }
177
+ async function appendHistoryEntry(historyPath, entry) {
178
+ const override = await runActiveServiceOverride("history_append", {
179
+ history_path: historyPath,
180
+ entry
181
+ });
182
+ if (override.handled) {
183
+ if (override.result === false) {
184
+ return;
185
+ }
186
+ if (typeof override.result === "string") {
187
+ await appendLineAtomic(historyPath, override.result);
188
+ return;
189
+ }
190
+ if (typeof override.result === "object" && override.result !== null) {
191
+ const record = override.result;
192
+ if (record.skip === true) {
193
+ return;
194
+ }
195
+ const nextHistoryPath = typeof record.history_path === "string" ? record.history_path : historyPath;
196
+ if (typeof record.line === "string") {
197
+ await appendLineAtomic(nextHistoryPath, record.line);
198
+ return;
199
+ }
200
+ const nextEntry = record.entry ?? entry;
201
+ await appendLineAtomic(nextHistoryPath, JSON.stringify(nextEntry));
202
+ return;
203
+ }
204
+ }
205
+ await appendLineAtomic(historyPath, JSON.stringify(entry));
206
+ }
207
+
208
+ // dist/core/history/history-stream-policy.js
209
+ import fs from "node:fs/promises";
210
+ import path from "node:path";
211
+ !(function() {
212
+ try {
213
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
214
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "6aa88fb8-fe40-5d0f-bee8-b348eda9309e");
215
+ } catch (e2) {
216
+ }
217
+ })();
218
+ function toSortedUniqueItemIds(itemIds) {
219
+ return [...new Set(itemIds.filter((value) => value.trim().length > 0))].sort((left, right) => left.localeCompare(right));
220
+ }
221
+ function strictMissingStreamError(itemId, commandLabel) {
222
+ return new PmCliError(`Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`, EXIT_CODE.NOT_FOUND);
223
+ }
224
+ async function createStream(historyPath, commandLabel) {
225
+ await ensureDir(path.dirname(historyPath));
226
+ const handle = await fs.open(historyPath, "a");
227
+ await handle.close();
228
+ return runActiveOnWriteHooks({
229
+ path: historyPath,
230
+ scope: "project",
231
+ op: `${commandLabel}:history:auto_create`
232
+ });
233
+ }
234
+ async function enforceHistoryStreamPolicyForItem(params) {
235
+ return enforceHistoryStreamPolicyForItems({
236
+ pmRoot: params.pmRoot,
237
+ settings: params.settings,
238
+ itemIds: [params.itemId],
239
+ commandLabel: params.commandLabel
240
+ });
241
+ }
242
+ async function enforceHistoryStreamPolicyForItems(params) {
243
+ const ids = toSortedUniqueItemIds(params.itemIds);
244
+ const autoCreated = [];
245
+ const warnings = [];
246
+ for (const itemId of ids) {
247
+ const historyPath = getHistoryPath(params.pmRoot, itemId);
248
+ if (await pathExists(historyPath)) {
249
+ continue;
250
+ }
251
+ if (params.settings.history.missing_stream === "strict_error") {
252
+ throw strictMissingStreamError(itemId, params.commandLabel);
253
+ }
254
+ warnings.push(...await createStream(historyPath, params.commandLabel));
255
+ warnings.push(`history_stream_auto_created:${itemId}`);
256
+ autoCreated.push(itemId);
257
+ }
258
+ return {
259
+ auto_created_ids: autoCreated,
260
+ warnings
261
+ };
262
+ }
263
+
264
+ // dist/core/store/front-matter-cache.js
265
+ import fs2 from "node:fs/promises";
266
+ import path2 from "node:path";
267
+ import { createHash } from "node:crypto";
268
+ !(function() {
269
+ try {
270
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
271
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "a14ed5c7-eb26-57d5-8b28-58d736a3c11c");
272
+ } catch (e2) {
273
+ }
274
+ })();
275
+ var CACHE_VERSION = 6;
276
+ var CACHE_FILENAME = "metadata-cache.json";
277
+ var BODY_CACHE_FILENAME = "metadata-cache-bodies.json";
278
+ var COLLECTIONS_CACHE_FILENAME = "metadata-cache-collections.json";
279
+ var HEAVY_METADATA_KEYS = [
280
+ "comments",
281
+ "notes",
282
+ "learnings",
283
+ "files",
284
+ "tests",
285
+ "test_runs",
286
+ "docs"
287
+ ];
288
+ function splitHeavyMetadata(metadata) {
289
+ const light = { ...metadata };
290
+ const heavy = {};
291
+ for (const key of HEAVY_METADATA_KEYS) {
292
+ if (key in light) {
293
+ heavy[key] = light[key];
294
+ delete light[key];
295
+ }
296
+ }
297
+ return { light, heavy };
298
+ }
299
+ function mergeHeavyMetadata(light, heavy) {
300
+ if (!heavy || Object.keys(heavy).length === 0) {
301
+ return light;
302
+ }
303
+ return { ...light, ...heavy };
304
+ }
305
+ function computeContextFingerprint(preferredFormat, typeToFolder, schema) {
306
+ const hash = createHash("sha256");
307
+ hash.update(`format:${preferredFormat ?? "default"}`);
308
+ const sortedTypes = Object.entries(typeToFolder).sort(([a], [b]) => a.localeCompare(b)).map(([type, folder]) => `${type}=${folder}`).join(",");
309
+ hash.update(`|types:${sortedTypes}`);
310
+ if (schema) {
311
+ hash.update(`|schema:${JSON.stringify(schema)}`);
312
+ }
313
+ return hash.digest("hex").slice(0, 16);
314
+ }
315
+ function getCachePath(pmRoot) {
316
+ return path2.join(pmRoot, "runtime", CACHE_FILENAME);
317
+ }
318
+ function getBodyCachePath(pmRoot) {
319
+ return path2.join(pmRoot, "runtime", BODY_CACHE_FILENAME);
320
+ }
321
+ function getCollectionsCachePath(pmRoot) {
322
+ return path2.join(pmRoot, "runtime", COLLECTIONS_CACHE_FILENAME);
323
+ }
324
+ async function loadCache(pmRoot) {
325
+ try {
326
+ const raw = await fs2.readFile(getCachePath(pmRoot), "utf8");
327
+ const parsed = JSON.parse(raw);
328
+ if (parsed.version !== CACHE_VERSION || typeof parsed.entries !== "object" || parsed.entries === null) {
329
+ return null;
330
+ }
331
+ return parsed;
332
+ } catch {
333
+ return null;
334
+ }
335
+ }
336
+ async function loadBodyCache(pmRoot) {
337
+ try {
338
+ const raw = await fs2.readFile(getBodyCachePath(pmRoot), "utf8");
339
+ const parsed = JSON.parse(raw);
340
+ if (parsed.version !== CACHE_VERSION || typeof parsed.bodies !== "object" || parsed.bodies === null) {
341
+ return null;
342
+ }
343
+ return parsed;
344
+ } catch {
345
+ return null;
346
+ }
347
+ }
348
+ async function loadCollectionsCache(pmRoot) {
349
+ try {
350
+ const raw = await fs2.readFile(getCollectionsCachePath(pmRoot), "utf8");
351
+ const parsed = JSON.parse(raw);
352
+ if (parsed.version !== CACHE_VERSION || typeof parsed.collections !== "object" || parsed.collections === null) {
353
+ return null;
354
+ }
355
+ return parsed;
356
+ } catch {
357
+ return null;
358
+ }
359
+ }
360
+ async function persistCache(cachePath, envelope) {
361
+ await fs2.mkdir(path2.dirname(cachePath), { recursive: true });
362
+ await writeFileAtomic(cachePath, JSON.stringify(envelope));
363
+ }
364
+ function appendWarning(warnings, warning) {
365
+ if (warnings && !warnings.includes(warning)) {
366
+ warnings.push(warning);
367
+ }
368
+ }
369
+ function statMatches(signature, mtimeMs, ctimeMs, size) {
370
+ return signature.mtime_ms === mtimeMs && signature.ctime_ms === ctimeMs && signature.size === size;
371
+ }
372
+ async function listAllDocumentCandidatesCached(pmRoot, preferredFormat, typeToFolder, warnings, schema, options = {}) {
373
+ const includeBody = options.includeBody !== false;
374
+ const includeCollections = options.includeCollections !== false;
375
+ const contextFingerprint = computeContextFingerprint(preferredFormat, typeToFolder, schema);
376
+ const existingCache = await loadCache(pmRoot);
377
+ const previousEntries = existingCache && existingCache.context_fingerprint === contextFingerprint ? existingCache.entries : {};
378
+ const existingBodyCache = includeBody ? await loadBodyCache(pmRoot) : null;
379
+ const previousBodies = existingBodyCache && existingBodyCache.context_fingerprint === contextFingerprint ? existingBodyCache.bodies : {};
380
+ const existingCollectionsCache = includeCollections ? await loadCollectionsCache(pmRoot) : null;
381
+ const previousCollections = existingCollectionsCache && existingCollectionsCache.context_fingerprint === contextFingerprint ? existingCollectionsCache.collections : {};
382
+ const entries = Object.entries(typeToFolder);
383
+ const dirResults = await Promise.all(entries.map(async ([, folder]) => {
384
+ const dirPath = path2.join(pmRoot, folder);
385
+ try {
386
+ const files = await fs2.readdir(dirPath);
387
+ return { folder, dirPath, files };
388
+ } catch (error) {
389
+ if (typeof error === "object" && error !== null && "code" in error && error.code !== "ENOENT") {
390
+ appendWarning(warnings, `item_list_directory_read_failed:${folder}`);
391
+ }
392
+ return { folder, dirPath, files: [] };
393
+ }
394
+ }));
395
+ const dispatchReadHooks = hasActiveOnReadHooks();
396
+ const newEntries = {};
397
+ const newBodies = {};
398
+ const newCollections = {};
399
+ const documentsById = /* @__PURE__ */ new Map();
400
+ let metadataMiss = false;
401
+ let bodyMiss = false;
402
+ let collectionsMiss = false;
403
+ const parseTasks = [];
404
+ for (const { folder, dirPath, files } of dirResults) {
405
+ for (const file of files) {
406
+ if (!ITEM_FILE_EXTENSIONS.some((ext) => file.toLowerCase().endsWith(ext))) {
407
+ continue;
408
+ }
409
+ const filePath = path2.join(dirPath, file);
410
+ const relativePath = path2.relative(pmRoot, filePath);
411
+ parseTasks.push((async () => {
412
+ try {
413
+ const stat = await fs2.stat(filePath);
414
+ const mtimeMs = stat.mtimeMs;
415
+ const ctimeMs = stat.ctimeMs;
416
+ const { size } = stat;
417
+ const itemFormat = getItemFormatFromPath(filePath);
418
+ if (dispatchReadHooks) {
419
+ for (const warning of await runActiveOnReadHooks({ path: filePath, scope: "project" })) {
420
+ appendWarning(warnings, warning);
421
+ }
422
+ }
423
+ const cachedEntry = previousEntries[relativePath];
424
+ const metadataCached = cachedEntry !== void 0 && statMatches(cachedEntry, mtimeMs, ctimeMs, size);
425
+ const cachedBody = previousBodies[relativePath];
426
+ const bodyCached = cachedBody !== void 0 && statMatches(cachedBody, mtimeMs, ctimeMs, size);
427
+ const cachedCollections = previousCollections[relativePath];
428
+ const collectionsCached = cachedCollections !== void 0 && statMatches(cachedCollections, mtimeMs, ctimeMs, size);
429
+ const needRead = !metadataCached || includeBody && !bodyCached || includeCollections && !collectionsCached;
430
+ let lightMetadata;
431
+ let heavyMetadata;
432
+ let bodyLength;
433
+ let body;
434
+ if (needRead) {
435
+ const raw = await fs2.readFile(filePath, "utf8");
436
+ const parsed = parseItemDocument(raw, {
437
+ format: itemFormat,
438
+ schema,
439
+ onWarning: (w) => appendWarning(warnings, w)
440
+ });
441
+ const split = splitHeavyMetadata(parsed.metadata);
442
+ lightMetadata = metadataCached ? cachedEntry.metadata : split.light;
443
+ bodyLength = metadataCached ? cachedEntry.body_length : parsed.body.length;
444
+ body = includeBody ? parsed.body : void 0;
445
+ if (includeCollections) {
446
+ heavyMetadata = collectionsCached ? cachedCollections.collections : split.heavy;
447
+ }
448
+ if (!metadataCached) {
449
+ metadataMiss = true;
450
+ }
451
+ if (includeBody && !bodyCached) {
452
+ bodyMiss = true;
453
+ }
454
+ if (includeCollections && !collectionsCached) {
455
+ collectionsMiss = true;
456
+ }
457
+ } else {
458
+ lightMetadata = cachedEntry.metadata;
459
+ bodyLength = cachedEntry.body_length;
460
+ body = includeBody ? cachedBody.body : void 0;
461
+ heavyMetadata = includeCollections && cachedCollections ? cachedCollections.collections : void 0;
462
+ }
463
+ newEntries[relativePath] = {
464
+ mtime_ms: mtimeMs,
465
+ ctime_ms: ctimeMs,
466
+ size,
467
+ metadata: lightMetadata,
468
+ body_length: bodyLength
469
+ };
470
+ if (includeBody && body !== void 0) {
471
+ newBodies[relativePath] = { mtime_ms: mtimeMs, ctime_ms: ctimeMs, size, body };
472
+ }
473
+ if (includeCollections && heavyMetadata !== void 0) {
474
+ newCollections[relativePath] = { mtime_ms: mtimeMs, ctime_ms: ctimeMs, size, collections: heavyMetadata };
475
+ }
476
+ const metadata = includeCollections ? mergeHeavyMetadata(lightMetadata, heavyMetadata) : lightMetadata;
477
+ const existing = documentsById.get(metadata.id);
478
+ const candidate = {
479
+ metadata,
480
+ body,
481
+ item_format: itemFormat,
482
+ item_path: filePath
483
+ };
484
+ if (!existing) {
485
+ documentsById.set(metadata.id, { candidate, itemFormat });
486
+ } else {
487
+ const shouldReplace = preferredFormat ? itemFormat === preferredFormat && existing.itemFormat !== preferredFormat : itemFormat === "toon" && existing.itemFormat !== "toon";
488
+ if (shouldReplace) {
489
+ documentsById.set(metadata.id, { candidate, itemFormat });
490
+ }
491
+ }
492
+ } catch {
493
+ appendWarning(warnings, `item_list_item_read_failed:${folder}/${file}`);
494
+ }
495
+ })());
496
+ }
497
+ }
498
+ await Promise.all(parseTasks);
499
+ const metadataDirty = metadataMiss || Object.keys(previousEntries).length !== Object.keys(newEntries).length;
500
+ if (metadataDirty || existingCache === null || existingCache.context_fingerprint !== contextFingerprint) {
501
+ await persistCache(getCachePath(pmRoot), {
502
+ version: CACHE_VERSION,
503
+ context_fingerprint: contextFingerprint,
504
+ entries: newEntries
505
+ }).catch(() => {
506
+ });
507
+ }
508
+ if (includeBody) {
509
+ const bodyDirty = bodyMiss || Object.keys(previousBodies).length !== Object.keys(newBodies).length;
510
+ if (bodyDirty || existingBodyCache === null || existingBodyCache.context_fingerprint !== contextFingerprint) {
511
+ await persistCache(getBodyCachePath(pmRoot), {
512
+ version: CACHE_VERSION,
513
+ context_fingerprint: contextFingerprint,
514
+ bodies: newBodies
515
+ }).catch(() => {
516
+ });
517
+ }
518
+ }
519
+ if (includeCollections) {
520
+ const collectionsDirty = collectionsMiss || Object.keys(previousCollections).length !== Object.keys(newCollections).length;
521
+ if (collectionsDirty || existingCollectionsCache === null || existingCollectionsCache.context_fingerprint !== contextFingerprint) {
522
+ await persistCache(getCollectionsCachePath(pmRoot), {
523
+ version: CACHE_VERSION,
524
+ context_fingerprint: contextFingerprint,
525
+ collections: newCollections
526
+ }).catch(() => {
527
+ });
528
+ }
529
+ }
530
+ return [...documentsById.values()].sort((left, right) => left.candidate.metadata.id.localeCompare(right.candidate.metadata.id)).map((entry) => entry.candidate);
531
+ }
532
+ async function listAllDocumentsCached(pmRoot, preferredFormat, typeToFolder, warnings, schema) {
533
+ const candidates = await listAllDocumentCandidatesCached(pmRoot, preferredFormat, typeToFolder, warnings, schema, {
534
+ includeBody: false
535
+ });
536
+ return candidates.map((candidate) => ({
537
+ metadata: candidate.metadata,
538
+ body: candidate.body ?? ""
539
+ }));
540
+ }
541
+ async function listAllDocumentsCachedLight(pmRoot, preferredFormat, typeToFolder, warnings, schema) {
542
+ const candidates = await listAllDocumentCandidatesCached(pmRoot, preferredFormat, typeToFolder, warnings, schema, {
543
+ includeBody: false,
544
+ includeCollections: false
545
+ });
546
+ return candidates.map((candidate) => ({
547
+ metadata: candidate.metadata,
548
+ body: candidate.body ?? ""
549
+ }));
550
+ }
551
+
552
+ // dist/core/store/item-store.js
553
+ import fs3 from "node:fs/promises";
554
+ import path3 from "node:path";
555
+ !(function() {
556
+ try {
557
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
558
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "e156425f-15da-5c83-b5e6-6c1c1271bf05");
559
+ } catch (e2) {
560
+ }
561
+ })();
562
+ async function fileExists(targetPath) {
563
+ try {
564
+ await fs3.access(targetPath);
565
+ return true;
566
+ } catch {
567
+ return false;
568
+ }
569
+ }
570
+ function appendWarning2(warnings, warning) {
571
+ if (!warnings) {
572
+ return;
573
+ }
574
+ if (!warnings.includes(warning)) {
575
+ warnings.push(warning);
576
+ }
577
+ }
578
+ function resolveItemFormatSearchOrder(preferredFormat) {
579
+ if (preferredFormat === "toon") {
580
+ return ["toon", "json_markdown"];
581
+ }
582
+ if (preferredFormat === "json_markdown") {
583
+ return ["json_markdown", "toon"];
584
+ }
585
+ return ["toon", "json_markdown"];
586
+ }
587
+ async function locateItem(pmRoot, rawId, idPrefix, preferredFormat, typeToFolder = TYPE_TO_FOLDER) {
588
+ const normalizedId = normalizeItemId(rawId, idPrefix);
589
+ const rawNormalizedId = normalizeRawItemId(rawId);
590
+ const candidateIds = normalizedId === rawNormalizedId ? [normalizedId] : [normalizedId, rawNormalizedId];
591
+ const entries = Object.entries(typeToFolder);
592
+ const searchOrder = resolveItemFormatSearchOrder(preferredFormat);
593
+ for (const candidateId of candidateIds) {
594
+ for (const [type] of entries) {
595
+ for (const itemFormat of searchOrder) {
596
+ const itemPath = getItemPath(pmRoot, type, candidateId, itemFormat, typeToFolder);
597
+ if (await fileExists(itemPath)) {
598
+ return {
599
+ id: candidateId,
600
+ type,
601
+ itemPath,
602
+ item_format: itemFormat
603
+ };
604
+ }
605
+ }
606
+ }
607
+ }
608
+ return null;
609
+ }
610
+ async function readLocatedItem(item, options = {}) {
611
+ const raw = await fs3.readFile(item.itemPath, "utf8");
612
+ await runActiveOnReadHooks({
613
+ path: item.itemPath,
614
+ scope: "project"
615
+ });
616
+ const document = parseItemDocument(raw, {
617
+ format: item.item_format,
618
+ schema: options.schema,
619
+ onWarning: (warning) => appendWarning2(options.warnings, warning)
620
+ });
621
+ return { raw, document };
622
+ }
623
+ async function listAllFrontMatter(pmRoot, preferredFormat, typeToFolder = TYPE_TO_FOLDER, warnings, schema) {
624
+ const documents = await listAllDocumentsCached(pmRoot, preferredFormat, typeToFolder, warnings, schema);
625
+ return documents.map((document) => document.metadata);
626
+ }
627
+ async function listAllFrontMatterLight(pmRoot, preferredFormat, typeToFolder = TYPE_TO_FOLDER, warnings, schema) {
628
+ const documents = await listAllDocumentsCachedLight(pmRoot, preferredFormat, typeToFolder, warnings, schema);
629
+ return documents.map((document) => document.metadata);
630
+ }
631
+ async function listAllFrontMatterWithBody(pmRoot, preferredFormat, typeToFolder = TYPE_TO_FOLDER, warnings, schema) {
632
+ const candidates = await listAllDocumentCandidatesCached(pmRoot, preferredFormat, typeToFolder, warnings, schema, { includeBody: true });
633
+ return candidates.map((candidate) => ({
634
+ ...candidate.metadata,
635
+ body: candidate.body ?? ""
636
+ }));
637
+ }
638
+ async function listKnownItemIds(pmRoot, typeToFolder) {
639
+ const folders = new Set(Object.values(typeToFolder));
640
+ const allIds = [];
641
+ await Promise.all([...folders].map(async (folder) => {
642
+ try {
643
+ const entries = await fs3.readdir(path3.join(pmRoot, folder));
644
+ for (const entry of entries) {
645
+ for (const ext of ITEM_FILE_EXTENSIONS) {
646
+ if (entry.toLowerCase().endsWith(ext)) {
647
+ allIds.push(entry.slice(0, -ext.length));
648
+ break;
649
+ }
650
+ }
651
+ }
652
+ } catch {
653
+ }
654
+ }));
655
+ return allIds;
656
+ }
657
+ function levenshtein(a, b) {
658
+ if (a === b)
659
+ return 0;
660
+ if (a.length === 0)
661
+ return b.length;
662
+ if (b.length === 0)
663
+ return a.length;
664
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
665
+ for (let i = 1; i <= a.length; i++) {
666
+ const curr = [i];
667
+ for (let j = 1; j <= b.length; j++) {
668
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
669
+ curr.push(Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost));
670
+ }
671
+ prev = curr;
672
+ }
673
+ return prev[b.length];
674
+ }
675
+ async function buildDidYouMeanSuggestions(pmRoot, badId, idPrefix, typeToFolder) {
676
+ const normalized = normalizeItemId(badId, idPrefix);
677
+ const ids = await listKnownItemIds(pmRoot, typeToFolder);
678
+ if (ids.length === 0)
679
+ return [];
680
+ const scored = ids.map((id) => ({ id, distance: levenshtein(id, normalized) })).filter((entry) => entry.distance <= Math.max(3, Math.floor(normalized.length / 2))).sort((left, right) => left.distance - right.distance).slice(0, 3).map((entry) => entry.id);
681
+ return scored;
682
+ }
683
+ async function buildItemNotFoundError(pmRoot, badId, idPrefix, typeToFolder) {
684
+ const suggestions = await buildDidYouMeanSuggestions(pmRoot, badId, idPrefix, typeToFolder);
685
+ const nextSteps = ["Confirm the active --path/PM_PATH scope, then retry with a valid id."];
686
+ if (suggestions.length > 0) {
687
+ nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`);
688
+ }
689
+ return new PmCliError(`Item ${badId} not found`, EXIT_CODE.NOT_FOUND, { nextSteps });
690
+ }
691
+ function bypassesAssigneeConflict(op, bypassAssigneeConflict) {
692
+ return op === "claim" || bypassAssigneeConflict === true && (op === "comment_add" || op === "note_add" || op === "learning_add" || op === "release" || op === "update" || op === "update_audit");
693
+ }
694
+ async function prepareLockedItem(params) {
695
+ const typeToFolder = params.typeToFolder ?? resolveItemTypeRegistry(params.settings, getActiveExtensionRegistrations()).type_to_folder;
696
+ const located = await locateItem(params.pmRoot, params.id, params.settings.id_prefix, params.settings.item_format, typeToFolder);
697
+ if (!located) {
698
+ throw await buildItemNotFoundError(params.pmRoot, params.id, params.settings.id_prefix, typeToFolder);
699
+ }
700
+ const releaseLock = await acquireLock(params.pmRoot, located.id, params.settings.locks.ttl_seconds, params.author, Boolean(params.force), params.settings.governance.force_required_for_stale_lock);
701
+ try {
702
+ const warnings = [];
703
+ const { raw: originalRaw, document } = await readLocatedItem(located, {
704
+ schema: params.settings.schema,
705
+ warnings
706
+ });
707
+ const assigned = document.metadata.assignee?.trim();
708
+ const governance = resolveGovernanceKnobs(params.settings);
709
+ const hasOwnershipConflict = assigned && assigned !== params.author && !params.force && !bypassesAssigneeConflict(params.op, params.bypassAssigneeConflict);
710
+ if (hasOwnershipConflict) {
711
+ if (governance.ownership_enforcement === "strict") {
712
+ throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`, EXIT_CODE.CONFLICT);
713
+ }
714
+ if (governance.ownership_enforcement === "warn") {
715
+ warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`);
716
+ }
717
+ }
718
+ return {
719
+ typeToFolder,
720
+ located,
721
+ originalRaw,
722
+ document,
723
+ warnings,
724
+ releaseLock
725
+ };
726
+ } catch (error) {
727
+ await releaseLock();
728
+ throw error;
729
+ }
730
+ }
731
+ async function mutateItem(params) {
732
+ const prepared = await prepareLockedItem({
733
+ pmRoot: params.pmRoot,
734
+ settings: params.settings,
735
+ id: params.id,
736
+ op: params.op,
737
+ author: params.author,
738
+ force: params.force,
739
+ bypassAssigneeConflict: params.bypassAssigneeConflict,
740
+ typeToFolder: params.typeToFolder
741
+ });
742
+ const { typeToFolder, located, originalRaw, document, warnings: parseWarnings, releaseLock } = prepared;
743
+ try {
744
+ const historyPolicy = await enforceHistoryStreamPolicyForItem({
745
+ pmRoot: params.pmRoot,
746
+ settings: params.settings,
747
+ itemId: located.id,
748
+ commandLabel: params.op
749
+ });
750
+ const beforeDocument = canonicalDocument(document, { schema: params.settings.schema });
751
+ const mutableDocument = canonicalDocument(structuredClone(document), { schema: params.settings.schema });
752
+ const mutation = params.mutate(mutableDocument);
753
+ mutableDocument.metadata.updated_at = nowIso();
754
+ const afterDocument = canonicalDocument(mutableDocument, { schema: params.settings.schema });
755
+ const targetItemFormat = "toon";
756
+ const serializedAfter = serializeItemDocument(afterDocument, {
757
+ format: targetItemFormat,
758
+ schema: params.settings.schema
759
+ });
760
+ const targetItemPath = getItemPath(params.pmRoot, afterDocument.metadata.type, located.id, targetItemFormat, typeToFolder);
761
+ const historyPath = getHistoryPath(params.pmRoot, located.id);
762
+ const serviceWriteOverride = await runActiveServiceOverride("item_store_write", {
763
+ op: params.op,
764
+ pm_root: params.pmRoot,
765
+ item_id: located.id,
766
+ source_item_path: located.itemPath,
767
+ target_item_path: targetItemPath,
768
+ history_path: historyPath,
769
+ item_format: targetItemFormat,
770
+ before: beforeDocument,
771
+ after: afterDocument,
772
+ contents: serializedAfter
773
+ });
774
+ let effectiveTargetItemPath = targetItemPath;
775
+ let effectiveSerializedAfter = serializedAfter;
776
+ let skipItemWrite = false;
777
+ if (serviceWriteOverride.handled && typeof serviceWriteOverride.result === "object" && serviceWriteOverride.result !== null) {
778
+ const overrideRecord = serviceWriteOverride.result;
779
+ if (typeof overrideRecord.target_item_path === "string" && overrideRecord.target_item_path.trim().length > 0) {
780
+ effectiveTargetItemPath = overrideRecord.target_item_path;
781
+ }
782
+ if (typeof overrideRecord.contents === "string") {
783
+ effectiveSerializedAfter = overrideRecord.contents;
784
+ }
785
+ if (overrideRecord.skip_write === true) {
786
+ skipItemWrite = true;
787
+ }
788
+ }
789
+ if (!skipItemWrite) {
790
+ await writeFileAtomic(effectiveTargetItemPath, effectiveSerializedAfter);
791
+ }
792
+ if (!skipItemWrite && effectiveTargetItemPath !== located.itemPath) {
793
+ await fs3.rm(located.itemPath);
794
+ }
795
+ const entry = createHistoryEntry({
796
+ nowIso: afterDocument.metadata.updated_at,
797
+ author: params.author,
798
+ op: params.op,
799
+ before: beforeDocument,
800
+ after: afterDocument,
801
+ message: params.message
802
+ });
803
+ try {
804
+ await appendHistoryEntry(historyPath, entry);
805
+ } catch (error) {
806
+ if (!skipItemWrite && effectiveTargetItemPath !== located.itemPath) {
807
+ await writeFileAtomic(located.itemPath, originalRaw);
808
+ await fs3.rm(effectiveTargetItemPath, { force: true });
809
+ } else if (!skipItemWrite) {
810
+ await writeFileAtomic(located.itemPath, originalRaw);
811
+ }
812
+ throw error;
813
+ }
814
+ const hookWarnings = [
815
+ ...await runActiveOnWriteHooks({
816
+ path: effectiveTargetItemPath,
817
+ scope: "project",
818
+ op: params.op
819
+ }),
820
+ ...await runActiveOnWriteHooks({
821
+ path: historyPath,
822
+ scope: "project",
823
+ op: `${params.op}:history`
824
+ })
825
+ ];
826
+ return {
827
+ item: afterDocument.metadata,
828
+ body: afterDocument.body,
829
+ changedFields: mutation.changedFields,
830
+ warnings: [
831
+ ...parseWarnings,
832
+ ...mutation.warnings ?? [],
833
+ ...historyPolicy.warnings,
834
+ ...serviceWriteOverride.warnings,
835
+ ...hookWarnings
836
+ ]
837
+ };
838
+ } finally {
839
+ await releaseLock();
840
+ }
841
+ }
842
+ async function deleteItem(params) {
843
+ const prepared = await prepareLockedItem({
844
+ pmRoot: params.pmRoot,
845
+ settings: params.settings,
846
+ id: params.id,
847
+ op: "delete",
848
+ author: params.author,
849
+ force: params.force
850
+ });
851
+ const { located, originalRaw, document, warnings: parseWarnings, releaseLock } = prepared;
852
+ try {
853
+ const historyPolicy = await enforceHistoryStreamPolicyForItem({
854
+ pmRoot: params.pmRoot,
855
+ settings: params.settings,
856
+ itemId: located.id,
857
+ commandLabel: "delete"
858
+ });
859
+ const beforeDocument = canonicalDocument(document, { schema: params.settings.schema });
860
+ const deletionTimestamp = nowIso();
861
+ const tombstoneDocument = EMPTY_CANONICAL_DOCUMENT;
862
+ const historyEntry = createHistoryEntry({
863
+ nowIso: deletionTimestamp,
864
+ author: params.author,
865
+ op: "delete",
866
+ before: beforeDocument,
867
+ after: tombstoneDocument,
868
+ message: params.message
869
+ });
870
+ const historyPath = getHistoryPath(params.pmRoot, located.id);
871
+ const serviceDeleteOverride = await runActiveServiceOverride("item_store_delete", {
872
+ op: "delete",
873
+ pm_root: params.pmRoot,
874
+ item_id: located.id,
875
+ item_path: located.itemPath,
876
+ history_path: historyPath,
877
+ before: beforeDocument
878
+ });
879
+ let effectiveItemPath = located.itemPath;
880
+ let skipDelete = false;
881
+ if (serviceDeleteOverride.handled && typeof serviceDeleteOverride.result === "object" && serviceDeleteOverride.result !== null) {
882
+ const overrideRecord = serviceDeleteOverride.result;
883
+ if (typeof overrideRecord.item_path === "string" && overrideRecord.item_path.trim().length > 0) {
884
+ effectiveItemPath = overrideRecord.item_path;
885
+ }
886
+ if (overrideRecord.skip_delete === true) {
887
+ skipDelete = true;
888
+ }
889
+ }
890
+ if (params.dryRun === true) {
891
+ return {
892
+ item: beforeDocument.metadata,
893
+ changedFields: ["deleted"],
894
+ targetPath: effectiveItemPath,
895
+ warnings: [...parseWarnings, ...historyPolicy.warnings, ...serviceDeleteOverride.warnings]
896
+ };
897
+ }
898
+ if (!skipDelete) {
899
+ await fs3.rm(effectiveItemPath);
900
+ }
901
+ try {
902
+ await appendHistoryEntry(historyPath, historyEntry);
903
+ } catch (error) {
904
+ if (!skipDelete) {
905
+ await writeFileAtomic(effectiveItemPath, originalRaw);
906
+ }
907
+ throw error;
908
+ }
909
+ const hookWarnings = [
910
+ ...await runActiveOnWriteHooks({
911
+ path: effectiveItemPath,
912
+ scope: "project",
913
+ op: "delete"
914
+ }),
915
+ ...await runActiveOnWriteHooks({
916
+ path: historyPath,
917
+ scope: "project",
918
+ op: "delete:history"
919
+ })
920
+ ];
921
+ return {
922
+ item: beforeDocument.metadata,
923
+ changedFields: ["deleted"],
924
+ warnings: [...parseWarnings, ...historyPolicy.warnings, ...serviceDeleteOverride.warnings, ...hookWarnings]
925
+ };
926
+ } finally {
927
+ await releaseLock();
928
+ }
929
+ }
930
+
931
+ export {
932
+ toItemRecord,
933
+ hashDocument,
934
+ hashEmptyDocument,
935
+ createHistoryEntry,
936
+ appendHistoryEntry,
937
+ enforceHistoryStreamPolicyForItem,
938
+ enforceHistoryStreamPolicyForItems,
939
+ HEAVY_METADATA_KEYS,
940
+ listAllDocumentCandidatesCached,
941
+ locateItem,
942
+ readLocatedItem,
943
+ listAllFrontMatter,
944
+ listAllFrontMatterLight,
945
+ listAllFrontMatterWithBody,
946
+ buildItemNotFoundError,
947
+ mutateItem,
948
+ deleteItem
949
+ };
950
+ //# sourceMappingURL=chunk-BUPWJ3IJ.js.map