@unbrained/pm-cli 2026.10.23 → 2026.10.25

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 (194) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +41 -0
  3. package/dist/cli/error-guidance.js +2 -2
  4. package/dist/cli/extension-command-help.js +2 -2
  5. package/dist/cli/register-history-activity.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/{chunk-R7KWBFM2.js → chunk-3CYXE6BV.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-444VPGQT.js +20 -0
  9. package/dist/cli-bundle/chunks/{chunk-5V4HU6GK.js → chunk-4GD6QOP6.js} +21 -21
  10. package/dist/cli-bundle/chunks/{chunk-5DKCD4KV.js → chunk-5ZPT67NJ.js} +35 -34
  11. package/dist/cli-bundle/chunks/{chunk-KY34HTT2.js → chunk-7C3GCLOO.js} +29 -29
  12. package/dist/cli-bundle/chunks/{chunk-MTRYEVZR.js → chunk-7T3H24HN.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-REXCO5AG.js → chunk-EYCVAAIP.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-2UX2TAN2.js → chunk-FNZT4BTE.js} +60 -56
  15. package/dist/cli-bundle/chunks/chunk-HMJSFWHK.js +2 -0
  16. package/dist/cli-bundle/chunks/{chunk-ZDVTXLA6.js → chunk-LNKPH2DD.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-HDKY2YX3.js → chunk-MVJGGCGQ.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-3S5FLCG7.js → chunk-O3ZTGRIH.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-ZEI3DC5E.js → chunk-RD6UW3MW.js} +3 -3
  20. package/dist/cli-bundle/chunks/chunk-RLXK2S7P.js +2 -0
  21. package/dist/cli-bundle/chunks/{chunk-F76ZUP73.js → chunk-RQKDANP7.js} +42 -42
  22. package/dist/cli-bundle/chunks/chunk-TLMXSYJA.js +2 -0
  23. package/dist/cli-bundle/chunks/{chunk-AAX7CNL7.js → chunk-UI3FD3DW.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-ZMJF5HQW.js → chunk-VAEB6IUQ.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-ZNDYAZZ6.js → chunk-XYLBOXSH.js} +6 -6
  26. package/dist/cli-bundle/chunks/{chunk-AXGFNNI3.js → chunk-YCCGZHOR.js} +2 -2
  27. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-XANVELIV.js → indexed-receipt-blobs-47I6KKDO.js} +2 -2
  28. package/dist/cli-bundle/chunks/{mutation-admission-P6LOBNLO.js → mutation-admission-747C6IUR.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-list-query-JOB65KDN.js → register-list-query-COST6KRV.js} +3 -3
  30. package/dist/cli-bundle/chunks/{register-mutation-QMNIN3RJ.js → register-mutation-JZVVJUHY.js} +2 -2
  31. package/dist/cli-bundle/chunks/register-operations-S4LKLUBJ.js +2 -0
  32. package/dist/cli-bundle/chunks/{register-setup-GNKWL3VL.js → register-setup-3ITZXPOL.js} +2 -2
  33. package/dist/cli-bundle/chunks/{settlement-hook-YUVCO65H.js → settlement-hook-5IVCF6ZY.js} +2 -2
  34. package/dist/cli-bundle/chunks/stage-3UUIYROS.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-DWQMYLFM.js → chunk-22727JYL.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-4MNUQCGR.js → chunk-3FM75SBJ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-ZHMF34DT.js → chunk-3M5FZCMC.js} +53 -53
  38. package/dist/cli-bundle/focused-chunks/{chunk-BUZ2Z4P3.js → chunk-46KDJH3K.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-5LBZR6YW.js +2 -0
  40. package/dist/cli-bundle/focused-chunks/{chunk-EDXTOAXP.js → chunk-74KC7FUQ.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-77NU7NPN.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-MLET6I3I.js → chunk-7DEZT4JN.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-NSMZY6IK.js → chunk-B5JOVH5F.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-HMYDUEQK.js +8 -0
  45. package/dist/cli-bundle/focused-chunks/chunk-IVLIUPVV.js +12 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-KIIGME23.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-P7DPS5M4.js → chunk-LWJ2X75I.js} +24 -24
  48. package/dist/cli-bundle/focused-chunks/{chunk-6GTZ24YV.js → chunk-MT5TYMEU.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-OMXMYTEX.js → chunk-NC5HUGHU.js} +3 -3
  50. package/dist/cli-bundle/focused-chunks/chunk-NI5SG2M2.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-QH5KMIYZ.js +91 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-UNTCCJPL.js → chunk-U6HXIF6G.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-CGL36F6I.js → chunk-URWYYJ7K.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-I2USTQNQ.js → chunk-W7MCCFYV.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-WMPDY5ZU.js +21 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-R536272H.js → chunk-Y4JHHY24.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-KI5YFKNN.js → chunk-ZYCOMRFT.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FVOA3XMI.js → indexed-receipt-blobs-YCLN2ZZG.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{mutation-admission-HTFAIHJL.js → mutation-admission-BQBQXILV.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{settlement-hook-2VXEB6PP.js → settlement-hook-XVS6P2XI.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/stage-VSIL4MTZ.js +2 -0
  62. package/dist/cli-bundle/main.js +21 -21
  63. package/dist/cli-bundle/sdk-authoring.js +1 -1
  64. package/dist/cli-bundle/sdk-contracts.js +2 -2
  65. package/dist/cli-bundle/sdk-core.js +24 -24
  66. package/dist/cli-bundle/sdk-governance.js +1 -1
  67. package/dist/cli-bundle/sdk-graph.js +1 -1
  68. package/dist/cli-bundle/sdk-merge.js +51 -52
  69. package/dist/cli-bundle/sdk-query.js +1 -1
  70. package/dist/cli-bundle/sdk-runtime.js +1 -1
  71. package/dist/cli-bundle/sdk-testing.js +1 -1
  72. package/dist/cli-bundle/sdk.js +9 -9
  73. package/dist/core/checkpoint/mutation-checkpoint.d.ts +6 -3
  74. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  75. package/dist/core/checkpoint/mutation-context.d.ts +10 -0
  76. package/dist/core/checkpoint/mutation-context.js +2 -0
  77. package/dist/core/diagnostics/remediation.js +1 -1
  78. package/dist/core/shared/errors.d.ts +13 -0
  79. package/dist/core/shared/errors.js +1 -1
  80. package/dist/core/store/item-store.js +1 -1
  81. package/dist/core/store/settings.js +2 -2
  82. package/dist/sdk/agent/command-recovery.d.ts +1 -0
  83. package/dist/sdk/agent/command-recovery.js +1 -1
  84. package/dist/sdk/agent/linked-resource-recovery.d.ts +13 -0
  85. package/dist/sdk/agent/linked-resource-recovery.js +2 -0
  86. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  87. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  88. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  89. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  90. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  91. package/dist/sdk/cli-contracts/registration-helpers.d.ts +2 -0
  92. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  93. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  94. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  95. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +3 -2
  96. package/dist/sdk/completion/fish.js +3 -1
  97. package/dist/sdk/completion/zsh.js +3 -1
  98. package/dist/sdk/core.d.ts +1 -1
  99. package/dist/sdk/core.js +1 -1
  100. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  101. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  102. package/dist/sdk/governance/health-merge-evidence.d.ts +5 -0
  103. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  104. package/dist/sdk/governance/health.js +1 -1
  105. package/dist/sdk/index.d.ts +2 -1
  106. package/dist/sdk/index.js +1 -1
  107. package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +7 -0
  108. package/dist/sdk/lifecycle/checkpoint-rollback.js +2 -0
  109. package/dist/sdk/lifecycle/close-many.d.ts +1 -1
  110. package/dist/sdk/lifecycle/close-many.js +1 -1
  111. package/dist/sdk/lifecycle/update-many.d.ts +1 -1
  112. package/dist/sdk/lifecycle/update-many.js +1 -1
  113. package/dist/sdk/merge/history-scalar-rebase.d.ts +9 -0
  114. package/dist/sdk/merge/history-scalar-rebase.js +2 -0
  115. package/dist/sdk/merge/ignored-artifacts.d.ts +13 -0
  116. package/dist/sdk/merge/ignored-artifacts.js +2 -0
  117. package/dist/sdk/merge/stage.js +1 -1
  118. package/dist/sdk/merge/three-way.js +1 -1
  119. package/dist/sdk/public-surface.json +1 -1
  120. package/dist/sdk/query/activity.d.ts +14 -2
  121. package/dist/sdk/query/activity.js +1 -1
  122. package/dist/sdk/query/calendar.d.ts +16 -0
  123. package/dist/sdk/query/calendar.js +3 -3
  124. package/dist/sdk/query/context.d.ts +2 -1
  125. package/dist/sdk/query/context.js +2 -2
  126. package/dist/sdk/query/get.d.ts +2 -1
  127. package/dist/sdk/query/get.js +1 -1
  128. package/dist/sdk/query/list.d.ts +2 -1
  129. package/dist/sdk/query/list.js +1 -1
  130. package/dist/sdk/query/search/types.d.ts +2 -1
  131. package/dist/sdk/query/search-contracts.js +1 -1
  132. package/dist/sdk/query/window-pagination.d.ts +20 -0
  133. package/dist/sdk/query/window-pagination.js +2 -0
  134. package/dist/sdk/query.d.ts +1 -0
  135. package/dist/sdk/query.js +1 -1
  136. package/dist/sdk/read-output-contracts.d.ts +10 -2
  137. package/dist/sdk/read-output-contracts.js +1 -1
  138. package/dist/sdk/runtime-input.js +1 -1
  139. package/dist/sdk/runtime-primitives.d.ts +1 -0
  140. package/dist/sdk/runtime-primitives.js +1 -1
  141. package/dist/sdk/runtime.d.ts +11 -11
  142. package/dist/sdk/runtime.js +1 -1
  143. package/dist/sdk/schema-migration.js +2 -2
  144. package/dist/sdk/templates.d.ts +7 -1
  145. package/dist/sdk/templates.js +2 -2
  146. package/dist/sdk/test/batch.js +2 -2
  147. package/dist/sdk/test/entry.d.ts +5 -1
  148. package/dist/sdk/test/entry.js +2 -1
  149. package/dist/sdk/test/execution.js +2 -2
  150. package/docs/COMMANDS.md +40 -3
  151. package/docs/EXTENSIONS.md +1 -1
  152. package/docs/MERGE_SAFETY.md +28 -0
  153. package/docs/READ_OUTPUT_CONTRACTS.md +15 -0
  154. package/docs/SDK.md +130 -6
  155. package/docs/TESTING.md +28 -0
  156. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  157. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +7 -3
  158. package/marketplace.json +1 -1
  159. package/package.json +1 -1
  160. package/packages/pm-beads/package.json +1 -1
  161. package/packages/pm-calendar/extensions/calendar/index.ts +6 -0
  162. package/packages/pm-calendar/package.json +1 -1
  163. package/packages/pm-command-kit/package.json +1 -1
  164. package/packages/pm-digital-twin/package.json +1 -1
  165. package/packages/pm-governance-audit/package.json +1 -1
  166. package/packages/pm-guide-shell/package.json +1 -1
  167. package/packages/pm-kanban/package.json +1 -1
  168. package/packages/pm-lifecycle-hooks/package.json +1 -1
  169. package/packages/pm-linked-test-adapters/package.json +1 -1
  170. package/packages/pm-search-advanced/package.json +1 -1
  171. package/packages/pm-templates/extensions/templates/runtime.ts +3 -1
  172. package/packages/pm-templates/package.json +1 -1
  173. package/packages/pm-todos/package.json +1 -1
  174. package/packages/pm-vcs/package.json +1 -1
  175. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  176. package/plugins/pm-claude/package.json +1 -1
  177. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  178. package/plugins/pm-codex/package.json +1 -1
  179. package/plugins/pm-codex/plugin.json +1 -1
  180. package/runtime-dependencies.json +1 -1
  181. package/dist/cli-bundle/chunks/chunk-2LTGJ5DL.js +0 -2
  182. package/dist/cli-bundle/chunks/chunk-MMVX5L32.js +0 -20
  183. package/dist/cli-bundle/chunks/chunk-QSY55FTA.js +0 -2
  184. package/dist/cli-bundle/chunks/register-operations-Z4VET3I7.js +0 -2
  185. package/dist/cli-bundle/chunks/stage-FW5OXCCR.js +0 -2
  186. package/dist/cli-bundle/focused-chunks/chunk-BM652VCB.js +0 -8
  187. package/dist/cli-bundle/focused-chunks/chunk-FO4U3FIP.js +0 -91
  188. package/dist/cli-bundle/focused-chunks/chunk-GXKP56W7.js +0 -2
  189. package/dist/cli-bundle/focused-chunks/chunk-JDN34LEZ.js +0 -2
  190. package/dist/cli-bundle/focused-chunks/chunk-LEHGCPZ6.js +0 -12
  191. package/dist/cli-bundle/focused-chunks/chunk-XIZYJDYW.js +0 -2
  192. package/dist/cli-bundle/focused-chunks/chunk-Z5LDTMZ3.js +0 -2
  193. package/dist/cli-bundle/focused-chunks/chunk-ZR6ZKQUK.js +0 -20
  194. package/dist/cli-bundle/focused-chunks/stage-X3BUGEJT.js +0 -2
@@ -1,2 +0,0 @@
1
- import{Ce as g,De as E,Ee as k,Fe as I,Ge as M,Hc as R,He as P,Mf as L,Ne as A,Nf as U,Pe as w,Pf as x,Re as F,lf as D,wc as N,yc as v,zc as b}from"./chunk-5DKCD4KV.js";import{M as T}from"./chunk-F76ZUP73.js";import{A as f,C as p}from"./chunk-R7KWBFM2.js";(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]="b7b0588b-c59a-528c-9d1d-2a3dfc9f8017")}catch{}})();var H=Symbol("pm.mcp-mutation-transport"),h={create:{parameters:w,aliases:g,strings:E,repeatables:k},update:{parameters:F,aliases:I,strings:M,repeatables:P}},J=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function y(e){return H in e}function _(e,t){return y(e)?N(t):v(e,t)}function he(e,t,r=[]){let i=v(e,{...e,...t});for(let l of r)Reflect.deleteProperty(i,l);return i}function s(e,t){let r=e[t];return typeof r=="string"&&r.trim().length>0?r:void 0}function u(e,t){let r=e[t];return typeof r=="string"?r.trim().length>0?r:void 0:typeof r=="number"&&Number.isFinite(r)?String(r):void 0}function Te(e,t){let r=e[t];return typeof r=="string"?r:typeof r=="number"&&Number.isFinite(r)?String(r):void 0}function c(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ve(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new p(`${t} must be a finite integer.`,f.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let r=Number(e);if(!Number.isInteger(r))throw new p(`${t} must be a finite integer.`,f.USAGE);return r}}function Re(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:s(e,"limit")??s(t,"limit")}function Se(e){let t=s(e,"outputFormat");return{json:!0,quiet:!0,author:s(e,"author"),path:s(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:s(e,"outputInclude"),outputLimit:u(e,"outputLimit"),outputBudget:u(e,"outputBudget"),outputSession:s(e,"outputSession"),outputCursor:s(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var z=new Set(["tags","blockedBy","blocked_by","skills","fields"]),j=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),X=new Set([...j].filter(e=>e!=="file")),Q=new Set(["files","files-discover","docs","test","test-all"]),G=new Set(["comments","notes","learnings"]);function Z(e,t){if(!(!G.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new p(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,f.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var ee=new Set(["claim","release","start-task","pause-task","close-task"]),Y={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},$=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function K(e,t=""){let r={},i=Q.has(t),l=t==="files"||t==="files-discover"||t==="docs",a=G.has(t)?X:j;for(let[n,o]of Object.entries(e)){if(Array.isArray(o)&&z.has(n)){r[n]=o.join(",");continue}if(n==="note"&&l){r[n]=o;continue}if(typeof o=="string"&&a.has(n)){r[n]=[o];continue}if(typeof o=="string"&&i&&(n==="add"||n==="remove")){r[n]=[o];continue}r[n]=o}return Object.assign(r,Object.fromEntries(Object.getOwnPropertySymbols(e).map(n=>[n,Reflect.get(e,n)]))),r}function te(e,t,r){let i=s(e,"author");return i!==void 0?i:r!==void 0&&ee.has(r)?s(e,"assignee")??s(t,"assignee"):void 0}function re(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function ne(e,t,r){let i={},l=h[e],a=new Set([...l.parameters.map(({param:n})=>n),...A.map(({param:n})=>n),...Y[e],...$,"force"]);for(let n of a){let o=l.aliases.find(d=>d.keys.includes(n))?.keys??[n];t[n]===void 0||o.some(d=>r[d]!==void 0)||(i[n]=t[n])}return i}function m(e,t){throw new p(`Invalid MCP ${e} value for "${t}". No changes were made.`,f.USAGE,{code:"invalid_argument_value",reason:"invalid_mutation_option_value",changed:!1,field:t,required:`Provide valid ${e} field values and an options object; inspect the pm_${e} input schema for supported types.`})}function ie(e,t,r){let i=h[e],l=[...i.parameters,...A,{param:"force"}];for(let{param:a}of l){if(T(D[a]).type!=="boolean")continue;let n=(i.aliases.find(o=>o.keys.includes(a))?.keys??[a]).find(o=>r[o]!==void 0&&typeof r[o]!="boolean");n!==void 0&&m(e,n)}for(let a of["idOnly","fullChangedFields"])t[a]!==void 0&&typeof t[a]!="boolean"&&m(e,a)}function oe(e,t,r){t.options!==void 0&&!c(t.options)&&m(e,"options"),ie(e,t,r);for(let n of z){let o=r[n];Array.isArray(o)&&o.some(d=>typeof d!="string")&&m(e,n)}let i=W(r,e),l=h[e];for(let{keys:n,target:o}of l.strings)n.some(d=>r[d]!==void 0)&&i[o]===void 0&&m(e,o);let a=l.repeatables.flatMap(({keys:n})=>n).find(n=>{let o=r[n];return o!==void 0&&typeof o!="string"&&(!Array.isArray(o)||o.some(d=>typeof d!="string"))});return a!==void 0&&m(e,a),i}function ae(e,t,r,i){let l=(t==="create"||t==="update")&&y(e),a={...l?ne(t,e,i):r,...i};return l?oe(t,e,a):K(a,t)}function Ce(e,t){let r=c(e.options)?e.options:void 0,i=T(e.options),l={},a=d=>{i[d]!==void 0||e[d]===void 0||(l[d]=e[d])};for(let d of Y[t??""]??[])a(d);for(let d of $)a(d);t!==void 0&&y(e)&&Z(t,i);let n=ae(e,t,l,i);if(t==="history-attest"&&y(e)&&(n.output!==void 0||typeof n.verify=="string"))throw new p("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",f.USAGE);let o=y(e)?e:r??e;return _(o,re(n,te(e,n,t)))}function Ne(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function be(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function se(e){let t=[],r=!0;for(let i of e.trim().toLowerCase()){if(i>="a"&&i<="z"||i>="0"&&i<="9"){t.push(i),r=!1;continue}r||(t.push("-"),r=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function ge(e){return!J.has(se(e))}function Ee(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function le(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function ke(e,t){let r=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),i={};for(let[a,n]of Object.entries(e))r.has(a)||(i[a]=n);let l={...i,...t};return delete l.args,delete l.author,l}function Ie(e,t){let r=_(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:r}}function C(e){return{type:u(e,"filterType"),tag:u(e,"filterTag"),priority:u(e,"filterPriority"),deadlineBefore:u(e,"filterDeadlineBefore"),deadlineAfter:u(e,"filterDeadlineAfter"),updatedAfter:u(e,"filterUpdatedAfter"),updatedBefore:u(e,"filterUpdatedBefore"),createdAfter:u(e,"filterCreatedAfter"),createdBefore:u(e,"filterCreatedBefore"),ids:R(e.ids),assignee:u(e,"filterAssignee"),assigneeFilter:u(e,"filterAssigneeFilter")??u(e,"filterAssignee_filter"),parent:u(e,"filterParent"),sprint:u(e,"filterSprint"),release:u(e,"filterRelease"),limit:u(e,"limit"),offset:u(e,"offset")}}function S(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return le(e)}function O(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function Me(e){let t=S(e.kind),r=S(e.exemptIsolate),i=S(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:O(e.maxDepth),limit:O(e.limit),after:s(e,"after"),direction:s(e,"direction"),maxPaths:O(e.maxPaths),sample:O(e.sample),...r===void 0?{}:{exemptIsolate:r},...i===void 0?{}:{exemptIsolateType:i},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function V(e){let t=x(e);return e.ids!==void 0&&(t.ids=R(e.ids)),t}function Pe(e){return{status:s(e,"filterStatus"),list:c(e.list)?V(e.list):C(e),reason:s(e,"reason"),resolution:s(e,"resolution"),expectedResult:s(e,"expectedResult")??s(e,"expected_result")??s(e,"expected"),actualResult:s(e,"actualResult")??s(e,"actual_result")??s(e,"actual"),validateClose:s(e,"validateClose")??s(e,"validate_close"),author:s(e,"author"),message:s(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:s(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var ue=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function B(e){let t={};for(let[r,i]of Object.entries(e))ue.has(r)||(t[r]=i);return q(t)}function q(e){return W(e,"update")}function W(e,t){let r=K(e,t),i=h[t],l=new Set([...i.parameters,...A].filter(({booleanish:a})=>a===!0).map(({param:a})=>a));for(let{keys:a}of i.repeatables)for(let n of a)typeof r[n]=="string"&&(r[n]=[r[n]]);for(let a of i.strings)for(let n of a.keys){let o=r[n];(typeof o=="number"&&Number.isFinite(o)||o===!1&&l.has(n))&&(r[n]=String(o))}return t==="create"?{...L(r,{requireType:!1})}:U(r)}function we(e){if(c(e.list)||c(e.update)){let t=c(e.update)?e.update:B(e),r=_(e,q(t));return{status:u(e,"filterStatus"),list:c(e.list)?V(e.list):C(e),update:b(t,r),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:s(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:u(e,"filterStatus"),list:C(e),update:_(e,B(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:s(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}export{y as a,he as b,s as c,u as d,Te as e,c as f,ve as g,Re as h,Se as i,Y as j,K as k,Ce as l,Ne as m,be as n,se as o,ge as p,Ee as q,le as r,ke as s,Ie as t,C as u,Me as v,Pe as w,q as x,we as y};
2
- //# sourceMappingURL=chunk-QSY55FTA.js.map
@@ -1,2 +0,0 @@
1
- import"./chunk-SGFQQXFD.js";import"./chunk-DEZPZOQ7.js";import{Cc as $,Dc as G,Ec as H,Ed as ie,Fc as W,Gc as j,Hc as B,Jb as N,Jc as I,Kc as z,Lc as Y,Mc as K,Nc as X,Oc as Q,Pb as U,Qc as Z,Rc as ee,Sb as q,Xa as F,ga as M,kd as te,nd as ae,pd as ne,rb as V,wd as oe,xd as re,yc as J,yd as C}from"./chunk-KY34HTT2.js";import"./chunk-QSY55FTA.js";import"./chunk-5V4HU6GK.js";import"./chunk-MMVX5L32.js";import"./chunk-4D25HF3V.js";import{Af as L,Ef as c,Hf as f,If as i,Jf as g,Zf as y,hc as _,yf as O,zf as P}from"./chunk-5DKCD4KV.js";import"./chunk-RUKSEZE7.js";import"./chunk-ZEI3DC5E.js";import"./chunk-IB7UB5TE.js";import{Nf as l,Of as u,Tc as x,k as T,l as E,oh as R,xa as v,zi as A}from"./chunk-F76ZUP73.js";import"./chunk-ZDVTXLA6.js";import"./chunk-VS565KBX.js";import{A as d,C as m}from"./chunk-R7KWBFM2.js";import"./chunk-XAWE4EAK.js";(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]="c3d9f24a-7089-5d60-ab12-93d03b86da80")}catch{}})();var se=new Map([["measurements","boolean"],["metric","string"],["measurementLimit","number"],["observe","string_array"],["direction","direction"],["measurementSource","string"],["measurementItem","string"],["measurementRevision","string"],["author","string"],["message","string"],["provenanceCoverage","boolean"],["fleetAttribution","boolean"],["since","string"],["eventLimit","number"],["minimumSample","number"]]),ke=new Set(["higher","lower","target"]),ve=[...se.keys()].sort((e,t)=>e.localeCompare(t)).join(", ");function xe(e,t){return e==="boolean"?typeof t=="boolean":e==="string"?typeof t=="string":e==="number"?typeof t=="number":e==="string_array"?Array.isArray(t)&&t.every(a=>typeof a=="string"):e==="direction"&&ke.has(t)}function le(e){if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch(a){throw new m(`--analytics must be valid JSON: ${String(a)}`,d.USAGE)}if(t===null||typeof t!="object"||Array.isArray(t))throw new m("--analytics must be a JSON object.",d.USAGE);for(let[a,n]of Object.entries(t)){let o=se.get(a);if(!xe(o,n))throw new m(o===void 0?`Unknown --analytics field "${a}". Accepted fields: ${ve}.`:`--analytics field "${a}" must be ${o.replace("_"," ")}.`,d.USAGE)}return t}(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]="dcd8c925-34ee-5faa-9132-1be43961c749")}catch{}})();(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]="29db968f-30ad-5f3c-bf95-e33be18614c6")}catch{}})();(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]="524ade8e-33d6-5353-b01d-c7baddc956e8")}catch{}})();(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]="02e10fe1-c111-5c09-8dbe-a67f2b97f0d0")}catch{}})();(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]="3d4a8db3-8a53-50b4-a96c-1affff2207a3")}catch{}})();(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]="d008ca8f-41bf-54fb-9b56-bc1d4af9f226")}catch{}})();(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]="de197522-9007-5e21-8f9c-06cbf63707d1")}catch{}})();(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]="a5e0162a-bbf1-50fe-8912-a820de155e90")}catch{}})();(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]="9ee008b9-3751-5794-8d01-1f6d3123d6cd")}catch{}})();(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]="b6fa277d-ccf2-5413-95d5-0790283203d5")}catch{}})();(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]="2d59e10e-c85b-542a-8859-b20a08e809fa")}catch{}})();var ce=(e,t)=>N(e,t,{runUpdate:(a,n,o)=>J(a,n,o)});(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]="3952425a-adce-59dd-84b6-97ac571eaa73")}catch{}})();async function Ae(e,t,a,n,o){let r=c(o),s=e==="run",p=e==="verdicts",w=e==="presets"||e==="apply",k=e==="promote",h=await U({action:e,...s||p||w||k?{}:{kind:t},id:s||p||k?a??t:a,preset:w?a??t:void 0,definition:i(n,"definition"),trigger:i(n,"trigger"),tree:i(n,"tree"),gate:i(n,"gate"),limit:i(n,"limit"),dry_run:n.dryRun===!0,fullChangedFields:r.fullChangedFields,idOnly:r.idOnly,author:i(n,"author"),message:i(n,"message"),owner:i(n,"owner"),apply:n.apply===!0,enforcement:i(n,"enforcement")},r);l(h,r),typeof h=="object"&&h!==null&&"exit_code"in h&&h.exit_code===1&&(process.exitCode=1)}function de(e){e.command("assurance").argument("<action>","Action; inspect `pm contracts --command assurance`").argument("[kind]","Declaration kind or run gate id").argument("[id]","Declaration/gate id").description("Manage SDK-owned assurance contracts.").option("--definition <json>","Put declaration JSON").option("--trigger <value>","Gate trigger").option("--tree <value>","Revision identity").option("--gate <id>","Verdict gate filter").option("--limit <number>","Verdict limit").option("--dry-run","Evaluate without recording").option("--author <value>","Mutation author").option("--message <value>","Mutation rationale").option("--owner <item-id>","Preset/derivation owner").option("--apply","Persist derived proposals").option("--enforcement <level>","Promote to warn or block").action(Ae)}(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]="a623e4b3-0b19-53e5-9953-df71495e8d2c")}catch{}})();function _e(e,t){let a=e?.trim().toLowerCase(),n=t?.trim().toLowerCase();if(a===void 0||a.length===0)return n;if(a==="local-analytics")return n&&n.length>0?n:"status";if(n!==void 0&&n.length>0)throw _({command_path:"telemetry",token:`${e} ${t}`,allowed:["status","flush","stats","clear","local-analytics"],token_kind:"path",examples:["pm telemetry stats --limit 10","pm telemetry local-analytics status --json"]});return a}function Ie(e){return{addValues:Array.isArray(e.add)?e.add:[],addJsonValues:Array.isArray(e.addJson)?e.addJson:[],removeValues:Array.isArray(e.remove)?e.remove:[],removeIndexValues:Array.isArray(e.removeIndex)?e.removeIndex:[]}}function fe(e,t){if(e.background===!0){if(e.run!==!0)throw new m("--background requires --run",d.USAGE);if(e.acknowledgeLinkedTests===!0)throw new m("--background cannot be combined with --acknowledge-linked-tests; acknowledgement is a non-executing foreground operation",d.USAGE);if(e.update!==void 0||e.updateIndex!==void 0||e.setJson!==void 0||t.addValues.length>0||t.addJsonValues.length>0||t.removeValues.length>0||t.removeIndexValues.length>0)throw new m("--background does not support --add/--add-json/--remove/--remove-index or metadata edits; update linked tests first, then run in background",d.USAGE)}}async function Ce(e,t,a,n){let o=await C({kind:"test",commandArgs:O(e,{...t,add:n.addValues,addJson:n.addJsonValues,remove:n.removeValues,removeIndex:n.removeIndexValues}),targetId:e,author:typeof t.author=="string"?t.author:void 0,noExtensions:a.noExtensions===!0},a);l(o,a)}function De(e){return{update:typeof e.update=="string"?e.update:void 0,updateIndex:typeof e.updateIndex=="string"||typeof e.updateIndex=="number"?e.updateIndex:void 0,setJson:typeof e.setJson=="string"?e.setJson:void 0}}function D(e,t){return{add:t.addValues,addJson:t.addJsonValues,remove:t.removeValues,removeIndex:t.removeIndexValues,...De(e),list:!!e.list,run:!!e.run,match:typeof e.match=="string"?e.match:void 0,onlyIndex:typeof e.onlyIndex=="string"||typeof e.onlyIndex=="number"?e.onlyIndex:void 0,onlyLast:!!e.onlyLast,timeout:typeof e.timeout=="string"?e.timeout:void 0,progress:!!e.progress,envSet:Array.isArray(e.envSet)?e.envSet:[],envClear:Array.isArray(e.envClear)?e.envClear:[],sharedHostSafe:!!e.sharedHostSafe,pmContext:typeof e.pmContext=="string"?e.pmContext:void 0,overrideLinkedPmContext:!!e.overrideLinkedPmContext,workspaceContext:typeof e.workspaceContext=="string"?e.workspaceContext:void 0,overrideLinkedWorkspaceContext:!!e.overrideLinkedWorkspaceContext,allowUntrustedLinkedTests:!!e.allowUntrustedLinkedTests,acknowledgeLinkedTests:!!e.acknowledgeLinkedTests,failOnContextMismatch:!!e.failOnContextMismatch,failOnSkipped:!!e.failOnSkipped,failOnEmptyTestRun:!!e.failOnEmptyTestRun,requireAssertionsForPm:!!e.requireAssertionsForPm,checkContext:!!e.checkContext,autoPmContext:!!e.autoPmContext,author:typeof e.author=="string"?e.author:void 0,message:typeof e.message=="string"?e.message:void 0,force:!!e.force,measure:Array.isArray(e.measure)?e.measure:[],metricBelow:typeof e.metricBelow=="string"?e.metricBelow:void 0,metricDiff:typeof e.metricDiff=="string"?e.metricDiff:void 0}}var Nt={buildRunTestOptions:D,buildRunTestAllOptions:pe,runWorkspacePositionAction:ye,validateBackgroundTestOptions:fe};async function Se(e,t,a,n){let o=await oe(e,D(t,n),a);(t.update!==void 0||t.updateIndex!==void 0||t.setJson!==void 0||n.addValues.length>0||n.addJsonValues.length>0||n.removeValues.length>0||t.run===!0||n.removeIndexValues.length>0)&&await y(a,o),l(o,a),(o.run_results.some(r=>r.status==="failed"||r.status==="refused")||o.fail_on_skipped_triggered===!0)&&(process.exitCode=d.DEPENDENCY_FAILED)}async function Te(e,t,a){let n=c(a),o=Date.now(),r=Ie(t);t.background===!0&&ne(e,D(t,r),n,v(process.cwd(),n.path),!0),fe(t,r),t.background===!0?await Ce(e,t,n,r):await Se(e,t,n,r),n.profile&&u(`profile:command=test took_ms=${Date.now()-o}`)}function b(e){let t=i(e,"author"),a=i(e,"assignee");if(t!==void 0&&a!==void 0&&t!==a)throw new m("Lifecycle ownership received conflicting --author and --assignee values; use one actor value for both aliases.",d.USAGE,{code:"conflicting_lifecycle_owner",examples:["pm claim pm-123","pm claim pm-123 --start","pm release pm-123"]});return{author:t??a,message:i(e,"message")}}async function Ee(e,t){let a=c(t),n=Date.now();if(e.background===!0){let r=await C({kind:"test-all",commandArgs:P(e),statusFilter:i(e,"status"),noExtensions:a.noExtensions===!0},a);l(r,a),a.profile&&u(`profile:command=test-all took_ms=${Date.now()-n}`);return}let o=await re(pe(e),a);await y(a,{ids:o.results.map(r=>r.id)}),l(o,a),(o.failed>0||o.fail_on_skipped_triggered===!0)&&(process.exitCode=d.DEPENDENCY_FAILED),a.profile&&u(`profile:command=test-all took_ms=${Date.now()-n}`)}function pe(e){return{status:i(e,"status"),limit:i(e,"limit"),offset:i(e,"offset"),timeout:i(e,"timeout"),progress:!!e.progress,envSet:Array.isArray(e.envSet)?e.envSet:[],envClear:Array.isArray(e.envClear)?e.envClear:[],sharedHostSafe:!!e.sharedHostSafe,pmContext:i(e,"pmContext"),overrideLinkedPmContext:!!e.overrideLinkedPmContext,workspaceContext:i(e,"workspaceContext"),overrideLinkedWorkspaceContext:!!e.overrideLinkedWorkspaceContext,allowUntrustedLinkedTests:!!e.allowUntrustedLinkedTests,failOnContextMismatch:!!e.failOnContextMismatch,failOnSkipped:!!e.failOnSkipped,failOnEmptyTestRun:!!e.failOnEmptyTestRun,requireAssertionsForPm:!!e.requireAssertionsForPm,checkContext:!!e.checkContext,autoPmContext:!!e.autoPmContext}}async function Re(e,t,a,n){let o=c(n),r=Date.now(),s=await ae({subcommand:_e(e,t),limit:i(a,"limit")},o);l(s,o),o.profile&&u(`profile:command=telemetry took_ms=${Date.now()-r}`)}async function Oe(e,t){let a=c(t),n=Date.now(),o=le(i(e,"analytics")),r=await te(a,{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:i(e,"tagPrefix"),fieldUtilization:e.fieldUtilization===!0,...o});r.recorded_observations?.some(s=>s.changed)===!0&&await y(a,{ids:r.recorded_observations?.flatMap(s=>s.observation.item_id?[s.observation.item_id]:[])}),l(r,a),a.profile&&u(`profile:command=stats took_ms=${Date.now()-n}`)}async function Pe(e,t){let a=c(t),n=Date.now(),o=i(e,"threshold"),r=i(e,"limit"),s=await F(a,{...e.exhaustive===!0?{exhaustive:!0}:{},status:Array.isArray(e.status)&&e.status.length>0?e.status:void 0,since:i(e,"since"),...o===void 0?{}:{threshold:Number(o)},...r===void 0?{}:{limit:Number(r)}});l(s,a),a.profile&&u(`profile:command=duplicates took_ms=${Date.now()-n}`)}async function Le(e,t){let a=c(t),n=Date.now(),o=!!e.strictExit||!!e.failOnWarn,r=await V(a,{strictExit:o,strictDirectories:!!e.strictDirectories,requireMergeDrivers:!!e.requireMergeDrivers,checkOnly:!!e.checkOnly,checkTelemetry:!!e.checkTelemetry,noRefresh:!!e.noRefresh,refreshVectors:!!e.refreshVectors,verboseStaleItems:!!e.verboseStaleItems,verboseAuthorEvents:!!e.verboseAuthorEvents,brief:!!e.brief,summary:!!e.summary||o,skipVectors:!!e.skipVectors,skipIntegrity:!!e.skipIntegrity,skipDrift:!!e.skipDrift,full:!!e.full});l(r,a),o&&!r.ok&&(x({...r,exit_code:d.GENERIC_FAILURE,error_code:"health_findings",error_category:"validation",command_resolution:"health_findings",resolution_stage:"execute"}),process.exitCode=d.GENERIC_FAILURE),a.profile&&u(`profile:command=health took_ms=${Date.now()-n}`)}async function Me(e,t){let a=c(t),n=Date.now(),o=await ce({checkMetadata:!!e.checkMetadata,metadataProfile:i(e,"metadataProfile"),checkResolution:!!e.checkResolution,checkCompleteness:!!e.checkCompleteness,checkLifecycle:!!e.checkLifecycle,checkStaleBlockers:!!e.checkStaleBlockers,dependencyCycleSeverity:i(e,"dependencyCycleSeverity"),parentCycleSeverity:i(e,"parentCycleSeverity"),checkFiles:!!e.checkFiles,checkCommandReferences:!!e.checkCommandReferences,scanMode:i(e,"scanMode"),includePmInternals:!!e.includePmInternals,verboseFileLists:!!e.verboseFileLists,verboseDiagnostics:!!e.verboseDiagnostics,allAffectedIds:!!e.allAffectedIds,checkHistoryDrift:!!e.checkHistoryDrift,checkStorageIntegrity:!!e.checkStorageIntegrity,fixHints:!!e.fixHints,autoFix:!!e.autoFix,dryRun:!!e.dryRun,fixScope:Array.isArray(e.fixScope)?e.fixScope:void 0,pruneMissing:!!e.pruneMissing,counts:!!e.counts,full:!!e.full},a);l(o,a),(e.strictExit||e.failOnWarn)&&(o.has_warnings||!o.ok)&&(x({...o,exit_code:d.GENERIC_FAILURE,error_code:"validation_findings",error_category:"validation",command_resolution:"validation_findings",resolution_stage:"execute"}),process.exitCode=d.GENERIC_FAILURE),a.profile&&u(`profile:command=validate took_ms=${Date.now()-n}`)}async function Fe(e,t){let a=c(t),n=Date.now(),o=await q(a,{dryRun:e.dryRun===!0,scope:Array.isArray(e.scope)?e.scope:[]});l(o,a),a.profile&&u(`profile:command=gc took_ms=${Date.now()-n}`)}async function Ve(e,t,a,n){let o=c(n),r=v(process.cwd(),o.path),s=e.trim().toLowerCase();if(!I.some(p=>p===s))throw _({command_path:"workspace snapshot",token:e,allowed:I,display_name:"workspace snapshot",token_kind:"action",examples:["pm workspace snapshot create before-migration","pm workspace snapshot restore before-migration"]});if(s==="list"){l(await K(r),o);return}if(s==="create"){l(await z(r,t===void 0?{}:{name:t}),o);return}if(t===void 0)throw new m(`pm workspace snapshot ${s} requires a snapshot name or fingerprint`,d.USAGE);if(s==="inspect"){l(await Y(r,t),o);return}if(s==="restore"){if(a.dryRun===!0){l(await X(r,t),o);return}let p=await A(r);l(await Q(r,t,{force:a.force===!0,author:R(i(a,"author"),p.author_default),message:i(a,"message"),lockTtlSeconds:p.locks.ttl_seconds,lockWaitMs:p.locks.wait_ms}),o);return}l(await Z(r,t),o)}async function ye(e,t){let a=c(t);l(await ee(a),a)}async function Ne(e,t){let a=c(t),n=Date.now(),o=await M({action:i(e,"action"),command:i(e,"command"),summary:!!e.summary,schemaOnly:!!e.schemaOnly,flagsOnly:!!e.flagsOnly,availabilityOnly:!!e.availabilityOnly,runtimeOnly:!!e.runtimeOnly||!!e.activeOnly,full:!!e.full},a);l(o,a),a.profile&&u(`profile:command=contracts took_ms=${Date.now()-n}`)}async function Ue(e,t,a){if(t.start===!0){ue(e,!1),await ge(e,t,a);return}let n=c(a),o=Date.now(),r={...b(t),ifAvailable:t.ifAvailable===!0,maxAttempts:t.maxAttempts};ue(e,t.next===!0);let s=t.next===!0?await G(!!t.force,n,r,{type:typeof t.type=="string"?t.type:void 0,tag:typeof t.tag=="string"?t.tag:void 0,priority:t.priority,assigneeFilter:typeof t.assigneeFilter=="string"?t.assigneeFilter:void 0,parent:typeof t.parent=="string"?t.parent:void 0,sprint:typeof t.sprint=="string"?t.sprint:void 0,release:typeof t.release=="string"?t.release:void 0,includeDecisions:t.includeDecisions===!0,includeGates:t.includeGates===!0,includeContainers:t.includeContainers===!0,tokenBudget:t.tokenBudget??t.token_budget,explainRanking:t.explainRanking===!0||t.explain_ranking===!0}):await $(e,!!t.force,n,r);await y(n,s),l(s,n),n.profile&&u(`profile:command=claim took_ms=${Date.now()-o}`)}function ue(e,t){if(!t&&!e)throw new m("Specify an item id or pass --next",d.USAGE);if(t&&e)throw new m("Specify either an item id or --next, not both",d.USAGE)}async function qe(e,t,a){if(t.pause===!0){await he(e,t,a);return}let n=c(a),o=Date.now(),r=await H(e,!!t.force,n,{...b(t),ownershipReleaseBypass:t.ownershipReleaseBypass===!0,handoff:t.handoff});await y(n,r),l(await L("release",[e],t,n,r),n),n.profile&&u(`profile:command=release took_ms=${Date.now()-o}`)}async function S(e){let t=c(e),a=T(e.name());!a||t.json||t.quiet||(await A(v(process.cwd(),t.path))).ux?.deprecation_hints&&u(E(a))}async function ge(e,t,a){await S(a);let n=c(a),o=Date.now(),r=await W(e,{...b(t),force:!!t.force,next:t.next===!0,ifAvailable:t.ifAvailable===!0},n);await y(n,r.update),l(r,n),n.profile&&u(`profile:command=start-task took_ms=${Date.now()-o}`)}async function he(e,t,a){await S(a);let n=c(a),o=Date.now(),r=await j(e,{...b(t),handoff:i(t,"handoff"),force:!!t.force},n);await y(n,r.release),l(r,n),n.profile&&u(`profile:command=pause-task took_ms=${Date.now()-o}`)}async function Je(e,t,a,n){await S(n);let o=c(n),r=Date.now(),s=await B(e,t,{...b(a),validateClose:i(a,"validateClose"),force:!!a.force},o);await y(o,s.release),l(s,o),o.profile&&u(`profile:command=close-task took_ms=${Date.now()-r}`)}function me(e){return e.option("--background","Run linked tests in managed background mode").option("--timeout <seconds>","Default run timeout in seconds (requires --run)").option("--progress","Emit stderr run progress (requires --run; automatic in TTY)").option("--env-set <value>","Set run environment (KEY=VALUE, repeatable)",f).option("--env-clear <value>","Clear run environment (NAME, repeatable)",f).option("--shared-host-safe","Apply additive shared-host-safe run defaults").option("--pm-context <mode>","PM test context: schema|tracker|auto|none (default: schema)").option("--override-linked-pm-context","Override stored context with --pm-context").option("--workspace-context <mode>","Source-workspace mode: source|isolated|snapshot (default: source)").option("--override-linked-workspace-context","Override stored context with --workspace-context").option("--allow-untrusted-linked-tests","Execute untrusted linked commands when project policy also permits it").option("--fail-on-context-mismatch","Fail linked PM commands when context item counts differ").option("--fail-on-skipped","Treat skipped linked tests as dependency failures").option("--fail-on-empty-test-run","Fail successful commands reporting zero executed tests").option("--require-assertions-for-pm","Require assertion metadata for linked PM command tests").option("--check-context","Check PM context before execution").option("--auto-pm-context","Route mismatched PM tracker reads through tracker context")}function Ut(e){de(e);let t=e.command("test").argument("<id>","Item id").option("--add <value>","Add verified isolated test (CSV/markdown or stdin)",f).option("--add-json <value>","Add verified isolated test (JSON object/array or stdin)",f).option("--remove <value>","Remove exact command/path (command=<value>, path=<value>, or stdin -)",f).option("--remove-index <n>","Remove 1-based --list position (repeatable)",f).option("--list","List linked tests without mutating").option("--update <value>","Edit exact command or path=<value>").option("--update-index <n>","Edit current 1-based --list position").option("--set-json <value>","Metadata patch; null clears optional fields").option("--run","Run linked test commands").option("--match <value>","Run matching command/path substring").option("--only-index <n>","Run 1-based --list position").option("--only-last","Run most recently added test");t.option("--acknowledge-linked-tests","Trust current commands in this clone without execution"),me(t).option("--measure <value>","Record name=value[,unit=...][,threshold=...]; requires --run",f).option("--metric-below <value>","Return evidence below name=value").option("--metric-diff <name>","Diff the latest two values").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership override").description("Manage tests linked to an item and optionally run them.").action(Te);let a=e.command("test-all").description("Run linked tests across matching items.").option("--status <value>","Filter items by status before running tests").option("--limit <n>","Limit matching items before running linked tests").option("--offset <n>","Skip matching items before running linked tests");me(a).action(Ee),e.command("test-runs-worker",{hidden:!0}).argument("<runId>","Background run id").description("Internal background worker command.").action(async(k,h,be)=>{let we=c(be);await ie(k,we)}),e.command("telemetry").argument("[namespace-or-subcommand]","Telemetry subcommand: status, flush, stats, clear (default: status)").argument("[subcommand]","Compatibility alias target for local-analytics: status, flush, stats, clear").option("--limit <n>","Maximum command groups returned by telemetry stats").description("Inspect and manage local telemetry queue/runtime state.").action(Re),e.command("duplicates").description("Find duplicate clusters across all statuses.").option("--status <value>","Statuses (repeatable or comma-separated)",f,[]).option("--since <value>","Created at or after this time").option("--threshold <value>","Minimum similarity (0-1)").option("--limit <n>","Maximum clusters").option("--exhaustive","Score all pairs within the safety bound").action(Pe),e.command("stats").description("Show project tracker statistics.").option("--include-empty","Restore zero-count registered item-type and lifecycle-status buckets").option("--storage","Include aggregate history-stream storage metrics (total streams/lines/bytes, largest + deepest streams, oldest/newest entries)").option("--metadata-coverage","Include metadata coverage % (acceptance_criteria, estimated_minutes, resolution, tags, parent) overall and by type").option("--by-assignee","Include a lifecycle-bucketed item breakdown grouped by assignee").option("--by-tag","Include a lifecycle-bucketed item breakdown grouped by tag").option("--by-priority","Include a lifecycle-bucketed item breakdown grouped by priority").option("--tag-prefix <value>","With --by-tag: only count tags starting with this prefix (e.g. domain:)").option("--field-utilization","Report content-field utilization rates (notes/learnings/files/docs/tests/comments/deps/body) for governance analysis").option("--analytics <json>","Improvement ledger/history analytics JSON").action(Oe),e.command("health").description("Show project tracker health checks.").option("--strict-directories","Treat optional item-type directories as required failures").option("--require-merge-drivers","Treat absent clone-local merge drivers as a required health failure").option("--check-only","Run read-only health diagnostics without refreshing vectors").option("--check-telemetry","Probe telemetry endpoint health and include network diagnostics").option("--no-refresh","Disable automatic vector refresh attempts during health checks").option("--refresh-vectors","Explicitly enable vector refresh attempts during health checks").option("--verbose-stale-items","Include full stale vectorization ID lists in health output").option("--verbose-author-events","Include every actionable unknown-author event coordinate for review or disposition").option("--brief","Emit compact health details for low-token agent checks").option("--summary","Emit one-line-style health status with check names and warning count").option("--skip-vectors","Skip vectorization check for a faster run").option("--skip-integrity","Skip item/history file integrity check for a faster run").option("--skip-drift","Skip history drift hash check for a faster run").option("--full","Run all checks including slow integrity, drift, and vectorization checks").option("--strict-exit","Return non-zero exit when health is not ok and default to actionable summary output; use --full for complete details").option("--fail-on-warn","Alias for --strict-exit").action(Le),e.command("validate").description("Validate metadata, lifecycle policies, files, command references, and history.").option("--check-metadata","Run metadata completeness checks").option("--metadata-profile <value>","Metadata profile (core|strict|custom)").option("--check-resolution","Run closed-item resolution metadata checks").option("--check-completeness","Check declarative lifecycle field requirements").option("--check-lifecycle","Run active-item lifecycle governance drift checks").option("--check-stale-blockers","Include stale blocker-pattern diagnostics in lifecycle checks").option("--dependency-cycle-severity <value>","Set dependency-cycle warning policy for lifecycle checks (off|warn|error)").option("--parent-cycle-severity <value>","Set parent-hierarchy cycle warning policy for lifecycle checks (off|warn|error)").option("--check-files","Run linked-file and orphaned-file checks").option("--check-command-references","Run linked-command PM-ID reference checks").option("--scan-mode <value>","Select file candidate scan mode for --check-files (default|tracked-all|tracked-all-strict)").option("--include-pm-internals","Include PM storage internals in tracked-all candidate scans").option("--verbose-file-lists","Include full file-path lists for validate --check-files details").option("--verbose-diagnostics","Include full diagnostic ID lists").option("--all-affected-ids","Emit complete missing_* affected-ID lists with no truncation (implied by --json)").option("--strict-exit","Return non-zero exit when validation warnings are present").option("--fail-on-warn","Alias for --strict-exit").option("--fix-hints","Add a machine-executable fix_hints[] of pm commands to each failing check's details").option("--auto-fix","Apply safe, deterministic field backfills").option("--dry-run","Preview planned --auto-fix/--prune-missing fixes without applying them").option("--fix-scope <scope>","Grant --auto-fix scopes (metadata, resolution, estimates, timestamps, lifecycle; comma-separated or repeatable). Default: metadata, resolution; other scopes require explicit opt-in",f).option("--prune-missing","Remove deleted-path file/doc links; preserves real files").option("--check-history-drift","Run item/history hash drift checks").option("--check-storage-integrity","Run the post-merge storage-integrity check (unreadable items, history conflict markers, resurrected deletes, unparseable config/schema)").option("--counts","Keep validation counts and totals while omitting per-item diagnostic arrays").option("--full","Return the complete validation diagnostic projection").action(Me),e.command("gc").option("--dry-run","Preview cleanup targets without deleting files; without this flag, pm gc deletes matched artifacts").option("--scope <value>","Limit cleanup to one or more scopes (comma-separated or repeatable): index, embeddings, runtime, locks, checkpoints, transactions",f).description("Delete optional cache artifacts by default (including expired lock debris) and show a summary.").action(Fe);let n=e.command("workspace").description("Inspect workspace state and snapshots.");n.command("position").description("Show merge and history readiness.").action(ye),n.command("snapshot").argument("<action>","Action: create, list, inspect, restore, delete").argument("[target]","Optional name for create; name or fingerprint otherwise").description("Manage content-addressed tracker snapshots.").option("--dry-run","Preview restore file, item, stream, and history-entry impact without mutating state").option("--force","Explicitly confirm a whole-workspace snapshot restore").option("--author <value>","Actor recorded on the restore audit event").option("--message <value>","Human-readable restore rationale").action(Ve),e.command("contracts").description("Show machine-readable command and schema contracts for agents.").option("--action <value>","Filter tool schema branches to a specific action").option("--command <value>","Scope contracts output to one CLI command (narrow-by-default)").option("--summary","Return one command+intent row per top-level command for cheap agent bootstrap").option("--schema-only","Return schema-focused output only").option("--flags-only","Return command flag contracts only").option("--availability-only","Return action availability surface only").option("--runtime-only","Include only actions invocable in the current runtime").option("--active-only","Alias for --runtime-only").option("--full","Include full schema and command-flag surfaces (large; default brief output omits heavy sections for unfiltered queries)").action(Ne);let o=e.command("claim").option("--start","Claim and start an explicit item").argument("[id]","Item id (omit with --next)").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force claim override").option("--if-available","Skip another author's claim (skipped=true)").option("--next","Atomically claim the next caller-available actionable item").option("--type <value>","Filter --next candidates by type").option("--tag <value>","Filter --next candidates by tag").option("--priority <value>","Filter --next candidates by priority").option("--assignee-filter <value>","Filter --next candidates: assigned|unassigned").option("--parent <id>","Scope --next candidates to a subtree").option("--sprint <value>","Filter --next candidates by sprint").option("--release <value>","Filter --next candidates by release").option("--max-attempts <n>","Bound the --next candidate walk (default 10; maximum 100)").option("--include-decisions","Allow --next to claim human-gated Decision items").option("--include-gates","Allow --next to claim outcome gates").option("--include-containers","Allow --next to claim containers with unfinished descendants").option("--token-budget <n>","Bound the estimated tokens used to rank --next candidates").option("--explain-ranking","Include ranking provenance for --next selection").description("Claim an item for active work.").action(Ue);g(o,"--assignee <value>","Alias for --author on lifecycle ownership commands"),g(o,"--token_budget <n>","Alias for --token-budget"),g(o,"--explain_ranking","Alias for --explain-ranking");let r=e.command("release").option("--pause","Use open status").option("--handoff <status>","Needs --message").argument("<id>","Item id").option("--author <value>","Author").option("--message <value>","Message").option("--force","Override ownership").description("Release ownership.").action(qe);g(r,"--assignee <value>","Alias for --author on lifecycle ownership commands");let s=e.command("start-task",{hidden:!0}).argument("<id>","Item id").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership or terminal override when required").description("Lifecycle alias: claim an item and move it to in_progress.").action(ge);g(s,"--assignee <value>","Alias for --author on lifecycle ownership commands");let p=e.command("pause-task",{hidden:!0}).argument("<id>","Item id").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership override when required").description("Lifecycle alias: move an item to open and release its claim.").action(he);g(p,"--assignee <value>","Alias for --author on lifecycle ownership commands");let w=e.command("close-task",{hidden:!0}).argument("<id>","Item id").argument("[reason]","Close reason text").option("--author <value>","Mutation author").option("--message <value>","History message").option("--validate-close <value>","Close-time validation mode: off|warn|strict").option("--force","Force ownership or terminal override when required").description("Lifecycle alias: close an item and release assignment metadata.").action(Je);g(w,"--assignee <value>","Alias for --author on lifecycle ownership commands")}export{Nt as _testOnlyRegisterOperations,Ut as registerOperationCommands,ue as requireClaimTarget};
2
- //# sourceMappingURL=register-operations-Z4VET3I7.js.map
@@ -1,2 +0,0 @@
1
- import{i as w}from"./chunk-ZEI3DC5E.js";import"./chunk-IB7UB5TE.js";import{xa as h}from"./chunk-F76ZUP73.js";import{d as u}from"./chunk-ZDVTXLA6.js";import{b as g}from"./chunk-VS565KBX.js";import{A as m,C as f}from"./chunk-R7KWBFM2.js";import"./chunk-XAWE4EAK.js";import{execFile as y}from"node:child_process";import{realpath as v}from"node:fs/promises";import l from"node:path";import{promisify as _}from"node:util";(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]="fe5937fc-def3-5ed4-9663-70a6e9d258a1")}catch{}})();var b=_(y);function c(e){return new f(`Automatic merge settlement refused: ${e}`,m.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"},nextSteps:["Inspect receipts, repair streams and Git changes. Resolve competing values or unrelated drift explicitly, then run pm merge reconcile and stage the reviewed artifacts manually."]})}async function x(e){let t=process.env.GIT_INDEX_FILE;if(t===void 0)return;let s=(await e(["rev-parse","--path-format=absolute","--git-path","index"])).stdout.trim();if(l.resolve(t)!==l.resolve(s))throw c("an alternate Git index requires explicit manual settlement")}async function R(e,t){if(t.length===0)return[];let s=t.map(a=>`:(literal)${a}`),o=new Set((await e(["ls-files","--cached","-z","--",...s])).stdout.split("\0")),r=t.filter(a=>!o.has(a)).map(a=>`:(literal)${a}`);if(r.length>0&&(await e(["diff","--cached","--name-only","--diff-filter=D","-z","--",...r])).stdout.length>0)throw c("a receipt has a staged deletion that requires explicit review");return r}async function k(e){let{git:t,preview:s,paths:o,newReceiptPathspecs:r}=e,a=!1;try{r.length>0&&(await t(["add","--",...r]),a=!0);let n=await e.apply();if(!n.ok||JSON.stringify(n.receipts.summaries)!==JSON.stringify(s.receipts.summaries)||n.repair.streams.some(p=>!s.repair.streams.some(d=>d.id===p.id)))throw c("reconciliation changed or did not finish; inspect the audit artifacts before staging");return o.length>0&&await t(["add","--",...o.map(p=>`:(literal)${p}`)]),{...n,staged_paths:o,guidance:["Lossless reconciliation artifacts are staged for the merge commit. Review git diff --cached before committing."]}}catch(n){throw a&&await t(["reset","--quiet","--",...r]),n}}function G(e){if(e.repair.totals.failed>0||e.receipts.missing_history_references_after>0||e.receipts.summaries.some(t=>t.conflict_fields.length>0)||e.repair.streams.some(t=>t.merge_receipt_proof?.trusted!==!0)||e.validation.checks.some(t=>t.name!=="history_drift"&&t.status!=="ok"))throw c("only fully authenticated receipt-backed repairs without discarded values can be staged")}async function I(e){try{return{...e,path:await v(h(process.cwd(),e.path))}}catch{throw c("the tracker root cannot be resolved")}}async function N(e){let{preview:t}=e;G(t);let{path:s}=await I(e.global),o=await w(s);if(o===null)throw c("a Git workspace is required");let r=i=>b("git",i,{cwd:o,env:g(),timeout:1e4});if(await x(r),(await r(["ls-files","--unmerged","-z"])).stdout.length>0)throw c("Git still has unresolved paths");let a=[...new Set([...[...new Set([...t.repair.streams.map(i=>i.id),...t.receipts.summaries.map(i=>i.item_id)])].map(i=>l.join(s,"history",`${i}.jsonl`)),...t.receipts.summaries.map(i=>l.join(s,"merge-receipts",`${i.receipt_id}.json`))])].map(i=>l.relative(o,i).replaceAll("\\","/"));if(a.some(u))throw c("reconciliation artifacts must belong to this Git workspace");let n=a.map(i=>`:(literal)${i}`),p=t.receipts.summaries.map(i=>l.relative(o,l.join(s,"merge-receipts",`${i.receipt_id}.json`)).replaceAll("\\","/"));if(n.length>0)try{await r(["diff","--quiet","--",...n])}catch{throw c("reconciliation paths have unstaged edits or Git cannot verify their index state")}let d=await R(r,p);return e.dryRun?{...t,staged_paths:[]}:k({...e,git:r,paths:a,newReceiptPathspecs:d})}export{I as resolveMergeSettlementGlobal,N as stageLosslessMergeReconciliation};
2
- //# sourceMappingURL=stage-FW5OXCCR.js.map
@@ -1,8 +0,0 @@
1
- import{b as K}from"./chunk-R536272H.js";import{Wa as H,_a as P,aa as W,ab as L,db as V}from"./chunk-P7DPS5M4.js";import{Kd as $,Z as G,qa as B,wa as E,wd as U}from"./chunk-OMXMYTEX.js";import{a as X,b as v,c as q}from"./chunk-FOA7XKWP.js";import{B as S,D as j,E as N,H as F,y as b,z as k}from"./chunk-BUZ2Z4P3.js";import{access as le,readFile as A,realpath as w}from"node:fs/promises";import{constants as me}from"node:fs";import{execFile as ue}from"node:child_process";import c from"node:path";import{promisify as de}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new e.Error().stack;r&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[r]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();var se="PM_SOURCE_CONTEXT_ACCESS",ce="PM_ALLOW_SOURCE_CONTEXT_WRITES";function J(e){let r=e[se],i=r===void 0||r.trim().toLowerCase()==="write"?"write":"read_only",t=i==="read_only"&&e[ce]?.trim()==="1";return{access:i,write_override_applied:t,source_writes_allowed:i==="write"||t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new e.Error().stack;r&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[r]="b1828465-0619-514c-8956-2a81dea9efbc")}catch{}})();var _=de(ue),T="# pm-cli:merge-drivers:start",pe="# pm-cli:merge-drivers:end",x="# pm-cli:merge-drivers:v2:start",Q="# pm-cli:merge-drivers:v2:end",fe="merge-fence",ge="merge-attributes";function R(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function he(e,r){let i=await w(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(i))return;let{stdout:t}=await _(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()===r?i:void 0}async function we(){let e=G(import.meta.url,["../../.."]),r=process.execPath,i=!1,t=await w(process.execPath),o=process.versions.bun,a=(process.env.PATH??"").split(c.delimiter).filter(n=>c.isAbsolute(n)).map(n=>c.join(n,o===void 0?c.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),s=o===void 0?a:[process.env.npm_execpath??"",...a,t].filter(n=>c.isAbsolute(n)&&/^(?:bun|bun\.exe)$/iu.test(c.basename(n)));for(let n of s)try{if(await le(n,me.X_OK),o!==void 0){let p=await he(n,o);if(p!==void 0){r=p,i=!0;break}continue}if(n!==t&&await w(n)===t){r=n;break}}catch{}if(o!==void 0&&!i)throw new k("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",b.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${R(r)} ${R(c.join(e,"dist","cli.js"))}`}var Z=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function ye(e){let r=e.explicitPath?.trim(),i=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),t=e.environment.PM_SOURCE_PM_PATH?.trim(),o=J(e.environment),a=!!(i&&t),s=r===void 0&&a&&(e.dryRun||o.source_writes_allowed);if(r!==void 0){let n=E(e.cwd,r);return{pm_root:n,workspace_start:n,source_coordinates_available:a,source_context_selected:!1,source_policy:o}}return s?{pm_root:c.resolve(t),workspace_start:c.resolve(i),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:a?E(e.cwd,".agents/pm"):E(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:o}}async function ee(e){try{let{stdout:r}=await _("git",["rev-parse","--show-toplevel"],{cwd:e,env:v(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await w(r.trim())}catch{return null}}async function te(e){let r=await ee(e);if(r===null)throw new k("pm merge install requires a git repository (merge drivers are git configuration).",b.USAGE);return r}function O(e,r){return c.relative(e,r).split(c.sep).join("/")}function z(e){return e.replace(/[\\*?[\]!]/gu,"\\$&")}function h(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Y(e,r){if(e[r]!=="'")return null;let i="";for(let t=r+1;t<e.length;t+=1){if(e.startsWith(`'"'"'`,t)){i+="'",t+=4;continue}if(e[t]==="'")return{value:i,nextOffset:t+1};i+=e[t]}return null}async function ve(e,r,i){if(L(r).filter(o=>o.constraint==="exact").some(o=>o.version!==i))return!1;let t=await ee(e);if(t!==null&&t!==await w(r)){let o=await Promise.all([t,r].map(async a=>{let s=await _("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:v(),timeout:1e4});return w(s.stdout.trim())}));if(o[0]===o[1])return!1}return!0}async function _e(e,r,i){let t=Y(e,0);if(t===null||e[t.nextOffset]!==" ")return!1;let o=Y(e,t.nextOffset+1);if(o===null||e.slice(o.nextOffset)!==r||!/^(?:node|bun)(?:\.exe)?$/iu.test(c.basename(t.value))||c.basename(o.value)!=="cli.js"||c.basename(c.dirname(o.value))!=="dist"||!await S(t.value)||!await S(o.value))return!1;try{let a=c.dirname(c.dirname(o.value)),s=JSON.parse(await A(c.join(a,"package.json"),"utf8")),n=typeof s.bin=="string"?s.bin:s.bin?.pm;return await ve(a,i,s.version)?s.name==="@unbrained/pm-cli"&&n==="dist/cli.js":!1}catch{return!1}}function M(e,r){let i=e.length>0?`${z(e)}/`:"",t=[`${h(`${i}**/*.toon`)} merge=pm-item-toon`,`${h(`${i}**/*.md`)} merge=pm-item-markdown`];for(let o of r){let a=z(o);t.push(`${h(`${i}${a}/*.toon`)} merge=pm-item-toon`),t.push(`${h(`${i}${a}/*.md`)} merge=pm-item-markdown`)}return t.push(`${h(`${i}**/*.jsonl`)} merge=pm-relationship`),t.push(`${h(`${i}history/*.jsonl`)} merge=pm-history`),t.push(`${h(`${i}settings.json`)} merge=pm-json`),t.push(`${h(`${i}**/*.json`)} merge=pm-json`),t.push(`${h(`${i}extensions/**`)} merge=text`),t.push(`${h(`${i}extensions/.managed-extensions.json`)} merge=pm-json`),t}function re(e){let r=[],i=0;for(;i<e.length;){let t=e.indexOf(T,i),o=e.indexOf(x,i),a=t===-1?o:o===-1?t:Math.min(t,o);if(a===-1)break;let s=a===o,n=s?x:T,p=s?Q:pe,u=e.indexOf(p,a+n.length),m=u===-1?e.length:u+p.length;r.push({start:a,end:m,closed:u!==-1,lines:e.slice(a+n.length,u===-1?m:u).split(`
2
- `).map(l=>l.trim()).filter(Boolean)}),i=m}return r}function ie(e,r,i){let t=new Set(r),o=h(i.length>0?`${i}/`:"").slice(0,-1);return e.some(a=>t.has(a)||a.startsWith(o)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(a.slice(o.length)))}async function oe(e,r,i,t){let o=c.join(e,".gitattributes"),a=t?null:(await _("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:v(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),s=a===null?null:await $(a,ge,120,"merge-fence",!1,!0,5e3);try{let n=await N(o)??"",p=[x,...i,Q].join(`
3
- `),u=re(n),m=u.filter(d=>ie(d.lines,i,r));m.length===0&&r===".agents/pm"&&u.length===1&&u[0].lines.every(d=>!d.includes("/"))&&m.push(u[0]);let l;if(m.length>0){let d=m[0];l=n;for(let y of m.slice(1).reverse())l=`${l.slice(0,y.start)}${l.slice(y.end)}`;l=`${l.slice(0,d.start)}${p}${l.slice(d.end)}`}else{let d=n.trimEnd();l=`${d.length>0?`${d}
4
-
5
- `:""}${p}
6
- `}return l===n?{path:o,changed:!1}:(t||await F(o,l),{path:o,changed:!0})}finally{await s?.()}}function ne(e){let r=B(e,null);return[...new Set(Object.values(r.type_to_folder))].sort((i,t)=>i.localeCompare(t))}async function Ve(e,r){let i=c.resolve(e),t=null,o="",a=i;for(let g=0;g<8;g+=1){let ae=c.join(a,".gitattributes");try{let C=await A(ae,"utf8");if(C.includes(x)||C.includes(T)){t=a,o=C;break}}catch{}let D=c.dirname(a);if(D===a)break;a=D}if(t===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=c.join(t,".gitattributes"),n=O(t,i),p=re(o),u=M(n,r),m=p.filter(g=>ie(g.lines,u,n)),l=m.flatMap(g=>g.closed?g.lines:[]),d=new Set(l),y=new Set(u),f=u.filter(g=>!d.has(g)),I=l.filter(g=>!y.has(g));return{status:m.length!==1||!m[0].closed||f.length>0||I.length>0?"drift":"ok",path:s,missing_patterns:f,stale_patterns:I,schema_scope:"project"}}async function Ke(e){let r=[],i=[];for(let t of Z){let o=`merge.${t.key}.driver`,a=` merge driver ${t.artifact} "%O" "%A" "%B"${t.itemPath===void 0?"":` --item-path ${t.itemPath}`}`;try{let{stdout:s}=await _("git",["config","--get",o],{cwd:e,env:v(),encoding:"utf8",windowsHide:!0,timeout:1e4}),n=s.trim();await _e(n,a,e)||i.push(o)}catch{r.push(o)}}return{status:r.length>0?"missing":i.length>0?"drift":"ok",missing_keys:r,drifted_keys:i}}async function Xe(e){let r;try{r=await te(c.resolve(e))}catch{return{status:"no_git"}}let i=O(r,c.resolve(e)),t=await P(e),o=W(void 0,t.author_default),a=await $(e,fe,t.locks.ttl_seconds,o,!1,H(t).force_required_for_stale_lock,t.locks.wait_ms);try{let s=c.join(r,".gitattributes"),n;try{n=await A(s,"utf8")}catch(l){if(l instanceof Error&&"code"in l&&j(l))return{status:"not_installed",path:s};throw l}if(!n.includes(x)&&!n.includes(T))return{status:"not_installed",path:s};let p=await P(e),u=ne(p),m=await oe(r,i,M(i,u),!1);return{status:m.changed?"refreshed":"unchanged",path:m.path}}finally{await a()}}async function qe(e,r){let i=ye({cwd:process.cwd(),explicitPath:r.path,dryRun:e.dryRun===!0,environment:process.env}),t=i.pm_root;await V(t);let o=await te(i.workspace_start);return ke({pmRoot:t,workspaceRoot:o,dryRun:e.dryRun===!0,preCommitHook:e.preCommitHook===!0})}async function be(e,r){let i=(await _("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:v(),timeout:1e4})).stdout.trim(),t=await $(i,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{let o=await q(e),a;try{a=(await _("git",["config",o,"--null","--get-regexp","."],{cwd:e,env:v(),timeout:1e4})).stdout}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!==1)throw n;a=""}let s=new Map(a.split("\0").filter(Boolean).map(n=>{let p=n.indexOf(`
7
- `);return[n.slice(0,p),n.slice(p+1)]}));for(let n of r)s.get(n.key)!==n.value&&await X(e,[o,n.key,n.value])}finally{await t()}}async function ke(e){let r=c.resolve(e.pmRoot),i=c.resolve(e.workspaceRoot),t=e.dryRun===!0,o,a;try{[o,a]=await Promise.all([w(r),w(i)])}catch(f){throw new k(`Cannot resolve tracker root ${r} or workspace root ${i}: ${String(f)}`,b.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=O(a,o);if(K(s))throw new k(`Tracker root ${r} is outside the git repository ${i}; there is nothing to configure for this repository.`,b.USAGE);let n=await P(o),p=ne(n),u=M(s,p),m=[],l=await we(),d=e.preCommitHook===!0?await import("./settlement-hook-2VXEB6PP.js").then(async f=>({plan:await f.prepareMergeSettlementHook(a,`${l} --pm-path ${R(s||".")}`),write:f.writeMergeSettlementHook})):void 0;for(let f of Z)m.push({key:`merge.${f.key}.name`,value:f.name}),m.push({key:`merge.${f.key}.driver`,value:`${l} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!t)try{await be(a,m)}catch{throw new k(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,b.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let y=await oe(a,s,u,t);return d!==void 0&&!t&&await d.write(d.plan),{ok:!0,dry_run:t,workspace_root:a,pm_root:o,gitattributes:{path:y.path,changed:y.changed,patterns:u,schema_scope:"project"},git_config:m,...d===void 0?{}:{settlement_hook:{path:d.plan.path,changed:d.plan.changed}},guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:U()}}export{se as a,ce as b,ee as c,ne as d,Ve as e,Ke as f,Xe as g,qe as h,ke as i};
8
- //# sourceMappingURL=chunk-BM652VCB.js.map
@@ -1,91 +0,0 @@
1
- import{$ as _t,Ea as je,Ga as me,Oa as bt,Wa as Et,bb as It,ca as gt,cb as fe,ea as wt,m as Ae,n as yt,ua as Le,va as Pe,wa as K,x as ue,y as ht,z as q}from"./chunk-P7DPS5M4.js";import{b as se}from"./chunk-4MNUQCGR.js";import{h as pt}from"./chunk-YLVHHWHN.js";import{Aa as Re,Ba as Ne,Ca as R,Dc as G,Kd as mt,Ld as ft,Na as st,Ra as ct,Sa as dt,Ub as lt,a as ae,ic as Y,kc as ke,lc as de,ma as ot,mc as L,na as nt,nc as Oe,oc as le,pc as De,qa as rt,sc as Me,va as ce,vd as ut,wd as Fe,xa as at}from"./chunk-OMXMYTEX.js";import{A as it,B as X,D as A,H as O,s as F,x as tt,y as p,z as f}from"./chunk-BUZ2Z4P3.js";import ai from"node:crypto";import pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function Ct(e){let i=[],t=!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){t=i.length>0;continue}t&&(i.push("-"),t=!1),i.push(o)}return i.length===0?"pm-":`${i.join("")}-`}function V(e){let i=e.trim().toLowerCase();return i.startsWith("#")&&(i=i.slice(1)),i}function J(e,i){let t=Ct(i),o=V(e);return o.startsWith(t)?o:`${t}${o}`}function si(e){let i=ut(e);if(i!==void 0)return i;let t="";for(let o=0;o<e;o+=1)t+=ai.randomInt(0,36).toString(36);return t}async function ci(e,i,t){let o=[...new Set(Object.values(t))].flatMap(n=>[pe.join(e,n,`${i}.md`),pe.join(e,n,`${i}.toon`)]);return o.push(pe.join(e,"history",`${i}.jsonl`)),(await Promise.all(o.map(n=>X(n)))).some(Boolean)}var vt=4,Tt=12;function di(e){return typeof e!="number"||!Number.isFinite(e)?vt:Math.min(Tt,Math.max(vt,Math.trunc(e)))}async function Bo(e,i,t={}){let o=di(t.tokenLength),n=Math.min(o+6,Tt),r=0;for(;o<=n;){for(let a=0;a<32;a+=1){let s=`${Ct(i)}${si(o)}`;if(!await(t.probeExisting===!1?X(pe.join(e,"history",`${s}.jsonl`)):ci(e,s,t.typeToFolder??F)))return s;r+=1}o+=1}throw new Error(`Unable to generate unique id after ${r} attempts`)}import St from"node:fs/promises";import Q from"node:path";import{isUtf8 as li}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="7db1d069-0038-57f8-8c3e-0b0ba66579ca")}catch{}})();var ui=1048576,mi=4194304;async function xt(e,i){let t=Q.dirname(e);for(;t!==Q.parse(e).root;){let n=await St.stat(t).catch(r=>{if(A(r))return null;throw r});if(n!==null){if(!n.isDirectory())throw new f("Workflow policy storage ancestor must be a directory.",p.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}t=Q.dirname(t)}let o=await St.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(i,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||!li(r.subarray(0,a)))throw new f("Workflow policy input exceeds its byte bound or is not valid UTF-8.",p.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 fi(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let i;try{i=JSON.parse(e)}catch{throw new f("schema/policies.json must contain valid JSON.",p.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return st(i)}async function pi(e){return fi(await xt(Q.join(e,"schema","policies.json"),ui))}async function yi(e,i){let t=await xt(R(e,i),mi);if(t===null)return[];let o;try{if(o=t.split(/\r?\n/).filter(n=>n.trim()).map(n=>JSON.parse(n)),!me(o).ok)throw new Error("invalid chain")}catch{throw new f("Approval evidence requires a valid item history chain.",p.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${i} --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 hi(e,i,t){let o=t.before?.status!==t.after?.status&&i.policies.some(a=>a.rule.kind==="approval"&&ct(a,t)),n=t.before?.id??t.after?.id,r=o&&typeof n=="string"?await yi(e,n):[];return dt(i,{...t,approvals:r})}async function $e(e){let i=await pi(e.pmRoot),t=await hi(e.pmRoot,i,{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(t.allowed)return t;let o=t.decisions.filter(d=>!d.satisfied&&d.effect==="refuse");if(!e.dryRun)try{await bt({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:t.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}catch(d){let u=new f("Workflow policy refusal could not be recorded in workspace history.",p.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 u.cause=d,u}let n=o.slice(0,3).map(d=>({policy_id:d.policy_id,rule:d.rule,description:i.policies.find(u=>u.id===d.policy_id).description,missing_fields:d.missing_fields})),r=[...new Set(n.flatMap(d=>d.missing_fields))],a=n.map(d=>`${d.policy_id} (${d.rule})`).join(", "),s=o.length>3?` and ${o.length-3} more`:"",l=e.after?.metadata.id??e.before.metadata.id,c=r.map(d=>{if(e.before===null)return`Supply ${d} in the original ${e.operation} request, then retry; the item was not created.`;let u=ot("update",d);return u===void 0?`Supply ${d} using its declared SDK or package mutation contract, then retry.`:G(["update",l,nt("update",u),`<${d}>`,"--pm-path",Q.resolve(e.pmRoot)])});throw new f(`Workflow policy refused ${e.operation}: ${a}${s}.${r.length?` Missing: ${r.join(", ")}.`:""}`,p.CONFLICT,{code:"workflow_policy_refused",reason:n.map(d=>d.policy_id).join(","),policy_violations:n,policy_violation_count:o.length,required:r.length?`Supply missing fields: ${r.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:n.map(d=>d.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:r},nextSteps:[...c,...new Set(o.slice(0,3).filter(d=>d.missing_fields.length===0).map(d=>d.remediation)),...o.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as _i}from"node:async_hooks";import{channel as gi}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var We=new _i,He=gi("@unbrained/pm-cli/item-metadata-enumeration/v1");function ye(e){He.publish(e)}async function sn(e){let i={enumeration_calls:0,metadata_rows:0},t=o=>{We.getStore()?.includes(i)&&(i.enumeration_calls+=1,i.metadata_rows+=o)};He.subscribe(t);try{return{result:await We.run([...We.getStore()??[],i],e),work:{...i}}}finally{He.unsubscribe(t)}}import P from"node:fs/promises";import Nt from"node:path";import{randomUUID as wi}from"node:crypto";import{createRequire as bi}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var Ei="metadata-query-index.sqlite",Z="5",Ue;function ee(){return Ue!==void 0||(Ue=wt(process.versions.node,bi(import.meta.url))),Ue}function Rt(e,i){return Math.max(0,Math.floor(e===void 0?i:e))}function H(e){return Nt.join(e,"runtime",Ei)}function Ii(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 _e(e,i,t){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(i,t)}function kt(e,i){let t=i.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(t.id,i.relativePath,JSON.stringify(t),t.status,t.type,t.priority,t.updated_at,t.created_at,t.parent??null,t.assignee??null,t.sprint??null,t.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(t.id),e.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(t.id,t.title,t.description,t.tags.join(" "),t.id);let o=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let r of Object.keys(t))o.run(t.id,r);let n=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let r of i.linkedFiles??[])n.run(t.id,r.path,r.scope,r.note??null)}async function Ot(e){let i=H(e.pmRoot),t=ee();if(!t){await P.rm(i,{force:!0});return}await P.mkdir(Nt.dirname(i),{recursive:!0});let o=`${i}.${wi()}.tmp`,n;try{n=new t(o),Ii(n),n.exec("BEGIN IMMEDIATE"),_e(n,"version",Z),_e(n,"context_fingerprint",e.contextFingerprint),_e(n,"source_cursor",e.sourceCursor);for(let r of e.rows)kt(n,r);n.exec("COMMIT"),n.close(),n=void 0,await P.rm(i,{force:!0}),await P.rename(o,i)}catch(r){throw n?.close(),await Promise.allSettled([P.rm(o,{force:!0})]),r}}function ge(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(i=>[String(i.key),String(i.value)]))}async function Dt(e){let i=ee();if(!i)return!1;let t=H(e.pmRoot),o;try{await P.access(t),o=new i(t),o.exec("PRAGMA foreign_keys = ON");let n=ge(o);if(n.version!==Z||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 l of e.deletedRelativePaths??[]){let c=a.get(l);r.run(l),c&&s.run(c.rowid)}return e.row&&kt(o,e.row),_e(o,"source_cursor",e.sourceCursor),o.exec("COMMIT"),o.close(),!0}catch{try{o?.exec("ROLLBACK")}catch{}return o?.close(),!1}}function he(e,i,t,o,n){!o||o.length===0||(e.push(`${t} ${n} (${o.map(()=>"?").join(", ")})`),i.push(...o))}function vi(e){let i=[],t=[];he(i,t,"status",e.statuses,"IN"),he(i,t,"status",e.excludeStatuses,"NOT IN"),he(i,t,"type",e.types,"IN"),he(i,t,"id",e.ids,"IN");for(let o of e.metadataKeys??[])i.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),t.push(o);for(let[o,n]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])n!==void 0&&(i.push(`${o} = ?`),t.push(n));return e.priority!==void 0&&(i.push("priority = ?"),t.push(e.priority)),{where:i.length===0?"":` WHERE ${i.join(" AND ")}`,parameters:t}}async function yn(e){let i=ee();if(!i)return null;let t=e.query??{},{where:o,parameters:n}=vi(t),r;try{r=new i(H(e.pmRoot),{readOnly:!0});let a=ge(r);if(a.version!==Z||a.source_cursor!==e.expectedSourceCursor)return r.close(),null;let s=r.prepare(`SELECT COUNT(*) AS count FROM items${o}`).get(...n),l=[],c="";t.limit!==void 0?(c+=" LIMIT ?",l.push(Math.max(0,Math.floor(t.limit))),t.offset!==void 0&&(c+=" OFFSET ?",l.push(Math.max(0,Math.floor(t.offset))))):t.offset!==void 0&&(c+=" LIMIT -1 OFFSET ?",l.push(Math.max(0,Math.floor(t.offset))));let d=r.prepare(`SELECT metadata_json FROM items${o}
72
- ORDER BY ${t.terminalStatuses&&t.terminalStatuses.length>0?`CASE WHEN status IN (${t.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${c}`).all(...n,...t.terminalStatuses??[],...l).map(u=>{let y=JSON.parse(String(u.metadata_json));if(!y.id)throw new TypeError("Indexed metadata row has no id");return y});return r.close(),{source_cursor:a.source_cursor,total:Number(s.count),items:d}}catch{return r?.close(),null}}async function hn(e){let i=ee();if(!i||e.paths.length===0)return null;let t;try{t=new i(H(e.pmRoot),{readOnly:!0});let o=ge(t);if(o.version!==Z||o.source_cursor!==e.expectedSourceCursor)return t.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}`,l=t.prepare(`SELECT COUNT(DISTINCT item_id) AS count
73
- FROM item_linked_files
74
- WHERE ${s}`).get(...a),c=Rt(e.limit,50),d=Rt(e.offset,0),u=t.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,d),y=[];if(u.length>0){let h=u.map(_=>String(_.id)),m=t.prepare(`SELECT item_id, path, scope, note
82
- FROM item_linked_files
83
- WHERE item_id IN (${h.map(()=>"?").join(", ")})
84
- AND ${s}
85
- ORDER BY path ASC, scope ASC`).all(...h,...a),g=new Map(h.map(_=>[_,[]]));for(let _ of m){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));y.push({item:b,files:g.get(String(_.id))})}}return t.close(),{source_cursor:o.source_cursor,total:Number(l.count),matches:y}}catch{return t?.close(),null}}async function _n(e){let i=ee();if(!i)return null;let t;try{t=new i(H(e.pmRoot),{readOnly:!0});let o=ge(t);if(o.version!==Z||o.source_cursor!==e.expectedSourceCursor)return t.close(),null;let n=t.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 t.close(),{source_cursor:o.source_cursor,items:n}}catch{return t?.close(),null}}async function we(e){await P.rm(H(e),{force:!0})}import E from"node:fs/promises";import w from"node:path";import{createHash as Ci,randomUUID as Pt}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var x=8,jt=500,Ti="metadata-derived-index",Si="metadata-cache.json",xi="metadata-cache-bodies.json",Ri="metadata-cache-collections.json",Ni="metadata-cache-delta.json",ki="metadata-cache-manifest.json",Mt=4,Oi=["comments","notes","learnings","files","tests","test_runs","docs"];function $t(){return se(Y())}function Ee(e){let i={...e},t={};for(let o of Oi)o in i&&(t[o]=i[o],delete i[o]);return{light:i,heavy:t}}function Wt(e,i){return!i||Object.keys(i).length===0?e:{...e,...i}}function Ht(e,i,t,o){let n=Ci("sha256");n.update(`format:${e??"default"}`);let r=Object.entries(i).sort(([a],[s])=>a.localeCompare(s)).map(([a,s])=>`${a}=${s}`).join(",");return n.update(`|types:${r}`),t&&n.update(`|schema:${JSON.stringify(t)}`),o.length>0&&n.update(`|extension_fields:${o.join(",")}`),n.digest("hex").slice(0,16)}function Ie(e){return w.join(e,"runtime",Si)}function ve(e){return w.join(e,"runtime",xi)}function Ce(e){return w.join(e,"runtime",Ri)}function ze(e){return w.join(e,"runtime",Ni)}function Xe(e){return w.join(e,"runtime",ki)}function Te(e,i){let t=w.extname(e);return`${e.slice(0,-t.length)}.${i}${t}`}var Di=24,v=new Map,Se=new WeakMap;function Ye(e){return Se.get(e)??e.source_cursor}function Mi(e,i){let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.entry?e.entries[o]=n.entry:delete e.entries[o];e.directory_signatures=i.directory_signatures,e.source_cursor=i.source_cursor}}function Fi(e,i){if(!e)return;let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.body?e.bodies[o]=n.body:delete e.bodies[o];e.source_cursor=i.source_cursor}}function Ai(e,i){if(!e)return;let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.collections?e.collections[o]=n.collections:delete e.collections[o];e.source_cursor=i.source_cursor}}function Li(e,i,t,o){!e||!o||e.context_fingerprint!==o.context_fingerprint||(Mi(e,o),Fi(i,o),Ai(t,o))}function Be(e,i){v.size>=Di&&!v.has(e)&&lt(v),v.set(e,i)}async function D(e,i){let t;try{t=await E.stat(e)}catch{return v.delete(e),null}let o=v.get(e);if(o&&te(o.signature,t.mtimeMs,t.ctimeMs,t.size))return v.delete(e),v.set(e,o),o.envelope;let n;try{n=i(await E.readFile(e,"utf8"))}catch{n=null}return Be(e,{signature:{mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size},envelope:n}),n}async function Pi(e,i,t){let o=s=>{let l=JSON.parse(s);return l.version!==x||typeof l.source_cursor!="string"||typeof l.entries!="object"||l.entries===null?null:l},n=Ie(e),r=await D(n,o);if(!i||r===null||r.context_fingerprint===i)return r;let a=await D(Te(n,i),o);return a===null&&ne(t,`metadata_cache_context_changed:${r.context_fingerprint}->${i}`),a}async function ji(e,i){let t=r=>{let a=JSON.parse(r);return a.version!==x||typeof a.source_cursor!="string"||typeof a.bodies!="object"||a.bodies===null?null:a},o=ve(e),n=await D(o,t);return i&&n?.context_fingerprint!==i?await D(Te(o,i),t):n}async function $i(e,i){let t=r=>{let a=JSON.parse(r);return a.version!==x||typeof a.source_cursor!="string"||typeof a.collections!="object"||a.collections===null?null:a},o=Ce(e),n=await D(o,t);return i&&n?.context_fingerprint!==i?await D(Te(o,i),t):n}async function Ge(e){let i=ze(e),t=await D(i,o=>{let n=JSON.parse(o);return n.version!==x||typeof n.base_source_cursor!="string"||typeof n.source_cursor!="string"||typeof n.changes!="object"||n.changes===null?null:n});if(t)return{envelope:t,invalid:!1};try{return await E.stat(i),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function qe(e){let i=Xe(e),t=await D(i,o=>{let n=JSON.parse(o);return n.version!==x||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(t)return t;try{await E.stat(i),await U(e)}catch{}return null}async function ie(e,i){await E.mkdir(w.dirname(e),{recursive:!0}),await O(e,JSON.stringify(i));try{let o=await E.stat(e);Be(e,{signature:{mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size},envelope:i})}catch{v.delete(e)}let t=w.dirname(w.dirname(e));if(e===Ie(t)||e===ve(t)||e===Ce(t)){let o=Te(e,i.context_fingerprint);await O(o,JSON.stringify(i));try{let l=await E.stat(o);Be(o,{signature:{mtime_ms:l.mtimeMs,ctime_ms:l.ctimeMs,size:l.size},envelope:i})}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(l=>l.isFile()&&l.name!==w.basename(e)&&l.name.startsWith(`${a}.`)&&l.name.endsWith(r)).map(l=>w.join(n,l.name));if(s.length>Mt){let l=(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 l.sort((d,u)=>d.mtime-u.mtime).slice(0,Math.max(0,l.length-Mt)))await E.rm(c.path,{force:!0}),v.delete(c.path)}}}function Wi(e,i,t){return t?i===t&&e!==t:i==="toon"&&e!=="toon"}function Ut(e,i,t){return e===void 0||Wi(e,i,t)}function ne(e,i){e&&!e.includes(i)&&e.push(i)}function te(e,i,t,o){return e.mtime_ms===i&&e.ctime_ms===t&&e.size===o}async function Hi(e,i,t){let o=w.join(e,i);try{let n=await E.readdir(o);return{folder:i,dirPath:o,files:n}}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&!A(n)&&ne(t,`item_list_directory_read_failed:${i}`),{folder:i,dirPath:o,files:[]}}}async function Ui(e,i){try{let t=await E.stat(w.join(e,i));return[i,{exists:!0,mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size}]}catch{return[i,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function be(e,i){return Object.fromEntries(await Promise.all(i.map(async t=>await Ui(e,t))))}function oe(e,i){return!e||Object.keys(e).length!==Object.keys(i).length?!1:Object.entries(i).every(([t,o])=>{let n=e[t];return n!==void 0&&n.exists===o.exists&&te(n,o.mtime_ms,o.ctime_ms,o.size)})}function Bi(e){return ce.some(i=>e.toLowerCase().endsWith(i))}function zi(e,i,t,o,n,r){o||(e.metadata=!0),i&&!n&&(e.body=!0),t&&!r&&(e.collections=!0)}async function Xi(e,i,t){if(t)for(let o of await le({path:e,scope:"project"}))ne(i,o)}function Ft(e,i,t,o){if(e)return i&&t?t.collections:o}async function Yi(e,i,t){let o=await E.stat(e),n=o.mtimeMs,r=o.ctimeMs,{size:a}=o,s=Ne(e);await Xi(e,t.warnings,t.dispatchReadHooks);let l=t.previousEntries[i],c=!t.forceSourceRead&&l!==void 0&&te(l,n,r,a),d=t.previousBodies[i],u=!t.forceSourceRead&&d!==void 0&&te(d,n,r,a),y=t.previousCollections[i],h=!t.forceSourceRead&&y!==void 0&&te(y,n,r,a);if(!(!c||t.includeBody&&!u||t.includeCollections&&!h))return{mtimeMs:n,ctimeMs:r,size:a,itemFormat:s,lightMetadata:l.metadata,heavyMetadata:Ft(t.includeCollections,h,y,void 0),bodyLength:l.body_length,body:t.includeBody?d.body:void 0};let m=await E.readFile(e,"utf8"),g=ue(m,{format:s,schema:t.schema,extensionFieldNames:t.extensionFieldNames,onWarning:b=>ne(t.warnings,b)}),_=Ee(g.metadata);return zi(t.state.misses,t.includeBody,t.includeCollections,c,u,h),{mtimeMs:n,ctimeMs:r,size:a,itemFormat:s,lightMetadata:c?l.metadata:_.light,heavyMetadata:Ft(t.includeCollections,h,y,_.heavy),bodyLength:c?l.body_length:g.body.length,body:t.includeBody?g.body:void 0}}function Gi(e,i,t,o){t.state.newEntries[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,metadata:o.lightMetadata,body_length:o.bodyLength},t.includeBody&&o.body!==void 0&&(t.state.newBodies[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,body:o.body}),t.includeCollections&&o.heavyMetadata!==void 0&&(t.state.newCollections[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,collections:o.heavyMetadata});let n=t.includeCollections?Wt(o.lightMetadata,o.heavyMetadata):o.lightMetadata,r=t.state.documentsById.get(n.id),a={metadata:n,body:o.body,item_format:o.itemFormat,item_path:e};Ut(r?.itemFormat,o.itemFormat,t.preferredFormat)&&t.state.documentsById.set(n.id,{candidate:a,itemFormat:o.itemFormat})}async function qi(e,i,t,o){try{let n=await Yi(i,t,o);Gi(i,t,o,n)}catch{ne(o.warnings,`item_list_item_read_failed:${e}/${w.basename(i)}`)}}function Ki(e,i){return e&&e.context_fingerprint===i?e.entries:{}}function Vi(e,i){return e&&e.context_fingerprint===i?e.bodies:{}}function Ji(e,i){return e&&e.context_fingerprint===i?e.collections:{}}function Qi(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Zi(e,i){let t=[];for(let{folder:o,dirPath:n,files:r}of e)for(let a of r){if(!Bi(a))continue;let s=w.join(n,a),l=w.relative(i.pmRoot,s);t.push(qi(o,s,l,i)),t.length===32&&(await Promise.all(t),t.length=0)}await Promise.all(t)}async function eo(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!oe(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await ie(Ie(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await ie(Xe(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let i=[...e.state.documentsById.values()].map(({candidate:t})=>({relativePath:w.relative(e.pmRoot,t.item_path),metadata:Ee(t.metadata).light,linkedFiles:t.metadata.files??[]}));i.length>=e.minimumIndexedItems?await Ot({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:i}):await we(e.pmRoot)}catch{}}async function to(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 ie(ve(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function io(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 ie(Ce(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function Ke(e,i,t={}){let o=await qe(e);return t.required!==!0&&(o===null||o.entry_count<jt)?async()=>{}:mt(e,Ti,30,i,!1,!1,3e3)}async function kn(e,i){let t=await qe(e);if(t===null)return null;let o=await Ge(e);if(o.invalid)return await U(e),null;let n=o.envelope?.context_fingerprint===t.context_fingerprint&&o.envelope.base_source_cursor===t.source_cursor?o.envelope.source_cursor:t.source_cursor,r=o.envelope?.context_fingerprint===t.context_fingerprint&&o.envelope.base_source_cursor===t.source_cursor?o.envelope.directory_signatures:t.directory_signatures;return i&&!oe(r,await be(e,i))?null:{source_cursor:n,entry_count:t.entry_count}}function At(e,i){let t=w.relative(e,i);return t===""||t===".."||t.startsWith(`..${w.sep}`)||w.isAbsolute(t)?null:t}async function U(e){await Promise.all([Ie(e),ve(e),Ce(e),ze(e),Xe(e)].map(async i=>{await E.rm(i,{force:!0}),v.delete(i)})),await we(e)}async function oo(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let i=await E.stat(e.mutation.itemPath),t=Ee(e.mutation.document.metadata),o={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size};return{entry:{...o,metadata:t.light,body_length:e.mutation.document.body.length},body:{...o,body:e.mutation.document.body},collections:{...o,collections:t.heavy}}}function no(e,i,t){return e?.context_fingerprint===i&&e.base_source_cursor===t?structuredClone(e.changes):{}}async function Ve(e){let i=At(e.pmRoot,e.itemPath),t=e.previousItemPath?At(e.pmRoot,e.previousItemPath):void 0;if(i===null||t===null)return await U(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let o=Ht(e.preferredFormat,e.typeToFolder,e.schema,$t()),n=await qe(e.pmRoot);if(n===null||n.context_fingerprint!==o)return[];let r=n.source_cursor,a=await Ge(e.pmRoot);if(a.invalid)return await U(e.pmRoot),["metadata_derived_index_refresh_failed"];let s=no(a.envelope,o,r),l=a.envelope?.context_fingerprint===o&&a.envelope.base_source_cursor===r?a.envelope.source_cursor:r;t!==void 0&&(s[t]={entry:null,body:null,collections:null}),s[i]=await oo({mutation:e});let c=Pt();return await ie(ze(e.pmRoot),{version:x,context_fingerprint:o,base_source_cursor:r,source_cursor:c,directory_signatures:await be(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:s}),await Dt({pmRoot:e.pmRoot,contextFingerprint:o,expectedSourceCursor:l,sourceCursor:c,row:e.document===null?null:{relativePath:i,metadata:Ee(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...t===void 0?[]:[t],...e.document===null?[i]:[]]})||await we(e.pmRoot),[]}catch{return await U(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function ro(e){return[...e.documentsById.values()].sort((i,t)=>i.candidate.metadata.id.localeCompare(t.candidate.metadata.id)).map(i=>i.candidate)}function Lt(e,i,t){return e?.context_fingerprint===i&&e.source_cursor===t}function ao(e,i,t,o,n){return e.every(r=>(!i||o[r]!==void 0)&&(!t||n[r]!==void 0))}function so(e){let i=new Map;for(let[t,o]of Object.entries(e.previousEntries)){let n=Ne(t);if(!n)continue;let r=e.includeCollections?Wt(o.metadata,e.previousCollections[t]?.collections):o.metadata,a=i.get(r.id);Ut(a?.itemFormat,n,e.preferredFormat)&&i.set(r.id,{itemFormat:n,candidate:{metadata:r,body:e.includeBody?e.previousBodies[t]?.body:void 0,item_format:n,item_path:w.join(e.pmRoot,t)}})}return[...i.values()].sort((t,o)=>t.candidate.metadata.id.localeCompare(o.candidate.metadata.id)).map(t=>t.candidate)}function co(e){return e.forceSourceScan||De()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!oe(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Lt(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Lt(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&ao(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function xe(e,i,t,o,n,r={}){let a=r.includeBody!==!1,s=r.includeCollections!==!1,l=$t(),c=Ht(i,t,n,l),d=await Ge(e);d.invalid&&await U(e);let u=await Pi(e,c,r.cacheDiagnostics),y=a?await ji(e,c):null,h=s?await $i(e,c):null;Li(u,y,h,d.envelope);let m=Ki(u,c),g=Vi(y,c),_=Ji(h,c),b=[...new Set(Object.values(t))],T=await be(e,b),$=Object.keys(m),N=Math.max(1,Math.floor(r.derivedIndexMinimumItems??jt));if(co({forceSourceScan:r.forceSourceScan===!0,contextFingerprint:c,existingCache:u,existingBodyCache:y,existingCollectionsCache:h,directorySignatures:T,entryKeys:$,minimumIndexedItems:N,includeBody:a,includeCollections:s,previousBodies:g,previousCollections:_}))return so({pmRoot:e,preferredFormat:i,includeBody:a,includeCollections:s,previousEntries:m,previousBodies:g,previousCollections:_});let I=await Promise.all(b.map(W=>Hi(e,W,o))),M=De(),C=Qi(),B={pmRoot:e,preferredFormat:i,warnings:o,schema:n,extensionFieldNames:l,includeBody:a,includeCollections:s,forceSourceRead:r.forceSourceScan===!0,dispatchReadHooks:M,previousEntries:m,previousBodies:g,previousCollections:_,state:C};await Zi(I,B);let k=await be(e,b),S=oe(T,k)?k:{},z=C.misses.metadata||Object.keys(m).length!==Object.keys(C.newEntries).length||!oe(u?.directory_signatures,S)||u===null?Pt():u.source_cursor;return await eo({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingCache:u,previousEntries:m,directorySignatures:S,state:C,minimumIndexedItems:N}),a&&await to({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingBodyCache:y,previousBodies:g,state:C}),s&&await io({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingCollectionsCache:h,previousCollections:_,state:C}),ro(C)}async function Bt(e,i,t,o,n){return(await xe(e,i,t,o,n,{includeBody:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}async function zt(e,i,t,o,n){return(await xe(e,i,t,o,n,{includeBody:!1,includeCollections:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();function lo(e,i){let t=e.trim().toLowerCase();if(t.length===0)return;let o=Math.floor(t.length/3);return i.map(n=>({candidate:n,distance:ae(t,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 Xt(e){return["pm",...e].map(i=>/^[A-Za-z0-9_./:@=-]+$/u.test(i)?i:JSON.stringify(i)).join(" ")}function An(e){let i=e.command_path.trim().replaceAll(/\s+/gu," "),t=e.token.trim(),o=t.length===0?"<empty>":t,n=[...new Set(e.allowed.map(y=>y.trim()))].filter(Boolean).sort((y,h)=>y.localeCompare(h));if(i.length===0||o.length===0||n.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let r=i.split(" "),a=e.trailing_args??[],s=e.display_name??`pm ${i}`,l=e.token_kind??"subcommand",c=e.retry_command?void 0:lo(o,n),d=Xt([...r,o,...a]),u=e.retry_command??(c?Xt([...r,c,...a]):void 0);return new f(`Unknown ${s} ${l} "${o}". Allowed: ${n.join(", ")}${e.message_suffix??""}`,e.exit_code??p.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:o,examples:[...u?[u]:[],...e.examples??[],`pm ${i} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:d,allowed_values:n,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}import uo from"node:fs/promises";import mo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="1d746e4d-ff6c-54ec-a94f-4ec4cb8f77b5")}catch{}})();function fo(e){return[...new Set(e.filter(i=>i.trim().length>0))].sort((i,t)=>i.localeCompare(t))}function po(e,i){return new f(`Missing history stream for ${e}. ${i} requires history streams when settings.history.missing_stream is strict_error.`,p.NOT_FOUND)}async function yo(e,i){return await it(mo.dirname(e)),await(await uo.open(e,"a")).close(),L({path:e,scope:"project",op:`${i}:history:auto_create`})}async function Je(e){return ho({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function ho(e){let i=fo(e.itemIds),t=[],o=[];for(let n of i){let r=R(e.pmRoot,n);if(!await X(r)){if(e.settings.history.missing_stream==="strict_error")throw po(n,e.commandLabel);o.push(...await yo(r,e.commandLabel)),o.push(`history_stream_auto_created:${n}`),t.push(n)}}return{auto_created_ids:t,warnings:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function re(e,i=!1){let t=e[0];if(t?.op!=="history_compact_baseline")return 0;let o=t.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(i)return null;throw new f("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",p.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."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="ddc5bb8f-83bc-5121-a628-a501e7ed5a73")}catch{}})();function _o(e,i){let t=-1;return e.forEach((o,n)=>{let r=Date.parse(o.ts);if(!Number.isFinite(r))throw new f(`History for this item contains invalid timestamp at entry ${n+1}.`,p.GENERIC_FAILURE);r<=i&&(t=n)}),t}function go(e,i){let t=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:t,last_timestamp:o}};return o!==null&&(n.examples=[o],i!==null&&(n.examples.unshift(String(i+1),String(i+e.length)),n.valid_range.first_version=i+1,n.valid_range.last_version=i+e.length)),{guidance:n,lastTimestamp:o}}function wo(e,i){let t={};if(i instanceof Error&&i.message.trim().length>0&&(t.reason=i.message.trim()),typeof i!="object"||i===null)return t;let o=i;if(typeof o.index=="number"&&Number.isInteger(o.index)&&o.index>=0&&(t.patchIndex=o.index),typeof o.operation=="object"&&o.operation!==null){let n=o.operation;Object.assign(t,Object.fromEntries(["op","path","from"].flatMap(r=>{let a=n[r];return typeof a=="string"?[[r,a]]:[]})))}if(t.patchIndex!==void 0){let n=e[t.patchIndex];n&&(t.op??=n.op,t.path??=n.path,t.from??=n.from)}return t}function Yt(e,i,t={}){let o=e.trim(),n=t.errorSubject??"history",r=n==="restore"?"Restore":"History",{guidance:a,lastTimestamp:s}=go(i,re(i,!0));if(!o)throw new f(`Missing ${n} target. Use a timestamp or version number.`,p.USAGE,a);if(/^\d+$/.test(o)){let d=re(i),u=Number(o);if(u>=1&&u<=d)throw new f(`History version ${u} was pruned by compaction.`,p.USAGE,{...a,code:"history_version_pruned"});if(!Number.isSafeInteger(u)||u<1||u>d+i.length)throw new f(`${r} version must be between ${d+1} and ${d+i.length} for this item.`,p.USAGE,a);return{kind:"version",raw:o,historyIndex:u-d-1}}let l=Date.parse(o);if(!Number.isFinite(l))throw new f(`Invalid ${n} target "${e}". Use a positive version number or ISO timestamp.`,p.USAGE,a);let c=_o(i,l);if(c<0||t.allowFutureTimestamp!==!0&&l>Date.parse(s))throw new f(n==="restore"?`No history entries exist at or before timestamp ${o}.`:`No history entry exists at timestamp ${o}.`,p.USAGE,a);return{kind:"timestamp",raw:o,historyIndex:c}}function Qe(e,i,t,o){let n=je(e,i);if(n.ok)return n.document;let r=wo(i,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 f(`Failed to apply history patch at entry ${t} (${a.join(", ")}). ${r.reason??String(n.error)}`,p.GENERIC_FAILURE)}function Gt(e,i){let t=e[0];if(t&&t.op!=="create"&&t.op!=="history_compact_baseline"){let a=je(K,t.patch);if(!a.ok||typeof a.document.metadata.id!="string")throw new f("History starts without a reconstructable item baseline.",p.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,i+1),n=me([...o]),r=structuredClone(K);for(let a=0;a<=i;a+=1){let s=e[a];if(!s)throw new f(`History target entry ${a+1} does not exist.`,p.USAGE);r=Qe(r,s.patch,a+1,s.op)}if(!n.ok)throw new f(`History cannot be replayed: ${n.errors.join(", ")}.`,p.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 Qn(e,i){if(Object.keys(e.metadata).length>0){if(typeof e.metadata.id!="string"||!Array.isArray(e.metadata.tags))throw new f("History has no complete item baseline for this target.",p.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 f(`History target ${i.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,p.USAGE)}import j from"node:fs/promises";import{statSync as bo}from"node:fs";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();function Eo(e,i){let t=-1,o=structuredClone(K);for(let[s,l]of e.entries()){if(o=Qe(o,l.patch,s+1,l.op),o.metadata.id!==void 0&&o.metadata.id!==i)throw new f(`History belongs to item ${String(o.metadata.id)}, expected ${i}.`,p.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});o.metadata.id===i&&Array.isArray(o.metadata.tags)&&(t=s)}let n=re(e,!0),r=t<0||n===null?null:n+t+1,a=r===null?void 0:String(r);if(t>=0&&a===void 0){let s=e[t].ts;Yt(s,e).historyIndex===t&&(a=s)}return{version:r,target:a}}async function qt(e,i,t){let o=new Set([J(i,t),V(i)]);for(let n of o){let r=R(e,n);if(!bo(r,{throwIfNoEntry:!1})?.isFile())continue;let a=await gt(r,n),s=-1;if(a.forEach((h,m)=>{h.op==="delete"&&(s=m)}),s<0)continue;let l=Gt(a,a.length-1);if(Object.keys(l.metadata).length!==0)continue;let{version:c,target:d}=Eo(a,n),u=d===void 0?["history",n,"--verify"]:["get",n,"--at",d],y=G(u);return new f(`Item ${n} was deleted at ${a[s].ts}; its history is retained.`,p.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:d!==void 0,last_materialized_version:c},nextSteps:[y,...d===void 0?["Recover the pre-compaction history from version control."]:[G(["restore",n,d])]],recovery:{suggested_retry:y,suggested_retry_args:u}})}}import{AsyncLocalStorage as Io}from"node:async_hooks";import vo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="53df109f-bd64-5879-96a6-39f70334910e")}catch{}})();var Co=new Io;function Kt(e,i){for(let t of Co.getStore()??[])t.pmRoot===vo.resolve(e)&&t.id===i.metadata.id&&t.validate(i)}import Ze from"node:path";import{isUtf8 as To}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="3ecac03b-7dfe-5ce3-a93d-6b9f948c68fe")}catch{}})();async function So(e){try{return await j.access(e),!0}catch{return!1}}function xo(e,i){e&&(e.includes(i)||e.push(i))}function Vt(e){return e??se(Y())}function Ro(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Jt(e,i,t="pm-",o,n=F){let r=i.trim(),a=r.startsWith("#")?r.slice(1):r;if(a.length===0)return null;let s=J(i,t),l=V(i),c=[...new Set([a,s,l])].filter(y=>y.length>0),d=Object.entries(n),u=Ro(o);for(let y of c){let h=new Map;for(let[m]of d)for(let g of u){let _=Re(e,m,y,g,n);await So(_)&&h.set(_,h.get(_)??{id:y,type:m,itemPath:_,item_format:g})}if(h.size>1){let m=[...h.keys()].map(g=>Ze.relative(e,g).split(Ze.sep).join("/")).sort();throw new f(`Item ${y} has ambiguous identity across ${m.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,p.CONFLICT,{code:"item_identity_ambiguous",item_id:y,paths:m})}for(let m of h.values())return m}return null}async function Qt(e,i={}){let t=await No(e,i);if(t.error!==null)throw t.error;return{raw:t.raw,document:t.document}}async function No(e,i={}){let t=await j.readFile(e.itemPath);if(!To(t))throw new f("Item contains invalid UTF-8; preserve a binary backup before recovering it.",p.CONFLICT,{code:"item_document_encoding_invalid",item_id:e.id,item_path:e.itemPath,byte_length:t.length,empty:!1});let o=t.toString("utf8");await le({path:e.itemPath,scope:"project"});let n;try{n=ue(o,{format:e.item_format,requireSupportedFormat:!0,schema:i.schema,extensionFieldNames:Vt(i.extensionFieldNames),onWarning:r=>xo(i.warnings,r)})}catch(r){if(r instanceof f&&r.code==="item_format_version_unsupported")throw new f(`Item ${e.id}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath});if(r instanceof f&&r.code==="item_document_invalid")return{raw:o,document:null,error:new f(`Cannot read ${e.id} at ${e.itemPath}${t.length===0?" (zero-length file)":""}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath,byte_length:t.length,empty:t.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 ko(e,i,t=F,o,n){await fe(e);let r=await Bt(e,i,t,o,n);return ye(r.length),r.map(a=>a.metadata)}async function Ur(e,i,t=F,o,n){await fe(e);let r=await zt(e,i,t,o,n);return ye(r.length),r.map(a=>a.metadata)}async function Br(e,i,t=F,o,n,r={}){await fe(e);let a=await xe(e,i,t,o,n,{includeBody:!0,forceSourceScan:r.forceSourceScan});return ye(a.length),a.map(s=>({...s.metadata,body:s.body}))}function Zt(e){return{async get(i){let t=await Jt(e.pmRoot,i,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return null;let{document:o}=await Qt(t,{schema:e.settings.schema});return{item:o.metadata,body:o.body}},list:()=>ko(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Oo(e,i){let t=new Set(Object.values(i)),o=[];return await Promise.all([...t].map(async n=>{try{let r=await j.readdir(Ze.join(e,n));for(let a of r)for(let s of ce)if(a.toLowerCase().endsWith(s)){o.push(a.slice(0,-s.length));break}}catch{}})),o}async function Do(e,i,t,o){let n=J(i,t),r=await Oo(e,o);if(r.length===0)return[];let a=Math.max(3,Math.floor(n.length/2));return r.map(s=>({id:s,distance:ae(s,n,a)})).filter(s=>s.distance!==null).sort((s,l)=>s.distance-l.distance).slice(0,3).map(s=>s.id)}async function Mo(e,i,t,o){let n=await qt(e,i,t);if(n)return n;let r=await Do(e,i,t,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 f(`Item ${i} not found`,p.NOT_FOUND,{nextSteps:a})}function Fo(e,i){return e==="claim"||i===!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 ei(e){let i=e.typeToFolder??rt(e.settings,Y()).type_to_folder,t=await Jt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,i);if(!t)throw await Mo(e.pmRoot,e.id,e.settings.id_prefix,i);let o=await ft(e.pmRoot,t.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 Qt(t,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:r}),l=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||l,d=_t(e.author),u=Et(e.settings);if(l&&c!==d&&!e.force&&!Fo(e.op,e.bypassAssigneeConflict)){if(u.ownership_enforcement==="strict")throw new f(`Item ${t.id} is assigned to ${l}. Use --force to override.`,p.CONFLICT);u.ownership_enforcement==="warn"&&r.push(`ownership_warning:assignee_conflict:${t.id}:${l}`)}return{typeToFolder:i,located:t,originalRaw:a,document:s,warnings:r,releaseLock:n,lease:o}}catch(r){throw await n(),r}}async function ti(e,i,t,o){return e.fence(async()=>{let n;try{n=await j.readFile(i.itemPath,"utf8")}catch(r){if(!A(r))throw r;n=null}if(n!==t)throw new f(`Item ${i.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,p.CONFLICT,{code:"stale_revision",item_id:i.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 Ao(e,i,t){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:i,effectiveSerializedAfter:t,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:i,effectiveSerializedAfter:typeof o.contents=="string"?o.contents:t,skipItemWrite:o.skip_write===!0}}async function Lo(e){let i=await Me("item_store_delete",e),t=i.handled&&typeof i.result=="object"&&i.result!==null?i.result:{};return{effectiveItemPath:typeof t.item_path=="string"&&t.item_path.trim().length>0?t.item_path:e.item_path,skipDelete:t.skip_delete===!0,warnings:i.warnings}}async function Po(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await O(e.originalItemPath,e.originalRaw),await j.rm(e.effectiveTargetItemPath,{force:!0});return}await O(e.originalItemPath,e.originalRaw)}}async function ii(e){pt(e.op);let i=await ei({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:t,located:o,originalRaw:n,document:r,warnings:a,releaseLock:s,lease:l}=i;try{Kt(e.pmRoot,r);let c=q(r,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=q(structuredClone(r),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(d);if(e.skipNoop===!0&&u.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...a,...u.warnings??[]]};let y=e.resolveHistoryContext?.(),h=Math.max(Ae(c.metadata),Ae(d.metadata));It(at(e.pmRoot),h),h>yt(d.metadata)&&(d.metadata.pm_format_version=h,u.changedFields.push("pm_format_version")),d.metadata.updated_at=Fe();let m=q(d,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await $e({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:c,after:m});await Oe({pm_root:e.pmRoot,operation:e.op,before:c,after:m,changed_fields:u.changedFields,sdk:Zt({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t})});let _=await Je({pmRoot:e.pmRoot,settings:e.settings,itemId:o.id,commandLabel:e.op}),b="toon",T=ht(m,{format:b,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),$=Re(e.pmRoot,m.metadata.type,o.id,b,t),N=R(e.pmRoot,o.id),I=await ti(l,o,n,async()=>{let k=await Me("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:o.id,source_item_path:o.itemPath,target_item_path:$,history_path:N,item_format:b,before:c,after:m,contents:T}),{effectiveTargetItemPath:S,effectiveSerializedAfter:z,skipItemWrite:W}=Ao(k,$,T),oi=await Ke(e.pmRoot,e.author),et=[];try{W||await O(S,z),!W&&S!==o.itemPath&&await j.rm(o.itemPath);let ni=Le({nowIso:m.metadata.updated_at,author:e.author,op:e.op,before:c,after:m,message:e.message,context:g.decisions.length===0?y:{...y,workflow_policies:g.decisions}});try{await Pe(N,ni)}catch(ri){throw await Po({skipItemWrite:W,effectiveTargetItemPath:S,originalItemPath:o.itemPath,originalRaw:n}),ri}W||(et=await Ve({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t,schema:e.settings.schema,itemPath:S,previousItemPath:o.itemPath,document:m}))}finally{await oi()}return{derivedIndexWarnings:et,effectiveTargetItemPath:S,overrideWarnings:k.warnings}}),{derivedIndexWarnings:M,effectiveTargetItemPath:C}=I,B=[...await L({path:C,scope:"project",op:e.op,item_id:m.metadata.id,item_type:m.metadata.type,before:c,after:m,changed_fields:u.changedFields}),...await L({path:N,scope:"project",op:`${e.op}:history`,item_id:m.metadata.id,item_type:m.metadata.type,before:c,after:m,changed_fields:u.changedFields})];return ke({id:m.metadata.id,op:e.op,item_type:m.metadata.type,previous_status:c.metadata.status,status:m.metadata.status,previous:de(c.metadata,u.changedFields),current:de(m.metadata,u.changedFields),changed_fields:u.changedFields}),{item:m.metadata,body:m.body,changedFields:u.changedFields,warnings:[...a,...u.warnings??[],...g.warnings,..._.warnings,...I.overrideWarnings,...M,...B]}}finally{await s()}}async function zr(e){return ii(e)}async function Xr(e){return ii(e)}async function Yr(e){let i=await ei({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:t,originalRaw:o,document:n,warnings:r,releaseLock:a,lease:s}=i;try{let l=Vt(void 0),c=q(n,{schema:e.settings.schema,extensionFieldNames:l}),d=await $e({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:Zt({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:i.typeToFolder})});let u=await Je({pmRoot:e.pmRoot,settings:e.settings,itemId:t.id,commandLabel:"delete"}),y=Fe(),h=tt,m=Le({nowIso:y,author:e.author,op:"delete",before:c,after:h,message:e.message,context:d.decisions.length===0?void 0:{workflow_policies:d.decisions}}),g=R(e.pmRoot,t.id),_=()=>Lo({op:"delete",pm_root:e.pmRoot,item_id:t.id,item_path:t.itemPath,history_path:g,before:c});if(e.dryRun===!0){let I=await _();return{item:c.metadata,changedFields:["deleted"],targetPath:I.effectiveItemPath,warnings:[...r,...d.warnings,...u.warnings,...I.warnings]}}let b=await ti(s,t,o,async()=>{let{effectiveItemPath:I,skipDelete:M,warnings:C}=await _(),B=await Ke(e.pmRoot,e.author),k=[];try{M||await j.rm(I);try{await Pe(g,m)}catch(S){throw M||await O(I,o),S}M||(k=await Ve({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:i.typeToFolder,schema:e.settings.schema,itemPath:I,document:null}))}finally{await B()}return{derivedIndexWarnings:k,effectiveItemPath:I,overrideWarnings:C}}),{derivedIndexWarnings:T,effectiveItemPath:$}=b,N=[...await L({path:$,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:h,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:h,changed_fields:["deleted"]})];return ke({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:de(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...r,...d.warnings,...u.warnings,...b.overrideWarnings,...T,...N]}}finally{await a()}}export{An as a,Je as b,ho as c,Ct as d,V as e,J as f,Bo as g,re as h,Yt as i,Qe as j,Gt as k,Qn as l,ui as m,fi as n,pi as o,yi as p,hi as q,$e as r,sn as s,yn as t,hn as u,_n as v,jt as w,Oi as x,Ke as y,kn as z,Ve as A,xe as B,Jt as C,Qt as D,No as E,ko as F,Ur as G,Br as H,Zt as I,Mo as J,zr as K,Xr as L,Yr as M};
91
- //# sourceMappingURL=chunk-FO4U3FIP.js.map