@unbrained/pm-cli 2026.11.2 → 2026.11.4

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 (242) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +24 -0
  3. package/dist/cli/error-guidance.d.ts +23 -35
  4. package/dist/cli/error-guidance.js +4 -3
  5. package/dist/cli/expected-revisions.d.ts +55 -0
  6. package/dist/cli/expected-revisions.js +2 -0
  7. package/dist/cli/main.js +2 -2
  8. package/dist/cli/runtime/field-route-retry.d.ts +15 -0
  9. package/dist/cli/runtime/field-route-retry.js +2 -0
  10. package/dist/cli/runtime/invocation-options.js +1 -1
  11. package/dist/cli-bundle/bundle-manifest.json +1 -1
  12. package/dist/cli-bundle/chunks/{chunk-3A4NVHYS.js → chunk-2GW662DP.js} +2 -2
  13. package/dist/cli-bundle/chunks/chunk-3OXQGGRD.js +115 -0
  14. package/dist/cli-bundle/chunks/chunk-5BVZ32G7.js +2 -0
  15. package/dist/cli-bundle/chunks/chunk-5S6RT5LX.js +9 -0
  16. package/dist/cli-bundle/chunks/chunk-5Z6LWFDL.js +31 -0
  17. package/dist/cli-bundle/chunks/{chunk-RGHLQGEX.js → chunk-6T2V3UIK.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-JRXD7SIL.js → chunk-7PGNAHNW.js} +2 -2
  19. package/dist/cli-bundle/chunks/chunk-7RCI7AAA.js +20 -0
  20. package/dist/cli-bundle/chunks/chunk-AQ5UHHQS.js +2 -0
  21. package/dist/cli-bundle/chunks/chunk-BK2XAQVC.js +2 -0
  22. package/dist/cli-bundle/chunks/{chunk-ABFFRQRO.js → chunk-BRIPGUAO.js} +2 -2
  23. package/dist/cli-bundle/chunks/chunk-BWAXA6S4.js +6 -0
  24. package/dist/cli-bundle/chunks/{chunk-HOGKWJU5.js → chunk-CERNIZLB.js} +66 -66
  25. package/dist/cli-bundle/chunks/chunk-DSCFJTHB.js +122 -0
  26. package/dist/cli-bundle/chunks/{chunk-VEOFWE32.js → chunk-L4BKTPJ6.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-NGRPD3ZO.js → chunk-NPEDFOVQ.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-J3JM36EH.js → chunk-O4ZLEN4T.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-533L6D2N.js → chunk-ODMJ3HIB.js} +3 -3
  30. package/dist/cli-bundle/chunks/{chunk-KJLGBLR3.js → chunk-QN7VCOUU.js} +2 -2
  31. package/dist/cli-bundle/chunks/chunk-QQHMNUZT.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-D52QQ7LP.js → chunk-RSAN2YUU.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-SRDO2NJU.js +2 -0
  34. package/dist/cli-bundle/chunks/chunk-T56MB6SF.js +2 -0
  35. package/dist/cli-bundle/chunks/chunk-TX2W6G37.js +3 -0
  36. package/dist/cli-bundle/chunks/{chunk-GK2CHAT3.js → chunk-UJMQP2HP.js} +2 -2
  37. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-IEJ2QOW3.js → indexed-receipt-blobs-I6RQGD6Y.js} +2 -2
  38. package/dist/cli-bundle/chunks/item-revision-UAZOBP2Q.js +2 -0
  39. package/dist/cli-bundle/chunks/item-transaction-N5F4LXYV.js +2 -0
  40. package/dist/cli-bundle/chunks/mutation-admission-QZQI2NN5.js +2 -0
  41. package/dist/cli-bundle/chunks/{register-list-query-NZTK3AXA.js → register-list-query-P3NOKQUA.js} +2 -2
  42. package/dist/cli-bundle/chunks/{register-mutation-2OFAMOVH.js → register-mutation-A6I5K5N6.js} +2 -2
  43. package/dist/cli-bundle/chunks/register-operations-SPKB3TNM.js +2 -0
  44. package/dist/cli-bundle/chunks/register-setup-ZZRHJ4IS.js +2 -0
  45. package/dist/cli-bundle/chunks/{settlement-hook-UTCEZBFT.js → settlement-hook-JHXLUBEN.js} +2 -2
  46. package/dist/cli-bundle/chunks/{stage-VLI4OBVX.js → stage-L3T725DS.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-5NGNO54M.js +44 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-PCCZ72C3.js → chunk-A2246ZM7.js} +54 -54
  49. package/dist/cli-bundle/focused-chunks/chunk-B6U44WPW.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-BAW3DGQO.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-BHNY3KPJ.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-745IDMTD.js → chunk-C7UX2ZI3.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-CBG67HUP.js +23 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-NJFMG3IK.js → chunk-CO2DNPH7.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-CXTDEQ3N.js +8 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-FEPE2CE4.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-FFO7RBLN.js +2 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-QNXXOFLQ.js → chunk-FXFDVM5O.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-QVFE5LIX.js → chunk-G6ERMFJ5.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +2 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-MQVBWFJF.js → chunk-IDAYTYNN.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/chunk-J3YOATXR.js +80 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-3UD6F2KQ.js → chunk-J6FDCAMH.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/chunk-J7M52SCZ.js +2 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-JQS7TYQ6.js +12 -0
  67. package/dist/cli-bundle/focused-chunks/chunk-MEJKELWC.js +26 -0
  68. package/dist/cli-bundle/focused-chunks/chunk-PMKR4MJI.js +2 -0
  69. package/dist/cli-bundle/focused-chunks/chunk-PNPYQDHU.js +2 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-Q4OIRSKL.js +2 -0
  71. package/dist/cli-bundle/focused-chunks/{chunk-I4Z2SCV5.js → chunk-QEVJ3Y67.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/{chunk-Q23K6WLV.js → chunk-SDLIUZEL.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/chunk-TFYTTDAK.js +2 -0
  74. package/dist/cli-bundle/focused-chunks/chunk-W3CSX6GI.js +3 -0
  75. package/dist/cli-bundle/focused-chunks/{chunk-B6OOKKOX.js → chunk-Y5GOUUYJ.js} +3 -3
  76. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FT3KF6VJ.js → indexed-receipt-blobs-7XGVHYAO.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/item-revision-L6GVT42D.js +2 -0
  78. package/dist/cli-bundle/focused-chunks/item-transaction-GYGP264N.js +2 -0
  79. package/dist/cli-bundle/focused-chunks/mutation-admission-UWTH56OD.js +2 -0
  80. package/dist/cli-bundle/focused-chunks/{settlement-hook-KMIBD4F2.js → settlement-hook-H56537UV.js} +2 -2
  81. package/dist/cli-bundle/focused-chunks/{stage-6B3O2GZ6.js → stage-WRSNJ7VI.js} +2 -2
  82. package/dist/cli-bundle/main.js +30 -29
  83. package/dist/cli-bundle/sdk-authoring.js +1 -1
  84. package/dist/cli-bundle/sdk-contracts.js +5 -5
  85. package/dist/cli-bundle/sdk-core.js +1 -1
  86. package/dist/cli-bundle/sdk-governance.js +1 -1
  87. package/dist/cli-bundle/sdk-graph.js +1 -1
  88. package/dist/cli-bundle/sdk-merge.js +57 -57
  89. package/dist/cli-bundle/sdk-query.js +1 -1
  90. package/dist/cli-bundle/sdk-runtime.js +1 -1
  91. package/dist/cli-bundle/sdk-testing.js +1 -1
  92. package/dist/cli-bundle/sdk.js +11 -11
  93. package/dist/core/config/positional-value.d.ts +1 -1
  94. package/dist/core/config/positional-value.js +1 -1
  95. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  96. package/dist/core/extensions/item-fields.d.ts +1 -1
  97. package/dist/core/extensions/item-fields.js +1 -1
  98. package/dist/core/extensions/reserved-host-flags.js +1 -1
  99. package/dist/core/history/history-rewrite.js +1 -1
  100. package/dist/core/schema/runtime-field-values.d.ts +30 -0
  101. package/dist/core/schema/runtime-field-values.js +1 -1
  102. package/dist/core/sentry/helpers.js +1 -1
  103. package/dist/core/sentry/instrument.js +1 -1
  104. package/dist/core/shared/command-types.d.ts +7 -0
  105. package/dist/core/shared/error-details.d.ts +98 -0
  106. package/dist/core/shared/error-details.js +2 -0
  107. package/dist/core/shared/errors.d.ts +37 -0
  108. package/dist/core/shared/errors.js +1 -1
  109. package/dist/core/store/item-mutation-precondition.d.ts +70 -6
  110. package/dist/core/store/item-mutation-precondition.js +1 -1
  111. package/dist/core/store/item-store.js +1 -1
  112. package/dist/core/store/settings-validator.js +1 -1
  113. package/dist/core/store/settings.js +1 -1
  114. package/dist/mcp/server.js +2 -2
  115. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  116. package/dist/sdk/cli-contracts/completeness.js +1 -1
  117. package/dist/sdk/cli-contracts/enum-contracts.d.ts +11 -0
  118. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  119. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  120. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  121. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  122. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  123. package/dist/sdk/cli-program.js +1 -1
  124. package/dist/sdk/config.d.ts +1 -1
  125. package/dist/sdk/config.js +1 -1
  126. package/dist/sdk/environment/project-runtime-compatibility.js +1 -1
  127. package/dist/sdk/errors.d.ts +6 -2
  128. package/dist/sdk/errors.js +1 -1
  129. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  130. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  131. package/dist/sdk/governance/validate.js +1 -1
  132. package/dist/sdk/history/salvage.js +3 -3
  133. package/dist/sdk/history-compact.d.ts +7 -1
  134. package/dist/sdk/history-compact.js +1 -1
  135. package/dist/sdk/history-repair.d.ts +2 -1
  136. package/dist/sdk/history-repair.js +1 -1
  137. package/dist/sdk/index.d.ts +4 -1
  138. package/dist/sdk/index.js +1 -1
  139. package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +10 -2
  140. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  141. package/dist/sdk/lifecycle/claim.js +1 -1
  142. package/dist/sdk/lifecycle/close-many.d.ts +11 -2
  143. package/dist/sdk/lifecycle/close-many.js +1 -1
  144. package/dist/sdk/lifecycle/close.d.ts +15 -0
  145. package/dist/sdk/lifecycle/close.js +1 -1
  146. package/dist/sdk/lifecycle/core-field-recovery.d.ts +26 -0
  147. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  148. package/dist/sdk/lifecycle/create.js +1 -1
  149. package/dist/sdk/lifecycle/item-revision.d.ts +162 -0
  150. package/dist/sdk/lifecycle/item-revision.js +2 -0
  151. package/dist/sdk/lifecycle/restore.js +1 -1
  152. package/dist/sdk/lifecycle/start-blockers.d.ts +52 -0
  153. package/dist/sdk/lifecycle/start-blockers.js +2 -0
  154. package/dist/sdk/lifecycle/task-composition.d.ts +11 -0
  155. package/dist/sdk/lifecycle/task-composition.js +1 -1
  156. package/dist/sdk/lifecycle/update-many.d.ts +11 -2
  157. package/dist/sdk/lifecycle/update-many.js +1 -1
  158. package/dist/sdk/lifecycle/update.js +2 -2
  159. package/dist/sdk/public-surface.json +1 -1
  160. package/dist/sdk/query/declared-blockers.d.ts +16 -0
  161. package/dist/sdk/query/declared-blockers.js +2 -0
  162. package/dist/sdk/query/get.d.ts +7 -0
  163. package/dist/sdk/query/get.js +1 -1
  164. package/dist/sdk/query/projection-contracts.js +1 -1
  165. package/dist/sdk/runtime-input.d.ts +12 -0
  166. package/dist/sdk/runtime-input.js +1 -1
  167. package/dist/sdk/runtime.d.ts +11 -1
  168. package/dist/sdk/runtime.js +1 -1
  169. package/dist/sdk/structured-mutations.js +1 -1
  170. package/dist/sdk/test/batch.js +2 -2
  171. package/dist/sdk/test/entry.d.ts +5 -0
  172. package/dist/sdk/test/entry.js +2 -2
  173. package/dist/sdk/test/execution.d.ts +1 -2
  174. package/dist/sdk/test/execution.js +2 -2
  175. package/dist/sdk/test/linked-command-detection.d.ts +10 -0
  176. package/dist/sdk/test/linked-command-detection.js +1 -1
  177. package/dist/sdk/test/update.d.ts +2 -0
  178. package/dist/sdk/test/update.js +1 -1
  179. package/dist/sdk/workspace-transaction.d.ts +17 -6
  180. package/dist/sdk/workspace-transaction.js +1 -1
  181. package/dist/types.d.ts +6 -0
  182. package/dist/types.js +1 -1
  183. package/docs/COMMANDS.md +91 -0
  184. package/docs/CONFIGURATION.md +1 -0
  185. package/docs/EXTENSIONS.md +2 -2
  186. package/docs/LINKED_TEST_EDITS.md +38 -5
  187. package/docs/SDK.md +185 -1
  188. package/docs/agent-task-token-baseline.json +1 -1
  189. package/docs/generated/FLAG_LEXICON_BUDGETS.md +111 -111
  190. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +15 -3
  191. package/marketplace.json +1 -1
  192. package/package.json +1 -1
  193. package/packages/pm-beads/package.json +1 -1
  194. package/packages/pm-calendar/package.json +1 -1
  195. package/packages/pm-command-kit/package.json +1 -1
  196. package/packages/pm-digital-twin/package.json +1 -1
  197. package/packages/pm-governance-audit/package.json +1 -1
  198. package/packages/pm-guide-shell/package.json +1 -1
  199. package/packages/pm-kanban/package.json +1 -1
  200. package/packages/pm-lifecycle-hooks/package.json +1 -1
  201. package/packages/pm-linked-test-adapters/package.json +1 -1
  202. package/packages/pm-search-advanced/package.json +1 -1
  203. package/packages/pm-templates/package.json +1 -1
  204. package/packages/pm-todos/package.json +1 -1
  205. package/packages/pm-vcs/package.json +1 -1
  206. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  207. package/plugins/pm-claude/package.json +1 -1
  208. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  209. package/plugins/pm-codex/package.json +1 -1
  210. package/plugins/pm-codex/plugin.json +1 -1
  211. package/runtime-dependencies.json +1 -1
  212. package/dist/cli-bundle/chunks/chunk-3ZQQVJT2.js +0 -20
  213. package/dist/cli-bundle/chunks/chunk-4HW253W2.js +0 -2
  214. package/dist/cli-bundle/chunks/chunk-4OELCF3O.js +0 -2
  215. package/dist/cli-bundle/chunks/chunk-BFZUJ5QP.js +0 -115
  216. package/dist/cli-bundle/chunks/chunk-DAZFCSDV.js +0 -2
  217. package/dist/cli-bundle/chunks/chunk-EN27ZQSV.js +0 -2
  218. package/dist/cli-bundle/chunks/chunk-K46GDAKX.js +0 -6
  219. package/dist/cli-bundle/chunks/chunk-OJR2YGXF.js +0 -31
  220. package/dist/cli-bundle/chunks/chunk-QHHFXNSQ.js +0 -3
  221. package/dist/cli-bundle/chunks/chunk-ZNWDYDFF.js +0 -129
  222. package/dist/cli-bundle/chunks/item-transaction-JHPBH6N7.js +0 -2
  223. package/dist/cli-bundle/chunks/mutation-admission-QUNQZCZ5.js +0 -2
  224. package/dist/cli-bundle/chunks/register-operations-RFMM5KZ6.js +0 -2
  225. package/dist/cli-bundle/chunks/register-setup-6B6Q7M5L.js +0 -2
  226. package/dist/cli-bundle/focused-chunks/chunk-4NVPDZLX.js +0 -12
  227. package/dist/cli-bundle/focused-chunks/chunk-4UUE3YXZ.js +0 -2
  228. package/dist/cli-bundle/focused-chunks/chunk-5UDDRPYR.js +0 -8
  229. package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +0 -2
  230. package/dist/cli-bundle/focused-chunks/chunk-EJJWOFP5.js +0 -91
  231. package/dist/cli-bundle/focused-chunks/chunk-FUGYXUUL.js +0 -80
  232. package/dist/cli-bundle/focused-chunks/chunk-HMXVTWIV.js +0 -3
  233. package/dist/cli-bundle/focused-chunks/chunk-JLN5CFYM.js +0 -2
  234. package/dist/cli-bundle/focused-chunks/chunk-K4FMZB4Y.js +0 -23
  235. package/dist/cli-bundle/focused-chunks/chunk-PF553UVP.js +0 -44
  236. package/dist/cli-bundle/focused-chunks/chunk-RUCG6UWN.js +0 -2
  237. package/dist/cli-bundle/focused-chunks/chunk-SGWYNU7T.js +0 -2
  238. package/dist/cli-bundle/focused-chunks/chunk-TGS5RXBY.js +0 -26
  239. package/dist/cli-bundle/focused-chunks/chunk-WD43E7RU.js +0 -2
  240. package/dist/cli-bundle/focused-chunks/chunk-YM4AMP7H.js +0 -2
  241. package/dist/cli-bundle/focused-chunks/item-transaction-F4SN7TXJ.js +0 -2
  242. package/dist/cli-bundle/focused-chunks/mutation-admission-7R2FXJ5O.js +0 -2
@@ -1,8 +0,0 @@
1
- import{r as q,s as V}from"./chunk-745IDMTD.js";import{m,s as M,u as k}from"./chunk-4UUE3YXZ.js";import{Fa as O,Fd as N,Id as D,Ld as j,R as x,W as g,be as z}from"./chunk-TGS5RXBY.js";import{A as C,E as _,I as L,z as S}from"./chunk-QVFE5LIX.js";import{constants as p}from"node:fs";import{lstat as A,mkdir as I,open as P}from"node:fs/promises";import h from"node:path";(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="5434ff6f-95af-5983-88cb-fd360d95cb9e")}catch{}})();function E(i,e){if(typeof i!="string"||i.trim().length===0)throw new TypeError(`Relationship event ${e} must be non-empty`);return i.trim()}function $(i,e){let t=e.require(i.kind),n=t.direction==="undirected"?[i.source,i.target].sort().join("\0"):`${i.source}\0${i.target}`;return`${t.kind}\0${n}`}function Q(i){return Object.freeze({...i,...i.payload===void 0?{}:{payload:Object.freeze(structuredClone(i.payload))}})}function U(i,e,t,n){let r=t.require(i.kind),o=n.outgoingOne.get(`${r.kind}\0${i.source}`);if(o!==void 0&&o!==e)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=n.incomingOne.get(`${r.kind}\0${i.target}`);if(s!==void 0&&s!==e)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let c=$(i,t),a=n.identities.get(c);if(a!==void 0&&a!==e)throw new TypeError(`Relationship edge already active: ${c}`)}function Y(i){let e=new Map;for(let t of i)t.action==="remove"?e.delete(t.relationshipId):e.set(t.relationshipId,t.edge);return e}function X(i,e,t){if(i.expectedVersion!==void 0&&i.expectedVersion!==e)throw new TypeError(`Relationship event version conflict: expected ${i.expectedVersion}, current ${e}`);let n=E(i.eventId,"eventId");if(t.has(n))throw new TypeError(`Relationship event already exists: ${n}`);if(i.action!=="add"&&i.action!=="remove"&&i.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${i.action}`);if(!Number.isFinite(Date.parse(i.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:n,relationshipId:E(i.relationshipId,"relationshipId"),author:E(i.author,"author"),timestamp:new Date(i.timestamp).toISOString()}}function Z(i,e,t,n,r,o){let s=t.has(e);if(i.action==="add"&&s)throw new TypeError(`Relationship is already active: ${e}`);if(i.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${e}`);if(i.action==="remove")return;if(!i.edge)throw new TypeError(`Relationship ${i.action} event requires an edge`);let c=typeof i.edge.source=="string"?i.edge.source.trim():"",a=typeof i.edge.target=="string"?i.edge.target.trim():"";if(!n.has(c)||!n.has(a))throw new TypeError(`Relationship endpoint not found: ${c} -> ${a}`);let d=new g([c,a],[i.edge],r).edges()[0];return U(d,e,r,o),Q(d)}var T=class{#t;#i;#n=[];#o=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(e,t={}){this.#t=new Set([...e].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean)),this.#i=t.registry??x()}get version(){return this.#n.length}events(){return Object.freeze([...this.#n])}*stream(e={}){let t=e.fromVersion??1,n=e.toVersion??this.version,r=e.batchSize??100;if(!Number.isInteger(t)||t<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(n)||n<0||n>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${n}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(t>n+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let o=t-1;o<n;o+=r)yield Object.freeze(this.#n.slice(o,Math.min(o+r,n)))}project(e,t,n={}){if(typeof t!="function")throw new TypeError("Relationship event projection requires a reducer");let r=e,o=0,s;for(let c of this.stream({...n,batchSize:256}))for(let a of c)r=t(r,a),o+=1,s=a;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(n.fromVersion??1)-1),processed:o,...s===void 0?{}:{asOf:s.timestamp}})}#s(e,t){let n=this.#i.require(t.kind);this.#r.identities.set($(t,this.#i),e),n.outgoing==="one"&&this.#r.outgoingOne.set(`${n.kind}\0${t.source}`,e),n.incoming==="one"&&this.#r.incomingOne.set(`${n.kind}\0${t.target}`,e)}#a(e){let t=this.#i.require(e.kind);this.#r.identities.delete($(e,this.#i)),t.outgoing==="one"&&this.#r.outgoingOne.delete(`${t.kind}\0${e.source}`),t.incoming==="one"&&this.#r.incomingOne.delete(`${t.kind}\0${e.target}`)}append(e){let t=X(e,this.version,this.#o),n=this.#e.get(t.relationshipId),r=Z(e,t.relationshipId,this.#e,this.#t,this.#i,this.#r),o=Object.freeze({eventId:t.eventId,relationshipId:t.relationshipId,action:e.action,...r===void 0?{}:{edge:r},author:t.author,timestamp:t.timestamp,...e.reason?.trim()?{reason:e.reason.trim()}:{},sequence:this.version+1});return this.#n.push(o),this.#o.add(t.eventId),n&&this.#a(n),e.action==="remove"?this.#e.delete(t.relationshipId):(this.#e.set(t.relationshipId,r),this.#s(t.relationshipId,r)),o}snapshot(e={}){if(e.atVersion!==void 0&&e.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let t;if(e.atTimestamp!==void 0){let o=Date.parse(e.atTimestamp);if(!Number.isFinite(o))throw new TypeError("Relationship snapshot timestamp must be valid");t=this.#n.filter(s=>Date.parse(s.timestamp)<=o)}else{let o=e.atVersion??this.version;if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship snapshot version out of range: ${o}`);t=this.#n.slice(0,o)}let n=Y(t),r=new g(this.#t,n.values(),this.#i);return Object.freeze({version:t.at(-1)?.sequence??0,...t.at(-1)?{asOf:t.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(e){if(!Number.isInteger(e.limit)||e.limit<1)throw new TypeError("Relationship event page limit must be positive");let t=N("relationship-events",{order:"append-sequence"}),n=e.cursor===void 0?this.version:Number(D(e.cursor,t).snapshot);if(!Number.isSafeInteger(n)||n<0||n>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=j(this.#n.slice(0,n),{cursor:e.cursor,fingerprint:t,limit:e.limit,readId:o=>o.eventId,snapshot:String(n)});return{version:n,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},ee="relationship-event-store",W=p.O_NOFOLLOW;function w(i){return z(i,ee,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function f(i,e="relationships/events.jsonl"){let t=h.resolve(i),n=h.resolve(t,e),r=h.relative(t,n);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${h.sep}`)||h.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await I(t,{recursive:!0}),(await A(t)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let o=t;for(let s of r.split(h.sep)){o=h.join(o,s);try{if((await A(o)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(_(c))break;throw c}}return n}async function y(i,e,t){let n=new T(e,{registry:t}),r,o;try{o=await P(i,p.O_RDONLY|W),r=await o.readFile("utf8")}catch(c){if(_(c))return{log:n,raw:""};throw c}finally{await o?.close()}let s=r.split(`
2
- `);for(let c=0;c<s.length;c+=1){let a=s[c].trim();if(!a)continue;let d;try{d=JSON.parse(a)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${c+1}`)}if(d.sequence!==n.version+1)throw new TypeError(`Invalid relationship event sequence at line ${c+1}`);n.append({eventId:d.eventId,relationshipId:d.relationshipId,action:d.action,...d.edge===void 0?{}:{edge:d.edge},author:d.author,timestamp:d.timestamp,...d.reason===void 0?{}:{reason:d.reason},expectedVersion:n.version})}return{log:n,raw:r}}function te(i,e,t,n){let r=Date.parse(e.timestamp),o;return e.action!=="remove"&&e.edge!==void 0&&(o=new g(t,[e.edge],n).edges()[0]),i.eventId===e.eventId.trim()&&i.relationshipId===e.relationshipId.trim()&&i.action===e.action&&i.author===e.author.trim()&&Number.isFinite(r)&&i.timestamp===new Date(r).toISOString()&&i.reason===(e.reason?.trim()||void 0)&&O(i.edge)===O(o)}var F=class i{#t;#i;#n;#o;#e;constructor(e,t,n,r){this.#t=e.pmRoot,this.#i=t,this.#n=e.registry,this.#o=n,this.#e=r}static async open(e){let t=Object.freeze([...e.nodes]),n=await f(e.pmRoot,e.relativePath),r=await w(e.pmRoot);try{await f(e.pmRoot,n);let{log:o}=await y(n,t,e.registry);return new i(e,t,n,o)}finally{await r()}}get path(){return this.#o}async currentVersion(){return this.#e=await this.#r(),this.#e.version}async append(e){let t=await w(this.#t);try{let n=await f(this.#t,this.#o),{log:r}=await y(n,this.#i,this.#n),o=r.append(e);await I(h.dirname(n),{recursive:!0}),await f(this.#t,n);let s=await P(n,p.O_APPEND|p.O_CREAT|p.O_WRONLY|W);try{await s.appendFile(`${JSON.stringify(o)}
3
- `,"utf8")}finally{await s.close()}return this.#e=r,o}finally{await t()}}async appendBatch(e,t={}){let n=await w(this.#t);try{let r=await f(this.#t,this.#o),{log:o,raw:s}=await y(r,this.#i,this.#n),c=o.version,a=new Map(o.events().map(l=>[l.eventId,l])),d=[],R=[];for(let l of e){let u=l.eventId.trim(),v=a.get(u);if(v!==void 0){if(t.existingEventPolicy==="skip_identical"&&te(v,l,this.#i,this.#n)){R.push(v.eventId);continue}if(t.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${u}`)}let b=o.append(l);a.set(b.eventId,b),d.push(b)}if(d.length>0){let l=s.length===0||s.endsWith(`
4
- `)?s:`${s}
5
- `;await I(h.dirname(r),{recursive:!0}),await f(this.#t,r),await L(r,`${l}${d.map(u=>JSON.stringify(u)).join(`
6
- `)}
7
- `)}return this.#e=o,Object.freeze({version_before:c,version_after:o.version,appended:Object.freeze(d),skipped_event_ids:Object.freeze(R)})}finally{await n()}}async snapshot(e={}){return this.#e=await this.#r(),this.#e.snapshot(e)}async page(e){return this.#e=await this.#r(),this.#e.page(e)}async*stream(e={}){this.#e=await this.#r(),yield*this.#e.stream(e)}async project(e,t,n={}){return this.#e=await this.#r(),this.#e.project(e,t,n)}async#r(){let e=await w(this.#t);try{let t=await f(this.#t,this.#o);return(await y(t,this.#i,this.#n)).log}finally{await e()}}};(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();function K(i){return[...i].sort().join("\0")}function ie(i,e,t){let n=i.successors.get(e);n?n.push(t):i.successors.set(e,[t]);let r=i.predecessors.get(t);r?r.push(e):i.predecessors.set(t,[e])}function G(i,e,t,n,r){let o=e.resolve(r);if(o?.ordering!==!0)return;let s=M(n),c=s===void 0?void 0:i.canonicalIds.get(s.toLowerCase());if(c===void 0)return;let a=(o.precedence??"source_before_target")==="source_before_target";ie(i,a?t:c,a?c:t)}function ne(i,e){let t={successors:new Map,predecessors:new Map,canonicalIds:new Map},n=i.filter(r=>typeof r?.id=="string"&&r.id.trim().length>0);for(let r of n){let o=r.id.trim();t.canonicalIds.set(o.toLowerCase(),o)}for(let r of n){let o=r.id.trim();G(t,e,o,r.blocked_by,"blocked_by");for(let s of r.dependencies??[])typeof s!="object"||s===null||G(t,e,o,s.id,typeof s.kind=="string"?s.kind:"related")}for(let r of[t.successors,t.predecessors])for(let o of r.values())o.sort();return t}function re(i,e){let t=new Set([e]),n=[e];for(;n.length>0;){let r=n.pop();for(let o of[i.successors,i.predecessors])for(let s of o.get(r)??[])t.has(s)||(t.add(s),n.push(s))}return t}function oe(i,e){let t=new Map;for(let n of e){let r=(i.successors.get(n)??[]).filter(o=>e.has(o));r.length>0&&t.set(n,r)}return t}function H(i,e,t){let n=ne(i,e),r=n.canonicalIds.get(t.trim().toLowerCase());if(r===void 0)return{cycles:[],successors:new Map,canonical:t};let o=oe(n,re(n,r));return{cycles:q(o).filter(s=>s.includes(r)),successors:o,canonical:r}}function se(i,e,t){let n=new Set(e),r=n.has(t)?t:e[0];if(i.get(r)?.includes(r))return[r,r];for(let o of i.get(r)??[]){if(!n.has(o))continue;let s=ae(i,n,r,o);if(s)return s}return[...e,e[0]]}function ae(i,e,t,n){let r=[[n]],o=new Set([t,n]);for(;r.length>0;){let s=r.shift(),c=s.at(-1);for(let a of i.get(c)??[]){if(a===t)return[t,...s,t];!e.has(a)||o.has(a)||(o.add(a),r.push([...s,a]))}}}function ve(i,e,t){let n=m(),r=H(i,n,t),o=H(e,n,t),s=new Set(r.cycles.map(K)),c=new Set(k(i,void 0,n).map(a=>`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`));return[...k(e,void 0,n).filter(a=>a.holder_id.toLowerCase()===t.trim().toLowerCase()&&!c.has(`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`)).map(a=>`ordering_storage_contradiction_created:${V(a)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...o.cycles.filter(a=>!s.has(K(a))).map(a=>`ordering_cycle_created:${se(o.successors,a,o.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="5f2ca18e-450d-5b6e-9e07-7bbf080764f9")}catch{}})();function Ee(i,e){let t=e.resolve(i);return t?.hierarchy===!0||t?.outgoing==="one"||t?.incoming==="one"}function J(i,e,t,n,r){let o=JSON.stringify([e,t,n]),s=i.get(o);s===void 0&&(s={kind:e,direction:t,node_id:n,endpoints:new Set},i.set(o,s)),s.endpoints.add(r)}function B(i,e){let t=new Map;for(let n of i)for(let r of n.dependencies??[]){let o=e.resolve(r.kind);o===void 0||o.hierarchy||(o.outgoing==="one"&&J(t,o.kind,"outgoing",n.id,r.id),o.incoming==="one"&&J(t,o.kind,"incoming",r.id,n.id))}return t}function Ie(i,e,t=m()){let n=B(i,t),r=B(e,t);for(let o of[...r.keys()].sort()){let s=r.get(o);if(s.endpoints.size<=1)continue;let c=n.get(o);if(![...s.endpoints].every(a=>c?.endpoints.has(a)))throw new C(`Relationship ${s.kind} permits only one ${s.direction} endpoint for ${s.node_id}.`,S.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:s.kind,relationship_cardinality:{kind:s.kind,direction:s.direction,node_id:s.node_id,endpoint_ids:[...s.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}export{T as a,F as b,ve as c,Ee as d,Ie as e};
8
- //# sourceMappingURL=chunk-5UDDRPYR.js.map
@@ -1,2 +0,0 @@
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]="bfaa3455-3237-5c98-8ef4-b353ce9530fe")}catch{}})();var o=Object.freeze({rows:10,paths:5,samples:10,path_depth:8,visited_paths:1e4});(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]="e216fd39-09ee-5a04-b0b5-44f518db4f93")}catch{}})();function s(e){let n=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(n)||/^(?:github|gitlab|jira|linear):/iu.test(n)}function d(e){let n=e?.trim().toLowerCase();return n==="global"||n==="external"}export{o as a,s as b,d as c};
2
- //# sourceMappingURL=chunk-AK2CI2GI.js.map
@@ -1,91 +0,0 @@
1
- import{Fa as He,Ha as fe,Pa as Tt,Ya as xt,aa as It,da as vt,eb as St,fa as Ct,fb as pe,m as Pe,n as bt,va as je,wa as $e,x as me,xa as K,y as Et,z as q}from"./chunk-FUGYXUUL.js";import{b as ce}from"./chunk-WD43E7RU.js";import{h as wt}from"./chunk-4PW5XWVI.js";import{Aa as Ne,Ba as Me,Ca as R,Cc as Ae,Na as mt,Nc as G,Nd as ht,Od as Le,Ra as ft,Sa as pt,a as se,be as _t,cc as yt,ce as gt,ma as ct,na as dt,qa as lt,sc as Y,uc as De,va as de,vc as le,wc as L,xa as ut,xc as Oe,yc as ue,zc as Fe}from"./chunk-TGS5RXBY.js";import{A as p,B as st,C as X,E as A,I as M,t as F,y as at,z as h}from"./chunk-QVFE5LIX.js";import pi from"node:crypto";import ye from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function kt(e){let t=[],i=!1;for(let o of(e??"").toLowerCase()){let n=o.charCodeAt(0),r=n>=48&&n<=57,a=n>=97&&n<=122;if(!r&&!a){i=t.length>0;continue}i&&(t.push("-"),i=!1),t.push(o)}return t.length===0?"pm-":`${t.join("")}-`}function V(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function J(e,t){let i=kt(t),o=V(e);return o.startsWith(i)?o:`${i}${o}`}function yi(e){let t=ht(e);if(t!==void 0)return t;let i="";for(let o=0;o<e;o+=1)i+=pi.randomInt(0,36).toString(36);return i}async function hi(e,t,i){let o=[...new Set(Object.values(i))].flatMap(n=>[ye.join(e,n,`${t}.md`),ye.join(e,n,`${t}.toon`)]);return o.push(ye.join(e,"history",`${t}.jsonl`)),(await Promise.all(o.map(n=>X(n)))).some(Boolean)}var Rt=4,Nt=12;function _i(e){return typeof e!="number"||!Number.isFinite(e)?Rt:Math.min(Nt,Math.max(Rt,Math.trunc(e)))}async function Zo(e,t,i={}){let o=_i(i.tokenLength),n=Math.min(o+6,Nt),r=0;for(;o<=n;){for(let a=0;a<32;a+=1){let s=`${kt(t)}${yi(o)}`;if(!await(i.probeExisting===!1?X(ye.join(e,"history",`${s}.jsonl`)):hi(e,s,i.typeToFolder??F)))return s;r+=1}o+=1}throw new Error(`Unable to generate unique id after ${r} attempts`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function Q(e,t=!1){let i=e[0];if(i?.op!=="history_compact_baseline")return 0;let o=i.context?.history_compaction,n=typeof o=="object"&&o!==null&&"version_offset"in o?o.version_offset:void 0;if(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(n+e.length))return n;if(t)return null;throw new p("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",h.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}import Mt from"node:fs/promises";import Z from"node:path";import{isUtf8 as gi}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="697f1dbe-8315-5901-ab11-e0c5211dbdbf")}catch{}})();var wi=1048576,bi=4194304;async function Dt(e,t){let i=Z.dirname(e);for(;i!==Z.parse(e).root;){let n=await Mt.stat(i).catch(r=>{if(A(r))return null;throw r});if(n!==null){if(!n.isDirectory())throw new p("Workflow policy storage ancestor must be a directory.",h.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}i=Z.dirname(i)}let o=await Mt.open(e,"r").catch(n=>{if(A(n))return null;throw n});if(o===null)return null;try{let n=(await o.stat()).size,r=Buffer.alloc(Math.min(t,n)+1),a=0;for(;a<r.length;){let s=await o.read(r,a,r.length-a,a);if(s.bytesRead===0)break;a+=s.bytesRead}if(a===r.length||!gi(r.subarray(0,a)))throw new p("Workflow policy input exceeds its byte bound or is not valid UTF-8.",h.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return r.toString("utf8",0,a)}finally{await o.close()}}function Ei(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let t;try{t=JSON.parse(e)}catch{throw new p("schema/policies.json must contain valid JSON.",h.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return mt(t)}async function Ii(e){return Ei(await Dt(Z.join(e,"schema","policies.json"),wi))}async function vi(e,t){let i=await Dt(R(e,t),bi);if(i===null)return[];let o;try{if(o=i.split(/\r?\n/).filter(n=>n.trim()).map(n=>JSON.parse(n)),!fe(o).ok)throw new Error("invalid chain")}catch{throw new p("Approval evidence requires a valid item history chain.",h.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${t} --verify before recording or using an approval.`]})}return o.flatMap(n=>{let r=n.context?.workflow_approval;if(n.op!=="policy_approve"||n.record_hash_version!==1||typeof n.record_hash!="string"||typeof r!="object"||r===null)return[];let a=r;return typeof a.policy_fingerprint!="string"||typeof a.content_fingerprint!="string"?[]:[{policy_fingerprint:a.policy_fingerprint,content_fingerprint:a.content_fingerprint,author:n.author}]})}async function Ci(e,t,i){let o=i.before?.status!==i.after?.status&&t.policies.some(a=>a.rule.kind==="approval"&&ft(a,i)),n=i.before?.id??i.after?.id,r=o&&typeof n=="string"?await vi(e,n):[];return pt(t,{...i,approvals:r})}async function We(e){let t=await Ii(e.pmRoot),i=await Ci(e.pmRoot,t,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(i.allowed)return i;let o=i.decisions.filter(l=>!l.satisfied&&l.effect==="refuse"),n=[],r="";if(!e.dryRun)try{let l=await Tt({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:i.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms});n.push({path:"history/_workspace.jsonl",op:"policy_refused",record_hash:l.entry.record_hash}),r=" Audit appended to tracker-relative history/_workspace.jsonl; retain it with the workspace changes. Each refused attempt records its own audit event."}catch(l){let y=new p("Workflow policy refusal could not be recorded in workspace history.",h.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw y.cause=l,y}let a=o.slice(0,3).map(l=>({policy_id:l.policy_id,rule:l.rule,description:t.policies.find(y=>y.id===l.policy_id).description,missing_fields:l.missing_fields})),s=[...new Set(a.flatMap(l=>l.missing_fields))],d=a.map(l=>`${l.policy_id} (${l.rule})`).join(", "),c=o.length>3?` and ${o.length-3} more`:"",m=e.after?.metadata.id??e.before.metadata.id,u=s.map(l=>{if(e.before===null)return`Supply ${l} in the original ${e.operation} request, then retry; the item was not created.`;let y=ct("update",l);return y===void 0?`Supply ${l} using its declared SDK or package mutation contract, then retry.`:G(["update",m,dt("update",y),`<${l}>`,"--pm-path",Z.resolve(e.pmRoot)])});throw new p(`Workflow policy refused ${e.operation}: ${d}${c}.${s.length?` Missing: ${s.join(", ")}.`:""}${r}`,h.CONFLICT,{code:"workflow_policy_refused",side_effects:n,reason:a.map(l=>l.policy_id).join(","),policy_violations:a,policy_violation_count:o.length,required:s.length?`Supply missing fields: ${s.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:a.map(l=>l.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:s},nextSteps:[...u,...new Set(o.slice(0,3).filter(l=>l.missing_fields.length===0).map(l=>l.remediation)),...o.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as Ti}from"node:async_hooks";import{channel as xi}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var Ue=new Ti,Be=xi("@unbrained/pm-cli/item-metadata-enumeration/v1");function he(e){Be.publish(e)}async function bn(e){let t={enumeration_calls:0,metadata_rows:0},i=o=>{Ue.getStore()?.includes(t)&&(t.enumeration_calls+=1,t.metadata_rows+=o)};Be.subscribe(i);try{return{result:await Ue.run([...Ue.getStore()??[],t],e),work:{...t}}}finally{Be.unsubscribe(i)}}import{AsyncLocalStorage as Si}from"node:async_hooks";import _e from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39bf765c-1374-5ba5-b8a9-44137f80c976")}catch{}})();var ee=new Si;function Cn(e,t){return ee.run([...ee.getStore()??[],{...e,pmRoot:_e.resolve(e.pmRoot)}],t)}function ze(e,t){for(let i of ee.getStore()??[])i.pmRoot===_e.resolve(e)&&i.id===t.metadata.id&&i.validate(t)}function Ot(e,t){for(let i of ee.getStore()??[])i.pmRoot===_e.resolve(e)&&i.id===t.metadata.id&&i.committed?.(t)}function Ft(e,t){return Object.assign({},...(ee.getStore()??[]).filter(i=>i.pmRoot===_e.resolve(e)&&i.id===t.metadata.id).map(i=>i.historyContext))}import P from"node:fs/promises";import Lt from"node:path";import{randomUUID as Ri}from"node:crypto";import{createRequire as ki}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var Ni="metadata-query-index.sqlite",te="5",Xe;function ie(){return Xe!==void 0||(Xe=Ct(process.versions.node,ki(import.meta.url))),Xe}function At(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function W(e){return Lt.join(e,"runtime",Ni)}function Mi(e){e.exec(`
2
- PRAGMA foreign_keys = ON;
3
- PRAGMA journal_mode = OFF;
4
- PRAGMA synchronous = OFF;
5
- CREATE TABLE metadata (
6
- key TEXT PRIMARY KEY,
7
- value TEXT NOT NULL
8
- ) STRICT;
9
- CREATE TABLE items (
10
- id TEXT PRIMARY KEY,
11
- relative_path TEXT NOT NULL UNIQUE,
12
- metadata_json TEXT NOT NULL,
13
- status TEXT NOT NULL,
14
- type TEXT NOT NULL,
15
- priority INTEGER NOT NULL,
16
- updated_at TEXT NOT NULL,
17
- created_at TEXT NOT NULL,
18
- parent TEXT,
19
- assignee TEXT,
20
- sprint TEXT,
21
- release TEXT
22
- ) STRICT;
23
- CREATE INDEX items_default_order
24
- ON items(priority, updated_at DESC, id);
25
- CREATE INDEX items_status_default_order
26
- ON items(status, priority, updated_at DESC, id);
27
- CREATE INDEX items_type_default_order
28
- ON items(type, priority, updated_at DESC, id);
29
- CREATE INDEX items_parent_default_order
30
- ON items(parent, priority, updated_at DESC, id);
31
- CREATE TABLE item_metadata_keys (
32
- item_id TEXT NOT NULL,
33
- key TEXT NOT NULL,
34
- PRIMARY KEY(item_id, key),
35
- FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE
36
- ) STRICT;
37
- CREATE INDEX item_metadata_keys_key_item
38
- ON item_metadata_keys(key, item_id);
39
- CREATE TABLE item_linked_files (
40
- item_id TEXT NOT NULL,
41
- path TEXT NOT NULL,
42
- scope TEXT NOT NULL,
43
- note TEXT,
44
- PRIMARY KEY(item_id, path, scope),
45
- FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE
46
- ) STRICT;
47
- CREATE INDEX item_linked_files_path_scope_item
48
- ON item_linked_files(path, scope, item_id);
49
- CREATE VIRTUAL TABLE item_search USING fts5(
50
- id UNINDEXED,
51
- title,
52
- description,
53
- tags,
54
- tokenize = 'unicode61'
55
- );
56
- `)}function we(e,t,i){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,i)}function Pt(e,t){let i=t.metadata;e.prepare(`INSERT INTO items(
57
- id, relative_path, metadata_json, status, type, priority,
58
- updated_at, created_at, parent, assignee, sprint, release
59
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
60
- ON CONFLICT(id) DO UPDATE SET
61
- relative_path = excluded.relative_path,
62
- metadata_json = excluded.metadata_json,
63
- status = excluded.status,
64
- type = excluded.type,
65
- priority = excluded.priority,
66
- updated_at = excluded.updated_at,
67
- created_at = excluded.created_at,
68
- parent = excluded.parent,
69
- assignee = excluded.assignee,
70
- sprint = excluded.sprint,
71
- release = excluded.release`).run(i.id,t.relativePath,JSON.stringify(i),i.status,i.type,i.priority,i.updated_at,i.created_at,i.parent??null,i.assignee??null,i.sprint??null,i.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(i.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(i.id),e.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(i.id),e.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(i.id,i.title,i.description,i.tags.join(" "),i.id);let o=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let r of Object.keys(i))o.run(i.id,r);let n=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let r of t.linkedFiles??[])n.run(i.id,r.path,r.scope,r.note??null)}async function jt(e){let t=W(e.pmRoot),i=ie();if(!i){await P.rm(t,{force:!0});return}await P.mkdir(Lt.dirname(t),{recursive:!0});let o=`${t}.${Ri()}.tmp`,n;try{n=new i(o),Mi(n),n.exec("BEGIN IMMEDIATE"),we(n,"version",te),we(n,"context_fingerprint",e.contextFingerprint),we(n,"source_cursor",e.sourceCursor);for(let r of e.rows)Pt(n,r);n.exec("COMMIT"),n.close(),n=void 0,await P.rm(t,{force:!0}),await P.rename(o,t)}catch(r){throw n?.close(),await Promise.allSettled([P.rm(o,{force:!0})]),r}}function be(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function $t(e){let t=ie();if(!t)return!1;let i=W(e.pmRoot),o;try{await P.access(i),o=new t(i),o.exec("PRAGMA foreign_keys = ON");let n=be(o);if(n.version!==te||n.context_fingerprint!==e.contextFingerprint||n.source_cursor!==e.expectedSourceCursor)return o.close(),!1;o.exec("BEGIN IMMEDIATE");let r=o.prepare("DELETE FROM items WHERE relative_path = ?"),a=o.prepare("SELECT rowid FROM items WHERE relative_path = ?"),s=o.prepare("DELETE FROM item_search WHERE rowid = ?");for(let d of e.deletedRelativePaths??[]){let c=a.get(d);r.run(d),c&&s.run(c.rowid)}return e.row&&Pt(o,e.row),we(o,"source_cursor",e.sourceCursor),o.exec("COMMIT"),o.close(),!0}catch{try{o?.exec("ROLLBACK")}catch{}return o?.close(),!1}}function ge(e,t,i,o,n){!o||o.length===0||(e.push(`${i} ${n} (${o.map(()=>"?").join(", ")})`),t.push(...o))}function Di(e){let t=[],i=[];ge(t,i,"status",e.statuses,"IN"),ge(t,i,"status",e.excludeStatuses,"NOT IN"),ge(t,i,"type",e.types,"IN"),ge(t,i,"id",e.ids,"IN");for(let o of e.metadataKeys??[])t.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),i.push(o);for(let[o,n]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])n!==void 0&&(t.push(`${o} = ?`),i.push(n));return e.priority!==void 0&&(t.push("priority = ?"),i.push(e.priority)),{where:t.length===0?"":` WHERE ${t.join(" AND ")}`,parameters:i}}async function Dn(e){let t=ie();if(!t)return null;let i=e.query??{},{where:o,parameters:n}=Di(i),r;try{r=new t(W(e.pmRoot),{readOnly:!0});let a=be(r);if(a.version!==te||a.source_cursor!==e.expectedSourceCursor)return r.close(),null;let s=r.prepare(`SELECT COUNT(*) AS count FROM items${o}`).get(...n),d=[],c="";i.limit!==void 0?(c+=" LIMIT ?",d.push(Math.max(0,Math.floor(i.limit))),i.offset!==void 0&&(c+=" OFFSET ?",d.push(Math.max(0,Math.floor(i.offset))))):i.offset!==void 0&&(c+=" LIMIT -1 OFFSET ?",d.push(Math.max(0,Math.floor(i.offset))));let m=r.prepare(`SELECT metadata_json FROM items${o}
72
- ORDER BY ${i.terminalStatuses&&i.terminalStatuses.length>0?`CASE WHEN status IN (${i.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${c}`).all(...n,...i.terminalStatuses??[],...d).map(u=>{let l=JSON.parse(String(u.metadata_json));if(!l.id)throw new TypeError("Indexed metadata row has no id");return l});return r.close(),{source_cursor:a.source_cursor,total:Number(s.count),items:m}}catch{return r?.close(),null}}async function On(e){let t=ie();if(!t||e.paths.length===0)return null;let i;try{i=new t(W(e.pmRoot),{readOnly:!0});let o=be(i);if(o.version!==te||o.source_cursor!==e.expectedSourceCursor)return i.close(),null;let n=e.paths.map(()=>"?").join(", "),r=e.scope===void 0?"":" AND scope = ?",a=[...e.paths,...e.scope===void 0?[]:[e.scope]],s=`path IN (${n})${r}`,d=i.prepare(`SELECT COUNT(DISTINCT item_id) AS count
73
- FROM item_linked_files
74
- WHERE ${s}`).get(...a),c=At(e.limit,50),m=At(e.offset,0),u=i.prepare(`SELECT items.id, items.metadata_json
75
- FROM items
76
- WHERE EXISTS (
77
- SELECT 1 FROM item_linked_files
78
- WHERE item_linked_files.item_id = items.id AND ${s}
79
- )
80
- ORDER BY items.priority ASC, items.updated_at DESC, items.id ASC
81
- LIMIT ? OFFSET ?`).all(...a,c,m),l=[];if(u.length>0){let y=u.map(_=>String(_.id)),f=i.prepare(`SELECT item_id, path, scope, note
82
- FROM item_linked_files
83
- WHERE item_id IN (${y.map(()=>"?").join(", ")})
84
- AND ${s}
85
- ORDER BY path ASC, scope ASC`).all(...y,...a),g=new Map(y.map(_=>[_,[]]));for(let _ of f){let b=String(_.item_id),T=g.get(b);T.push({path:String(_.path),scope:String(_.scope),..._.note===null?{}:{note:String(_.note)}}),g.set(b,T)}for(let _ of u){let b=JSON.parse(String(_.metadata_json));l.push({item:b,files:g.get(String(_.id))})}}return i.close(),{source_cursor:o.source_cursor,total:Number(d.count),matches:l}}catch{return i?.close(),null}}async function Fn(e){let t=ie();if(!t)return null;let i;try{i=new t(W(e.pmRoot),{readOnly:!0});let o=be(i);if(o.version!==te||o.source_cursor!==e.expectedSourceCursor)return i.close(),null;let n=i.prepare(`SELECT items.metadata_json
86
- FROM item_search
87
- JOIN items ON items.id = item_search.id
88
- WHERE item_search MATCH ?
89
- ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
90
- LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(r=>JSON.parse(String(r.metadata_json)));return i.close(),{source_cursor:o.source_cursor,items:n}}catch{return i?.close(),null}}async function Ee(e){await P.rm(W(e),{force:!0})}import E from"node:fs/promises";import w from"node:path";import{createHash as Oi,randomUUID as zt}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var S=8,Xt=500,Fi="metadata-derived-index",Ai="metadata-cache.json",Li="metadata-cache-bodies.json",Pi="metadata-cache-collections.json",ji="metadata-cache-delta.json",$i="metadata-cache-manifest.json",Ht=4,Hi=["comments","notes","learnings","files","tests","test_runs","docs"];function Yt(){return ce(Y())}function ve(e){let t={...e},i={};for(let o of Hi)o in t&&(i[o]=t[o],delete t[o]);return{light:t,heavy:i}}function Gt(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function qt(e,t,i,o){let n=Oi("sha256");n.update(`format:${e??"default"}`);let r=Object.entries(t).sort(([a],[s])=>a.localeCompare(s)).map(([a,s])=>`${a}=${s}`).join(",");return n.update(`|types:${r}`),i&&n.update(`|schema:${JSON.stringify(i)}`),o.length>0&&n.update(`|extension_fields:${o.join(",")}`),n.digest("hex").slice(0,16)}function Ce(e){return w.join(e,"runtime",Ai)}function Te(e){return w.join(e,"runtime",Li)}function xe(e){return w.join(e,"runtime",Pi)}function Ge(e){return w.join(e,"runtime",ji)}function qe(e){return w.join(e,"runtime",$i)}function Se(e,t){let i=w.extname(e);return`${e.slice(0,-i.length)}.${t}${i}`}var Wi=24,v=new Map,Re=new WeakMap;function Ke(e){return Re.get(e)??e.source_cursor}function Ui(e,t){let i=Ke(e);if(!(t.base_source_cursor!==i||e.source_cursor===t.source_cursor)){Re.set(e,i);for(let[o,n]of Object.entries(t.changes))n.entry?e.entries[o]=n.entry:delete e.entries[o];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function Bi(e,t){if(!e)return;let i=Ke(e);if(!(t.base_source_cursor!==i||e.source_cursor===t.source_cursor)){Re.set(e,i);for(let[o,n]of Object.entries(t.changes))n.body?e.bodies[o]=n.body:delete e.bodies[o];e.source_cursor=t.source_cursor}}function zi(e,t){if(!e)return;let i=Ke(e);if(!(t.base_source_cursor!==i||e.source_cursor===t.source_cursor)){Re.set(e,i);for(let[o,n]of Object.entries(t.changes))n.collections?e.collections[o]=n.collections:delete e.collections[o];e.source_cursor=t.source_cursor}}function Xi(e,t,i,o){!e||!o||e.context_fingerprint!==o.context_fingerprint||(Ui(e,o),Bi(t,o),zi(i,o))}function Ye(e,t){v.size>=Wi&&!v.has(e)&&yt(v),v.set(e,t)}async function D(e,t){let i;try{i=await E.stat(e)}catch{return v.delete(e),null}let o=v.get(e);if(o&&oe(o.signature,i.mtimeMs,i.ctimeMs,i.size))return v.delete(e),v.set(e,o),o.envelope;let n;try{n=t(await E.readFile(e,"utf8"))}catch{n=null}return Ye(e,{signature:{mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size},envelope:n}),n}async function Yi(e,t,i){let o=s=>{let d=JSON.parse(s);return d.version!==S||typeof d.source_cursor!="string"||typeof d.entries!="object"||d.entries===null?null:d},n=Ce(e),r=await D(n,o);if(!t||r===null||r.context_fingerprint===t)return r;let a=await D(Se(n,t),o);return a===null&&ae(i,`metadata_cache_context_changed:${r.context_fingerprint}->${t}`),a}async function Gi(e,t){let i=r=>{let a=JSON.parse(r);return a.version!==S||typeof a.source_cursor!="string"||typeof a.bodies!="object"||a.bodies===null?null:a},o=Te(e),n=await D(o,i);return t&&n?.context_fingerprint!==t?await D(Se(o,t),i):n}async function qi(e,t){let i=r=>{let a=JSON.parse(r);return a.version!==S||typeof a.source_cursor!="string"||typeof a.collections!="object"||a.collections===null?null:a},o=xe(e),n=await D(o,i);return t&&n?.context_fingerprint!==t?await D(Se(o,t),i):n}async function Ve(e){let t=Ge(e),i=await D(t,o=>{let n=JSON.parse(o);return n.version!==S||typeof n.base_source_cursor!="string"||typeof n.source_cursor!="string"||typeof n.changes!="object"||n.changes===null?null:n});if(i)return{envelope:i,invalid:!1};try{return await E.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function Je(e){let t=qe(e),i=await D(t,o=>{let n=JSON.parse(o);return n.version!==S||typeof n.context_fingerprint!="string"||typeof n.source_cursor!="string"||!Number.isInteger(n.entry_count)||n.entry_count<0||typeof n.directory_signatures!="object"||n.directory_signatures===null?null:n});if(i)return i;try{await E.stat(t),await U(e)}catch{}return null}async function ne(e,t){await E.mkdir(w.dirname(e),{recursive:!0}),await M(e,JSON.stringify(t));try{let o=await E.stat(e);Ye(e,{signature:{mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size},envelope:t})}catch{v.delete(e)}let i=w.dirname(w.dirname(e));if(e===Ce(i)||e===Te(i)||e===xe(i)){let o=Se(e,t.context_fingerprint);await M(o,JSON.stringify(t));try{let d=await E.stat(o);Ye(o,{signature:{mtime_ms:d.mtimeMs,ctime_ms:d.ctimeMs,size:d.size},envelope:t})}catch{v.delete(o)}let n=w.dirname(e),r=w.extname(e),a=w.basename(e,r),s=(await E.readdir(n,{withFileTypes:!0}).catch(()=>[])).filter(d=>d.isFile()&&d.name!==w.basename(e)&&d.name.startsWith(`${a}.`)&&d.name.endsWith(r)).map(d=>w.join(n,d.name));if(s.length>Ht){let d=(await Promise.all(s.map(async c=>{try{return{path:c,mtime:(await E.stat(c)).mtimeMs}}catch{return null}}))).filter(c=>c!==null);for(let c of d.sort((m,u)=>m.mtime-u.mtime).slice(0,Math.max(0,d.length-Ht)))await E.rm(c.path,{force:!0}),v.delete(c.path)}}}function Ki(e,t,i){return i?t===i&&e!==i:t==="toon"&&e!=="toon"}function Kt(e,t,i){return e===void 0||Ki(e,t,i)}function ae(e,t){e&&!e.includes(t)&&e.push(t)}function oe(e,t,i,o){return e.mtime_ms===t&&e.ctime_ms===i&&e.size===o}async function Vi(e,t,i){let o=w.join(e,t);try{let n=await E.readdir(o);return{folder:t,dirPath:o,files:n}}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&!A(n)&&ae(i,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:o,files:[]}}}async function Ji(e,t){try{let i=await E.stat(w.join(e,t));return[t,{exists:!0,mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function Ie(e,t){return Object.fromEntries(await Promise.all(t.map(async i=>await Ji(e,i))))}function re(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([i,o])=>{let n=e[i];return n!==void 0&&n.exists===o.exists&&oe(n,o.mtime_ms,o.ctime_ms,o.size)})}function Qi(e){return de.some(t=>e.toLowerCase().endsWith(t))}function Zi(e,t,i,o,n,r){o||(e.metadata=!0),t&&!n&&(e.body=!0),i&&!r&&(e.collections=!0)}async function eo(e,t,i){if(i)for(let o of await ue({path:e,scope:"project"}))ae(t,o)}function Wt(e,t,i,o){if(e)return t&&i?i.collections:o}async function to(e,t,i){let o=await E.stat(e),n=o.mtimeMs,r=o.ctimeMs,{size:a}=o,s=Me(e);await eo(e,i.warnings,i.dispatchReadHooks);let d=i.previousEntries[t],c=!i.forceSourceRead&&d!==void 0&&oe(d,n,r,a),m=i.previousBodies[t],u=!i.forceSourceRead&&m!==void 0&&oe(m,n,r,a),l=i.previousCollections[t],y=!i.forceSourceRead&&l!==void 0&&oe(l,n,r,a);if(!(!c||i.includeBody&&!u||i.includeCollections&&!y))return{mtimeMs:n,ctimeMs:r,size:a,itemFormat:s,lightMetadata:d.metadata,heavyMetadata:Wt(i.includeCollections,y,l,void 0),bodyLength:d.body_length,body:i.includeBody?m.body:void 0};let f=await E.readFile(e,"utf8"),g=me(f,{format:s,schema:i.schema,extensionFieldNames:i.extensionFieldNames,onWarning:b=>ae(i.warnings,b)}),_=ve(g.metadata);return Zi(i.state.misses,i.includeBody,i.includeCollections,c,u,y),{mtimeMs:n,ctimeMs:r,size:a,itemFormat:s,lightMetadata:c?d.metadata:_.light,heavyMetadata:Wt(i.includeCollections,y,l,_.heavy),bodyLength:c?d.body_length:g.body.length,body:i.includeBody?g.body:void 0}}function io(e,t,i,o){i.state.newEntries[t]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,metadata:o.lightMetadata,body_length:o.bodyLength},i.includeBody&&o.body!==void 0&&(i.state.newBodies[t]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,body:o.body}),i.includeCollections&&o.heavyMetadata!==void 0&&(i.state.newCollections[t]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,collections:o.heavyMetadata});let n=i.includeCollections?Gt(o.lightMetadata,o.heavyMetadata):o.lightMetadata,r=i.state.documentsById.get(n.id),a={metadata:n,body:o.body,item_format:o.itemFormat,item_path:e};Kt(r?.itemFormat,o.itemFormat,i.preferredFormat)&&i.state.documentsById.set(n.id,{candidate:a,itemFormat:o.itemFormat})}async function oo(e,t,i,o){try{let n=await to(t,i,o);io(t,i,o,n)}catch{ae(o.warnings,`item_list_item_read_failed:${e}/${w.basename(t)}`)}}function no(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function ro(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function ao(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function so(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function co(e,t){let i=[];for(let{folder:o,dirPath:n,files:r}of e)for(let a of r){if(!Qi(a))continue;let s=w.join(n,a),d=w.relative(t.pmRoot,s);i.push(oo(o,s,d,t)),i.length===32&&(await Promise.all(i),i.length=0)}await Promise.all(i)}async function lo(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!re(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await ne(Ce(e.pmRoot),{version:S,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await ne(qe(e.pmRoot),{version:S,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let t=[...e.state.documentsById.values()].map(({candidate:i})=>({relativePath:w.relative(e.pmRoot,i.item_path),metadata:ve(i.metadata).light,linkedFiles:i.metadata.files??[]}));t.length>=e.minimumIndexedItems?await jt({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await Ee(e.pmRoot)}catch{}}async function uo(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await ne(Te(e.pmRoot),{version:S,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function mo(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await ne(xe(e.pmRoot),{version:S,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function Qe(e,t,i={}){let o=await Je(e);return i.required!==!0&&(o===null||o.entry_count<Xt)?async()=>{}:_t(e,Fi,30,t,!1,!1,3e3)}async function Gn(e,t){let i=await Je(e);if(i===null)return null;let o=await Ve(e);if(o.invalid)return await U(e),null;let n=o.envelope?.context_fingerprint===i.context_fingerprint&&o.envelope.base_source_cursor===i.source_cursor?o.envelope.source_cursor:i.source_cursor,r=o.envelope?.context_fingerprint===i.context_fingerprint&&o.envelope.base_source_cursor===i.source_cursor?o.envelope.directory_signatures:i.directory_signatures;return t&&!re(r,await Ie(e,t))?null:{source_cursor:n,entry_count:i.entry_count}}function Ut(e,t){let i=w.relative(e,t);return i===""||i===".."||i.startsWith(`..${w.sep}`)||w.isAbsolute(i)?null:i}async function U(e){await Promise.all([Ce(e),Te(e),xe(e),Ge(e),qe(e)].map(async t=>{await E.rm(t,{force:!0}),v.delete(t)})),await Ee(e)}async function fo(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await E.stat(e.mutation.itemPath),i=ve(e.mutation.document.metadata),o={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...o,metadata:i.light,body_length:e.mutation.document.body.length},body:{...o,body:e.mutation.document.body},collections:{...o,collections:i.heavy}}}function po(e,t,i){return e?.context_fingerprint===t&&e.base_source_cursor===i?structuredClone(e.changes):{}}async function Ze(e){let t=Ut(e.pmRoot,e.itemPath),i=e.previousItemPath?Ut(e.pmRoot,e.previousItemPath):void 0;if(t===null||i===null)return await U(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let o=qt(e.preferredFormat,e.typeToFolder,e.schema,Yt()),n=await Je(e.pmRoot);if(n===null||n.context_fingerprint!==o)return[];let r=n.source_cursor,a=await Ve(e.pmRoot);if(a.invalid)return await U(e.pmRoot),["metadata_derived_index_refresh_failed"];let s=po(a.envelope,o,r),d=a.envelope?.context_fingerprint===o&&a.envelope.base_source_cursor===r?a.envelope.source_cursor:r;i!==void 0&&(s[i]={entry:null,body:null,collections:null}),s[t]=await fo({mutation:e});let c=zt();return await ne(Ge(e.pmRoot),{version:S,context_fingerprint:o,base_source_cursor:r,source_cursor:c,directory_signatures:await Ie(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:s}),await $t({pmRoot:e.pmRoot,contextFingerprint:o,expectedSourceCursor:d,sourceCursor:c,row:e.document===null?null:{relativePath:t,metadata:ve(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...i===void 0?[]:[i],...e.document===null?[t]:[]]})||await Ee(e.pmRoot),[]}catch{return await U(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function yo(e){return[...e.documentsById.values()].sort((t,i)=>t.candidate.metadata.id.localeCompare(i.candidate.metadata.id)).map(t=>t.candidate)}function Bt(e,t,i){return e?.context_fingerprint===t&&e.source_cursor===i}function ho(e,t,i,o,n){return e.every(r=>(!t||o[r]!==void 0)&&(!i||n[r]!==void 0))}function _o(e){let t=new Map;for(let[i,o]of Object.entries(e.previousEntries)){let n=Me(i);if(!n)continue;let r=e.includeCollections?Gt(o.metadata,e.previousCollections[i]?.collections):o.metadata,a=t.get(r.id);Kt(a?.itemFormat,n,e.preferredFormat)&&t.set(r.id,{itemFormat:n,candidate:{metadata:r,body:e.includeBody?e.previousBodies[i]?.body:void 0,item_format:n,item_path:w.join(e.pmRoot,i)}})}return[...t.values()].sort((i,o)=>i.candidate.metadata.id.localeCompare(o.candidate.metadata.id)).map(i=>i.candidate)}function go(e){return e.forceSourceScan||Fe()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!re(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Bt(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Bt(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&ho(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function ke(e,t,i,o,n,r={}){let a=r.includeBody!==!1,s=r.includeCollections!==!1,d=Yt(),c=qt(t,i,n,d),m=await Ve(e);m.invalid&&await U(e);let u=await Yi(e,c,r.cacheDiagnostics),l=a?await Gi(e,c):null,y=s?await qi(e,c):null;Xi(u,l,y,m.envelope);let f=no(u,c),g=ro(l,c),_=ao(y,c),b=[...new Set(Object.values(i))],T=await Ie(e,b),$=Object.keys(f),k=Math.max(1,Math.floor(r.derivedIndexMinimumItems??Xt));if(go({forceSourceScan:r.forceSourceScan===!0,contextFingerprint:c,existingCache:u,existingBodyCache:l,existingCollectionsCache:y,directorySignatures:T,entryKeys:$,minimumIndexedItems:k,includeBody:a,includeCollections:s,previousBodies:g,previousCollections:_}))return _o({pmRoot:e,preferredFormat:t,includeBody:a,includeCollections:s,previousEntries:f,previousBodies:g,previousCollections:_});let I=await Promise.all(b.map(H=>Vi(e,H,o))),O=Fe(),C=so(),B={pmRoot:e,preferredFormat:t,warnings:o,schema:n,extensionFieldNames:d,includeBody:a,includeCollections:s,forceSourceRead:r.forceSourceScan===!0,dispatchReadHooks:O,previousEntries:f,previousBodies:g,previousCollections:_,state:C};await co(I,B);let N=await Ie(e,b),x=re(T,N)?N:{},z=C.misses.metadata||Object.keys(f).length!==Object.keys(C.newEntries).length||!re(u?.directory_signatures,x)||u===null?zt():u.source_cursor;return await lo({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingCache:u,previousEntries:f,directorySignatures:x,state:C,minimumIndexedItems:k}),a&&await uo({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingBodyCache:l,previousBodies:g,state:C}),s&&await mo({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingCollectionsCache:y,previousCollections:_,state:C}),yo(C)}async function Vt(e,t,i,o,n){return(await ke(e,t,i,o,n,{includeBody:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}async function Jt(e,t,i,o,n){return(await ke(e,t,i,o,n,{includeBody:!1,includeCollections:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}import j from"node:fs/promises";import{statSync as Io}from"node:fs";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ddc5bb8f-83bc-5121-a628-a501e7ed5a73")}catch{}})();function wo(e,t){let i=-1;return e.forEach((o,n)=>{let r=Date.parse(o.ts);if(!Number.isFinite(r))throw new p(`History for this item contains invalid timestamp at entry ${n+1}.`,h.GENERIC_FAILURE);r<=t&&(i=n)}),i}function bo(e,t){let i=e[0]?.ts??null,o=e.at(-1)?.ts??null,n={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:i,last_timestamp:o}};return o!==null&&(n.examples=[o],t!==null&&(n.examples.unshift(String(t+1),String(t+e.length)),n.valid_range.first_version=t+1,n.valid_range.last_version=t+e.length)),{guidance:n,lastTimestamp:o}}function Eo(e,t){let i={};if(t instanceof Error&&t.message.trim().length>0&&(i.reason=t.message.trim()),typeof t!="object"||t===null)return i;let o=t;if(typeof o.index=="number"&&Number.isInteger(o.index)&&o.index>=0&&(i.patchIndex=o.index),typeof o.operation=="object"&&o.operation!==null){let n=o.operation;Object.assign(i,Object.fromEntries(["op","path","from"].flatMap(r=>{let a=n[r];return typeof a=="string"?[[r,a]]:[]})))}if(i.patchIndex!==void 0){let n=e[i.patchIndex];n&&(i.op??=n.op,i.path??=n.path,i.from??=n.from)}return i}function Qt(e,t,i={}){let o=e.trim(),n=i.errorSubject??"history",r=n==="restore"?"Restore":"History",{guidance:a,lastTimestamp:s}=bo(t,Q(t,!0));if(!o)throw new p(`Missing ${n} target. Use a timestamp or version number.`,h.USAGE,a);if(/^\d+$/.test(o)){let m=Q(t),u=Number(o);if(u>=1&&u<=m)throw new p(`History version ${u} was pruned by compaction.`,h.USAGE,{...a,code:"history_version_pruned"});if(!Number.isSafeInteger(u)||u<1||u>m+t.length)throw new p(`${r} version must be between ${m+1} and ${m+t.length} for this item.`,h.USAGE,a);return{kind:"version",raw:o,historyIndex:u-m-1}}let d=Date.parse(o);if(!Number.isFinite(d))throw new p(`Invalid ${n} target "${e}". Use a positive version number or ISO timestamp.`,h.USAGE,a);let c=wo(t,d);if(c<0||i.allowFutureTimestamp!==!0&&d>Date.parse(s))throw new p(n==="restore"?`No history entries exist at or before timestamp ${o}.`:`No history entry exists at timestamp ${o}.`,h.USAGE,a);return{kind:"timestamp",raw:o,historyIndex:c}}function et(e,t,i,o){let n=He(e,t);if(n.ok)return n.document;let r=Eo(t,n.error),a=[`history_op=${o}`,r.patchIndex===void 0?null:`patch_index=${r.patchIndex}`,r.op?`op=${r.op}`:null,r.path?`path=${r.path}`:null,r.from?`from=${r.from}`:null].filter(s=>s!==null);throw new p(`Failed to apply history patch at entry ${i} (${a.join(", ")}). ${r.reason??String(n.error)}`,h.GENERIC_FAILURE)}function Zt(e,t){let i=e[0];if(i&&i.op!=="create"&&i.op!=="history_compact_baseline"){let a=He(K,i.patch);if(!a.ok||typeof a.document.metadata.id!="string")throw new p("History starts without a reconstructable item baseline.",h.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}let o=e.slice(0,t+1),n=fe([...o]),r=structuredClone(K);for(let a=0;a<=t;a+=1){let s=e[a];if(!s)throw new p(`History target entry ${a+1} does not exist.`,h.USAGE);r=et(r,s.patch,a+1,s.op)}if(!n.ok)throw new p(`History cannot be replayed: ${n.errors.join(", ")}.`,h.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:n.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return r}function Zn(e,t){if(Object.keys(e.metadata).length>0){if(typeof e.metadata.id!="string"||!Array.isArray(e.metadata.tags))throw new p("History has no complete item baseline for this target.",h.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return e}throw new p(`History target ${t.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,h.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();function vo(e,t){let i=-1,o=structuredClone(K);for(let[s,d]of e.entries()){if(o=et(o,d.patch,s+1,d.op),o.metadata.id!==void 0&&o.metadata.id!==t)throw new p(`History belongs to item ${String(o.metadata.id)}, expected ${t}.`,h.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});o.metadata.id===t&&Array.isArray(o.metadata.tags)&&(i=s)}let n=Q(e,!0),r=i<0||n===null?null:n+i+1,a=r===null?void 0:String(r);if(i>=0&&a===void 0){let s=e[i].ts;Qt(s,e).historyIndex===i&&(a=s)}return{version:r,target:a}}async function ei(e,t,i){let o=new Set([J(t,i),V(t)]);for(let n of o){let r=R(e,n);if(!Io(r,{throwIfNoEntry:!1})?.isFile())continue;let a=await vt(r,n),s=-1;if(a.forEach((y,f)=>{y.op==="delete"&&(s=f)}),s<0)continue;let d=Zt(a,a.length-1);if(Object.keys(d.metadata).length!==0)continue;let{version:c,target:m}=vo(a,n),u=m===void 0?["history",n,"--verify"]:["get",n,"--at",m],l=G(u);return new p(`Item ${n} was deleted at ${a[s].ts}; its history is retained.`,h.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:n,tombstone:{deleted:!0,deleted_at:a[s].ts,recoverable:m!==void 0,last_materialized_version:c},nextSteps:[l,...m===void 0?["Recover the pre-compaction history from version control."]:[G(["restore",n,m])]],recovery:{suggested_retry:l,suggested_retry_args:u}})}}import{AsyncLocalStorage as Co}from"node:async_hooks";import ti from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c343ed33-0135-5d3a-94a4-67314b295168")}catch{}})();var ii=new Co;function pr(e,t){return ii.run({...e,pmRoot:ti.resolve(e.pmRoot)},t)}function oi(e,t){let i=ii.getStore();return i?.pmRoot===ti.resolve(e)&&i.itemId===t?{bulk_checkpoint:i.checkpointId}:void 0}import it from"node:path";import To from"node:fs/promises";import xo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d746e4d-ff6c-54ec-a94f-4ec4cb8f77b5")}catch{}})();function So(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,i)=>t.localeCompare(i))}function Ro(e,t){return new p(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,h.NOT_FOUND)}async function ko(e,t){return await st(xo.dirname(e)),await(await To.open(e,"a")).close(),L({path:e,scope:"project",op:`${t}:history:auto_create`})}async function tt(e){return No({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function No(e){let t=So(e.itemIds),i=[],o=[];for(let n of t){let r=R(e.pmRoot,n);if(!await X(r)){if(e.settings.history.missing_stream==="strict_error")throw Ro(n,e.commandLabel);o.push(...await ko(r,e.commandLabel)),o.push(`history_stream_auto_created:${n}`),i.push(n)}}return{auto_created_ids:i,warnings:o}}import{isUtf8 as Mo}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8266acd6-5564-5d56-8025-82608136296d")}catch{}})();async function Do(e){try{return await j.access(e),!0}catch{return!1}}function Oo(e,t){e&&(e.includes(t)||e.push(t))}function ni(e){return e??ce(Y())}function Fo(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function ri(e,t,i="pm-",o,n=F){let r=t.trim(),a=r.startsWith("#")?r.slice(1):r;if(a.length===0)return null;let s=J(t,i),d=V(t),c=[...new Set([a,s,d])].filter(l=>l.length>0),m=Object.entries(n),u=Fo(o);for(let l of c){let y=new Map;for(let[f]of m)for(let g of u){let _=Ne(e,f,l,g,n);await Do(_)&&y.set(_,y.get(_)??{id:l,type:f,itemPath:_,item_format:g})}if(y.size>1){let f=[...y.keys()].map(g=>it.relative(e,g).split(it.sep).join("/")).sort();throw new p(`Item ${l} has ambiguous identity across ${f.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,h.CONFLICT,{code:"item_identity_ambiguous",item_id:l,paths:f})}for(let f of y.values())return f}return null}async function ai(e,t={}){let i=await Ao(e,t);if(i.error!==null)throw i.error;return{raw:i.raw,document:i.document}}async function Ao(e,t={}){let i=await j.readFile(e.itemPath);if(!Mo(i))throw new p("Item contains invalid UTF-8; preserve a binary backup before recovering it.",h.CONFLICT,{code:"item_document_encoding_invalid",item_id:e.id,item_path:e.itemPath,byte_length:i.length,empty:!1});let o=i.toString("utf8");await ue({path:e.itemPath,scope:"project"});let n;try{n=me(o,{format:e.item_format,requireSupportedFormat:!0,schema:t.schema,extensionFieldNames:ni(t.extensionFieldNames),onWarning:r=>Oo(t.warnings,r)})}catch(r){if(r instanceof p&&r.code==="item_format_version_unsupported")throw new p(`Item ${e.id}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath});if(r instanceof p&&r.code==="item_document_invalid")return{raw:o,document:null,error:new p(`Cannot read ${e.id} at ${e.itemPath}${i.length===0?" (zero-length file)":""}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath,byte_length:i.length,empty:i.length===0,nextSteps:[`Run pm history ${e.id} --full, then pm restore ${e.id} <version> to recover a recorded state.`]})};throw r}return{raw:o,document:n,error:null}}async function Lo(e,t,i=F,o,n){await pe(e);let r=await Vt(e,t,i,o,n);return he(r.length),r.map(a=>a.metadata)}async function Zr(e,t,i=F,o,n){await pe(e);let r=await Jt(e,t,i,o,n);return he(r.length),r.map(a=>a.metadata)}async function ea(e,t,i=F,o,n,r={}){await pe(e);let a=await ke(e,t,i,o,n,{includeBody:!0,forceSourceScan:r.forceSourceScan});return he(a.length),a.map(s=>({...s.metadata,body:s.body}))}function si(e){return{async get(t){let i=await ri(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!i)return null;let{document:o}=await ai(i,{schema:e.settings.schema});return{item:o.metadata,body:o.body}},list:()=>Lo(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Po(e,t){let i=new Set(Object.values(t)),o=[];return await Promise.all([...i].map(async n=>{try{let r=await j.readdir(it.join(e,n));for(let a of r)for(let s of de)if(a.toLowerCase().endsWith(s)){o.push(a.slice(0,-s.length));break}}catch{}})),o}async function jo(e,t,i,o){let n=J(t,i),r=await Po(e,o);if(r.length===0)return[];let a=Math.max(3,Math.floor(n.length/2));return r.map(s=>({id:s,distance:se(s,n,a)})).filter(s=>s.distance!==null).sort((s,d)=>s.distance-d.distance).slice(0,3).map(s=>s.id)}async function $o(e,t,i,o){let n=await ei(e,t,i);if(n)return n;let r=await jo(e,t,i,o),a=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return r.length>0&&a.unshift(`Did you mean one of: ${r.join(", ")}?`),new p(`Item ${t} not found`,h.NOT_FOUND,{code:"item_not_found",id:t,nextSteps:a})}function Ho(e,t){return e==="claim"||t===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function ci(e){let t=e.typeToFolder??lt(e.settings,Y()).type_to_folder,i=await ri(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!i)throw await $o(e.pmRoot,e.id,e.settings.id_prefix,t);let o=await gt(e.pmRoot,i.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms,{waitPolicy:"progress"}),n=o.release;try{let r=[],{raw:a,document:s}=await ai(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:r}),d=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||d,m=It(e.author),u=xt(e.settings);if(d&&c!==m&&!e.force&&!Ho(e.op,e.bypassAssigneeConflict)){if(u.ownership_enforcement==="strict")throw new p(`Item ${i.id} is assigned to ${d}. Use --force to override.`,h.CONFLICT);u.ownership_enforcement==="warn"&&r.push(`ownership_warning:assignee_conflict:${i.id}:${d}`)}return{typeToFolder:t,located:i,originalRaw:a,document:s,warnings:r,releaseLock:n,lease:o}}catch(r){throw await n(),r}}async function di(e,t,i,o){return e.fence(async()=>{let n;try{n=await j.readFile(t.itemPath,"utf8")}catch(r){if(!A(r))throw r;n=null}if(n!==i)throw new p(`Item ${t.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,h.CONFLICT,{code:"stale_revision",item_id:t.id,reason:n===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return o()})}function Wo(e,t,i){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:t,effectiveSerializedAfter:i,skipItemWrite:!1};let o=e.result;return{effectiveTargetItemPath:typeof o.target_item_path=="string"&&o.target_item_path.trim().length>0?o.target_item_path:t,effectiveSerializedAfter:typeof o.contents=="string"?o.contents:i,skipItemWrite:o.skip_write===!0}}async function Uo(e){let t=await Ae("item_store_delete",e),i=t.handled&&typeof t.result=="object"&&t.result!==null?t.result:{};return{effectiveItemPath:typeof i.item_path=="string"&&i.item_path.trim().length>0?i.item_path:e.item_path,skipDelete:i.skip_delete===!0,warnings:t.warnings}}async function Bo(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await M(e.originalItemPath,e.originalRaw),await j.rm(e.effectiveTargetItemPath,{force:!0});return}await M(e.originalItemPath,e.originalRaw)}}async function ot(e){wt(e.op);let t=await ci({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:i,located:o,originalRaw:n,document:r,warnings:a,releaseLock:s,lease:d}=t;try{ze(e.pmRoot,r);let c=q(r,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),m=q(structuredClone(r),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(m);if(e.skipNoop===!0&&u.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...a,...u.warnings??[]]};let l={...e.resolveHistoryContext?.(),...oi(e.pmRoot,o.id),...Ft(e.pmRoot,r)},y=Math.max(Pe(c.metadata),Pe(m.metadata));St(ut(e.pmRoot),y),y>bt(m.metadata)&&(m.metadata.pm_format_version=y,u.changedFields.push("pm_format_version")),m.metadata.updated_at=Le();let f=q(m,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await We({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:c,after:f});await Oe({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:u.changedFields,sdk:si({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:i})});let _=await tt({pmRoot:e.pmRoot,settings:e.settings,itemId:o.id,commandLabel:e.op}),b="toon",T=Et(f,{format:b,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),$=Ne(e.pmRoot,f.metadata.type,o.id,b,i),k=R(e.pmRoot,o.id),I=await di(d,o,n,async()=>{let N=await Ae("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:o.id,source_item_path:o.itemPath,target_item_path:$,history_path:k,item_format:b,before:c,after:f,contents:T}),{effectiveTargetItemPath:x,effectiveSerializedAfter:z,skipItemWrite:H}=Wo(N,$,T),ui=await Qe(e.pmRoot,e.author),rt=[];try{H||await M(x,z),!H&&x!==o.itemPath&&await j.rm(o.itemPath);let mi=je({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:g.decisions.length===0?Object.keys(l).length===0?void 0:l:{...l,workflow_policies:g.decisions}});try{await $e(k,mi)}catch(fi){throw await Bo({skipItemWrite:H,effectiveTargetItemPath:x,originalItemPath:o.itemPath,originalRaw:n}),fi}H||(rt=await Ze({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:i,schema:e.settings.schema,itemPath:x,previousItemPath:o.itemPath,document:f}))}finally{await ui()}return{derivedIndexWarnings:rt,effectiveTargetItemPath:x,overrideWarnings:N.warnings}}),{derivedIndexWarnings:O,effectiveTargetItemPath:C}=I;Ot(e.pmRoot,f);let B=[...await L({path:C,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:u.changedFields}),...await L({path:k,scope:"project",op:`${e.op}:history`,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:u.changedFields})];return De({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:le(c.metadata,u.changedFields),current:le(f.metadata,u.changedFields),changed_fields:u.changedFields}),{item:f.metadata,body:f.body,changedFields:u.changedFields,warnings:[...a,...u.warnings??[],...g.warnings,..._.warnings,...I.overrideWarnings,...O,...B]}}finally{await s()}}async function ta(e){let{historyContext:t,...i}=e;return ot({...i,resolveHistoryContext:()=>t})}async function ia(e){return ot(e)}async function oa(e){return ot(e)}async function na(e){let t=await ci({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:i,originalRaw:o,document:n,warnings:r,releaseLock:a,lease:s}=t;try{ze(e.pmRoot,n);let d=ni(void 0),c=q(n,{schema:e.settings.schema,extensionFieldNames:d}),m=await We({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:c,after:null,dryRun:e.dryRun});await Oe({pm_root:e.pmRoot,operation:"delete",before:c,after:null,changed_fields:["deleted"],sdk:si({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let u=await tt({pmRoot:e.pmRoot,settings:e.settings,itemId:i.id,commandLabel:"delete"}),l=Le(),y=at,f=je({nowIso:l,author:e.author,op:"delete",before:c,after:y,message:e.message,context:m.decisions.length===0?void 0:{workflow_policies:m.decisions}}),g=R(e.pmRoot,i.id),_=()=>Uo({op:"delete",pm_root:e.pmRoot,item_id:i.id,item_path:i.itemPath,history_path:g,before:c});if(e.dryRun===!0){let I=await _();return{item:c.metadata,changedFields:["deleted"],targetPath:I.effectiveItemPath,warnings:[...r,...m.warnings,...u.warnings,...I.warnings]}}let b=await di(s,i,o,async()=>{let{effectiveItemPath:I,skipDelete:O,warnings:C}=await _(),B=await Qe(e.pmRoot,e.author),N=[];try{O||await j.rm(I);try{await $e(g,f)}catch(x){throw O||await M(I,o),x}O||(N=await Ze({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:I,document:null}))}finally{await B()}return{derivedIndexWarnings:N,effectiveItemPath:I,overrideWarnings:C}}),{derivedIndexWarnings:T,effectiveItemPath:$}=b,k=[...await L({path:$,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:y,changed_fields:["deleted"]}),...await L({path:g,scope:"project",op:"delete:history",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:y,changed_fields:["deleted"]})];return De({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:le(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...r,...m.warnings,...u.warnings,...b.overrideWarnings,...T,...k]}}finally{await a()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ec94c4fe-bfe9-5888-8b10-0ea190da923d")}catch{}})();function nt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function ca(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!nt(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return nt(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&nt(t.feasible_tokens)&&t.reason===void 0;case"unavailable":return t.minimum_feasible_tokens===null&&t.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(t.reason);default:return!1}}var zo="PmCliError";function da(e){if(!Yo(e)||e.code!=="item_already_exists"||e.exitCode!==h.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function Xo(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=h.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function la(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let i=new p(e,Xo(t.exitCode??h.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(i,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),i}function Yo(e){if(!(e instanceof Error)||e.name!==zo)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)&&typeof t.context=="object"&&t.context!==null&&!Array.isArray(t.context)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();function Go(e,t){let i=e.trim().toLowerCase();if(i.length===0)return;let o=Math.floor(i.length/3);return t.map(n=>({candidate:n,distance:se(i,n.toLowerCase(),o)??Number.POSITIVE_INFINITY})).filter(({distance:n})=>Number.isFinite(n)).sort((n,r)=>n.distance!==r.distance?n.distance-r.distance:n.candidate.localeCompare(r.candidate))[0]?.candidate}function li(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function ya(e){let t=e.command_path.trim().replaceAll(/\s+/gu," "),i=e.token.trim(),o=i.length===0?"<empty>":i,n=[...new Set(e.allowed.map(l=>l.trim()))].filter(Boolean).sort((l,y)=>l.localeCompare(y));if(t.length===0||o.length===0||n.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let r=t.split(" "),a=e.trailing_args??[],s=e.display_name??`pm ${t}`,d=e.token_kind??"subcommand",c=e.retry_command?void 0:Go(o,n),m=li([...r,o,...a]),u=e.retry_command??(c?li([...r,c,...a]):void 0);return new p(`Unknown ${s} ${d} "${o}". Allowed: ${n.join(", ")}${e.message_suffix??""}`,e.exit_code??h.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:o,examples:[...u?[u]:[],...e.examples??[],`pm ${t} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:m,allowed_values:n,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}export{ya as a,tt as b,No as c,kt as d,V as e,J as f,Zo as g,Q as h,Qt as i,et as j,Zt as k,Zn as l,wi as m,Ei as n,Ii as o,vi as p,Ci as q,We as r,bn as s,Cn as t,ze as u,pr as v,Dn as w,On as x,Fn as y,Xt as z,Hi as A,Qe as B,Gn as C,Ze as D,ke as E,ri as F,ai as G,Ao as H,Lo as I,Zr as J,ea as K,si as L,$o as M,ta as N,ia as O,oa as P,na as Q,ca as R,zo as S,da as T,la as U,Yo as V};
91
- //# sourceMappingURL=chunk-EJJWOFP5.js.map