@unbrained/pm-cli 2026.10.25 → 2026.10.27

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 (211) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +44 -1
  3. package/dist/cli/error-guidance.d.ts +5 -0
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/register-list-query.js +5 -5
  6. package/dist/cli/register-mutation.js +2 -2
  7. package/dist/cli-bundle/bundle-manifest.json +1 -1
  8. package/dist/cli-bundle/chunks/{chunk-O3ZTGRIH.js → chunk-25MTQAHX.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-YCCGZHOR.js → chunk-2XUDAQK5.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-VAEB6IUQ.js → chunk-32QK43XG.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-RD6UW3MW.js → chunk-34OQP43K.js} +3 -3
  12. package/dist/cli-bundle/chunks/{chunk-TLMXSYJA.js → chunk-57YPOOED.js} +2 -2
  13. package/dist/cli-bundle/chunks/chunk-5PTMQBKJ.js +30 -0
  14. package/dist/cli-bundle/chunks/{chunk-FNZT4BTE.js → chunk-EKV5GP6P.js} +86 -86
  15. package/dist/cli-bundle/chunks/{chunk-LNKPH2DD.js → chunk-ER7RLJW5.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-F26MRQZY.js +6 -0
  17. package/dist/cli-bundle/chunks/chunk-H434DKYU.js +2 -0
  18. package/dist/cli-bundle/chunks/{chunk-MVJGGCGQ.js → chunk-HIX2OMEZ.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-4GD6QOP6.js → chunk-NNIYQHYT.js} +3 -3
  20. package/dist/cli-bundle/chunks/chunk-O3LPT34G.js +20 -0
  21. package/dist/cli-bundle/chunks/{chunk-3CYXE6BV.js → chunk-ONC4BBQP.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-UI3FD3DW.js → chunk-OQOEBWHU.js} +2 -2
  23. package/dist/cli-bundle/chunks/chunk-Q55KZDNF.js +2 -0
  24. package/dist/cli-bundle/chunks/chunk-QQYLNHZK.js +128 -0
  25. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +2 -0
  26. package/dist/cli-bundle/chunks/chunk-UHKN6TJM.js +114 -0
  27. package/dist/cli-bundle/chunks/{chunk-7T3H24HN.js → chunk-X5TMR7KC.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-EYCVAAIP.js → chunk-XERBUA6A.js} +2 -2
  29. package/dist/cli-bundle/chunks/indexed-receipt-blobs-63WYG2PY.js +4 -0
  30. package/dist/cli-bundle/chunks/{mutation-admission-747C6IUR.js → mutation-admission-L3A6FSZ7.js} +2 -2
  31. package/dist/cli-bundle/chunks/{register-list-query-COST6KRV.js → register-list-query-YSQ7UTFI.js} +9 -9
  32. package/dist/cli-bundle/chunks/register-mutation-6HRXYASW.js +20 -0
  33. package/dist/cli-bundle/chunks/{register-operations-S4LKLUBJ.js → register-operations-4O3YOYXF.js} +2 -2
  34. package/dist/cli-bundle/chunks/{register-setup-3ITZXPOL.js → register-setup-3WAXNDMY.js} +2 -2
  35. package/dist/cli-bundle/chunks/{settlement-hook-5IVCF6ZY.js → settlement-hook-CRW6PVQK.js} +2 -2
  36. package/dist/cli-bundle/chunks/{stage-3UUIYROS.js → stage-I46WD4EN.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-U6HXIF6G.js → chunk-4TXZBGOR.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-22727JYL.js → chunk-B266DDBJ.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-Y4JHHY24.js → chunk-BH7RE2ZY.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-ZYCOMRFT.js → chunk-E5C24MCV.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-HWD63G54.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-J67PFM3O.js +91 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-46KDJH3K.js → chunk-KTXU5WU6.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/chunk-MVY6JDIH.js +12 -0
  46. package/dist/cli-bundle/focused-chunks/{chunk-NC5HUGHU.js → chunk-NLZUI234.js} +4 -4
  47. package/dist/cli-bundle/focused-chunks/{chunk-B5JOVH5F.js → chunk-R2MTHS2H.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-SM2KGD4J.js +79 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-HMYDUEQK.js → chunk-SYL73MEI.js} +3 -3
  50. package/dist/cli-bundle/focused-chunks/{chunk-77NU7NPN.js → chunk-TAFMNTA5.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-74KC7FUQ.js → chunk-TGUOEOKP.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-U4UBQBS7.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-URWYYJ7K.js → chunk-WDKZB3V6.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-XK3XMZM4.js +2 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-3M5FZCMC.js → chunk-Y57A4ZDI.js} +55 -55
  56. package/dist/cli-bundle/focused-chunks/chunk-YC6NCPLK.js +22 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-7DEZT4JN.js → chunk-YQKLKRMW.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-3FM75SBJ.js → chunk-YW5GHQN2.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-ZA6AEYIM.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-ZH7GTEWL.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-GAFC52LQ.js +4 -0
  62. package/dist/cli-bundle/focused-chunks/{mutation-admission-BQBQXILV.js → mutation-admission-ENBFMV2X.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{settlement-hook-XVS6P2XI.js → settlement-hook-PUYJJDFL.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{stage-VSIL4MTZ.js → stage-MAWZTM2H.js} +2 -2
  65. package/dist/cli-bundle/main.js +4 -4
  66. package/dist/cli-bundle/sdk-authoring.js +1 -1
  67. package/dist/cli-bundle/sdk-contracts.js +2 -2
  68. package/dist/cli-bundle/sdk-core.js +33 -33
  69. package/dist/cli-bundle/sdk-governance.js +1 -1
  70. package/dist/cli-bundle/sdk-graph.js +1 -1
  71. package/dist/cli-bundle/sdk-merge.js +57 -57
  72. package/dist/cli-bundle/sdk-query.js +1 -1
  73. package/dist/cli-bundle/sdk-runtime.js +1 -1
  74. package/dist/cli-bundle/sdk-testing.js +1 -1
  75. package/dist/cli-bundle/sdk.js +9 -9
  76. package/dist/core/extensions/extension-types.d.ts +3 -0
  77. package/dist/core/extensions/extension-types.js +1 -1
  78. package/dist/core/history/event-index.d.ts +6 -0
  79. package/dist/core/history/event-index.js +7 -6
  80. package/dist/core/history/read.d.ts +3 -1
  81. package/dist/core/history/read.js +1 -1
  82. package/dist/core/output/mutation-projection.js +1 -1
  83. package/dist/core/policy/workflow-policy-store.js +1 -1
  84. package/dist/core/shared/errors.d.ts +9 -0
  85. package/dist/core/shared/errors.js +1 -1
  86. package/dist/core/shared/secret-rules.d.ts +17 -0
  87. package/dist/core/shared/secret-rules.js +2 -1
  88. package/dist/core/store/item-mutation-precondition.d.ts +8 -0
  89. package/dist/core/store/item-mutation-precondition.js +1 -1
  90. package/dist/core/store/item-store.js +1 -1
  91. package/dist/mcp/tool-definitions.js +1 -1
  92. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  93. package/dist/sdk/cli-contracts/completeness.js +1 -1
  94. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  95. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  96. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  97. package/dist/sdk/cli-contracts/registration-helpers.d.ts +1 -1
  98. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  99. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +4 -0
  100. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  101. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  102. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  103. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  104. package/dist/sdk/context-signal-store.js +2 -2
  105. package/dist/sdk/core.d.ts +1 -1
  106. package/dist/sdk/core.js +1 -1
  107. package/dist/sdk/extension-command-context.js +2 -2
  108. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  109. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  110. package/dist/sdk/index.d.ts +2 -1
  111. package/dist/sdk/index.js +1 -1
  112. package/dist/sdk/item-transaction.js +1 -1
  113. package/dist/sdk/lifecycle/close-many.d.ts +3 -0
  114. package/dist/sdk/lifecycle/close-many.js +1 -1
  115. package/dist/sdk/lifecycle/close.d.ts +3 -1
  116. package/dist/sdk/lifecycle/close.js +1 -1
  117. package/dist/sdk/lifecycle/create.d.ts +2 -0
  118. package/dist/sdk/lifecycle/create.js +1 -1
  119. package/dist/sdk/lifecycle/plan.d.ts +2 -0
  120. package/dist/sdk/lifecycle/plan.js +1 -1
  121. package/dist/sdk/lifecycle/restore.js +1 -1
  122. package/dist/sdk/lifecycle-policy.d.ts +11 -0
  123. package/dist/sdk/lifecycle-policy.js +1 -1
  124. package/dist/sdk/merge/indexed-receipt-blobs.d.ts +3 -1
  125. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  126. package/dist/sdk/merge/receipt-file-boundary.d.ts +2 -0
  127. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  128. package/dist/sdk/merge/receipts.js +2 -2
  129. package/dist/sdk/mutation-events.d.ts +6 -0
  130. package/dist/sdk/mutation-events.js +1 -1
  131. package/dist/sdk/mutation-guard.d.ts +6 -1
  132. package/dist/sdk/mutation-guard.js +1 -1
  133. package/dist/sdk/output/fit-envelope.d.ts +98 -0
  134. package/dist/sdk/output/fit-envelope.js +2 -0
  135. package/dist/sdk/public-surface.json +1 -1
  136. package/dist/sdk/query.d.ts +1 -0
  137. package/dist/sdk/query.js +1 -1
  138. package/dist/sdk/read-output-session.d.ts +1 -1
  139. package/dist/sdk/read-output-session.js +1 -1
  140. package/dist/sdk/runtime-extended-actions.js +1 -1
  141. package/dist/sdk/runtime-input.js +1 -1
  142. package/dist/sdk/runtime-primitives.d.ts +1 -1
  143. package/dist/sdk/runtime-primitives.js +1 -1
  144. package/dist/sdk/runtime.d.ts +2 -2
  145. package/dist/sdk/runtime.js +1 -1
  146. package/dist/sdk/scheduling-shortcuts.d.ts +2 -0
  147. package/dist/sdk/scheduling-shortcuts.js +1 -1
  148. package/dist/sdk/test/execution.js +2 -2
  149. package/dist/sdk/test/receipt-index-snapshot.d.ts +2 -0
  150. package/dist/sdk/test/receipt-index-snapshot.js +2 -0
  151. package/dist/sdk/test/workspace-snapshot.d.ts +1 -1
  152. package/dist/sdk/test/workspace-snapshot.js +1 -1
  153. package/dist/sdk/workspace-transaction.d.ts +3 -1
  154. package/dist/sdk/workspace-transaction.js +2 -2
  155. package/docs/COMMANDS.md +2 -1
  156. package/docs/MUTATION_INTEGRITY.md +33 -0
  157. package/docs/PERFORMANCE.md +21 -6
  158. package/docs/QUALITY_EVIDENCE.md +9 -0
  159. package/docs/READ_OUTPUT_CONTRACTS.md +55 -1
  160. package/docs/RELEASING.md +11 -0
  161. package/docs/SDK.md +88 -6
  162. package/docs/SDK_CONTEXT_COORDINATION.md +35 -4
  163. package/docs/TESTING.md +14 -1
  164. package/docs/WORKFLOW_POLICIES.md +14 -1
  165. package/docs/agent-task-token-baseline.json +1 -1
  166. package/docs/agent-task-transcripts.json +1 -1
  167. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -4
  168. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
  169. package/marketplace.json +1 -1
  170. package/package.json +1 -1
  171. package/packages/pm-beads/package.json +1 -1
  172. package/packages/pm-calendar/extensions/calendar/shortcuts.ts +2 -2
  173. package/packages/pm-calendar/package.json +1 -1
  174. package/packages/pm-command-kit/package.json +1 -1
  175. package/packages/pm-digital-twin/package.json +1 -1
  176. package/packages/pm-governance-audit/package.json +1 -1
  177. package/packages/pm-guide-shell/package.json +1 -1
  178. package/packages/pm-kanban/package.json +1 -1
  179. package/packages/pm-lifecycle-hooks/package.json +1 -1
  180. package/packages/pm-linked-test-adapters/package.json +1 -1
  181. package/packages/pm-search-advanced/package.json +1 -1
  182. package/packages/pm-templates/package.json +1 -1
  183. package/packages/pm-todos/package.json +1 -1
  184. package/packages/pm-vcs/package.json +1 -1
  185. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  186. package/plugins/pm-claude/package.json +1 -1
  187. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  188. package/plugins/pm-codex/package.json +1 -1
  189. package/plugins/pm-codex/plugin.json +1 -1
  190. package/runtime-dependencies.json +1 -1
  191. package/dist/cli-bundle/chunks/chunk-444VPGQT.js +0 -20
  192. package/dist/cli-bundle/chunks/chunk-5ZPT67NJ.js +0 -127
  193. package/dist/cli-bundle/chunks/chunk-7C3GCLOO.js +0 -30
  194. package/dist/cli-bundle/chunks/chunk-HMJSFWHK.js +0 -2
  195. package/dist/cli-bundle/chunks/chunk-RLXK2S7P.js +0 -2
  196. package/dist/cli-bundle/chunks/chunk-RQKDANP7.js +0 -113
  197. package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +0 -2
  198. package/dist/cli-bundle/chunks/chunk-XYLBOXSH.js +0 -6
  199. package/dist/cli-bundle/chunks/indexed-receipt-blobs-47I6KKDO.js +0 -4
  200. package/dist/cli-bundle/chunks/register-mutation-JZVVJUHY.js +0 -20
  201. package/dist/cli-bundle/focused-chunks/chunk-5LBZR6YW.js +0 -2
  202. package/dist/cli-bundle/focused-chunks/chunk-IVLIUPVV.js +0 -12
  203. package/dist/cli-bundle/focused-chunks/chunk-KIIGME23.js +0 -2
  204. package/dist/cli-bundle/focused-chunks/chunk-LWJ2X75I.js +0 -78
  205. package/dist/cli-bundle/focused-chunks/chunk-MT5TYMEU.js +0 -3
  206. package/dist/cli-bundle/focused-chunks/chunk-NI5SG2M2.js +0 -2
  207. package/dist/cli-bundle/focused-chunks/chunk-QH5KMIYZ.js +0 -91
  208. package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +0 -2
  209. package/dist/cli-bundle/focused-chunks/chunk-W7MCCFYV.js +0 -2
  210. package/dist/cli-bundle/focused-chunks/chunk-WMPDY5ZU.js +0 -21
  211. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-YCLN2ZZG.js +0 -4
@@ -1,2 +0,0 @@
1
- import{constants as r}from"node:fs";import{lstat as d,open as u}from"node:fs/promises";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new t.Error().stack;n&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[n]="b063a672-991a-5251-a2f3-6a1c7bcafd2f")}catch{}})();var c={lstat:d,open:u};function b(t){return t.O_NOFOLLOW??0}async function p(t,n,i=c){let l=await i.lstat(t);if(l.isSymbolicLink()||!l.isFile()||l.size>n)return null;let a=await i.open(t,r.O_RDONLY|b(r));try{let s=await a.stat();if(!s.isFile()||s.size>n)return null;let o=Buffer.alloc(s.size),e=0;for(;e<o.length;){let{bytesRead:f}=await a.read(o,e,o.length-e,e);if(f===0)break;e+=f}return(await a.stat()).size===s.size&&e===s.size?o.toString("utf8",0,e):null}finally{await a.close()}}export{p as a};
2
- //# sourceMappingURL=chunk-RUKSEZE7.js.map
@@ -1,6 +0,0 @@
1
- import{A as ge,Ab as fo,B as Jn,Bb as Ke,C as Zn,Cc as wo,D as ze,E as eo,F as to,I as ro,J as no,Rb as ho,T as oo,Tb as po,U as io,Vb as yo,Wb as go,X as so,ab as mo,d as wn,da as ao,ea as co,f as ye,g as V,h as Tn,ha as lo,i as Mn,ia as It,ja as kt,ka as Ve,p as St,ra as uo,s as Yn,w as Xn,yc as _o}from"./chunk-444VPGQT.js";import{Ad as Un,Bd as Gn,Cd as Ge,Dd as $n,E as Oe,Ed as $e,Fd as We,G as je,Gd as Be,H as kn,Hd as Wn,I as he,J as pe,K as Rn,L as xn,Ld as Bn,M as qe,Mc as Dn,Md as Et,Nb as Fn,Nc as Pn,O as An,P as Cn,Pc as Hn,Qc as Ln,Sc as vt,Tc as On,Vd as zn,a as N,c as bn,cd as Ne,d as ee,e as bt,f as vn,gd as Ue,i as En,if as Kn,jf as Qn,p as Sn,rd as jn,sd as qn,u as te,wd as Nn,x as Le,ze as Vn}from"./chunk-5ZPT67NJ.js";import{$c as ce,$h as pn,Ba as B,Bh as yt,C as ae,Cd as J,Cg as on,D as Re,Da as Ae,Dh as cn,Ee as Vr,Eg as le,Fe as Kr,Ff as Te,Fi as In,Gf as ht,H as xe,Hf as tn,I as Nr,If as rn,Ih as ln,Je as Qr,Jg as sn,Jh as dn,Kg as Fe,Kh as un,Le as Yr,Lg as De,Lh as mn,Oc as R,Pa as P,Rf as H,Rh as z,Se as I,Sh as fn,Uh as gt,Vc as $r,Ve as Ce,Vh as ue,Wc as mt,We as Xr,Wh as me,Xe as Jr,Xh as _t,Ye as ft,Yh as L,Zc as Y,Zh as hn,_c as Wr,_h as fe,bg as C,cf as Zr,cg as pt,ci as wt,fi as yn,gd as X,gi as He,hi as gn,ii as _n,jd as Br,mf as en,mg as q,og as Z,oh as Pe,pa as G,pd as zr,ph as an,qh as de,v as ut,xa as A,xg as Me,ya as Ur,za as Gr,zg as nn,zi as O}from"./chunk-RQKDANP7.js";import{A as f,C as h,E as ke,G as qr,K as j,u as jr}from"./chunk-3CYXE6BV.js";import vo from"node:fs/promises";import Eo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function Wi(e,t,r){let n=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||n.has(s))continue;n.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=r){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function Bi(e,t){let r=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),n=[];for(let o of r){if(t.scope==="closed"&&o.bucket!=="closed"){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return n}function bo(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return Wi(t.ids,r,t.minEntries)}return Bi(e,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]="c6009e5f-840e-5e3a-b8b9-6e9d42d63410")}catch{}})();function zi(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let r=e.trim();if(r.length===0)throw new h("history-compact --before requires a non-empty value.",f.USAGE);if(/^\d+$/.test(r)){let i=Number.parseInt(r,10),s=N(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new h(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,f.USAGE);let a=i-s-1;return{kind:"version",raw:r,compactCount:a,retainedCount:t.length-a}}let n=Date.parse(r);if(!Number.isFinite(n))throw new h(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,f.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new h(`History for this item contains invalid timestamp at entry ${i+1}.`,f.GENERIC_FAILURE);if(a>=n)break;o+=1}return{kind:"timestamp",raw:r,compactCount:o,retainedCount:t.length-o}}function Vi(e,t){let r=ue(),n=ue();for(let o=0;o<e.length;o+=1){let i=e[o];r=ee(r,i.patch,o+1,i.op),o+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function Ki(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:cn.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&_t(fe(e.document),n,C(r.hash_algorithm)).includes(r.after_hash))}}function Qi(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function Yi(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function Xi(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:r}=Vi(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),o=N(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=z({hashAlgorithm:C(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:L(ue()),after:L(t),message:Yi(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:ln(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[dn({...s,before_hash:_t(ue(),i.item_hash_version??1,C(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...n];return e.dryRun||a.push(z({nowIso:I(),author:e.author,op:"history_compact",before:L(r),after:L(r),message:Qi(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Ji(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await ye(r.path),s=await V(n,e,o,i.type_to_folder);return Ke({pmRoot:n,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>Zi(s,t,a)})}function Zi(e,t,r){let n=e.historyPath,o=r.entries,i=r.verification;if(!i.ok)throw new h(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,f.CONFLICT);let s=zi(t.before,o),a=s.compactCount>0,c=!!t.dryRun,d=r.author,l=[];a||l.push("history_compact_noop_before_boundary");let u=Ki(r.loadedItem,o);u.matchedChainBefore===!1&&l.push("history_compact_item_chain_mismatch");let{rewrittenEntries:m,baselineEntryAdded:p,auditEntryAdded:g}=Xi({historyEntries:o,boundary:s,changed:a,dryRun:c,author:d,options:t}),_=N(o,!0),y=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:a,rewrittenEntries:m,report:({verification:w,warnings:v})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:y},history:{path:n,entries_scanned:o.length,entries_after:m.length,baseline_entry_added:p,audit_entry_added:g,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...l,...v])].sort((b,E)=>b.localeCompare(E)),generated_at:I()})}}var es=3;function ts(e){for(let r of["allOver","minEntries"]){let n=e[r];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new h(`history-compact ${r} must be a non-negative safe integer.`,f.USAGE)}let t=Ln(e.ids);if(e.ids!==void 0&&t==="")throw new h("history-compact ids requires at least one valid item ID.",f.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Hn(t)}}function il(e,t){let r=t.ids!==void 0&&t.ids.length>0,n=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(r?1:0)+(n?1:0)==0)throw new h("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",f.USAGE);if(e!==void 0&&(r||n))throw new h("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",f.USAGE);if(r&&n)throw new h("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",f.USAGE)}function rs(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function ns(e){let t=q(e.settings.schema),r=ze(t),n=await qe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(n.map(d=>[d.id,r.classify(d.status)])),i=Eo.join(e.pmRoot,"history"),s=[],a=[];if(!await ke(i))return{candidates:s,preselectionErrors:a};let c=(await vo.readdir(i)).filter(d=>d.endsWith(".jsonl")).sort((d,l)=>d.localeCompare(l));for(let d of c){let l=Eo.join(i,d),u=d.slice(0,-6);try{let m=await vo.readFile(l,"utf8");await ce({path:l,scope:"project"}),s.push({id:u,entries:rs(m),bucket:o.get(u)??null})}catch(m){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:m instanceof Error?m.message:String(m)})}}return{candidates:s,preselectionErrors:a}}async function os(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Ji(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function sl(e,t){let r=ts(e),{pmRoot:n,settings:o,typeRegistry:i}=await ye(t.path),{candidates:s,preselectionErrors:a}=await ns({pmRoot:n,settings:o,typeToFolder:i.type_to_folder}),c=r.ids!==void 0&&r.ids.length>0?"ids":"scan",d=e.minEntries??es,l=o.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&l.enabled,m=e.allOver??(u?l.max_entries:void 0),p=bo(s,{ids:r.ids,scope:e.scope,minEntries:d,allOver:m}),g=!!e.dryRun,_=[...a],y={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of p){let v=await os({row:w,options:r,dryRun:g,global:t});if(_.push(v.result),!v.selected){y.items_skipped+=1;continue}y.selected+=1,v.compacted&&(y.items_compacted+=1),v.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:g,mode:c,scope:e.scope??null,criteria:{min_entries:d,all_over:m??null,policy_threshold_applied:u},totals:y,results:_,generated_at:I()}}import Rt from"node:fs/promises";(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]="ebf3254f-1fed-5972-b91a-b8ff101675f4")}catch{}})();function xt(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function Io(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function ko(e){let t=e.trim();if(t.length===0)throw new h("history-redact --regex requires a non-empty pattern.",f.USAGE);let r=t,n="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(r=t.slice(1,o),n=Io(t.slice(o+1)))}if(r.length===0)throw new h("history-redact --regex cannot use an empty pattern.",f.USAGE);try{new RegExp(r,n)}catch{throw new h("Invalid --regex value; provide a valid JavaScript regular expression.",f.USAGE)}return{kind:"regex",source:r,flags:n}}function Ro(e,t){let r=[...new Set(xt(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),n=[...new Set(xt(t).map(i=>i.trim()))].filter(i=>i.length>0).map(ko),o=[...r,...n];if(o.length===0)throw new h("history-redact requires at least one matcher via --literal or --regex.",f.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function xo(e,t,r){if(t.length===0)return{value:e,replacements:0};let n=0,o=0;for(;n<=e.length;){let i=e.indexOf(t,n);if(i===-1)break;o+=1,n=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(r),replacements:o}}function Ao(e,t,r){let n=new RegExp(t.source,t.flags),o=[...e.matchAll(n)];return o.length===0?{value:e,replacements:0}:{value:e.replace(n,r),replacements:o.length}}function At(e,t,r){let n=e,o=0;for(let i of t){let s=i.kind==="literal"?xo(n,i.value,r):Ao(n,i,r);n=s.value,o+=s.replacements}return{value:n,replacements:o}}function _e(e,t,r){if(typeof e=="string")return At(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(o=>{let i=_e(o,t,r);return n+=i.replacements,i.value}),replacements:n}}if(typeof e=="object"&&e!==null){let n=0,o={};for(let[i,s]of Object.entries(e)){let a=_e(s,t,r);n+=a.replacements,o[i]=a.value}return{value:o,replacements:n}}return{value:e,replacements:0}}function So(e,t,r){let n=0;return{patch:e.map(o=>{if(!Object.prototype.hasOwnProperty.call(o,"value"))return o;let i=_e(o.value,t,r);return n+=i.replacements,i.replacements>0?{...o,value:i.value}:o}),replacements:n}}function is(e){let t=structuredClone(gt),r=0,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];me(t,void 0,C(i.hash_algorithm))!==i.before_hash&&(r+=1),t=ee(t,i.patch,o+1,i.op),me(t,void 0,C(i.hash_algorithm))!==i.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function ss(e,t,r){let n=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let d=At(e.message,t,r);s=d.value,n+=d.replacements,d.replacements>0&&(o=!0)}let a=So(e.patch,t,r);n+=a.replacements,o||=a.replacements>0;let c=e.reanchor_evidence?.map(d=>{let l=d.patch?So(d.patch,t,r):{patch:void 0,replacements:0},u=d.record?_e(d.record,t,r):{value:void 0,replacements:0};n+=l.replacements,n+=u.replacements;let m=l.replacements>0||u.replacements>0;if(o||=m,!m)return d;i=!0;let{patch:p,record:g,record_hash:_,record_hash_version:y,...w}=d;return l.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:n,changed:o,reanchorEvidenceRedacted:i}}function as(e,t,r){let n=structuredClone(gt),o=0,i=0,s=[];for(let a=0;a<e.length;a+=1){let c=e[a],d=un(c);if(!d.ok)throw new h(`history-redact refuses invalid immutable record ${a+1} (${d.error}).`,f.GENERIC_FAILURE);let l=ss(c,t,r);i+=l.replacements,l.changed&&(o+=1);let u=me(n,void 0,C(c.hash_algorithm));n=ee(n,l.entry.patch,a+1,l.entry.op);let m=me(n,void 0,C(c.hash_algorithm));s.push(mn(c,{...l.entry,before_hash:u,after_hash:m},{retainPriorRecord:l.changed,retainPriorRecordHash:!l.changed}))}return{entries:s,finalDocument:n,entriesChanged:o,replacements:i}}function Co(e){return Object.keys(e.metadata).length>0}function cs(e){if(!Co(e.finalDocument))return{raw:null,path:null,document:null};let t=De(L(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new h("history-redact would change the item id; narrow your patterns.",f.USAGE);return{document:t,path:B(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Fe(t,{format:"toon",schema:e.settings.schema})}}function ls(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function ds(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??L(e.rewritten.finalDocument);return t.push(z({nowIso:I(),author:e.author,op:"history_redact",before:r,after:r,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function us(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Oe(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await j(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Rt.rm(e.currentItem.path,{force:!0}),await j(e.subject.historyPath,yn(e.rewrittenEntries))}catch(c){try{await ms(e.subject.historyPath,r,o,i)}finally{await yt(e.subject.historyPath)}throw c}await yt(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await je({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await n().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await fs(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function ms(e,t,r,n){t===null?await Rt.rm(e,{force:!0}):await j(e,t);for(let o of r){let i=n.get(o);i===void 0?await Rt.rm(o,{force:!0}):await j(o,i)}}async function fs(e,t){let r=[],n=new Set(t.filter(o=>o!==null));for(let o of n)r.push(...await Y({path:o,scope:"project",op:"history_redact"}));return r.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),r}async function kl(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await ye(r.path),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,d=Ro(t.literal,t.regex),l=await V(n,e,o,i.type_to_folder);return Ke({pmRoot:n,subject:l,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>hs({pmRoot:n,subject:l,settings:o,typeRegistry:i,options:t,rules:d,replacement:c,replacementIsDefault:a},u)})}function hs(e,t){let{pmRoot:r,subject:n,settings:o,typeRegistry:i,options:s,rules:a,replacement:c,replacementIsDefault:d}=e,l=t.entries,u=is(l),m=as(l,a,c),p=u.hashMismatchesBefore+u.hashMismatchesAfter,g=!!s.dryRun,_=m.replacements>0,y=[];p>0&&y.push(`history_redact_preexisting_hash_mismatches:${p}`),_||y.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},v=cs({pmRoot:r,subject:n,settings:o,typeToFolder:i.type_to_folder,finalDocument:m.finalDocument}),b=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),E=t.author,S=ls(s,m),{rewrittenEntries:k,auditEntryAdded:x}=ds({rewritten:m,dryRun:g,changed:_,nextItemDocument:v.document,author:E,message:S});return{changed:_,rewrittenEntries:k,...us({pmRoot:r,subject:n,settings:o,typeRegistry:i,currentItem:w,nextItem:v,author:E,rewrittenEntries:k}),report:({verification:Q,warnings:lt})=>({id:n.id,dry_run:g,changed:_,patterns:{literal_count:a.filter(T=>T.kind==="literal").length,regex_count:a.filter(T=>T.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:n.historyPath,entries_scanned:l.length,entries_changed:m.entriesChanged,replacements:m.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:p,audit_entry_added:x,verify_ok:Q.ok,verify_errors:Q.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:b},warnings:[...new Set([...y,...lt])].sort((T,dt)=>T.localeCompare(dt)),generated_at:I()})}}var Rl={applyLiteralRule:xo,applyRegexRule:Ao,buildRedactionRules:Ro,hasItemMetadata:Co,normalizeRegexFlags:Io,normalizeStringArrayInput:xt,parseRegexRule:ko,redactStringValue:At,redactUnknownValue:_e};(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]="63c96190-0df9-5803-aa61-b973493a7277")}catch{}})();var Ct={format:"pm-history-attestation",version:1,stream_hash:"exact_file_bytes",rollup_hash:"stable_json_without_workspace_digest",ordering:"stream_id_code_unit_ascending",consistency:"per_stream_snapshot_with_change_detection",trust:"independently_retained_bundle"};import{createHash as ps}from"node:crypto";import{isUtf8 as ys}from"node:buffer";import we from"node:fs/promises";import Tt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function To(e){try{return(await we.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(qr(t))return[];throw t}}function gs(e,t,r,n){let o=t.at(-1),i;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){i=t[c];break}let s=t[0]?.context?.history_compaction,a=typeof s=="object"&&s!==null&&"pruned_stream_digest"in s&&typeof s.pruned_stream_digest=="string"?s.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:r,stream_digest:n,latest_after_hash:o?.after_hash??null,latest_record_hash:o?.record_hash??null,latest_hash_algorithm:o?C(o.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:i?{op:i.op,ts:i.ts,record_hash:i.record_hash??null}:null}}function _s(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!ys(t))return null;let n=[];for(let o of t.toString("utf8").split(/\r?\n/u)){if(!o.trim())continue;let i=JSON.parse(o);if(typeof i!="object"||i===null||Array.isArray(i))return null;let s=i;if(![s.op,s.author,s.ts,s.before_hash,s.after_hash].every(a=>typeof a=="string")||!Array.isArray(s.patch))return null;n.push(s)}return wt(n).ok?gs(e,n,t.length,r):null}catch{return null}}async function Mt(e,t){if(!(await we.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Tt.join(e,"history"),n=await To(r),o=new Map,i=[];for(let s of n){let a=s.slice(0,-6),c={id:a,digest:null,stream:null};i.push(c);let d=Tt.join(r,s);try{let l=await we.lstat(d);if(o.set(s,P([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await we.readFile(d);c.digest=ps(t).update(u).digest("hex"),c.stream=_s(a,u,c.digest)}catch{}}if(P(n)!==P(await To(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of o){let c=await we.lstat(Tt.join(r,s));if(a!==P([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return i}(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]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function Ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dt(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function re(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function ws(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:re(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||re(e.latest_record_hash,e.latest_hash_algorithm))}function bs(e){return e===null?!0:!Ft(e)||!Dt(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Ce(e.ts)&&(e.record_hash===null||re(e.record_hash,"sha256")||re(e.record_hash,"sha512"))}function vs(e,t){return!Ft(e)||!Dt(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(r=>typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&re(e.stream_digest,t)&&ws(e)&&(e.checkpoint_digest===null||re(e.checkpoint_digest,"sha256"))&&bs(e.last_maintenance)}function Mo(e){if(!Ft(e)||!Dt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Ct.format||e.version!==1||typeof e.generated_at!="string"||!Ce(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,r;for(let i of e.streams){if(!vs(i,t))throw new TypeError("Invalid history attestation stream");let s=i.id;if(r!==void 0&&s<=r)throw new TypeError("Invalid history attestation stream order");r=s}let{workspace_digest:n,...o}=e;if(pt(P(o),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function Fo(e={}){let t=C(e.hashAlgorithm),r=e.generatedAt??I();if(!Ce(r))throw new TypeError("Invalid history attestation timestamp");let n=await Mt(A(e.cwd??process.cwd(),e.pmRoot),t),o=n.filter(s=>s.stream===null);if(o.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${o.map(s=>s.id).join(", ")}`);let i={format:Ct.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return Mo({...i,workspace_digest:pt(P(i),t)})}async function Do(e,t={}){let r=Mo(e),n=await Mt(A(t.cwd??process.cwd(),t.pmRoot),r.hash_algorithm),o=new Map(n.map(l=>[l.id,l])),i=new Map(r.streams.map(l=>[l.id,l])),s=r.streams.filter(l=>!o.has(l.id)).map(l=>l.id),a=n.filter(l=>!i.has(l.id)).map(l=>l.id),c=n.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of r.streams){let u=o.get(l.id);u&&(u.digest!==l.stream_digest||P(u.stream)!==P(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+c.length+d.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:d.map(l=>l.id),missing_streams:s,added_streams:a,invalid_streams:c,transitions:d}}import Po from"node:fs/promises";(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]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function Xl(e,t){for(let n of["verify","output","hashAlgorithm"]){let o=e[n];if(!(n==="verify"&&typeof o=="object"&&o!==null)&&o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new h(`history attest ${n} requires a nonempty string.`,f.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new h("history attest --verify cannot be combined with --output or --hash-algorithm",f.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await Po.readFile(e.verify,"utf8")):e.verify}catch{throw new h("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",f.USAGE)}return Do(n,{pmRoot:t.path})}let r=await Fo({pmRoot:t.path,hashAlgorithm:C(e.hashAlgorithm)});if(e.output===void 0)return r;try{await Po.writeFile(e.output,`${JSON.stringify(r,null,2)}
2
- `,{flag:"wx",mode:384})}catch{throw new h("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",f.USAGE)}return{output:e.output,workspace_digest:r.workspace_digest,streams:r.streams.length}}import Es from"fast-json-patch";import Pt from"node:fs/promises";(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]="ce212ffb-1f13-5893-9690-31dbb4e0de13")}catch{}})();async function Ho(e,t,r){let n=await Rn(e,{schema:t.schema});return n.error===null?{raw:n.raw,document:n.document}:{raw:n.raw,document:Lo(r),recovered:!0}}function Ss(e,t){return bn(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Lo(e){let t=bt(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:De(L(t))}async function Is(e,t,r,n){let o=await V(e,t,r,n),i=o.located?await Le({pmRoot:e,settings:r,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function ks(e,t){let r=fe(e),n=fe(t),o=Es.compare(r,n),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function Rs(e){let t=await fo({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:r=>Ho(r,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function xs(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Lo(t),originalRaw:null}}function As(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new h(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,f.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function Cs(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await j(e.existingItemPath,e.resolvedOriginalRaw),await Pt.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await j(e.existingItemPath,e.resolvedOriginalRaw);return}await Pt.rm(e.restoredItemPath,{force:!0})}async function Ts(e){return[...await Y({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await Y({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function hd(e,t,r,n){let o=A(process.cwd(),n.path);await H(o);let i=await O(o),s=G(i,R()),a=await Is(o,e,i,s.type_to_folder),c=a.id,{raw:d,entries:l}=await an(a.historyPath,c);if(l.length===0)throw new h(`No history exists for ${c}; restore is unavailable.`,f.NOT_FOUND);let u=Ss(t,l),m=vn(bt(l,u.historyIndex),u),p=hn(m,{schema:i.schema});if(p.metadata.id!==c)throw new h(`Restore target resolved to item ${p.metadata.id}, expected ${c}.`,f.GENERIC_FAILURE);let g=(a.located?await Ho(a.located,i,l):null)?.raw??null,_=Pe(r.author,i.author_default),y=await Zr(o,c,i.locks.ttl_seconds,_,!!r.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms,{waitPolicy:"progress"}),w=y.release;try{let{loadedItemUnderLock:v,existingItemPath:b}=await Rs({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:d,currentItemRawBeforeLock:g,history:l}),E="toon",S=xs(v,l);p.metadata.pm_format_version=nn(Math.max(Me(p.metadata),Me(S.document.metadata))),In(Ur(o),Me(p.metadata));let k=As({document:S.document,author:_,force:r.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),x=ks(S.document,p),Q=await Sn({pmRoot:o,settings:i,operation:"restore",author:_,before:S.document,after:p});await Wr({pm_root:o,operation:"restore",before:S.document,after:p,changed_fields:x,sdk:An({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let lt=Fe(p,{format:E,schema:i.schema}),T=B(o,p.metadata.type,c,E,s.type_to_folder),dt=await y.fence(async()=>{let Ui=await Oe(o,_),Or;try{await j(T,lt),b&&T!==b&&await Pt.rm(b);let Gi=z({nowIso:I(),author:_,op:"restore",before:S.document,after:p,message:r.message,context:Q.decisions.length===0?void 0:{workflow_policies:Q.decisions}});try{await fn(a.historyPath,Gi)}catch($i){throw await Cs({existingItemPath:b,resolvedOriginalRaw:S.originalRaw,restoredItemPath:T}),$i}Or=await je({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:T,previousItemPath:b??void 0,document:p})}finally{await Ui()}return Or}),Ni=await Ts({restoredItemPath:T,historyPath:a.historyPath,before:S.document,after:p});$r({id:p.metadata.id,op:"restore",item_type:p.metadata.type,previous_status:S.document.metadata.status,status:p.metadata.status,previous:mt(S.document.metadata,x),current:mt(p.metadata,x),changed_fields:x});let Hr=l[u.historyIndex],Lr=N(l,!0);return{item:p.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:Lr===null?null:Lr+u.historyIndex+1,entry_ts:Hr.ts,entry_op:Hr.op},changed_fields:x,warnings:[...Q.warnings,...v?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...k,...dt,...Ni]}}finally{await w()}}(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]="190eb119-9510-59d6-bb3a-d1f807c68281")}catch{}})();var Ms=["status","type","tag","priority","deadlineBefore","deadlineAfter","updatedAfter","updatedBefore","createdAfter","createdBefore","ids","assignee","assigneeFilter","parent","sprint","release"],Fs=["filterAcMissing","filterEstimatesMissing","filterResolutionMissing","filterMetadataMissing","filterReviewerMissing","filterRiskMissing","filterConfidenceMissing","filterSprintMissing","filterReleaseMissing","hasNotes","hasLearnings","hasFiles","hasDocs","hasTests","hasComments","hasDeps","hasBody","hasLinkedCommand","noNotes","noLearnings","noFiles","noDocs","noTests","noComments","noDeps","emptyBody","noLinkedCommand"];function Ds(e){return e!=null&&(typeof e!="string"||e.split(",").some(t=>t.trim().length>0))}function yd(e,t,r={}){let n=r.includePagination!==!1;return[t,...Ms.map(o=>e?.[o]),...n?[e?.limit,e?.offset]:[]].some(Ds)||Fs.some(o=>e?.[o]===!0)}function Oo(e){return{type:e.type,tag:e.tag,priority:e.priority,deadlineBefore:e.deadlineBefore,deadlineAfter:e.deadlineAfter,assignee:e.assignee,assigneeFilter:e.assigneeFilter,parent:e.parent,sprint:e.sprint,release:e.release}}(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]="59f55926-8d04-52f8-a7fc-d32edd32b760")}catch{}})();var jo=["parent","type","priority","status","assignee","tags","sprint","release"];function No(e,t){let r=Ne(e,t,{strict:!0,flagLabel:"--status"});if(!(!r||r.length===0))return r}function Uo(e,t=["estimate","estimated_minutes","priority"]){let r=e.sum?.trim(),n=e.avg?.trim(),o=r&&r.length>0?r:void 0,i=n&&n.length>0?n:void 0;if(!o&&!i)return null;if(o&&i&&o!==i)throw new h("Aggregate --sum and --avg must target the same numeric field",f.USAGE);let s=o??i;if(!t.includes(s))throw new h(`Aggregate numeric field "${s}" is not registered. Allowed: ${t.join(", ")}`,f.USAGE);return{field:s,sum:o!==void 0,avg:i!==void 0}}function Go(e){let t=e?.trim()??"status";if(t.length===0)throw new h("--group-by requires at least one field name",f.USAGE);let r=Vn(t);if(r.length===0)throw new h("--group-by requires a comma-separated list of fields",f.USAGE);for(let n of r)if(!jo.includes(n))throw new h(`Aggregate group fields must be one of ${jo.join("|")}; received "${n}"`,f.USAGE);return r}function $o(e){let t=[...new Set(e.map(r=>r.trim().toLowerCase()).filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n));return t.length===0?null:t.join(",")}function Wo(e,t){switch(e){case"parent":return t.parent??null;case"type":return t.type;case"priority":return t.priority;case"status":return t.status;case"assignee":return t.assignee??null;case"tags":return $o(t.tags);case"sprint":return t.sprint??null;case"release":return t.release??null;default:return null}}function Bo(e,t){let r=e??null,n=t??null;return r===n?0:r===null?1:n===null?-1:typeof r=="number"&&typeof n=="number"?r-n:String(r).localeCompare(String(n))}function Qe(e,t){return e.map(r=>`${r}:${JSON.stringify(t[r]??null)}`).join("|")}var Ps={parent:"(unparented)",type:"(untyped)",priority:"(no priority)",status:"(no status)",assignee:"(unassigned)",tags:"(untagged)",sprint:"(no sprint)",release:"(no release)"};function qo(e,t){return t==null||t===""?Ps[e]:String(t)}function Hs(e,t){return e.length===1?qo(e[0],t[e[0]]):e.map(r=>`${r}=${qo(r,t[r])}`).join(" | ")}function zo(e,t,r){for(let n of r){let o=Bo(e.group[n],t.group[n]);if(o!==0)return o}return 0}function Vo(e,t){let r=e[t];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let n=r.trim();if(n.length===0)return null;let o=Number(n);if(Number.isFinite(o))return o}return null}function Ko(e,t){return t<=0?0:Math.round(e/t*1e4)/100}function Ht(e,t,r){let n=on(String(t),r)??t;if(n===r.open_status){e.open_count+=1;return}if(n==="in_progress"||r.active_statuses.has(n)&&n!==r.open_status){e.in_progress_count+=1;return}if(r.terminal_done_statuses.has(n)||n===r.close_status){e.closed_count+=1;return}e.other_count+=1}function Ls(e,t){return{row:{group:e,count:1},numeric_count:t===null?0:1,numeric_sum:t??0,null_count:t===null?1:0,open_count:0,in_progress_count:0,closed_count:0,other_count:0}}function Os(e,t){if(t===null){e.null_count+=1;return}e.numeric_count+=1,e.numeric_sum+=t}function js(e){e.accumulator.row.count+=1,e.includeCompletion&&Ht(e.accumulator,e.item.status,e.statusRegistry),e.numericAggregation!==null&&Os(e.accumulator,e.numericValue)}function qs(e,t,r,n){for(let o of t){let i=Qe(r,o),s=e.get(i);if(s){js({...n,accumulator:s});continue}let a=Ls(o,n.numericValue);n.includeCompletion&&Ht(a,n.item.status,n.statusRegistry),e.set(i,a)}}function Ns(e,t){let r={};for(let n of e)r[n]=Wo(n,t);return r}function Us(e,t,r){let n=[Ns(e,t)];if(r==="tuple")return n;for(let o of e){let i=t[o];if(!Array.isArray(i))continue;let s=[...new Set(i.map(a=>a.trim().toLowerCase()).filter(Boolean))].sort();s.length!==0&&(n=n.flatMap(a=>s.map(c=>({...a,[o]:c}))))}return n}function Gs(e,t,r,n){let o={...e.row,group_label:Hs(t,e.row.group)};return r&&(o.open=e.open_count,o.in_progress=e.in_progress_count,o.closed=e.closed_count,o.other=e.other_count,o.completion_pct=Ko(e.closed_count,e.row.count)),n!==null&&(o.null_count=e.null_count,n.sum&&(o.sum=e.numeric_sum),n.avg&&(o.avg=e.numeric_count===0?null:e.numeric_sum/e.numeric_count)),o}function $s(e){return{group_by:e.groupBy,set_mode:e.setMode,count:!0,completion:e.includeCompletion,include_unparented:e.includeUnparented,status:e.status?.[0]??null,status_values:e.status,type:e.options.type??null,tag:e.options.tag??null,priority:e.options.priority??null,deadline_before:e.options.deadlineBefore??null,deadline_after:e.options.deadlineAfter??null,assignee:e.options.assignee??null,assignee_filter:e.options.assigneeFilter??null,parent:e.options.parent??null,sprint:e.options.sprint??null,release:e.options.release??null,...e.numericAggregation!==null?{sum:e.options.sum??null,avg:e.options.avg??null,numeric_field:e.numericAggregation.field}:{}}}async function Ed(e,t){if(e.count===!1)throw new h("Aggregate grouped counts are always enabled; omit count=false.",f.USAGE);let r=A(process.cwd(),t.path),n=await O(r),o=q(n.schema),i=["estimate","estimated_minutes","priority",...Z(n.schema).definitions.filter(b=>b.type==="number").map(b=>b.metadata_key)],s=Go(e.groupBy),a=e.setMode??"element";if(a!=="element"&&a!=="tuple")throw new h("Aggregate --set-mode must be element or tuple",f.USAGE);let c=No(e.status,o),d=Uo(e,[...new Set(i)].sort((b,E)=>b.localeCompare(E))),l=e.completion===!0,u=e.includeUnparented===!0,m=await Ve(void 0,{...Oo(e),status:e.status,noTruncate:!0,strictRead:!0},t),p=new Map,g=0,_=0,y=0;for(let b of m.items){let E=b;if(s.includes("parent")&&E.parent===void 0&&!u){g+=1;continue}let S=d===null?null:Vo(E,d.field),k=Us(s,E,a);qs(p,k,s,{item:E,statusRegistry:o,includeCompletion:l,numericAggregation:d,numericValue:S}),y+=k.length,_+=1}let w=[...p.values()].map(b=>Gs(b,s,l,d)).sort((b,E)=>zo(b,E,s)),v=m.warnings&&m.warnings.length>0?m.warnings:void 0;return{...Ws(w,s,e),count:w.length,totals:{items_considered:m.items.length,items_grouped:_,items_skipped_unparented:g,group_memberships:y},filters:$s({groupBy:s,setMode:a,includeCompletion:l,includeUnparented:u,status:c,options:e,numericAggregation:d}),now:I(),...v?{warnings:v}:{}}}function Ws(e,t,r){let n=uo(r.limit,"limit")??50,o=r.after===void 0?-1:e.findIndex(a=>Qe(t,a.group)===r.after);if(r.after!==void 0&&o<0)throw new h("Aggregate --after cursor is absent from the current grouping; restart without --after.",f.USAGE);let i=e.slice(o+1,o+1+n),s=o+1+i.length<e.length;return{groups:i,returned_count:i.length,truncated:s,next_after:s?Qe(t,i.at(-1).group):null}}var Sd={buildGroupKey:Qe,compareAggregateRows:zo,compareNullableGroupValue:Bo,completionPct:Ko,normalizeTagGroupValue:$o,parseGroupBy:Go,parseNumericAggregation:Uo,parseStatus:No,readNumericAggregateValue:Vo,resolveGroupValue:Wo,updateCompletionCounts:Ht};(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]="21742dd3-12b5-5285-89d8-036693459eb8")}catch{}})();var Qo=1e6,Yo=20;function Xo(e,t,r,n=Yo){if(!Number.isSafeInteger(n)||n<0)throw new h("Child projection sample limit must be a non-negative integer.",f.USAGE);let o=e.trim().toLowerCase(),i={},s=[],a=0;for(let y of t){if(a+=1,a>Qo)throw new h(`Child projection exceeded the ${Qo.toLocaleString("en-US")} item safety bound.`,f.GENERIC_FAILURE,{code:"child_projection_item_bound_exceeded",required:"Use an indexed or parent-filtered metadata source.",why:"Unbounded graph scans can exhaust memory in universal project stores.",nextSteps:["Build the derived item index, then retry the parent read."]});s.push(y)}let c=new Map(s.map(y=>[y.id.trim().toLowerCase(),y])),d=so(io(s,oo())),l=new Set(d.children_by_parent.get(o)??[]);for(let y of s)y.parent?.trim().toLowerCase()===o&&l.add(y.id.trim().toLowerCase());let u=[...l].map(y=>c.get(y)),m=0;for(let y of u){let w=y.status.trim().toLowerCase();i[w]=(i[w]??0)+1,le(w,r)||(m+=1)}u.sort((y,w)=>y.id.localeCompare(w.id));let p=u.slice(0,n).map(y=>({id:y.id,title:y.title,type:y.type,status:y.status,priority:y.priority})),g=u.length>p.length,_=n===0?Yo:n;return{count:u.length,active:m,by_status:Object.fromEntries(Object.entries(i).sort(([y],[w])=>y.localeCompare(w))),sample:p,sample_limit:n,truncated:g,next_offset:g?p.length:null,continuation:g?`pm list --status all --parent ${e} --offset ${p.length} --limit ${_}`:null,scanned:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db3fe399-8eb8-5b17-8a9e-89eda4774234")}catch{}})();var Bs=new Set(["event","meeting","reminder"]);function zs(e){return Bs.has(e.type.trim().toLowerCase())||e.deadline!==void 0||(e.reminders?.length??0)>0||(e.events?.length??0)>0}function Lt(e){if(!zs(e))return;let t=[...e.events??[]].sort((n,o)=>n.start_at.localeCompare(o.start_at)),r=t[0];return{deadline:e.deadline??null,start_at:r?.start_at??null,end_at:r?.end_at??null,location:r?.location??null,reminders:[...e.reminders??[]],events:t}}import{readdir as Ks}from"node:fs/promises";import Ot from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1815b206-18b5-5e76-b863-8b0f8ac2947a")}catch{}})();var Qs=new Set(["epic","feature","milestone","plan"]),Ys=new Set(Object.keys(jr).map(e=>e.toLowerCase()));function qt(e){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(t=>[t,e[t]?.length??0]))}function Xs(e,t,r,n,o){let i=qt(e);return[...t.length>0?["body"]:[],...Object.entries(i).flatMap(([s,a])=>a>0?[s]:[]),...i.files+i.tests+i.docs>0?["linked"]:[],...r===void 0?["children"]:r.count>0?["children"]:[],...typeof e.assignee=="string"&&e.assignee.trim().length>0?["claim_state"]:[],...Lt(e)?["schedule"]:[],...n&&St(e).length>0?["blockers"]:[],...!o.full&&e.dependencies?.some(({id:s,kind:a,...c})=>Object.values(c).some(d=>d!==void 0))?["dependency_provenance"]:[]]}function Zo(e){let t=e.trim().toLowerCase();return t.length>0&&(Qs.has(t)||!Ys.has(t))}function Jo(e){return{ts:e.ts,author:e.author,message:e.message??null}}function Js(e,t){let r=e?.trim(),n=r&&r.length>0?r:null,o=[...t].reverse().find(s=>s.op==="claim"),i=[...t].reverse().find(s=>s.op==="release");return{claimed:n!==null,assignee:n,last_claim:o?Jo(o):null,last_release:i?Jo(i):null}}function Zs(e){if(e===void 0||e.trim().length===0)return"standard";let t=e.trim().toLowerCase();if(t==="full")return"deep";if(Te.includes(t))return t;throw new h("Get --depth must be one of brief|standard|deep|full",f.USAGE,{field:"depth",value:e,recovery:{allowed_values:[...Te,"full"]}})}function ea(e,t,r){let n=qt(e),o={...e};if(!r&&e.dependencies!==void 0&&(o.dependencies=e.dependencies.map(({id:g,kind:_})=>({id:g,kind:_}))),t==="deep")return{...o,comments:e.comments??[],notes:e.notes??[],learnings:e.learnings??[],files:e.files??[],tests:e.tests??[],docs:e.docs??[],reminders:e.reminders??[],events:e.events??[],notes_count:n.notes,tests_count:n.tests,collection_counts:n};let{comments:i,notes:s,learnings:a,files:c,tests:d,docs:l,reminders:u,events:m,...p}=o;return{...p,notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:n}}function ta(e){if(e===void 0)return null;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new h("Get --fields requires a comma-separated list of field names",f.USAGE);return t}function Ye(e){return e.startsWith("item.")?e.slice(5):e}function ra(e,t,r){if(e===null)return;let n=ht(t),o=new Set(n),i=e.filter(s=>{let a=Ye(s);return!o.has(s)&&!o.has(a)});if(i.length>0){let s=["get",r,"--fields",e.filter(a=>!i.includes(a)).join(",")||"id,title,status"];throw new h(`Unknown get --fields value(s): ${i.join(", ")}`,f.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:n,suggested_retry:J(s),suggested_retry_args:s}})}}var na=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function oa(e,t,r){return Object.hasOwn(t,r)?t[r]:e[r]!==void 0?e[r]:na.has(r)?[]:void 0}function ia(e,t){let r=e,n={notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:qt(e)},o={id:e.id};for(let i of t){let s=Ye(i);s==="body"||s==="linked"||s.startsWith("linked.")||s==="claim_state"||s.startsWith("claim_state.")||s==="children"||s.startsWith("children.")||s==="schedule"||s.startsWith("schedule.")||s==="blockers"||(o[s]=oa(r,n,s))}return o}function be(e,t){return e?.some(r=>r===t||r===`item.${t}`)??!1}function ne(e,t){return e.some(r=>{let n=Ye(r);return n===t||n.startsWith(`${t}.`)})}function sa(e,t){if(e.full&&(e.fields!==void 0||e.depth!==void 0))throw new h("Get projection options are mutually exclusive; remove the extra projection flag and retry.",f.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:J(["get",t,"--full"]),suggested_retry_args:["get",t,"--full"]}});if(e.tree!==!0&&e.treeDepth!==void 0)throw new h("Get --tree-depth requires --tree",f.USAGE);if(e.at!==void 0&&e.tree===!0)throw new h("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",f.USAGE);return{depth:e.full?"deep":Zs(e.depth),full:e.full===!0||e.depth?.trim().toLowerCase()==="full",treeDepth:e.tree===!0?Xn(e.treeDepth,"--tree-depth"):void 0,fields:ta(e.fields),fieldProjection:e.fields!==void 0}}async function aa(e,t,r){let n=A(process.cwd(),t.path);await H(n);let o=await O(n),i=G(o,R());if(r!==void 0){let c=await Mn(e,r,{pmRoot:t.path});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:c.document.metadata.id,metadata:c.document.metadata,body:c.document.body,historical:c}}let s=await he(n,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await Cn(n,e,o.id_prefix,i.type_to_folder);let a=await pe(s,{schema:o.schema});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:s.id,metadata:a.document.metadata,body:a.document.body}}function ca(e,t,r,n){let o=[...Z(t.schema).definitions.map(i=>i.metadata_key),...te(R())];if(ra(e,o,n),r&&ne(e??[],"children"))throw new h("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",f.USAGE);if(r&&ne(e??[],"blockers"))throw new h("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",f.USAGE)}function jt(e){let{fieldProjection:t,depth:r,fields:n,field:o}=e;return t?o==="body"||o==="linked"?be(n,o):ne(n,o):r!=="brief"}async function la(e,t){if(!t)return;let r=Ae(e.pmRoot,e.locatedId),n=await de(r,e.locatedId);return Js(e.metadata.assignee,e.historical?n.slice(0,e.historical.target.historyIndex+1):n)}function da(e,t,r,n){let o=n||be(r,"linked.files"),i=n||be(r,"linked.tests"),s=n||be(r,"linked.docs");!n&&!o&&!i&&!s||(e.linked={files:o?t.metadata.files??[]:[],tests:i?t.metadata.tests??[]:[],docs:s?t.metadata.docs??[]:[]})}async function ua(e,t){if(!t)return;let r=q(e.settings.schema),n=await qe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema);return Xo(e.locatedId,n,r)}function ma(e,t){let r=new Map;for(let n of e){let o=n.external?n.id:t.get(n.id.toLowerCase())?.id??n.id;r.set(n.external?`external:${o}`:`local:${o.toLowerCase()}`,{...n,id:o})}return[...r.values()]}async function fa(e,t){let r=Ot.basename(e),n=(await Ks(Ot.dirname(e)).catch(o=>{throw wn("Cannot verify the blocker's physical file identity",{exitCode:f.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:o})})).filter(o=>o.toLowerCase()===r.toLowerCase()).sort((o,i)=>+(i===r)-+(o===r)||o.localeCompare(i)).map(o=>Ot.parse(o).name)[0];if(n===void 0)throw new h(`Blocker canonical file disappeared during identity verification: ${t}`,f.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return n}async function ha(e,t,r){if(t.historical!==void 0||!(r.fieldProjection?ne(r.fields,"blockers"):r.depth!=="brief"))return;let n=St(t.metadata);if(n.length===0)return;let o=new Map([t.metadata.blocked_by,...(t.metadata.dependencies??[]).filter(a=>a.kind==="blocked_by").map(a=>a.id)].filter(a=>typeof a=="string").map(a=>[a.trim().toLowerCase(),a.trim()])),i=new Map;for(let a of n){if(Kn(a)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(a)||t.metadata.dependencies?.some(l=>l.id.trim()===a&&l.kind==="blocked_by"&&Qn(l.source_kind)))continue;let c=await he(t.pmRoot,o.get(a),t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(c===null)continue;let d=await pe(c,{schema:t.settings.schema});if(c.id=await fa(c.itemPath,c.id),d.document.metadata.id!==c.id)throw new h(`Blocker identity differs from its canonical file: ${c.id}`,f.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});i.set(a.toLowerCase(),d.document.metadata)}let s=ma(Yn({blocked_by:t.metadata.blocked_by,dependencies:t.metadata.dependencies,updated_at:t.metadata.updated_at},i,q(t.settings.schema)),i);e.blockers={scope:"declared",open:s.filter(a=>!a.resolved).map(({resolved:a,...c})=>c),closed_count:s.filter(a=>a.resolved).length},!r.fieldProjection&&!r.full&&delete e.item.blocked_by}function pa(e,t,r,n){if(!n)return;let o=Lt(t.metadata);if(o){if(r===null||be(r,"schedule")){e.schedule=o;return}e.schedule=Object.fromEntries(Object.entries(o).filter(([i])=>r.some(s=>Ye(s)===`schedule.${i}`)))}}async function ya(e,t,r,n){if(t.tree!==!0)return;let o=await Ve(void 0,{parent:e.locatedId,tree:!0,treeDepth:r===void 0?void 0:String(r),full:!0},n);return{root_id:e.locatedId,root_title:e.metadata.title,depth_limit:r??null,count:o.count,items:o.items.map(i=>i)}}async function Xd(e,t,r={}){let n=sa(r,e),o=await aa(e,t,r.at);ca(n.fields,o.settings,o.historical!==void 0,o.locatedId);let i=jt({...n,field:"body"}),s=jt({...n,field:"linked"}),a=jt({...n,field:"claim_state"}),c=o.historical===void 0&&(n.fieldProjection?ne(n.fields,"children"):n.depth==="deep"&&(n.full||Zo(o.metadata.type))),d=n.fieldProjection?ne(n.fields,"schedule"):n.depth!=="brief",l=await la(o,a),u={item:n.fieldProjection?ia(o.metadata,n.fields):ea(o.metadata,n.depth,n.full)};i&&(u.item.body=o.body),da(u,o,n.fields,s),l&&(u.claim_state=l),pa(u,o,n.fields,d),await ha(u,o,n);let m=await ua(o,c);m!==void 0&&(u.children=m);let p=await ya(o,r,n.treeDepth,t);if(p!==void 0&&(u.tree=p),o.historical&&(u.reconstructed=!0,u.as_of_version=o.historical.as_of_version,u.as_of_timestamp=o.historical.as_of_timestamp),o.historical===void 0)try{await en({pmRoot:o.pmRoot,author:Pe(void 0,o.settings.author_default),itemIds:[o.locatedId],intent:"get"})}catch{}return Br(u,n.fieldProjection?[]:Xs(o.metadata,o.body,m,o.historical===void 0,n)),u}var Jd={shouldAutoIncludeGetChildren:Zo};(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]="9c9c1249-e52a-5203-8a84-d54211c30202")}catch{}})();function ga(e,t){return t===void 0?e:e.slice(Math.max(0,e.length-t))}function _a(e,t){return e.map(({entry:r,version:n})=>{let o=new Set,i=pn(r.patch);for(let s of i)o.add(vt(s.path)),s.from&&o.add(vt(s.from));return{index:n,...t?{version:t.offset===null?null:t.offset+n}:{},ts:r.ts,op:r.op,author:r.author,patch_ops:i.length,changed_fields:[...o].sort((s,a)=>s.localeCompare(a))}})}function wa(e){if(e[0]?.op!=="history_compact_baseline")return;let t=N(e,!0);return{offset:t,first_version:t===null?null:t+1,last_version:t===null?null:t+e.length}}async function ba(e,t){let r=A(process.cwd(),t.path);await H(r);let n=await O(r),o=G(n,R()),i=e.trim()===He,s=i?He:En(e,n.id_prefix),a=await he(r,s,n.id_prefix,n.item_format,o.type_to_folder),c=a?.id??s,d=i?gn(r):Ae(r,c);if(!a&&!await ke(d))throw new h(`Item ${e} not found`,f.NOT_FOUND);return a&&await Le({pmRoot:r,settings:n,itemId:a.id,commandLabel:"history"}),{historyPath:d,located:a,resolvedId:c,settings:n}}async function cu(e,t,r){let n=Ue(t.limit),{historyPath:o,located:i,resolvedId:s,settings:a}=await ba(e,r),c=await de(o,s),d=wa(c),l=a.agent_identity.identity_vocabulary,u=ho(a.agent_identity.harness_signals),m=yo({harness:t.harness,agentInstance:t.agentInstance,provenance:t.provenanceFilter},l,u),p=va(c).filter(({entry:k})=>m(k)),g=ga(p,n),_=g.map(({entry:k})=>k),y=t.compact===!0,w=y?_a(g,d):void 0,v=t.provenance===!0?g.map(({entry:k,durableVersion:x})=>po(k,l,{itemId:s,version:x})):void 0,b=t.provenance===!0?"provenance":y?"compact":"full",E={compact:{compact_history:w},provenance:{provenance_history:v},full:{history:_}}[b],S={id:s,...E,compact:y,projection:{mode:b,row_key:{compact:"compact_history",provenance:"provenance_history",full:"history"}[b]},omission_receipt:zr("history",b),count:_.length,limit:n??null,version_addressing:d,...t.provenanceSummary===!0?{provenance_summary:go(p.map(({entry:k})=>k),l,u)}:{}};if((t.diff||t.field!==void 0)&&(S.diff=On(c,{windowStartIndex:Math.max(0,c.length-_.length),field:t.field})),t.verify){let k=i?(await pe(i,{schema:a.schema})).document:void 0;if(S.verification=Tn(c,k),s===He&&S.verification.ok){let x=await _n(A(process.cwd(),r.path));S.verification={...S.verification,ok:x.ok,errors:x.ok?S.verification.errors:[...S.verification.errors,"verify_failed:workspace_state_mismatch"],workspace_state_matches_latest:x.ok,workspace_state_mismatches:x.mismatched_documents,workspace_state_missing:x.missing_documents,workspace_state_unreadable:x.unreadable_documents}}}return S}function va(e){let t=N(e,!0);return e.map((r,n)=>({entry:r,version:n+1,durableVersion:t===null?void 0:t+n+1}))}(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]="28cc85af-b7e7-5069-97a9-18844352cc59")}catch{}})();function Ea(e){if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(t!=="keyword"&&t!=="semantic"&&t!=="hybrid")throw new h("Search mode must be one of keyword|semantic|hybrid",f.USAGE);return t}function Xe(e){return e===!0}function ei(e){return Nr(e,0,1)??void 0}function ti(e){if(e===void 0)return"or";let t=e.trim().toLowerCase();if(t!=="and"&&t!=="or"&&t!=="exact")throw new h("Search --match-mode must be one of and|or|exact",f.USAGE);return t}function ri(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number(String(e).trim());if(!Number.isFinite(t)||t<0)throw new h("Search --min-score must be a finite number >= 0",f.USAGE);return t}function K(e,t){if(e==null)return;let r=String(e).trim();if(r.length!==0)return ft(r,new Date,t)}function M(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Nt(e,t){if(e!==void 0)return ft(e,new Date,t)}function Sa(e){if(e===void 0)return;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new h("Search --fields requires a comma-separated list of field names",f.USAGE);return[...new Set(t)]}function Je(e,t="<query>"){let r=e.compact===!0,n=e.full===!0,o=Sa(e.fields);if(Number(r)+Number(n)+ +(o!==void 0)>1)throw new h("Search projection options are mutually exclusive. Use one of --compact, --full, or --fields.",f.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:J(["search",t,"--full"]),suggested_retry_args:["search",t,"--full"]}});return r?{mode:"compact",fields:[...tn]}:n?{mode:"full",fields:[]}:o?{mode:"fields",fields:o}:{mode:"full",fields:[]}}function Ut(e,t,r="<query>"){if(e.mode!=="fields")return;let n=rn([...t.definitions.flatMap(s=>[s.key,s.metadata_key]),...te(R())]),o=new Set(n),i=e.fields.filter(s=>{let a=s.trim();return!o.has(a)});if(i.length>0){let s=["search",r,"--fields",e.fields.filter(a=>!i.includes(a)).join(",")||"id,title,status,score"];throw new h(`Unknown search --fields value(s): ${i.join(", ")}`,f.USAGE,{code:"unknown_field_projection",examples:["pm search <query> --fields id,title,status,score","pm search <query> --fields id,title,item.description,matched_fields"],nextSteps:["Use item.<field> for explicit item metadata fields, or run pm search --help for projection examples."],recovery:{allowed_values:n,suggested_retry:J(s),suggested_retry_args:s}})}}function Ze(e){let t=M(e);if(!t)throw new h("Search query must not be empty",f.USAGE);return t.split(/\s+/u).filter(Boolean)}function Gt(e){let t=e.search?.max_results;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):50}var Ia=["auto","keyword","semantic","hybrid"];function ka(e){let t=e.search?.default_mode;if(typeof t!="string")return"auto";let r=t.trim().toLowerCase();return Ia.includes(r)?r:"auto"}function $t(e){if(typeof e.requested=="string"&&e.requested.trim().length>0)return{mode:Ea(e.requested),source:"explicit"};let t=ka(e.settings);return t!=="auto"?{mode:t,source:"settings"}:{mode:e.semanticRunnable?"hybrid":"keyword",source:"auto"}}function Wt(e){let t=e.search?.score_threshold;return typeof t=="number"&&Number.isFinite(t)?t:0}function Bt(e){let t=e.search?.hybrid_semantic_weight;return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1?t:.7}function zt(e){let t={title_exact_bonus:10,title_weight:48,description_weight:5,tags_weight:6,status_weight:2,body_weight:1,comments_weight:1,notes_weight:1,learnings_weight:1,reminders_weight:2,events_weight:2,dependencies_weight:3,linked_content_weight:1},r=e.search?.tuning;if(!r)return t;let n=(o,i)=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:i;return{title_exact_bonus:n(r.title_exact_bonus,t.title_exact_bonus),title_weight:n(r.title_weight,t.title_weight),description_weight:n(r.description_weight,t.description_weight),tags_weight:n(r.tags_weight,t.tags_weight),status_weight:n(r.status_weight,t.status_weight),body_weight:n(r.body_weight,t.body_weight),comments_weight:n(r.comments_weight,t.comments_weight),notes_weight:n(r.notes_weight,t.notes_weight),learnings_weight:n(r.learnings_weight,t.learnings_weight),reminders_weight:n(r.reminders_weight,t.reminders_weight),events_weight:n(r.events_weight,t.events_weight),dependencies_weight:n(r.dependencies_weight,t.dependencies_weight),linked_content_weight:n(r.linked_content_weight,t.linked_content_weight)}}import Ra from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e1f303b6-a641-5550-b58c-ef023b68d5e4")}catch{}})();function Vt(e){return Kr("search",{pmRoot:e.pmRoot===void 0?void 0:Ra.resolve(e.pmRoot),query:e.query.trim(),mode:e.mode,options:Vr(e.searchOptions,Fn)})}function ni(e){let t=Yr(e.sorted,{cursor:e.searchOptions.after,fingerprint:Vt(e),limit:e.limit,readId:r=>r.item.id});return{limited:t.rows,pageExtras:{applied_limit:e.limit,...t.has_more?{has_more:!0,truncated:!0}:{},...t.next_cursor?{next_cursor:t.next_cursor}:{}}}}(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]="c8a2412e-2b0c-59c2-81ad-43de4d51562f")}catch{}})();function oi(e){if(typeof e!="string")return!1;let t=e.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);return t.length===1&&t[0]==="all"}var xa=[{optionKey:"status",summaryKey:"status",normalize:e=>oi(e)?"all":e},{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"parent",summaryKey:"parent"}];function oe(e){let{mode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:c,runtimeFieldFilters:d}=e,l={};return lo(l,n,xa),Object.assign(l,kt(n)),Object.assign(l,It(n)),r!==void 0&&r!=="or"&&(l.match_mode=r),o&&(l.include_linked=!0),i&&(l.title_exact=!0),s&&(l.phrase_exact=!0),a>0&&(l.score_threshold=a),t==="hybrid"&&n.semanticWeight!==void 0&&(l.hybrid_semantic_weight=c),n.limit!==void 0&&(l.limit=n.limit),d&&Object.keys(d).length>0&&(l.runtime_filters=d),l}function ie(e){let{effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:c,queryExpansion:d,rerank:l,runtimeFieldFilters:u}=e,m=p=>p??null;return{mode:t,match_mode:r,status:n.status===void 0||oi(n.status)?"all":n.status,type:m(n.type),tag:m(n.tag),priority:m(n.priority),deadline_before:m(n.deadlineBefore),deadline_after:m(n.deadlineAfter),updated_after:m(n.updatedAfter),updated_before:m(n.updatedBefore),created_after:m(n.createdAfter),created_before:m(n.createdBefore),assignee:m(n.assignee),sprint:m(n.sprint),release:m(n.release),parent:m(n.parent),...kt(n),...It(n),include_linked:o,title_exact:i,phrase_exact:s,score_threshold:a,hybrid_semantic_weight:t==="hybrid"?c:null,query_expansion_enabled:d.enabled,query_expansion_provider:d.provider,rerank_enabled:l.enabled,rerank_model:l.model,rerank_top_k:l.top_k,limit:m(n.limit),runtime_filters:u}}(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]="0272e482-0dab-5970-b19a-4da286fd112b")}catch{}})();var Aa=1.2,Ca=.75;function Kt(e){return X(e)}function Ta(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return t}function si(e){let t=[],r=new Map,n=0;for(let i of e){let s=Kt(i.text),a=Ta(s);n+=s.length;for(let c of a.keys())r.set(c,(r.get(c)??0)+1);t.push({id:i.id,termFrequencies:a,length:s.length})}let o=t.length;return{documents:t,documentFrequency:r,documentCount:o,averageDocumentLength:o>0?n/o:0}}function Ma(e,t){return Math.log(1+(e-t+.5)/(t+.5))}function ai(e,t,r){let n=new Map;if(e.documentCount===0||e.averageDocumentLength===0)return n;let o=[...new Set(t.filter(s=>s.length>0))];if(o.length===0)return n;let i=new Map;for(let s of o){let a=e.documentFrequency.get(s);a!==void 0&&i.set(s,Ma(e.documentCount,a))}if(i.size===0)return n;for(let s of e.documents){let a=0;for(let[c,d]of i){let l=s.termFrequencies.get(c);if(l===void 0)continue;let u=1-r.b+r.b*s.length/e.averageDocumentLength,m=l+r.k1*u;a+=d*(l*(r.k1+1)/m)}a>0&&n.set(s.id,a)}return n}function ii(e,t,r,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n,Math.max(r,e))}function ci(e){let t=r=>typeof r=="string"?[r]:typeof r=="number"?[String(r)]:Array.isArray(r)?r.flatMap(t):typeof r=="object"&&r!==null?Object.values(r).flatMap(t):[];return t(Object.values(e)).join(" ")}function li(e){let t=e?.search?.bm25;return{k1:ii(t?.k1,Aa,0,1e3),b:ii(t?.b,Ca,0,1)}}(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]="b75c3c5e-e2b7-5e65-a56a-883dc896290e")}catch{}})();var Qt=4,Fa=20,Da=200,Pa=new Set(["a","an","and","for","from","in","into","of","on","or","the","to","with"]);function Yt(e,t){let r=[],n=new Set;for(let o of e){let i=o.trim().replaceAll(/\s+/g," ");if(i.length===0)continue;let s=i.toLowerCase();if(!n.has(s)&&(n.add(s),r.push(i),r.length>=t))break}return r}function Ha(e){let t=e.toLowerCase();return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&(t.endsWith("ches")||t.endsWith("shes")||t.endsWith("xes")||t.endsWith("zes")||t.endsWith("sses"))?t.slice(0,-2):t.length>3&&t.endsWith("s")&&!t.endsWith("ss")&&!t.endsWith("us")&&!t.endsWith("is")&&!t.endsWith("as")?t.slice(0,-1):t}function La(e){let t=e.toLowerCase();return t.length>2&&(!t.endsWith("s")||t.endsWith("ss"))?t.endsWith("y")&&!/[aeiou]y$/u.test(t)?`${t.slice(0,-1)}ies`:t.endsWith("ch")||t.endsWith("sh")||t.endsWith("x")||t.endsWith("z")||t.endsWith("ss")?`${t}es`:`${t}s`:t}function di(e,t=Qt){let r=e.trim().replaceAll(/\s+/g," ");if(r.length===0)return[];let n=X(r);if(n.length===0)return[r];let o=n.filter(a=>!Pa.has(a.toLowerCase())),i=n.map(a=>Ha(a)),s=o.map(a=>La(a));return Yt([r,n.join(" "),o.join(" "),i.join(" "),s.join(" ")],Math.max(1,t))}function ui(e){let t=Array.isArray(e)?e:e?.queries;return Array.isArray(t)?Yt(t.filter(r=>typeof r=="string"),Qt):[]}function mi(e,t,r){return Yt([...e,...t],Math.max(1,r))}function fi(e,t){let r=e.search?.query_expansion,n=ae(r?.provider);return{enabled:r?.enabled===!0,provider:n??t,max_queries:Qt}}function hi(e,t){let r=e.search?.rerank,n=ae(r?.model),o=xe(r?.top_k)??Fa;return{enabled:r?.enabled===!0,model:n??t,top_k:Math.min(Da,o)}}function pi(e){let t=Array.isArray(e)?e:e?.hits;if(!Array.isArray(t))return[];let r=new Map;for(let o of t){if(typeof o!="object"||o===null)continue;let i=ae(o.id),s=o.score;if(!i||typeof s!="number"||!Number.isFinite(s))continue;let a=r.get(i);(a===void 0||s>a)&&r.set(i,s)}let n=[...r.entries()].map(([o,i])=>({id:o,score:i}));return n.sort((o,i)=>o.score!==i.score?i.score-o.score:o.id.localeCompare(i.id)),n}function Oa(e,t){let r=e.length,n=0;for(let o=0;o<r;o+=1)n+=e[o]*t[o];return n}function yi(e){let t=0;for(let r=0;r<e.length;r+=1)t+=e[r]*e[r];return Math.sqrt(t)}function ja(e,t,r){if(!e||!t||e.length===0||t.length===0||e.length!==t.length)return 0;let n=Oa(e,t),o=yi(t),i=r*o;return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(i)||i===0?0:Math.max(-1,Math.min(1,n/i))}async function gi(e,t,r,n,o){if(n.length===0)return new Map;let i=ae(t)??e.model,s=i===e.model?e:{...e,model:i},a=[r.trim(),...n.map(m=>m.text)],c=await Ge(s,a,o?{timeout_ms:o}:{}),d=c[0];if(!d)return new Map;let l=yi(d),u=new Map;for(let m=0;m<n.length;m+=1){let p=n[m],g=c[m+1];if(!g)continue;let _=ja(d,g,l);u.set(p.id,Math.max(0,Math.min(1,(_+1)/2)))}return u}(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]="a5d1f401-e5eb-5b6e-8b5a-d8135128f44b")}catch{}})();function se(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function U(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string"):[]}function ve(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.kind=="string"):[]}function Xt(e){let t=e.metadata;return[t.title,t.description,t.status,se(t.tags).join(" "),e.body,U(t.comments).map(r=>r.text).join(" "),U(t.notes).map(r=>r.text).join(" "),U(t.learnings).map(r=>r.text).join(" "),$e(t).join(" "),We(t).join(" "),ve(t.dependencies).map(r=>`${r.id} ${r.kind}`).join(" "),Be(t)]}function Jt(e,t){return Xt(e).some(r=>M(r).includes(t))}function Zt(e,t,r){return!r.titleExact&&!r.phraseExact?e:e.filter(n=>!(r.titleExact&&M(n.metadata.title)!==t||r.phraseExact&&!Jt(n,t)))}function qa(e){if(e&&[...e].some(t=>t.toLowerCase()==="none"||t.toLowerCase()==="null"))throw new h('--assignee no longer accepts "none" or "null".',f.USAGE)}function Na(e,t,r){let n=ge(e.assignee,{label:"--assignee"});qa(n);let o=ao(e),i=co(e);return{typeFilter:Jn(e.type,t),tagFilter:ge(e.tag,{label:"--tag",normalize:s=>s.toLowerCase()}),priorityFilter:Zn(e.priority),deadlineBefore:Nt(e.deadlineBefore,"deadline-before"),deadlineAfter:Nt(e.deadlineAfter,"deadline-after"),updatedAfter:K(e.updatedAfter,"updated-after"),updatedBefore:K(e.updatedBefore,"updated-before"),createdAfter:K(e.createdAfter,"created-after"),createdBefore:K(e.createdBefore,"created-before"),assigneeFilter:n,sprintFilter:ge(e.sprint,{label:"--sprint"}),releaseFilter:ge(e.release,{label:"--release"}),parentFilter:e.parent?.trim(),statusSet:r&&r.length>0?new Set(r):void 0,missingMetadataFilters:o,missingMetadataActive:eo(o),contentFieldFilters:i,contentFiltersActive:ro(i)}}function Ua(e,t){return Ga(e,t)&&Jr(e,t)&&$a(e,t)}function Ga(e,t){if(t.statusSet&&!t.statusSet.has(e.status)||t.typeFilter&&!t.typeFilter.has(e.type))return!1;let r=t.tagFilter;return!(r&&!se(e.tags).some(n=>r.has(n))||t.priorityFilter!==void 0&&!t.priorityFilter.has(e.priority))}function $a(e,t){return!(t.assigneeFilter!==void 0&&(e.assignee===void 0||!t.assigneeFilter.has(e.assignee))||t.sprintFilter!==void 0&&(e.sprint===void 0||!t.sprintFilter.has(e.sprint))||t.releaseFilter!==void 0&&(e.release===void 0||!t.releaseFilter.has(e.release))||t.parentFilter!==void 0&&e.parent!==t.parentFilter)}function Wa(e,t,r,n){let o=e.metadata;return!(!Ua(o,t)||!qn(o,r)||t.missingMetadataActive&&!to(o,t.missingMetadataFilters,n)||t.contentFiltersActive&&!no(o,t.contentFieldFilters))}function er(e,t,r,n,o,i){let s=Na(t,r,o);return e.filter(a=>Wa(a,s,n,i))}(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]="a3f9e7fa-7ebf-5fc7-93a4-f12cff30f4ff")}catch{}})();var Ba=2,za=120,Va=6,Ka=40,Qa=1e3,Ya=900,Xa="\xAB",Ja="\xBB",_i=60;function et(e,t){let r=0,n=0;for(;;){let o=e.indexOf(t,n);if(o<0)return r;r+=1,n=o+t.length}}var wi=[{name:"title",weightKey:"title_weight",value:e=>e.metadata.title},{name:"description",weightKey:"description_weight",value:e=>e.metadata.description},{name:"tags",weightKey:"tags_weight",value:e=>se(e.metadata.tags).join(" ")},{name:"status",weightKey:"status_weight",value:e=>typeof e.metadata.status=="string"?e.metadata.status:""},{name:"body",weightKey:"body_weight",value:e=>e.body},{name:"comments",weightKey:"comments_weight",value:e=>U(e.metadata.comments).map(t=>t.text).join(" ")},{name:"notes",weightKey:"notes_weight",value:e=>U(e.metadata.notes).map(t=>t.text).join(" ")},{name:"learnings",weightKey:"learnings_weight",value:e=>U(e.metadata.learnings).map(t=>t.text).join(" ")},{name:"reminders",weightKey:"reminders_weight",value:e=>$e(e.metadata).join(" ")},{name:"events",weightKey:"events_weight",value:e=>We(e.metadata).join(" ")},{name:"dependencies",weightKey:"dependencies_weight",value:e=>ve(e.metadata.dependencies).map(t=>`${t.id} ${t.kind}`).join(" ")},{name:"plan",weightKey:"body_weight",value:e=>Be(e.metadata)}],Za=new Map(wi.map(e=>[e.name,e]));function tr(e,t){let r=t.filter(o=>o.length>0).sort((o,i)=>i.length-o.length).map(o=>o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));if(r.length===0)return e;let n=new RegExp(r.join("|"),"gi");return e.replace(n,o=>`${Xa}${o}${Ja}`)}function rr(e,t){if(e.length===0)return null;let r=e.toLowerCase(),n=-1,o=0;for(let l of t){if(l.length===0)continue;let u=r.indexOf(l);u>=0&&(n<0||u<n)&&(n=u,o=l.length)}if(n<0)return null;let i=Math.max(0,n-_i),s=Math.min(e.length,n+o+_i),a=tr(e.slice(i,s),t),c=i>0?"\u2026":"",d=s<e.length?"\u2026":"";return`${c}${a}${d}`}function tt(e,t,r){let n=[];for(let o of t){let i=Za.get(o);if(i===void 0)continue;let s=rr(i.value(e),r);s!==null&&n.push({field:o,snippet:s})}return n}function ec(e,t,r){return[...wi.map(n=>({name:n.name,value:n.value(e),weight:r[n.weightKey]})),{name:"linked_content",value:t,weight:r.linked_content_weight}]}function tc(e,t,r){let n=M(e.id),o=typeof r=="string"?r.trim().toLowerCase():"",i=M(o),s=i.length>0&&n.startsWith(i)?n.slice(i.length).trim():n;return t!==n&&t!==s?null:{item:e,score:t===n?Qa:Ya,matched_fields:["id"],matched_all_terms:!0,exact_id_match:!0}}function rc(e,t,r,n,o){for(let i of e){let s=t.get(i)??0;s>0&&(o.score+=s*n.title_exact_bonus,o.matched.add("title"),o.matchedTokens.add(i));for(let a of r){let c=et(a.value.toLowerCase(),i);c>0&&(o.score+=c*a.weight,o.matched.add(a.name),o.matchedTokens.add(i))}}}function nc(e,t,r,n){M(e.title)===t&&(n.score+=za,n.matched.add("title"));for(let o of r){let i=et(M(o.value),t);i>0&&(n.score+=i*o.weight*Va,n.matched.add(o.name))}}function nr(e,t,r,n,o,i,s=!1){let a=e.metadata,c=tc(a,r,i);if(c)return c;let d=new Map;for(let g of X(a.title))d.set(g,(d.get(g)??0)+1);let l=ec(e,n,o),u={score:0,matched:new Set,matchedTokens:new Set};rc(t,d,l,o,u);let m=new Set(t),p=m.size>0&&u.matchedTokens.size===m.size;return s&&m.size>1&&p&&(u.score+=Ka),t.length>=Ba&&r.includes(" ")&&nc(a,r,l,u),u.score<=0?null:{item:a,score:u.score,matched_fields:[...u.matched].sort((g,_)=>g.localeCompare(_)),matched_all_terms:p}}function or(e,t){return[...e].sort((r,n)=>{let o=n.score-r.score;if(o!==0)return o;let i=le(r.item.status,t),s=le(n.item.status,t);if(i!==s)return i?1:-1;let a=r.item.priority-n.item.priority;if(a!==0)return a;let c=Xr(n.item.updated_at,r.item.updated_at);return c!==0?c:r.item.id.localeCompare(n.item.id)})}function ir(e,t,r,n,o,i,s,a=!1){return nr(e,t,r,n?o.get(e.metadata.id)??"":"",i,s,a)}function Ee(e){if(e.size===0)return new Map;let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let o of e.values())t=Math.min(t,o),r=Math.max(r,o);if(r===t)return new Map([...e.keys()].map(o=>[o,1]));let n=new Map;for(let[o,i]of e)n.set(o,(i-t)/(r-t));return n}(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]="c8484fbd-5fb2-56aa-9d69-26646be262a9")}catch{}})();function nt(e){let t=[],r=e;for(let n=0;n<5&&r&&typeof r=="object";n+=1){let o=r.code;typeof o=="string"&&t.push(o.toLowerCase()),r=r.cause}return t.join(" ")}function ot(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase(),r=nt(e),n=`${t} ${r}`;return n.includes("timed out")||n.includes("timeout")||n.includes("etimedout")?"timeout":n.includes("econnrefused")||n.includes("connection refused")||n.includes("connect ")||n.includes("enotfound")||n.includes("eai_again")||n.includes("econnreset")||n.includes("fetch failed")?"connection":"error"}function sr(e,t){let r=ot(t);return`search_${e}_fallback:${r}:using_keyword_mode`}function bi(e){return e?.commands?.some(t=>t.command.trim()==="reindex")===!0?{command:"pm reindex --mode hybrid",args:["reindex","--mode","hybrid"]}:{command:"pm install search-advanced --project",args:["install","search-advanced","--project"],follow_up_command:"pm reindex --mode hybrid",follow_up_args:["reindex","--mode","hybrid"]}}async function ar(e,t,r){try{let n=await zn(e);n.warnings.length>0&&r.push(...n.warnings);let o=mo(t.map(s=>({id:s.metadata.id,updated_at:s.metadata.updated_at})),n.entries);if(o.length===0)return;let i=bi(R());r.push(...vi(o.length,i)),process.stderr.write(`[pm] warning: ${o.length} item${o.length===1?" is":"s are"} new or modified since the last reindex and ${o.length===1?"is":"are"} NOT in the semantic index yet \u2014 run '${i.command}'${i.follow_up_command?`, then '${i.follow_up_command}'`:""}. (Write-time embedding is governed by search.mutation_refresh_policy; staleness means the embed was skipped, failed, or the backend was unreachable.)
3
- `)}catch{}}function vi(e,t){return[`vector_index_stale:${e}`,`vector_index_recovery:${t.args.join(" ")}`,...t.follow_up_args?[`vector_index_recovery_follow_up:${t.follow_up_args.join(" ")}`]:[]]}function it(e,t,r,n){if(!t.active)throw new h(`Search mode '${e}' requires a configured embedding provider in settings.providers.openai or settings.providers.ollama`,f.USAGE);if(!r.active&&!n)throw new h(`Search mode '${e}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,f.USAGE);return{provider:t.active,vectorStore:r.active??null}}var F=Re;function Se(e){let t=R(),r=Dn(t,e);if(!r)return null;let n=r.runtime_definition??r.definition,o=n.query,i=n.queryExpansion??n.query_expansion,s=n.rerank,a=F(n.name)??F(r.definition.name)??e;if(!a)return null;let c={providerName:a,...typeof o=="function"?{query:o}:{},...typeof i=="function"?{queryExpansion:i}:{},...typeof s=="function"?{rerank:s}:{}};return!c.query&&!c.queryExpansion&&!c.rerank?null:c}function cr(e){let t=F(e.search?.provider),r=Se(t);return r?.query?{providerName:r.providerName,query:r.query}:null}function lr(e){let t=R(),r=F(e.vector_store?.adapter),n=Pn(t,r);if(!n)return null;let o=n.runtime_definition??n.definition,i=o.query;if(typeof i!="function")return null;let s=o.upsert;return{adapterName:F(o.name)??F(n.definition.name)??r??"extension",query:i,...typeof s=="function"?{upsert:s}:{}}}function dr(e,t,r){let n=Array.isArray(t)?t:t?.hits;if(!Array.isArray(n))throw new h(`Extension search provider "${e}" must return an array of hits or { hits: [...] }`,f.GENERIC_FAILURE);let o=new Set,i=[];for(let s of n){if(typeof s!="object"||s===null)continue;let a=F(s.id),c=s.score;if(!a||typeof c!="number"||!Number.isFinite(c)||o.has(a))continue;let d=r.get(a);if(!d)continue;let l=s.matched_fields,u=Array.isArray(l)&&l.every(m=>typeof m=="string")?[...new Set(l.map(m=>m.trim()).filter(m=>m.length>0))].sort((m,p)=>m.localeCompare(p)):[`provider:${e}`];o.add(a),i.push({item:d.metadata,score:c,matched_fields:u})}return i}function ur(e,t){let r=[],n=new Map;for(let o of e){if(n.has(o.id))continue;let i=t.get(o.id);i&&(n.set(o.id,o.score),r.push({item:i.metadata,score:o.score,matched_fields:["semantic"]}))}return{semanticHits:r,semanticScores:n}}function rt(e,t){let r=t.filter(c=>c.exact_id_match===!0);if(r.length===0)return e;let n=new Set(r.map(c=>c.item.id)),o=e.filter(c=>!n.has(c.item.id)),i=o.reduce((c,d)=>Math.max(c,d.score),0),s=r.sort((c,d)=>d.score-c.score),a=i+s.length+1;return[...s.map((c,d)=>({...c,score:a-d,matched_fields:["id"]})),...o]}function st(e,t,r,n,o="semantic"){let i=new Map(r.map(u=>[u.item.id,u.score])),s=new Map(r.map(u=>[u.item.id,u.matched_fields])),a=Ee(t),c=Ee(i),d=new Set([...t.keys(),...i.keys()]),l=1-n;return[...d].map(u=>{let m=e.get(u),p=a.get(u)??0,g=c.get(u)??0,_=p*n+g*l;if(_<=0)return null;let y=new Set;t.has(u)&&y.add(o);for(let w of s.get(u)??[])y.add(w);return{item:m.metadata,score:_,matched_fields:[...y].sort((w,v)=>w.localeCompare(v))}}).filter(u=>u!==null)}function mr(e){let t=e.configuredProvider?.trim().toLowerCase();return t==="bm25"?"explicit":t==="auto"&&!e.hasEmbeddingProvider&&!e.hasExtensionSearchProvider?"auto-fallback":null}function fr(e){let t=e.filteredDocuments.map(s=>({id:s.metadata.id,text:ci(Wn(s,{fields:e.corpusFields}))})),r=si(t),n=ai(r,Kt(e.query),e.bm25Params),o=new Map(e.filteredDocuments.map(s=>[s.metadata.id,s]));if(e.requestedMode==="semantic"){let s=[...n].map(([a,c])=>({item:o.get(a).metadata,score:c,matched_fields:["bm25"]}));return rt(s,e.keywordHits)}let i=st(o,n,e.keywordHits,e.hybridSemanticWeight,"bm25");return rt(i,e.keywordHits)}function hr(e){let t=new Map;for(let n of e)for(let o of n){let i=t.get(o.id);(!i||o.score>i.score)&&t.set(o.id,o)}let r=[...t.values()];return r.sort((n,o)=>n.score!==o.score?o.score-n.score:n.id.localeCompare(o.id)),r}function pr(e){let t=e.metadata,r=Array.isArray(t?.tags)?t.tags.join(" "):"";return[t?.title,t?.description,t?.type,t?.status,r,e.body].map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0).join(`
4
- `)}async function oc(e,t){let r=e.queryExpansion.enabled?di(t,e.queryExpansion.max_queries):[t],n=r.length>0?r:[t];if(!e.queryExpansion.enabled)return n;if(e.queryExpansionExtension?.expand)try{let o=await Promise.resolve(e.queryExpansionExtension.expand({query:t,mode:e.requestedMode,settings:e.settings}));return mi(n,ui(o),e.queryExpansion.max_queries)}catch{return e.warnings.push(`search_query_expansion_provider_failed:${e.queryExpansionExtension.providerName}:using_builtin`),n}return e.queryExpansion.provider&&e.queryExpansion.provider!=="openai"&&e.queryExpansion.provider!=="ollama"&&e.warnings.push(`search_query_expansion_provider_unavailable:${e.queryExpansion.provider}:using_builtin`),n}async function ic(e,t,r,n){if(e.extensionVectorAdapter?.query)try{return await Promise.resolve(e.extensionVectorAdapter.query({vector:t,limit:r,settings:e.settings}))}catch(o){if(!e.vectorStore)throw new h(`Extension vector adapter query failed and no built-in fallback store is configured (${o instanceof Error?o.message:String(o)})`,f.GENERIC_FAILURE);return e.warnings.push(`search_vector_adapter_failed:${e.extensionVectorAdapter.adapterName}:using_builtin`),await Et(e.vectorStore,t,r,n)}if(e.vectorStore)return await Et(e.vectorStore,t,r,n);throw new h("Semantic search requires either a configured vector store or an extension vector adapter query handler",f.USAGE)}function sc(e,t,r){return[...e].sort((n,o)=>n.score!==o.score?o.score-n.score:n.item.id.localeCompare(o.item.id)).slice(0,r).map(n=>{let o=t.get(n.item.id);return o?{hit:n,text:pr(o)}:null}).filter(n=>n!==null)}async function ac(e,t,r){if(!e.rerankExtension?.rerank)return null;try{let n=await Promise.resolve(e.rerankExtension.rerank({query:t,mode:"hybrid",model:e.rerank.model,top_k:e.rerank.top_k,settings:e.settings,candidates:r.map(i=>({id:i.hit.item.id,text:i.text,score:i.hit.score}))})),o=pi(n);return o.length>0?new Map(o.map(i=>[i.id,i.score])):(e.warnings.push(`search_rerank_provider_invalid_response:${e.rerankExtension.providerName}:using_builtin`),null)}catch{return e.warnings.push(`search_rerank_provider_failed:${e.rerankExtension.providerName}:using_builtin`),null}}async function cc(e,t,r){let n=await ac(e,t,r);if(n)return n;let o=r.map(i=>({id:i.hit.item.id,text:i.text}));try{return await gi(e.provider,e.rerank.model,t,o,e.embeddingTimeoutMs)}catch{return e.warnings.push("search_rerank_failed:using_hybrid_scores"),null}}function lc(e,t){let r=new Set(t.keys()),n=e.map(o=>{let i=t.get(o.item.id);if(i===void 0)return o;let s=new Set(o.matched_fields);return s.add("rerank"),{...o,score:i,matched_fields:[...s].sort((a,c)=>a.localeCompare(c))}});return n.sort((o,i)=>{let s=r.has(o.item.id),a=r.has(i.item.id);return s!==a?s?-1:1:o.score!==i.score?i.score-o.score:o.item.id.localeCompare(i.item.id)}),n}async function dc(e,t,r,n){if(!e.rerank.enabled||r.length<=1)return r;let o=sc(r,n,e.rerank.top_k),i=await cc(e,t,o);return i&&i.size>0?lc(r,i):r}async function yr(e){let t=Math.max(e.limit??e.maxResults,e.maxResults),r=e.embeddingTimeoutMs!==void 0?{timeout_ms:e.embeddingTimeoutMs}:{},n=e.vectorQueryTimeoutMs!==void 0?{timeout_ms:e.vectorQueryTimeoutMs}:{},o=e.query.trim(),i=await oc(e,o),s=await Ge(e.provider,i,r),a=await Promise.all(s.map(async g=>await ic(e,g,t,n))),c=hr(a),d=new Map(e.filteredDocuments.map(g=>[g.metadata.id,g])),{semanticHits:l,semanticScores:u}=ur(c,d),m=u.size;if(e.requestedMode==="semantic")return{hits:rt(l,e.keywordHits),vectorMatchCount:m};let p=await dc(e,o,st(d,u,e.keywordHits,e.hybridSemanticWeight),d);return{hits:rt(p,e.keywordHits),vectorMatchCount:m}}function Ei(e){let t=Se(e.provider??void 0);return t?.queryExpansion?{providerName:t.providerName,expand:t.queryExpansion}:null}function Si(e){let t=Se(F(e.search?.provider));return t?.rerank?{providerName:t.providerName,rerank:t.rerank}:null}import at from"node:fs/promises";import gr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de9a1cbd-f277-52ef-adc6-66225f2d2f4f")}catch{}})();function _r(e){let t=(e.files??[]).map(s=>({scope:s.scope,path:s.path.trim()})),r=(e.docs??[]).map(s=>({scope:s.scope,path:s.path.trim()})),n=(e.tests??[]).filter(s=>typeof s.path=="string"&&s.path.trim().length>0).map(s=>({scope:s.scope,path:s.path.trim()})),o=[...t,...r,...n].filter(s=>s.path.length>0).sort((s,a)=>s.scope.localeCompare(a.scope)||s.path.localeCompare(a.path)),i=new Map;for(let s of o)i.set(`${s.scope}:${s.path}`,s);return[...i.values()]}async function Ii(e){let t=gr.resolve(e);try{let r=await at.realpath(t);return{resolved:t,realpath:r}}catch{return null}}async function wr(e,t){let[r,n]=await Promise.all([Ii(e),Ii(t)]);return{projectContainmentRoot:r,globalContainmentRoot:n}}async function br(e,t){let r=_r(e.metadata),n=[];for(let o of r){let i=o.scope==="global"?t.globalContainmentRoot:t.projectContainmentRoot;if(!i)continue;let s=gr.resolve(i.resolved,o.path);if(!ut(i.resolved,s))continue;let a;try{a=await at.realpath(s)}catch{continue}if(ut(i.realpath,a))try{await ce({path:s,scope:o.scope}),n.push(await at.readFile(s,"utf8"))}catch{}}return n.join(`
5
- `)}async function vr(e,t,r,n){let o=te(R()),i=async(d,l,u)=>{let m=async(p,g)=>{await ce({path:p,scope:"project"});let _=await at.readFile(p,"utf8");return sn(_,{format:g,schema:n,extensionFieldNames:o,onWarning:y=>s.push(y)}).body};try{return await m(l,u)}catch{let p=u==="toon"?"json_markdown":"toon",g=B(e,d.type,d.id,p,r);try{return await m(g,p)}catch{return s.push(`item_list_item_read_failed:${gr.relative(e,g)}`),""}}},s=[],a=await kn(e,t,r,s,n),c=[];if(a.length===0){let d=await xn(e,t,r,s,n);for(let l of d){let u=B(e,l.type,l.id,t,r),m=await i(l,u,t);c.push({metadata:l,body:m})}return{documents:c,warnings:[...new Set(s)].sort((l,u)=>l.localeCompare(u))}}for(let d of a){if(typeof d.body=="string"){c.push({metadata:d.metadata,body:d.body});continue}let l=await i(d.metadata,d.item_path,d.item_format);c.push({metadata:d.metadata,body:l})}return{documents:c,warnings:[...new Set(s)].sort((d,l)=>d.localeCompare(l))}}async function ki(e,t,r){let n=new Map;if(!e||t!=="keyword"&&t!=="hybrid")return n;let o=process.cwd(),i=await wr(o,Gr(o)),s=await Promise.all(r.map(async a=>[a.metadata.id,await br(a,i)]));for(let[a,c]of s)n.set(a,c);return n}(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]="17122985-4157-5732-9142-444327cb273d")}catch{}})();var Ri=["tag","status","type","priority"];function Er(e){let t={},r=[];for(let n of e.split(/\s+/).filter(o=>o.length>0)){let o=n.indexOf(":"),i=o>0?n.slice(0,o).toLowerCase():"",s=o>0?n.slice(o+1):"",a=Ri.includes(i)?i:void 0;if(a&&s.length>0&&t[a]===void 0){t[a]=s;continue}r.push(n)}return{residualQuery:r.join(" "),inlineFilters:t}}function Sr(e,t,r){let n={...e};for(let o of Ri){let i=t[o];if(i!==void 0){if(Re(n[o])!==void 0){r.push(`search_inline_filter_ignored:${o}:flag_takes_precedence`);continue}n[o]=i}}return n}function xi(e,t){let r=[],n=Er(e),o=Object.keys(n.inlineFilters).length>0;if(o&&n.residualQuery.trim().length===0)throw new h("Inline field:value tokens consumed the entire query, leaving no search terms.",f.USAGE,{examples:["pm search auth tag:area:search","pm list --tag area:search --status open"],nextSteps:["Add keyword terms alongside the inline filters, or use pm list for pure tag/status/type/priority filtering."]});let i=o?n.residualQuery:e,s=Sr(t,n.inlineFilters,r);return{query:i,options:s,inlineWarnings:r,highlight:s.highlight===!0,includeLinked:Xe(s.includeLinked),titleExact:Xe(s.titleExact),phraseExact:Xe(s.phraseExact),matchMode:ti(typeof s.matchMode=="string"?s.matchMode:void 0),minScoreOverride:ri(s.minScore),countOnly:s.count===!0,tokens:Ze(i),normalizedQuery:M(i),limit:Ue(s.limit),projection:Je(s,e),modeWasExplicit:typeof s.mode=="string"&&s.mode.trim().length>0}}function Ai(e){if(e.after!==void 0&&e.count===!0)throw new h("Search --after cannot be combined with --count.",f.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7beacb7-66a5-581f-93f0-68ceb4b8e41e")}catch{}})();function kr(e,t,r,n,o,i,s,a,c,d,l,u,m,p){let g=m?{total:0,count_only:!0}:{};if(d.mode==="compact"&&n.compact===!0){let y=oe({mode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,runtimeFieldFilters:u});return{query:e.trim(),mode:t,...Cr(p),items:[],count:0,...g,filters:y,...l.length>0?{warnings:l}:{}}}let _=d.mode==="full"?null:[...d.fields];return{query:e.trim(),mode:t,mode_source:p,items:[],count:0,...g,filters:ie({effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,queryExpansion:a,rerank:c,runtimeFieldFilters:u??{}}),projection:{mode:d.mode,fields:_},now:I(),...l.length>0?{warnings:l}:{}}}function Rr(e,t){let r=t.trim();if(r.length===0)return null;if(r==="score")return e.score;if(r==="matched_fields")return e.matched_fields;if(r.startsWith("item.")){let i=r.slice(5);return i.length===0?null:e.item[i]??null}let n=e,o=e.item;return Object.prototype.hasOwnProperty.call(o,r)?o[r]??null:Object.prototype.hasOwnProperty.call(n,r)?n[r]??null:null}function xr(e,t){return t.mode==="full"?e.map(({matched_all_terms:r,exact_id_match:n,...o})=>o):e.map(r=>{let n={};for(let o of t.fields)n[o]=Rr(r,o);return n})}function Ar(e,t){return kr(e.query,e.effectiveMode,e.matchMode,e.options,e.includeLinked,e.scoreThreshold,e.hybridSemanticWeight,e.queryExpansion,e.rerank,e.projection,e.warnings,e.runtimeFieldFilters,t,e.modeSource)}function Ci(e,t){if(e.projection.mode==="compact"&&e.options.compact===!0)return Ir({query:e.query.trim(),mode:e.effectiveMode,...Cr(e.modeSource),items:[],count:t,total:t,count_only:!0,filters:oe({mode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters})},e.warnings);let r=e.projection.mode==="full"?null:[...e.projection.fields];return Ir({query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:[],count:t,total:t,count_only:!0,filters:ie({effectiveMode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,queryExpansion:e.queryExpansion,rerank:e.rerank,runtimeFieldFilters:e.runtimeFieldFilters}),projection:{mode:e.projection.mode,fields:r},now:I()},e.warnings)}function Cr(e){return e==="settings"?{mode_source:e}:{}}function Ir(e,t){return t.length===0?e:{...e,warnings:t}}function Ie(e,t){return t?{...e,workspace_memory:t}:e}function Ti(e,t,r){if(!e.highlight)return{hits:r,projection:e.projection};let n=new Map(t.map(i=>[i.metadata.id,i])),o=r.map(i=>({...i,highlights:tt(n.get(i.item.id),i.matched_fields,e.tokens)}));return e.projection.mode==="full"||e.projection.fields.includes("highlights")?{hits:o,projection:e.projection}:{hits:o,projection:{mode:e.projection.mode,fields:[...e.projection.fields,"highlights"]}}}function Mi(e,t,r,n,o,i){let s=n<r?{total:r}:{};if(e.projection.mode==="compact"&&e.options.compact===!0)return Ir({query:e.query.trim(),mode:e.effectiveMode,...Cr(e.modeSource),items:t,count:t.length,...s,...i,filters:oe({mode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters})},e.warnings);let a=o.mode==="full"?null:[...o.fields];return{query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:t,count:t.length,...s,...i,filters:ie({effectiveMode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,queryExpansion:e.queryExpansion,rerank:e.rerank,runtimeFieldFilters:e.runtimeFieldFilters}),projection:{mode:o.mode,fields:a},now:I(),...e.warnings.length>0?{warnings:e.warnings}:{}}}(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]="3bfd872f-6ed7-551c-a027-3748493de3e9")}catch{}})();var af={applyFilters:er,applyExactQueryFilters:Zt,applyInlineQueryFilters:Sr,buildHitHighlights:tt,buildVerboseSearchFilters:ie,buildExplicitSemanticFallbackWarning:sr,buildCompactSearchFilterSummary:oe,buildHybridLexicalScore:ir,buildRerankCorpus:pr,buildSemanticHits:ur,classifyImplicitSemanticFallbackReason:ot,collectErrorCauseCodes:nt,collectExactPhraseFields:Xt,collectLinkedPaths:_r,combineHybridHits:st,computeBuiltInBm25Hits:fr,computeSemanticOrHybridHits:yr,resolveBuiltInBm25Mode:mr,countOccurrences:et,dependencyEntries:ve,documentContainsExactPhrase:Jt,emptySearchResult:kr,highlightFieldSnippet:rr,loadDocuments:vr,markTokenRuns:tr,parseInlineQueryFilters:Er,maybeEmitVectorIndexStaleWarning:ar,loadLinkedCorpus:br,mergeVectorHitsById:hr,normalizeExtensionProviderHits:dr,normalizeScoreMap:Ee,parseProjectionConfig:Je,parseTimestampWindow:K,parseTokens:Ze,projectSearchHits:xr,readSearchFieldValue:Rr,requireSemanticDependencies:it,resolveExtensionSearchProvider:cr,resolveExtensionSearchProviderByName:Se,resolveExtensionVectorAdapter:lr,resolveLinkedCorpusRoots:wr,scoreDocument:nr,sortHits:or,stringArray:se,textEntries:U,validateSearchProjectionFields:Ut};async function uc(e,t){let r=A(process.cwd(),t.path);await H(r);let n=await O(r),o=Nn(n).settings,i=q(o.schema),s=Z(o.schema);Ut(e.projection,s,e.query);let a=jn(e.options,s,"search"),c=G(o,R()),d=Gn(o),l=Bn(o,r),u=cr(o),m=lr(o),p=ei(e.options.semanticWeight),g=fi(o,d.active?.name??null),_=hi(o,d.active?.model??F(o.search?.embedding_model)??"text-embedding-3-small");return{pmRoot:r,settings:o,statusRegistry:i,runtimeFieldRegistry:s,runtimeFieldFilters:a,typeRegistry:c,maxResults:Gt(o),scoreThreshold:e.minScoreOverride??Wt(o),semanticWeightProvided:e.options.semanticWeight!==void 0,semanticWeightOverride:p,hybridSemanticWeight:p??Bt(o),tuning:zt(o),providerResolution:d,vectorResolution:l,extensionSearchProvider:u,extensionVectorAdapter:m,bm25Mode:mr({configuredProvider:F(o.search?.provider),hasEmbeddingProvider:d.active!==null,hasExtensionSearchProvider:u!==null}),queryExpansion:g,queryExpansionExtension:Ei(g),rerank:_,rerankExtension:Si(o),...mc({requested:e.options.mode,settings:o,configuredProvider:n.search?.provider??null,providerResolution:d,vectorResolution:l,extensionSearchProvider:u,extensionVectorAdapter:m})}}function mc(e){let t=Un(e.providerResolution.active?.name,e.configuredProvider)==="configured"&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null),r=e.extensionSearchProvider!==null||t,n=$t({requested:e.requested,settings:e.settings,semanticRunnable:r});return{effectiveMode:n.mode,modeSource:n.source}}async function fc(e,t){let r=await vr(t.pmRoot,t.settings.item_format??"toon",t.typeRegistry.type_to_folder,t.settings.schema),n=Ne(typeof e.options.status=="string"?e.options.status:void 0,t.statusRegistry,{strict:!0}),o=ze(t.statusRegistry),i=er(r.documents,e.options,t.typeRegistry,t.runtimeFieldFilters,n,o);return{warnings:r.warnings,allDocuments:r.documents,filteredDocuments:Zt(i,e.normalizedQuery,{titleExact:e.titleExact,phraseExact:e.phraseExact||e.matchMode==="exact"})}}async function hc(e,t,r){let n=await ki(e.includeLinked,t.effectiveMode,r),o=e.matchMode==="or";return r.map(i=>ir(i,e.tokens,e.normalizedQuery,e.includeLinked,n,t.tuning,t.settings.id_prefix,o)).filter(i=>i!==null).filter(i=>e.matchMode!=="and"||i.matched_all_terms===!0)}async function pc(e,t,r,n,o){if(t.bm25Mode===null||t.effectiveMode==="keyword")return null;let i=fr({requestedMode:t.effectiveMode,query:e.query,filteredDocuments:r,keywordHits:n,corpusFields:$n(t.settings),bm25Params:li(t.settings),hybridSemanticWeight:t.hybridSemanticWeight});return t.bm25Mode==="auto-fallback"&&o.push(`search_${t.effectiveMode}_offline_bm25:no_embedding_provider:using_lexical_bm25`),i}async function yc(e,t,r,n){if(!t.extensionSearchProvider)return null;let o=t.providerResolution.active!==null&&(t.vectorResolution.active!==null||t.extensionVectorAdapter!==null);try{let i=await Promise.resolve(t.extensionSearchProvider.query({query:e.query,mode:t.effectiveMode,tokens:e.tokens,options:e.options,settings:t.settings,documents:r}));return dr(t.extensionSearchProvider.providerName,i,n)}catch(i){if(!o)throw new h(`Extension search provider "${t.extensionSearchProvider.providerName}" failed: ${i instanceof Error?i.message:String(i)}`,f.GENERIC_FAILURE);return null}}function gc(e,t,r,n){return t.vectorMatchCount>0?t.hits:(n.push(`search_${e}_degraded:no_vector_matches:results_are_lexical`),e==="semantic"?r:t.hits)}async function _c(e,t,r,n,o){let i=!e.extensionSearchProvider&&e.providerResolution.active!==null&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null);o&&i&&await ar(e.pmRoot,r,n),e.extensionSearchProvider||it(t,e.providerResolution,e.vectorResolution,e.extensionVectorAdapter!==null)}async function wc(e){let{prepared:t,runtime:r,filteredDocuments:n,keywordHits:o,warnings:i,modeWasExplicit:s}=e,a=o,c=await pc(t,r,n,o,i),d=r.effectiveMode;if(c!==null||d==="keyword")return{effectiveMode:r.effectiveMode,hits:c??a};try{if(await _c(r,d,n,i,s),n.length===0||t.limit===0)return{effectiveMode:r.effectiveMode,hits:[]};let l=new Map(n.map(u=>[u.metadata.id,u]));if(a=await yc(t,r,n,l)??a,a===o){let{provider:u,vectorStore:m}=it(d,r.providerResolution,r.vectorResolution,r.extensionVectorAdapter!==null),p=await yr({requestedMode:d,query:t.query,filteredDocuments:n,keywordHits:o,hybridSemanticWeight:r.hybridSemanticWeight,limit:t.limit,maxResults:r.maxResults,provider:u,vectorStore:m,extensionVectorAdapter:r.extensionVectorAdapter,queryExpansion:r.queryExpansion,queryExpansionExtension:r.queryExpansionExtension,rerank:r.rerank,rerankExtension:r.rerankExtension,warnings:i,settings:r.settings});a=gc(d,p,o,i)}return{effectiveMode:r.effectiveMode,hits:a}}catch(l){return i.push(sr(r.effectiveMode,l)),{effectiveMode:"keyword",hits:o}}}function Fi(e){e.searchOptions.after!==void 0&&Qr(e.searchOptions.after,Vt(e))}async function Di(e,t,r){Ai(t);let n=xi(e,t),o=await uc(n,r),i=await fc(n,o),s=i.warnings;s.push(...n.inlineWarnings);let a=await _o(i.allDocuments.map(E=>E.metadata),{pmRoot:o.pmRoot,statusRegistry:o.statusRegistry,now:I()});s.push(...a.warnings);let c=wo(a,n.query);o.effectiveMode==="hybrid"&&o.semanticWeightProvided&&o.semanticWeightOverride===void 0&&s.push("search_hybrid_semantic_weight_override_invalid:using_settings_default");let d={query:n.query,modeSource:o.modeSource,matchMode:n.matchMode,options:n.options,includeLinked:n.includeLinked,titleExact:n.titleExact,phraseExact:n.phraseExact,scoreThreshold:o.scoreThreshold,hybridSemanticWeight:o.hybridSemanticWeight,queryExpansion:o.queryExpansion,rerank:o.rerank,projection:n.projection,warnings:s,runtimeFieldFilters:o.runtimeFieldFilters};if(o.effectiveMode==="keyword"&&(i.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Fi({query:n.query,mode:o.effectiveMode,searchOptions:n.options,pmRoot:o.pmRoot}),Ie(Ar({...d,effectiveMode:o.effectiveMode},n.countOnly),c);let l=await hc(n,o,i.filteredDocuments),u=await wc({prepared:n,runtime:o,filteredDocuments:i.filteredDocuments,keywordHits:l,warnings:s,modeWasExplicit:n.modeWasExplicit});if(u.effectiveMode!=="keyword"&&u.hits.length===0&&(i.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Fi({query:n.query,mode:u.effectiveMode,searchOptions:n.options,pmRoot:o.pmRoot}),Ie(Ar({...d,effectiveMode:u.effectiveMode},n.countOnly),c);let m=u.hits.filter(E=>E.exact_id_match===!0||E.score>=o.scoreThreshold),p=or(m,o.statusRegistry),g=p.length,_=ni({pmRoot:o.pmRoot,sorted:p,query:n.query,mode:u.effectiveMode,searchOptions:n.options,limit:n.limit??o.maxResults}),y={...d,effectiveMode:u.effectiveMode};if(n.countOnly)return Ie(Ci(y,g),c);let{hits:w,projection:v}=Ti(n,i.filteredDocuments,_.limited),b=xr(w,v);return Ie(Mi(y,b,g,_.limited.length,v,_.pageExtras),c)}(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]="f303192a-cac2-588b-b988-e3a8132f4199")}catch{}})();var Pi=["ndcg","mrr","precision","recall"];function Tr(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Eval minimum must be an object of metric floors");let t={};for(let[r,n]of Object.entries(e)){if(!Pi.some(o=>o===r))throw new TypeError(`Unknown eval minimum metric: ${r}`);if(typeof n!="number"||!Number.isFinite(n)||n<0||n>1)throw new TypeError(`Eval minimum.${r} must be a finite number in [0, 1]`);t[r]=n}return t}function Hi(e,t){let r=Tr(t),n=[];for(let o of Pi){let i=r[o];if(i===void 0)continue;let s=e[o];!Number.isFinite(s)||s<0||s>1?n.push(`${o}:invalid`):s<i&&n.push(`${o}:${s}<${i}`)}return n}(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]="c34cc860-67c7-548b-99ff-f4155ef44bb0")}catch{}})();var Oi=10,$="https://schema.unbrained.dev/pm/eval-query-set/v1",bc={schema:$,accepted_top_level:["array","object"],required_query_fields:["query","relevant_ids"],optional_fields:["mode","description","minimum"],modes:["keyword","semantic","hybrid"]},ct={schema:$,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},D=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},vc=new Set(["keyword","semantic","hybrid"]);function Li(e,t){let r=0,n=Math.min(t,e.length);for(let o=0;o<n;o+=1)r+=e[o]/Math.log2(o+2);return r}function Ec(e,t,r){if(t.size===0)return 0;let n=e.map(a=>t.has(a)?1:0),o=Li(n,r),i=Array.from({length:t.size},()=>1),s=Li(i,r);return s===0?0:o/s}function Sc(e,t,r){let n=Math.min(r,e.length);for(let o=0;o<n;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function Mr(e,t,r){let n=Math.min(r,e.length),o=0;for(let i=0;i<n;i+=1)t.has(e[i])&&(o+=1);return o}function Ic(e,t,r){return r<=0?0:Mr(e,t,r)/r}function kc(e,t,r){return t.size===0?0:Mr(e,t,r)/t.size}function ji(e,t,r){return{ndcg:Ec(e,t,r),mrr:Sc(e,t,r),precision:Ic(e,t,r),recall:kc(e,t,r),relevant_total:t.size,retrieved_relevant:Mr(e,t,r)}}function qi(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let r=e.reduce((n,o)=>({ndcg:n.ndcg+o.ndcg,mrr:n.mrr+o.mrr,precision:n.precision+o.precision,recall:n.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:r.ndcg/t,mrr:r.mrr/t,precision:r.precision/t,recall:r.recall/t,query_count:t}}function Rc(e,t){if(typeof e!="object"||e===null)throw new D(`Eval query at index ${t} must be an object`);let r=e,n=typeof r.query=="string"?r.query.trim():"";if(n.length===0)throw new D(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(r.relevant_ids))throw new D(`Eval query at index ${t} must have a "relevant_ids" array`);if(r.relevant_ids.some(i=>typeof i!="string"))throw new D(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(r.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new D(`Eval query at index ${t} must list at least one relevant id`);if(r.mode!==void 0&&(typeof r.mode!="string"||!vc.has(r.mode)))throw new D(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:n,relevant_ids:o,...r.minimum===void 0?{}:{minimum:Tr(r.minimum)},...r.mode!==void 0?{mode:r.mode}:{},...typeof r.description=="string"&&r.description.trim().length>0?{description:r.description.trim()}:{}}}function Fr(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==$)throw new D(`Unsupported eval query set schema; expected "${$}"`);let r=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(r))throw new D('Eval query set must be an array of queries or an object with a "queries" array');if(r.length===0)throw new D("Eval query set must contain at least one query");return{schema:$,queries:r.map((n,o)=>Rc(n,o))}}import xc from"node:fs/promises";import Dr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d26721c-719a-5c7e-8baf-72cbf1088988")}catch{}})();var Ac=Dr.join("search","eval-queries.json"),Pr={schema:$,examples:[JSON.stringify(ct)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},Cc=new Set(["keyword","semantic","hybrid"]),Tc=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!Cc.has(t))throw new h("Eval --mode must be one of keyword|semantic|hybrid",f.USAGE);return t},Mc=e=>{if(e===void 0||e==="")return Oi;let t=xe(e);if(t===null)throw new h("Eval --k must be a positive integer",f.USAGE);return t},Fc=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),r=Number(t);if([t.length===0,!Number.isFinite(r),r<0,r>1].includes(!0))throw new h("Eval --fail-under must be a number in the range [0, 1]",f.USAGE);return r},W=e=>Math.round(e*1e4)/1e4,Dc=async e=>{try{return await xc.readFile(e,"utf8")}catch{throw new h(`Eval query set not found at ${e}`,f.NOT_FOUND,{...Pr,examples:[`echo '${JSON.stringify(ct)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},Pc=(e,t)=>{try{return JSON.parse(e)}catch(r){throw new h(`Eval query set at ${t} is not valid JSON: ${r instanceof Error?r.message:String(r)}`,f.USAGE,Pr)}},Hc=e=>{try{return Fr(e)}catch(t){throw new h(t instanceof Error?t.message:String(t),f.USAGE,Pr)}},Lc=async e=>Hc(Pc(await Dc(e),e)),Oc=async(e,t,r,n)=>{let o=e.mode??t,i=(await Di(e.query,{mode:o,limit:String(r),fields:"id"},n)).items.map(a=>a.id).filter(a=>typeof a=="string"),s=ji(i,new Set(e.relevant_ids),r);return{metrics:s,report:{query:e.query,...e.minimum===void 0?{}:{violations:Hi(s,e.minimum)},mode:o,relevant_total:s.relevant_total,retrieved_relevant:s.retrieved_relevant,ndcg:W(s.ndcg),mrr:W(s.mrr),precision:W(s.precision),recall:W(s.recall)}}},jc=(e,t,r,n)=>{let o=qi(r);return{k:e,query_count:t.length,aggregate:{ndcg:W(o.ndcg),mrr:W(o.mrr),precision:W(o.precision),recall:W(o.recall)},queries:t,...n!==void 0?{fail_under:n}:{},passed:(n===void 0||o.ndcg>=n)&&t.every(i=>(i.violations?.length??0)===0)}},Sf=async(e,t)=>{let r=A(process.cwd(),t.path);await H(r);let n=Mc(e.k),o=Tc(e.mode),i=Fc(e.failUnder),s=e.queries?Dr.resolve(process.cwd(),e.queries):Dr.join(r,Ac),a=await Lc(s),c=[],d=[];for(let l of a.queries){let{report:u,metrics:m}=await Oc(l,o,n,t);d.push(m),c.push(u)}return jc(n,c,d,i)};export{Ji as a,es as b,il as c,sl as d,kl as e,Rl as f,Ct as g,Mo as h,Fo as i,Do as j,Xl as k,yd as l,hd as m,Ed as n,Sd as o,Qo as p,Yo as q,Xo as r,zs as s,Lt as t,Xd as u,Jd as v,cu as w,Gt as x,$t as y,Wt as z,Bt as A,zt as B,Vt as C,ni as D,oe as E,ie as F,nt as G,ot as H,bi as I,vi as J,af as K,Di as L,Pi as M,Tr as N,Hi as O,$ as P,bc as Q,ct as R,Fr as S,Ac as T,Sf as U};
6
- //# sourceMappingURL=chunk-XYLBOXSH.js.map
@@ -1,4 +0,0 @@
1
- import{d as g}from"./chunk-LNKPH2DD.js";import{b as m}from"./chunk-VS565KBX.js";import"./chunk-3CYXE6BV.js";import"./chunk-XAWE4EAK.js";import{execFile as T}from"node:child_process";import{realpath as E}from"node:fs/promises";import I from"node:path";import{promisify as D}from"node:util";(function(){try{var n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new n.Error().stack;r&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[r]="a29ee03b-9955-56c6-a72e-1e93182e5de8")}catch{}})();var h=D(T),_="[a-f0-9]{40}(?:[a-f0-9]{24})?",$=new RegExp(`^100(?:644|755) (${_}) 0$`,"u"),M=new RegExp(`^(${_}) blob (\\d+)$`,"u");async function y(n,r,s){let t=h("git",n,{...s,encoding:"buffer"}),e=t.child.stdin;return e!==null&&(e.on("error",()=>{t.child.kill()}),e.end(`${r.join(`
2
- `)}
3
- `)),(await t).stdout}function N(n,r){let s=new Map;for(let t of n.split("\0")){let e=t.indexOf(" "),i=t.slice(e+1),o=$.exec(t.slice(0,e));o!==null&&r.has(i)&&s.set(i,o[1])}return s}function B(n,r,s){let t=[],e=[],i=0;for(let o of n.trimEnd().split(/\r?\n/u)){let c=M.exec(o);if(c===null||!r.has(c[1]))continue;let l=Number(c[2]);!Number.isSafeInteger(l)||l>s||(e.length>0&&i+l+128>s&&(t.push(e),e=[],i=0),e.push({id:c[1],size:l}),i+=l+128)}return e.length>0&&t.push(e),t}function O(n,r,s){let t=0;for(let{id:e,size:i}of r){let o=n.indexOf(10,t)+1;if(o===0||n.subarray(t,o-1).toString("ascii")!==`${e} blob ${i}`||n[o+i]!==10)throw new Error("Invalid indexed receipt batch framing");s.set(e,n.subarray(o,o+i).toString("utf8")),t=o+i+1}if(t!==n.length)throw new Error("Unexpected indexed receipt batch data")}async function z(n,r,s,t){let e=m();e.GIT_NO_REPLACE_OBJECTS="1",process.env.GIT_INDEX_FILE!==void 0&&(e.GIT_INDEX_FILE=I.resolve(process.env.GIT_INDEX_FILE));let i={cwd:n,env:e,windowsHide:!0,timeout:1e4,maxBuffer:t+256};try{let o=(await h("git",["rev-parse","--show-toplevel"],{...i,encoding:"utf8"})).stdout.trim(),[c,l]=await Promise.all([E(o),E(r)]),f=I.relative(c,l).replaceAll("\\","/");if(g(f))return new Map;i.cwd=c;let b=new Map(s.map(a=>[`${f}/${a}`,a])),v=(await h("git",["ls-files","--stage","-z","--",`:(literal)${f}/`],{...i,encoding:"utf8"})).stdout,d=N(v,new Set(b.keys()));if(d.size===0)return new Map;let w=new Set(d.values()),x=(await y(["cat-file","--batch-check"],[...w],i)).toString("utf8"),p=new Map;for(let a of B(x,w,t))O(await y(["cat-file","--batch"],a.map(u=>u.id),i),a,p);return new Map([...d].filter(([,a])=>p.has(a)).map(([a,u])=>[b.get(a),p.get(u)]))}catch{return new Map}}export{z as readIndexedReceiptBlobs};
4
- //# sourceMappingURL=indexed-receipt-blobs-47I6KKDO.js.map
@@ -1,20 +0,0 @@
1
- import{a as wt}from"./chunk-YCCGZHOR.js";import"./chunk-SGFQQXFD.js";import"./chunk-DEZPZOQ7.js";import{b as le,f as St,k as At,l as kt,m as _t,n as xt,p as Ct,q as Dt}from"./chunk-HMJSFWHK.js";import{a as he}from"./chunk-O3ZTGRIH.js";import{$ as Xt,A as vt,B as ht,C as bt,T as Bt,U as jt,V as qt,W as Vt,X as zt,Y as Jt,Z as Kt,_ as Wt,aa as ae,ba as ne,ca as re,p as ot,q as dt,r as ct,s as pt,t as te,u as oe,v as ie,w as ft,x as gt}from"./chunk-FNZT4BTE.js";import"./chunk-MVJGGCGQ.js";import"./chunk-XYLBOXSH.js";import{$a as lt,Hc as yt,Qa as at,Ya as nt,Zb as ee,_a as rt,ab as st,tc as ut,ya as tt,yc as mt}from"./chunk-7C3GCLOO.js";import"./chunk-RLXK2S7P.js";import{$ as Ye,A as xe,B as Ce,C as De,D as Ie,E as Re,G as Te,H as Ee,I as Oe,J as Fe,K as Me,L as Pe,M as Ne,N as $e,O as He,P as Le,Q as Ue,R as Ge,S as Be,T as je,U as qe,V as Ve,W as ze,X as Je,Y as Ke,Z as We,_ as Xe,aa as Ze,ba as Qe,ca as et,x as L}from"./chunk-4GD6QOP6.js";import{sa as it,zb as Q}from"./chunk-444VPGQT.js";import"./chunk-4D25HF3V.js";import{Jf as E,Kc as I,Le as W,Nf as y,Oe as Ae,Qf as c,Rc as z,Rf as l,Sf as w,Tf as O,Uc as J,Uf as H,Vf as X,Wf as Y,Xf as _e,cc as we,gg as b,nc as V,oc as Se,uc as C,xf as ke,ye as K}from"./chunk-5ZPT67NJ.js";import"./chunk-RUKSEZE7.js";import"./chunk-TLMXSYJA.js";import{o as Z}from"./chunk-RD6UW3MW.js";import"./chunk-IB7UB5TE.js";import{Cd as j,Kf as h,N as ye,Nf as f,Of as v,Sa as ve,ga as ge,jb as B,og as be,oh as q,xa as x,zi as T}from"./chunk-RQKDANP7.js";import"./chunk-LNKPH2DD.js";import"./chunk-VS565KBX.js";import{A as p,C as u}from"./chunk-3CYXE6BV.js";import{a as fe}from"./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]="48b9050b-3290-55d6-82cc-b9d14cc33186")}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]="f111051f-3880-5ff0-9138-5166cd8a93a9")}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]="e599b2e9-fc63-5982-b7cf-ae208c127f62")}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]="fd8685dd-856f-51b2-9bfa-f1df88acb070")}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]="e972ba26-a7b8-5e91-9e63-21416be686eb")}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]="a310e747-0cd7-5dff-b8a0-29d3c4ded9f3")}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]="f27f4c13-4b15-5536-bc5a-b1f263fab5db")}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]="529dd34d-5a81-504f-9641-28093d41d247")}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]="6e6bec6b-9415-5f41-87e8-2d1248fba748")}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]="fd91be06-efd5-5b43-895a-e47a1c144333")}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]="5760feb1-435b-5b0e-b4ed-c22f6a955bed")}catch{}})();var F={};fe(F,{PROFILE_SUBCOMMANDS:()=>Bt,formatProfileApplyHuman:()=>Xt,formatProfileLintHuman:()=>Wt,formatProfileListHuman:()=>Jt,formatProfileShowHuman:()=>Kt,runProfileApply:()=>zt,runProfileLint:()=>Vt,runProfileList:()=>jt,runProfileShow:()=>qt});(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]="2d367793-8aa5-5a00-8c8c-60512a27f62a")}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]="e8448334-e87d-5984-9e89-04e506e0a2a7")}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]="12792dbc-d8ac-50aa-8ebd-bc68a70fa195")}catch{}})();async function se(e){typeof e.description=="string"&&e.description.trim()==="-"&&(e.description=await C().resolveValue(e.description,"--description")??"")}import{readFile as Yt}from"node:fs/promises";import Zt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6154c844-0615-5c2a-ac12-48cb73783d53")}catch{}})();async function Qt(e,t,o,i){let a=y(i),r=o.expectedResult??o.expected,n=await ft(e,t,{status:typeof o.status=="string"?o.status:void 0,expectedResult:typeof r=="string"?r:void 0,author:typeof o.author=="string"?o.author:a.author,message:typeof o.message=="string"?o.message:void 0,force:o.force===!0},a);await b(a,n),f(n,a)}async function eo(e,t){let o=typeof e.from=="string"?e.from.trim():"";if(o.length>0&&o!=="-"){if(t.getOptionValueSource("stdinJson")==="cli")throw new u("pm item mutate cannot combine --from <path> with explicit --stdin-json. Select one input source.",p.USAGE);try{return await Yt(Zt.resolve(process.cwd(),o),"utf8")}catch(i){throw new u(`pm item mutate could not read --from ${o}: ${he(i)}`,p.USAGE,{code:"mutation_document_unreadable",required:"Pass a readable JSON, JSON Lines, or envelope document path, or `-` for stdin.",why:"The whole document must be available before any tracker write begins."})}}return await C().resolveValue("-","--stdin-json")??""}async function to(e,t){let o=y(t),i=await eo(e,t);if(i.trim().length===0)throw new u("pm item mutate requires a non-empty JSON batch on stdin or via --from <path>.",p.USAGE);if(e.transactionId!==void 0&&(typeof e.transactionId!="string"||e.transactionId.trim().length===0))throw new u("pm item mutate requires --transaction-id <value> to be non-empty when provided.",p.USAGE);let a=x(process.cwd(),o.path),r=await T(a),n=await Dt({pmRoot:a,input:i,settings:r,...typeof e.transactionId=="string"?{transactionId:e.transactionId}:{},...typeof e.upsertKey=="string"?{upsertKey:e.upsertKey}:{}}),{mutations:s,references:d,rows:m}=n,g=n.transaction_id,S={transaction_id:g,transaction_id_source:n.transaction_id_source,...n.upsert_key===void 0?{}:{upsert_key:n.upsert_key}},A=le(e),D=q(typeof e.author=="string"?e.author:o.author,r.author_default);if(e.dryRun===!0){let R=await Ct({pmRoot:a,author:D,plan:n});f({...S,dry_run:!0,validation:R.validation,mutation_count:s.length,mutations:s,references:d,rows:R.rows},o);return}let $=await kt({pmRoot:a,transactionId:g,author:D,mutations:s,...A});f({...$,...S,mutation_count:s.length,references:d,rows:m},o)}function oo(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():typeof t=="string"?t.trim():""}async function io(e,t,o,i){let a=y(i),r=typeof o.transactionId=="string"?o.transactionId.trim():"";if(r.length===0)throw new u("pm item complete requires --transaction-id <value>.",p.USAGE);let n=oo(t,o.reason);if(n.length===0)throw new u("pm item complete requires a close reason.",p.USAGE);let s=Object.fromEntries(["file","doc","test","comment","note","learning"].filter(k=>o[k]!==void 0).map(k=>[k,o[k]])),d=o.force===!0,{lockTtlSeconds:m,lockWaitMs:g}=le(o),S={...typeof o.resolution=="string"?{resolution:o.resolution}:{},...typeof o.expectedResult=="string"?{expectedResult:o.expectedResult}:{},...typeof o.actualResult=="string"?{actualResult:o.actualResult}:{},...typeof o.completedAt=="string"?{completedAt:o.completedAt}:{},...typeof o.validateClose=="string"?{validateClose:o.validateClose}:{},...d?{force:!0}:{}},A={id:e,reason:n,...Object.keys(s).length===0?{}:{evidence:s},...Object.keys(S).length===0?{}:{closeOptions:S},...d?{releaseOptions:{force:!0}}:{}},D=x(process.cwd(),a.path),$=q(typeof o.author=="string"?o.author:a.author,(await T(D)).author_default);if(o.dryRun===!0){let k=_t(A),Gt=await At({pmRoot:D,transactionId:r,author:$,mutations:k});f({transaction_id:r,dry_run:!0,validation:Gt,mutation_count:k.length,mutations:k},a);return}let R=await xt({pmRoot:D,transactionId:r,author:$,...A,lockTtlSeconds:m,lockWaitMs:g});f({...R,mutation_count:Object.keys(R.results).length},a)}function It(e){let t=e.commands.find(o=>o.name()==="item")??e.command("item").description("Run item lifecycle operations.");t.command("reopen <id> <reason>").option("--status <value>","Active target status: open or in_progress").option("--expected-result <value>","Current active planning expectation; otherwise the receipt offers recovery").option("--expected <value>","Alias for --expected-result").option("--message <value>","Human-readable recurrence history message").option("--force","Override ownership or stale-lock conflicts").option("--author <value>","Mutation author").description("Reopen terminal work with recurrence evidence.").action(Qt),t.command("mutate").option("--transaction-id <value>","Stable idempotency key used to resume an interrupted batch; derived from the document when omitted").option("--stdin-json","Read the JSON mutation array from stdin",!0).option("--from <path>","Read the JSON, JSON Lines, or envelope document from a file (- for stdin)").option("--upsert-key <field>","Update the existing item whose field matches instead of creating a duplicate").option("--dry-run","Validate and preview the batch without writing").option("--create-compensation <mode>","Created-item compensation policy: close or delete","close").option("--lock-ttl-seconds <n>","Workspace transaction lock lifetime in seconds").option("--lock-wait-ms <n>","Maximum time to wait for the workspace transaction lock").option("--author <value>","Mutation author").description("Apply SDK-backed mutations atomically.").action(to),t.command("complete <id> [reason]").requiredOption("--transaction-id <value>","Stable idempotency key for the composed completion").option("--reason <value>","Close reason when omitted positionally").option("--file <value>","Linked file evidence",c).option("--doc <value>","Linked documentation evidence",c).option("--test <value>","Linked test evidence",c).option("--comment <value>","Evidence comment",c).option("--note <value>","Completion note",c).option("--learning <value>","Durable completion learning",c).option("--resolution <value>","Structured resolution evidence").option("--expected-result <value>","Expected result evidence").option("--actual-result <value>","Actual result evidence").option("--completed-at <value>","Actual completion time").option("--validate-close <mode>","Close validation: off, warn, or strict").option("--lock-ttl-seconds <n>","Workspace transaction lock lifetime in seconds").option("--lock-wait-ms <n>","Maximum time to wait for the workspace transaction lock").option("--dry-run","Validate and preview completion without writing").option("--force","Override lifecycle and ownership conflicts").option("--author <value>","Completion author").description("Close with evidence and release the claim.").action(io)}(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]="458845bd-2d07-59d5-b322-6ab634fcefa9")}catch{}})();async function ao(e,t){let o=y(t),i=Array.isArray(e.event)?e.event:[],a=await tt(x(process.cwd(),o.path),{historyEvent:i,allActionable:e.allActionable===!0,dryRun:e.dryRun===!0,planFingerprint:l(e,"planFingerprint"),limit:e.limit,attributedAuthor:l(e,"attributedAuthor"),reviewer:l(e,"reviewer"),reason:l(e,"reason")});f(a,o)}function Rt(e){e.command("history-author-acknowledge").option("--event <item-id:line>","Unknown-author event coordinate (repeatable)",c).option("--all-actionable","Select all actionable events").option("--dry-run","Preview a deterministic source-bound plan").option("--plan-fingerprint <sha256>","Apply the exact fingerprint returned by --dry-run").option("--limit <n>","Maximum coordinate rows returned in the plan").option("--attributed-author <value>","Reviewed principal attribution").option("--reviewer <value>","Disposition reviewer").option("--reason <value>","Review evidence").description("Append audited dispositions for immutable unknown-author events.").action(ao)}(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]="53ca90df-8382-5cc2-8906-8491afe5101a")}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]="e2514244-d31d-5ee4-b037-b9101f9a24e1")}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]="10a4ed4d-39d3-5b7b-87b1-4a6f95f0f2ab")}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]="796e71dc-4693-50da-bbb8-57b19ff0af95")}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]="e464e0e0-01a2-56c9-a05d-9b1b9dd6a6ee")}catch{}})();function de(e,t,o,i){if(t.trim().toLowerCase()!=="add"||!o?.trim())return;let a=l(i,"add")??l(i,"text")??l(i,"note")??l(i,"body")??l(i,"comment"),r=l(i,"file"),n=[e,o.trim()];a!==void 0?n.push("--add",a):i.stdin===!0?n.push("--stdin"):r!==void 0?n.push("--file",r):n.push("--add","-");let s=j(n),d=j([e,o.trim(),"--add","-"]);throw new u(`The positional token "add" was parsed as the item id, while "${o.trim()}" was parsed as annotation text. ${e} does not use an add subcommand.`,p.USAGE,{code:"annotation_transposed_subcommand",reason:"noun_verb_object_transposition",required:`Place the item id immediately after ${e}, then use --add for annotation text.`,examples:[...new Set([s,d])],recovery:{attempted_command:`pm ${e} add ${o.trim()}`,normalized_args:[e,"add",o.trim()],parsed_positionals:[{role:"transposed_subcommand",value:"add"},{role:"item_id",value:o.trim()}],suggested_retry:s}})}function Tt(e,t,o){let i=o.flatMap(a=>{let r=l(t,a);return r===void 0?[]:[{alias:a,value:r}]});if([...new Set(i.map(({value:a})=>a))].length>1)throw new u(`Specify ${e} text with one alias or the same value across aliases: ${i.map(({alias:a})=>`--${a}`).join(", ")}`,p.USAGE,{code:"annotation_alias_conflict"});return i[0]?.value}function no(e,t){let o=typeof t.edit=="number"?t.edit:void 0,i=typeof t.delete=="number"?t.delete:void 0,a=Tt("comment",t,["add","text","body","comment"]),r=typeof e=="string"?e:void 0,n=t.stdin===!0,s=l(t,"file");if(+(a!==void 0)+ +(r!==void 0)+Number(n)+ +(s!==void 0)>1)throw a!==void 0&&r!==void 0&&!n&&s===void 0?new u("Specify comment text either as positional [text] or with --add, not both",p.USAGE):new u("Specify comment text with exactly one source: positional [text], --add, --stdin, or --file",p.USAGE);let d=a??r;return{add:d,readFromStdin:n,readFromFile:s,editIndex:o,deleteIndex:i,isMutation:typeof d=="string"||n||s!==void 0||o!==void 0||i!==void 0}}function Et(e,t,o){let i=Tt(e,o,e==="note"?["add","text","note"]:["add","text"]),a=typeof t=="string"?t:void 0;if(i!==void 0&&a!==void 0)throw new u(`Specify ${e} text either as positional [text] or with --add, not both`,p.USAGE);let r=i??a,n=e==="note"?l(o,"addJson"):void 0,s=o.stdin===!0,d=l(o,"file"),m=typeof o.edit=="number"?o.edit:void 0,g=typeof o.delete=="number"?o.delete:void 0;return{add:r,addJson:n,readFromStdin:s,readFromFile:d,editIndex:m,deleteIndex:g,isMutation:typeof r=="string"||n!==void 0||s||d!==void 0||m!==void 0||g!==void 0}}async function ro(e,t,o,i){let a=y(i),r=Date.now();de("comments",e,t,o);let n=no(t,o),s=await ot(e,{add:n.add,stdin:n.readFromStdin,file:n.readFromFile,edit:n.editIndex,delete:n.deleteIndex,limit:l(o,"limit"),fullHistory:o.fullHistory===!0,ifAbsent:o.ifAbsent===!0,author:l(o,"author"),message:l(o,"message"),ownershipAppendBypass:o.ownershipAppendBypass===!0,force:!!o.force},a);n.isMutation&&s.changed!==!1&&await b(a,s),ce("comments",s,a,r)}async function lo(e,t,o,i){let a=y(i),r=Date.now();de("notes",e,t,o);let n=Et("note",t,o),s=await bt(e,{add:n.add,addJson:n.addJson,stdin:n.readFromStdin,file:n.readFromFile,edit:n.editIndex,delete:n.deleteIndex,limit:l(o,"limit"),since:l(o,"since"),eventType:l(o,"eventType"),includeMeta:o.includeMeta===!0,fullHistory:o.fullHistory===!0,ifAbsent:o.ifAbsent===!0,author:l(o,"author"),message:l(o,"message"),ownershipAppendBypass:o.ownershipAppendBypass===!0,force:!!o.force},a);n.isMutation&&s.changed!==!1&&await b(a,s),ce("notes",s,a,r)}async function so(e,t,o,i){let a=y(i),r=Date.now();de("learnings",e,t,o);let n=Et("learning",t,o),s=await dt(e,{add:n.add,stdin:n.readFromStdin,file:n.readFromFile,edit:n.editIndex,delete:n.deleteIndex,limit:l(o,"limit"),fullHistory:o.fullHistory===!0,ifAbsent:o.ifAbsent===!0,author:l(o,"author"),message:l(o,"message"),ownershipAppendBypass:o.ownershipAppendBypass===!0,force:!!o.force},a);n.isMutation&&s.changed!==!1&&await b(a,s),ce("learnings",s,a,r)}function ce(e,t,o,i){f(t,o),o.profile&&v(`profile:command=${e} took_ms=${Date.now()-i}`)}function Ot(e,t){let o=e.command("comments").argument("<id>","Item id").argument("[text]","Optional comment text shorthand (equivalent to --add)").option("--add <text>","Append comment text; use text=<value> for structured input or - for stdin").option("--stdin","Read comment text from stdin (supports multiline markdown)").option("--file <path>","Read comment text from a file or stdin (-)").option("--edit <index>","Replace one comment using positional text, --add, --stdin, or --file",t("--edit")).option("--delete <index>","Delete the comment at 1-based <index>",t("--delete")).option("--limit <n>","Return only latest n comments").option("--full-history","Return complete comment history instead of a bounded mutation receipt").option("--if-absent","Append only when resolved author and text are absent").option("--author [value]","Comment author; defaults to PM_AUTHOR or settings").option("--message <value>","History message").option("--force","Force ownership override").description("List, add, edit, or delete comments for an item.").action(ro);w(o,"--body <text>","Alias for --add",!1),w(o,"--text <text>","Alias for --add",!1),w(o,"--comment <text>","Alias for --add",!1);let i=e.command("notes").argument("<id>","Item id").argument("[text]","Optional note text shorthand for --add").option("--add <text>","Add a text note (- reads stdin)").option("--note <text>","Alias for --add").option("--add-json <json>","Append a JSON event").option("--stdin","Read note text from stdin").option("--file <path>","Read note from file or stdin (-)").option("--edit <index>","Replace a 1-based note using the selected text input",t("--edit")).option("--delete <index>","Delete the note at 1-based <index>",t("--delete")).option("--limit <n>","Return only latest n notes").option("--since <timestamp>","Filter JSON events from this ISO time").option("--event-type <value>","Filter JSON events by top-level type").option("--include-meta","Include count and truncation metadata").option("--full-history","Return complete note history instead of a bounded receipt").option("--if-absent","Append only when resolved author and text are absent").option("--author [value]","Author; defaults to PM_AUTHOR/settings").option("--message <value>","History message").option("--force","Force ownership override").description("Manage merge-safe text notes and JSON context events.").action(lo);w(i,"--text <text>","Alias for --add",!1);let a=e.command("learnings").argument("<id>","Item id").argument("[text]","Optional learning text shorthand for --add").option("--add <text>","Append learning text; use text=<value> or - for stdin").option("--stdin","Read learning text from stdin").option("--file <path>","Read learning text from a file or stdin (-)").option("--edit <index>","Replace one learning using positional text, --add, --stdin, or --file",t("--edit")).option("--delete <index>","Delete the learning at 1-based <index>",t("--delete")).option("--limit <n>","Return only latest n learnings").option("--full-history","Return complete learning history instead of a bounded receipt").option("--if-absent","Append only when resolved author and text are absent").option("--author [value]","Learning author (optional; falls back to PM_AUTHOR/settings)").option("--message <value>","History message").option("--force","Force ownership override").description("List, add, edit, or delete learnings for an item.").action(so);w(a,"--text <text>","Alias for --add",!1)}(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]="d861c49e-6054-54af-a733-069cd9238f8a")}catch{}})();function pe(e,t){return o=>{let i=Number(o);if(!Number.isInteger(i)||i<t)throw new u(`${e} must be an integer greater than or equal to ${t}.`,p.USAGE);return i}}async function co(e,t,o){let i=y(o);if(t.scope!==void 0&&t.scope!=="project"&&t.scope!=="global")throw new u("--scope must be either project or global.",p.USAGE);let a=await lt({paths:e,scope:t.scope,limit:typeof t.limit=="number"?t.limit:void 0,offset:typeof t.offset=="number"?t.offset:void 0,noTruncate:t.noTruncate===!0,strictRead:t.strictRead===!0,explain:t.explain===!0,lineRange:typeof t.lines=="string"?nt(t.lines):void 0,decisionDepth:typeof t.decisionDepth=="number"?t.decisionDepth:void 0},i);f(a,i)}function Ft(e){e.command("lookup").argument("<paths...>","Project-relative or absolute source paths").option("--scope <scope>","Restrict links to project or global scope").option("--limit <n>","Maximum referencing items to return",pe("--limit",1)).option("--offset <n>","Number of referencing items to skip",pe("--offset",0)).option("--no-truncate","Return every referencing item").option("--strict-read","Fail when any authoritative item cannot be read").option("--explain","Include ranked source-to-work rationale").option("--lines <start:end>","Attribute an inclusive source line range").option("--decision-depth <n>","Maximum governing-decision relationship depth",pe("--decision-depth",1)).description("Find and explain pm items that govern requested source paths.").action(co)}(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]="016842ad-f6e8-56a4-9b9f-f4eaf4c1be71")}catch{}})();var po=["add-","apply-","list-","remove-","show-"],uo=new Set(["field","fields","help","status","statuses","type","types"]);function ue(e){let t=e.trim(),o=t.toLowerCase();return o.length===0?!1:t[0]===o[0]||uo.has(o)||po.some(i=>o.startsWith(i))}function U(e){if(e!=null){if(typeof e=="number"){if(!Number.isInteger(e))throw new u("--order must be a finite integer.",p.USAGE);return e}if(typeof e=="string"){if(e.trim().length===0)return;let t=Number(e);if(!Number.isInteger(t))throw new u("--order must be a finite integer.",p.USAGE);return t}throw new u("--order must be a finite integer.",p.USAGE)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f9ea812-e170-5c91-a646-88286797d97d")}catch{}})();function M(e){if(Array.isArray(e))return e;if(typeof e=="string")return[e]}var P={};fe(P,{SCHEMA_SUBCOMMANDS:()=>De,_testOnlySchemaCommand:()=>et,formatSchemaAddFieldHuman:()=>Ke,formatSchemaAddStatusHuman:()=>je,formatSchemaAddTypeHuman:()=>Ge,formatSchemaApplyPresetHuman:()=>Ze,formatSchemaEvolutionMigrationHuman:()=>Ce,formatSchemaInferTypesHuman:()=>Qe,formatSchemaListFieldsHuman:()=>Xe,formatSchemaListHuman:()=>Ve,formatSchemaRemoveFieldHuman:()=>We,formatSchemaRemoveStatusHuman:()=>qe,formatSchemaRemoveTypeHuman:()=>Be,formatSchemaShowFieldHuman:()=>Ye,formatSchemaShowHuman:()=>ze,formatSchemaShowStatusHuman:()=>Je,runSchemaAddField:()=>Pe,runSchemaAddStatus:()=>Te,runSchemaAddType:()=>Ie,runSchemaApplyPreset:()=>Le,runSchemaEvolutionMigration:()=>xe,runSchemaInferTypes:()=>Ue,runSchemaList:()=>Oe,runSchemaListFields:()=>$e,runSchemaRemoveField:()=>Ne,runSchemaRemoveStatus:()=>Ee,runSchemaRemoveType:()=>Re,runSchemaShow:()=>Fe,runSchemaShowField:()=>He,runSchemaShowStatus:()=>Me,runWorkflowPolicyAction:()=>L});(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]="a4b4d693-ba4c-529a-a5d4-8f6c874830ad")}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]="f3dbaad8-f73e-5d14-aeaa-aaf077a944f6")}catch{}})();function mo(e,t){let o=t.normalizedSubcommand;return o!=="rename-type"&&o!=="rename-field"&&o!=="remap-status"?null:e.runSchemaEvolutionMigration({kind:o,from:t.typeName,to:l(t.options,"to"),...o==="rename-field"&&typeof t.options.type=="string"?{type:t.options.type}:{}},{migrationId:l(t.options,"migrationId")??l(t.options,"migration_id"),dryRun:t.options.dryRun===!0,author:t.author,force:t.force},t.globalOptions)}function fo(e,t){let{normalizedSubcommand:o,typeName:i,globalOptions:a,author:r,force:n}=t;switch(o){case"list":return e.runSchemaList(a);case"show":return e.runSchemaShow(i,a);case"show-status":return e.runSchemaShowStatus(i,a);case"list-fields":return e.runSchemaListFields(a);case"show-field":return e.runSchemaShowField(i,a);case"remove-type":return e.runSchemaRemoveType(i,{author:r,force:n},a);case"remove-field":return e.runSchemaRemoveField(i,{author:r,force:n},a);case"remove-status":return e.runSchemaRemoveStatus(i,{author:r,force:n},a);case"apply-preset":return e.runSchemaApplyPreset(i,{author:r,force:n},a);default:return null}}async function yo(e,t){let{normalizedSubcommand:o,typeName:i,options:a,globalOptions:r}=t,{author:n,force:s,description:d}=t,m=mo(e,t);if(m)return m;let g=fo(e,t);if(g)return g;switch(o){case"add-field":return e.runSchemaAddField(i,{type:typeof a.type=="string"?a.type:void 0,commands:t.commands,description:d,cliFlag:typeof a.cliFlag=="string"?a.cliFlag:void 0,alias:t.aliases,required:!!a.required,requiredOnCreate:!!a.requiredOnCreate,allowUnset:a.allowUnset!==!1,requiredTypes:t.requiredTypes,author:n,force:s},r);case"add-status":return e.runSchemaAddStatus(i,{role:t.roles,alias:t.aliases,description:d,order:t.order,author:n,force:s},r);default:return a.infer===!0?e.runSchemaInferTypes({minCount:t.minCount,apply:!!a.apply,author:n,force:s},r):e.runSchemaAddType(i,{description:d,defaultStatus:t.defaultStatus,folder:typeof a.folder=="string"?a.folder:void 0,alias:t.aliases,author:n,force:s},r)}}function go(e,t){if("migration_id"in t){h(`${e.formatSchemaEvolutionMigrationHuman(t)}
2
- `);return}switch(t.action){case"list":h(`${e.formatSchemaListHuman(t)}
3
- `);return;case"show":h(`${e.formatSchemaShowHuman(t)}
4
- `);return;case"show-status":h(`${e.formatSchemaShowStatusHuman(t)}
5
- `);return;case"list-fields":h(`${e.formatSchemaListFieldsHuman(t)}
6
- `);return;case"show-field":h(`${e.formatSchemaShowFieldHuman(t)}
7
- `);return;case"remove-type":h(`${e.formatSchemaRemoveTypeHuman(t)}
8
- `);break;case"remove-field":h(`${e.formatSchemaRemoveFieldHuman(t)}
9
- `);break;case"apply-preset":h(`${e.formatSchemaApplyPresetHuman(t)}
10
- `);break;case"infer-types":h(`${e.formatSchemaInferTypesHuman(t)}
11
- `);break;case"add-field":h(`${e.formatSchemaAddFieldHuman(t)}
12
- `);break;case"add-status":h(`${e.formatSchemaAddStatusHuman(t)}
13
- `);break;case"remove-status":h(`${e.formatSchemaRemoveStatusHuman(t)}
14
- `);break;default:h(`${e.formatSchemaAddTypeHuman(t)}
15
- `);break}t.warnings.length>0&&v(`schema ${t.action} warnings: ${H(t.warnings)}`)}function Mt(e){if(Array.isArray(e))return e.flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}async function vo(e,t,o,i){let a=y(i),r=Date.now(),{SCHEMA_SUBCOMMANDS:n}=P,s=(e??"").trim().toLowerCase(),d=t;if(ho(s,n),!n.includes(s)&&d===void 0&&!ue(e)&&(d=e,s="add-type"),!n.includes(s))throw I({command_path:"schema",token:s,allowed:n});let m=ve.find(g=>g===s);if(we(s,o.dryRun===!0),m)f(await L(m,t,{definition:o.definition,policy:l(o,"policy"),message:l(o,"message"),author:l(o,"author"),dryRun:o.dryRun===!0},a),a);else{let g=await yo(P,{normalizedSubcommand:s,typeName:d,options:o,aliases:M(o.alias),roles:M(o.role),commands:Mt(o.commands),requiredTypes:Mt(o.requiredTypes),defaultStatus:l(o,"defaultStatus")??l(o,"default_status"),order:U(o.order),minCount:U(o.minCount),author:l(o,"author"),force:!!o.force,description:l(o,"description"),globalOptions:a});a.json===!0||a.defaultOutputFormat==="json"?f(g,a):a.quiet||go(P,g)}a.profile&&v(`profile:command=schema took_ms=${Date.now()-r}`)}function ho(e,t){if(!e)throw new u(`pm schema requires a subcommand. Allowed: ${t.join(", ")}`,p.USAGE,{code:"missing_required_argument",examples:["pm schema list","pm schema show Task","pm schema show-status open",'pm schema add-type Spike --description "Time-boxed investigation" --default-status open',"pm schema remove-type Spike","pm schema add-status review --role active --alias in_review","pm schema remove-status review","pm schema add-field severity_level --type string --commands create,update","pm schema list-fields","pm schema apply-preset agile","pm schema add-type --infer --min-count 10","pm schema rename-type Spike --to Experiment --migration-id spike-v2 --dry-run","pm schema rename-field severity --to impact --migration-id severity-v2","pm schema remap-status review --to verifying --migration-id review-v2"]})}function Pt(e){let t=e.command("schema").option("--definition <json>","Policy or proposed fields JSON").option("--policy <id>","Policy id for policy-approve").option("--message <text>","Audit rationale for a policy mutation").argument("[subcommand]","Required; schema verb (list/show, add/remove, rename/remap, policy-*), or custom type shorthand").argument("[name]","Definition/source name or item id; policy-mode: advise|refuse").option("--description <text>","Type, status, or field description").option("--default-status <status>","Default status for this type").option("--folder <dir>","Storage folder for items of this custom type").option("--alias <name>","Alias for the custom type, status, or field flag (repeatable, csv-friendly)",c).option("--role <value>","Lifecycle role for a custom status (repeatable): draft, active, blocked, terminal, terminal_done, terminal_canceled, default_open, default_close, default_cancel",c).option("--order <n>","Display/sort order for a custom status").optionsGroup("Field options (add-field):").option("--type <type>","Value type for a custom field (add-field): string, number, boolean, string_array, array, object").option("--commands <list>","Field commands (repeatable/csv): create, update, update_many, list, search, calendar, context",c).option("--cli-flag <flag>","Override the auto-derived CLI flag for a custom field (add-field)").option("--required","Mark a custom field as always required (add-field)").option("--required-on-create","Mark a custom field as required at create time (add-field)").option("--no-allow-unset","Disallow clearing a custom field via --unset (add-field)").option("--required-types <list>","Restrict a custom field's requirement to specific item types (add-field; repeatable, comma-friendly)",c).optionsGroup("Type inference and migration options:").option("--infer","Infer custom item types from title-prefix conventions (add-type; preview unless --apply)").option("--min-count <n>","Minimum items sharing a prefix for add-type --infer (default 10)").option("--apply","Register inferred types (add-type --infer); without it the command previews only").option("--to <name>","Target definition name for rename/remap migrations").option("--migration-id <id>","Stable idempotency key for a resumable schema migration").option("--dry-run","Preview rename/remap migrations and workflow-policy actions without writes").option("--author <value>","Mutation author").option("--force","Force ownership/lock override").description("Manage types, statuses, fields, presets, and workflow policies.");w(t,"--default_status <status>","Alias for --default-status",!1),w(t,"--migration_id <id>","Alias for --migration-id",!1),t.action(vo)}(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]="9d4b7326-d103-505a-8bf1-6a2e3d176c1b")}catch{}})();var bo=new Set(ye.map(e=>e.toLowerCase())),wo=new Set(ke.map(e=>e==="estimate"?"estimatedMinutes":e));async function So(e,t,o,i,a){switch(t){case"list":return e.runProfileList();case"show":return e.runProfileShow(o);case"lint":return e.runProfileLint(o);default:return e.runProfileApply(o,{dryRun:i.dryRun===!0,author:typeof i.author=="string"?i.author:void 0,force:i.force===!0},a)}}function Ao(e,t){switch(t.action){case"list":h(`${e.formatProfileListHuman(t)}
16
- `);return;case"show":h(`${e.formatProfileShowHuman(t)}
17
- `);return;case"lint":h(`${e.formatProfileLintHuman(t)}
18
- `);return;default:h(`${e.formatProfileApplyHuman(t)}
19
- `),t.warnings.length>0&&v(`profile apply warnings: ${H(t.warnings)}`);break}}function ko(e){return t=>{let o=Number(t);if(!Number.isInteger(o)||o<1)throw new u(`${e} must be a positive integer (1-based index).`,p.USAGE);return o}}function Nt(e,t){e.option("--filter-has-notes",`Select only items that have notes before ${t}`).option("--filter-no-notes",`Select only items that have no notes before ${t}`).option("--filter-has-learnings",`Select only items that have learnings before ${t}`).option("--filter-no-learnings",`Select only items that have no learnings before ${t}`).option("--filter-has-files",`Select only items that have linked files before ${t}`).option("--filter-no-files",`Select only items that have no linked files before ${t}`).option("--filter-has-docs",`Select only items that have linked docs before ${t}`).option("--filter-no-docs",`Select only items that have no linked docs before ${t}`).option("--filter-has-tests",`Select only items that have linked tests before ${t}`).option("--filter-no-tests",`Select only items that have no linked tests before ${t}`).option("--filter-has-comments",`Select only items that have comments before ${t}`).option("--filter-no-comments",`Select only items that have no comments before ${t}`).option("--filter-has-deps",`Select only items that have dependencies before ${t}`).option("--filter-no-deps",`Select only items that have no dependencies before ${t}`).option("--filter-has-body",`Select only items that have a non-empty body before ${t}`).option("--filter-empty-body",`Select only items with an empty body before ${t}`).option("--filter-has-linked-command",`Select only items whose linked tests carry a runnable command before ${t}`).option("--filter-no-linked-command",`Select only items whose linked tests carry no runnable command before ${t}`).option("--filter-reviewer-missing",`Select only items missing reviewer before ${t}`).option("--filter-risk-missing",`Select only items missing risk before ${t}`).option("--filter-confidence-missing",`Select only items missing confidence before ${t}`).option("--filter-sprint-missing",`Select only items missing sprint before ${t}`).option("--filter-release-missing",`Select only items missing release before ${t}`)}var _o=[["filterHasNotes","filterNoNotes","--filter-has-notes","--filter-no-notes"],["filterHasLearnings","filterNoLearnings","--filter-has-learnings","--filter-no-learnings"],["filterHasFiles","filterNoFiles","--filter-has-files","--filter-no-files"],["filterHasDocs","filterNoDocs","--filter-has-docs","--filter-no-docs"],["filterHasTests","filterNoTests","--filter-has-tests","--filter-no-tests"],["filterHasComments","filterNoComments","--filter-has-comments","--filter-no-comments"],["filterHasDeps","filterNoDeps","--filter-has-deps","--filter-no-deps"],["filterHasBody","filterEmptyBody","--filter-has-body","--filter-empty-body"],["filterHasLinkedCommand","filterNoLinkedCommand","--filter-has-linked-command","--filter-no-linked-command"]];function $t(e){let t=o=>e[o]===!0?!0:void 0;for(let[o,i,a,r]of _o)if(e[o]===!0&&e[i]===!0)throw new u(`Cannot combine ${a} with ${r} for the same field.`,p.USAGE);return{filterReviewerMissing:t("filterReviewerMissing"),filterRiskMissing:t("filterRiskMissing"),filterConfidenceMissing:t("filterConfidenceMissing"),filterSprintMissing:t("filterSprintMissing"),filterReleaseMissing:t("filterReleaseMissing"),hasNotes:t("filterHasNotes"),hasLearnings:t("filterHasLearnings"),hasFiles:t("filterHasFiles"),hasDocs:t("filterHasDocs"),hasTests:t("filterHasTests"),hasComments:t("filterHasComments"),hasDeps:t("filterHasDeps"),hasBody:t("filterHasBody"),hasLinkedCommand:t("filterHasLinkedCommand"),noNotes:t("filterNoNotes"),noLearnings:t("filterNoLearnings"),noFiles:t("filterNoFiles"),noDocs:t("filterNoDocs"),noTests:t("filterNoTests"),noComments:t("filterNoComments"),noDeps:t("filterNoDeps"),emptyBody:t("filterEmptyBody"),noLinkedCommand:t("filterNoLinkedCommand")}}function me(e,t){for(let o of t){let i=[],a=e.args,r=n=>(e.args!==a&&(i.length=0,a=e.args),i.push(n),i);o.required?e.requiredOption(o.option,o.description):o.repeatable?e.option(o.option,o.description,r):e.option(o.option,o.description);for(let n of o.aliasOptions??[])K(o.option,n.option)?w(e,n.option,n.description,o.repeatable===!0,o.repeatable?r:void 0):o.repeatable?e.option(n.option,n.description,r):e.option(n.option,n.description)}}function xo(e){let t=o=>typeof e[o]=="string"?e[o]:void 0;return{type:t("filterType"),tag:t("filterTag"),priority:t("filterPriority"),deadlineBefore:t("filterDeadlineBefore"),deadlineAfter:t("filterDeadlineAfter"),updatedAfter:t("filterUpdatedAfter"),updatedBefore:t("filterUpdatedBefore"),createdAfter:t("filterCreatedAfter"),createdBefore:t("filterCreatedBefore"),ids:t("ids"),assignee:t("filterAssignee"),assigneeFilter:t("filterAssigneeFilter")??t("filterAssignee_filter"),parent:t("filterParent"),sprint:t("filterSprint"),release:t("filterRelease"),filterAcMissing:e.filterAcMissing===!0?!0:void 0,filterEstimatesMissing:e.filterEstimatesMissing===!0||e.filterEstimateMissing===!0?!0:void 0,filterResolutionMissing:e.filterResolutionMissing===!0?!0:void 0,filterMetadataMissing:e.filterMetadataMissing===!0?!0:void 0,...$t(e),limit:t("limit"),offset:t("offset"),includeBody:!0}}function N(...e){for(let t of e)if(typeof t=="string")return t}function Co(e,t,o){if(!(e!=="many"||t!==void 0||o.title!==void 0||o.type!==void 0))throw new u("pm create many is not a command; bulk creation is pm item mutate.",p.USAGE,{code:"bulk_create_route",required:"Pipe a JSON array, JSON Lines, or {schema_version, mutations} document to pm item mutate, or pass --from <path>.",why:"pm item mutate commits every record in one workspace transaction with a replay-safe transaction id, so an interrupted or repeated import never duplicates items.",nextSteps:["pm item mutate --from items.jsonl --dry-run --json","pm item mutate --from items.jsonl --upsert-key external_id --json","pm guide lifecycle"],examples:["pm item mutate --from items.jsonl --json",`printf '%s\\n' '{"title":"First","type":"Task"}' '{"title":"Second","type":"Task"}' | pm item mutate --json`]})}function Do(e,t,o){return typeof t=="string"&&t.length>0?{positionalType:e,positionalTitle:t}:typeof e!="string"||e.length===0?{positionalType:void 0,positionalTitle:void 0}:typeof o.title=="string"&&o.title.trim().length>0&&o.type===void 0?{positionalType:e,positionalTitle:void 0}:{positionalType:void 0,positionalTitle:e}}function Io(e,t,o){if(e!==void 0||typeof t!="string"||t.length===0||o.title!==void 0||o.type!==void 0||!bo.has(t.trim().toLowerCase()))return;let i=t.trim();throw new u(`pm create needs a title \u2014 "${i}" looks like an item type, not a title. Use either: pm create ${i} "<title>" or pm create "<title>" --type ${i}.`,p.USAGE,{code:"create_positional_type_without_title",why:'Without this guard the single positional is used as the title and the type defaults to Task \u2014 so the command would silently create a Task literally titled "'+i+'".',examples:[`pm create ${i} "Wire up SSO for the agent harness"`,`pm create "Wire up SSO for the agent harness" --type ${i}`],nextSteps:[`Re-run with both type and title: pm create ${i} "<title>"`]})}var Ro=["body","bodyFile","description","dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ids"];function G(e){let t=Ro.flatMap(o=>{let i=e[o],a=typeof i=="string"&&i.trim()==="-"?1:Array.isArray(i)?i.filter(n=>typeof n=="string"&&n.trim()==="-").length:0,r=`--${o.replace(/[A-Z]/g,n=>`-${n.toLowerCase()}`)}`;return Array.from({length:a},()=>r)});if(e.stdinJson===!0&&t.unshift("--stdin-json"),t.length>1)throw new u(`Only one option may consume stdin per command invocation. Found: ${t.join(", ")}.`,p.USAGE)}function Ht(e,t,o){let i=[];t&&i.push("body"),o&&i.push("description"),Se(e,i)}function Lt(e,t){return!t&&typeof e.description=="string"&&e.description.trim()==="-"}async function Ut(e,t,o,i){let a=await T(x(process.cwd(),i.path));return St(e,t,o,be(a.schema).definitions)}async function To(e,t,o,i){let a=y(i),r=Date.now();G(o);let n=o.stdinJson===!0;if(n){let A=await C().resolveValue("-","--stdin-json");o=await Ut(A??"","create",o,a)}Co(e,t,o);let s=Do(e,t,o);Io(s.positionalType,s.positionalTitle,o),typeof s.positionalType=="string"&&s.positionalType.length>0&&o.type===void 0&&(o.type=s.positionalType),typeof s.positionalTitle=="string"&&s.positionalTitle.length>0&&o.title===void 0&&(o.title=s.positionalTitle);let d=Lt(o,n);n||await se(o);let m=typeof o.bodyFile=="string";m&&(o.body=await J(String(o.bodyFile),o.body!==void 0?String(o.body):void 0),delete o.bodyFile);let g=X(o,{requireType:!1});Ht(g,m,d),n&&V(g);let S=await ut(g,a);await b(a,S),f(S,a),a.profile&&v(`profile:command=create took_ms=${Date.now()-r}`)}function Eo(e){return{type:l(e,"filterType"),tag:l(e,"filterTag"),priority:l(e,"filterPriority"),deadlineBefore:l(e,"filterDeadlineBefore"),deadlineAfter:l(e,"filterDeadlineAfter"),updatedAfter:l(e,"filterUpdatedAfter"),updatedBefore:l(e,"filterUpdatedBefore"),createdAfter:l(e,"filterCreatedAfter"),createdBefore:l(e,"filterCreatedBefore"),ids:l(e,"ids"),assignee:l(e,"filterAssignee"),assigneeFilter:N(e.filterAssigneeFilter,e.filterAssignee_filter),parent:l(e,"filterParent"),sprint:l(e,"filterSprint"),release:l(e,"filterRelease"),...$t(e),limit:l(e,"limit"),offset:l(e,"offset")}}async function Oo(e,t){let o=y(t),i=Date.now();G(e),e.ids=await z(l(e,"ids"));let a=await pt({status:l(e,"filterStatus"),list:Eo(e),reason:l(e,"reason"),completedAt:l(e,"completedAt"),resolution:l(e,"resolution"),expectedResult:N(e.expectedResult,e.expected_result,e.expected),actualResult:N(e.actualResult,e.actual_result,e.actual),validateClose:e.validateClose===!0?"warn":l(e,"validateClose"),author:l(e,"author"),message:l(e,"message"),force:!!e.force,dryRun:e.dryRun===!0?!0:void 0,rollback:l(e,"rollback"),checkpoint:e.checkpoint===!1?!1:void 0},o);await b(o,a),f(a,o),o.profile&&v(`profile:command=close-many took_ms=${Date.now()-i}`)}async function Fo(e,t){let o=y(t),i=Date.now();G(e),e.ids=await z(l(e,"ids"));let a=await ht({status:l(e,"filterStatus"),list:xo(e),update:Y(_e(e)),dryRun:e.dryRun===!0?!0:void 0,rollback:l(e,"rollback"),checkpoint:e.checkpoint===!1?!1:void 0},o);await b(o,a),f(await E("update-many",[],e,o,a),o),o.profile&&v(`profile:command=update-many took_ms=${Date.now()-i}`)}async function Mo(e,t,o,i){let a=y(i),r=Date.now(),n=typeof o.reason=="string"&&o.reason.trim().length>0&&o.reason||typeof o.closeReason=="string"&&o.closeReason.trim().length>0&&o.closeReason||void 0,s=typeof t=="string"&&t.length>0?t:n,d=await(o.releaseAssignment===!0?yt:ee)(e,s,{author:l(o,"author"),message:l(o,"message"),validateClose:o.validateClose===!0?"warn":l(o,"validateClose"),force:!!o.force,duplicateOf:l(o,"duplicateOf"),completedAt:l(o,"completedAt"),resolution:l(o,"resolution"),expectedResult:N(o.expectedResult,o.expected_result,o.expected),actualResult:N(o.actualResult,o.actual_result,o.actual)},a);await b(a,d),f(d,a),a.profile&&v(`profile:command=close took_ms=${Date.now()-r}`)}function Po(e){let t={...e},o=[["blocked_by","blockedBy"],["resume_context","resumeContext"],["from_search","fromSearch"],["step_title","stepTitle"],["step_body","stepBody"],["step_owner","stepOwner"],["step_status","stepStatus"],["step_evidence","stepEvidence"],["step_blocked_reason","stepBlockedReason"],["step_replacement","stepReplacement"],["depends_on","dependsOn"],["link_kind","linkKind"],["link_note","linkNote"],["promote_to_item_dep","promoteToItemDep"],["allow_multiple_active","allowMultipleActive"],["decision_text","decisionText"],["decision_rationale","decisionRationale"],["decision_evidence","decisionEvidence"],["discovery_text","discoveryText"],["validation_text","validationText"],["validation_command","validationCommand"],["validation_expected","validationExpected"],["materialize_type","materializeType"],["materialize_parent","materializeParent"],["materialize_tags","materializeTags"]];for(let[a,r]of o)t[a]!==void 0&&t[r]===void 0&&(t[r]=t[a]);let i=X(t,{requireType:!1});return i.blockedBy=t.blockedBy,i}function No(e,t){if(!e)throw new u(`pm plan requires a subcommand. Allowed: ${t.join(", ")}`,p.USAGE,{code:"missing_required_argument",examples:['pm plan create --title "Refactor lock retry"',"pm plan show pm-a1b2 --depth standard",'pm plan add-step pm-a1b2 --step-title "Read lock.ts"']});if(!t.includes(e))throw I({command_path:"plan",token:e,allowed:t,examples:e==="list"||e==="ls"?["pm list --type Plan","pm list --all --type Plan"]:void 0,retry_command:e==="list"||e==="ls"?"pm list --type Plan":void 0})}function $o(e,t){if(e!=="reorder-step"||typeof t!="string")return;let o=Number.parseInt(t,10);if(!Number.isFinite(o))throw new u(`reorder-step requires an integer new order, got "${t}"`,p.USAGE);return o}async function Ho(e,t,o,i,a,r){let n=y(r),s=Date.now(),d=(e??"").trim().toLowerCase();No(d,gt);let m=Po(a),g=$o(d,i),S=d==="create"&&typeof t=="string"&&t.length>0&&m.title===void 0?void 0:t;S===void 0&&typeof t=="string"&&t.length>0&&(m.title=t);let A=await vt({subcommand:d,id:S,stepRef:o,reorderTo:g,options:m,global:n});await b(n,A),f(A,n),n.profile&&v(`profile:command=plan took_ms=${Date.now()-s}`)}async function Lo(e,t,o){if(e!==void 0)throw new u("merge reconcile takes no positional arguments.",p.USAGE);let i=await re({dryRun:t.dryRun===!0,force:t.force===!0,stage:t.stage===!0,message:typeof t.message=="string"?t.message:void 0,author:o.author},o);f(i,o),i.ok||(process.exitCode=p.GENERIC_FAILURE)}async function Uo(e,t,o,i,a,r){if(e===void 0||t===void 0||o===void 0||i===void 0)throw new u("merge driver requires <artifact> <base> <ours> <theirs> (git supplies %O %A %B). Example: pm merge driver history %O %A %B",p.USAGE);let n=await ne({artifact:e,basePath:t,oursPath:o,theirsPath:i,outputPath:typeof a.output=="string"?a.output:void 0,itemPath:typeof a.itemPath=="string"?a.itemPath:void 0,prefer:typeof a.prefer=="string"?a.prefer:void 0},r);f(n,r),n.ok||(process.exitCode=p.GENERIC_FAILURE)}async function Go(e,t,o,i,a,r,n){let s=y(n),d=Date.now();switch(e.trim().toLowerCase()){case"install":{if(t!==void 0)throw new u("merge install takes no positional arguments.",p.USAGE);let m=await Z({dryRun:r.dryRun===!0,preCommitHook:r.preCommitHook===!0},s);f(m,s);break}case"reconcile":await Lo(t,r,s);break;case"report":{if(t!==void 0)throw new u("merge report takes no positional arguments.",p.USAGE);let m=await Q({includeReconciled:r.includeReconciled===!0});f(m,s),m.ok||(process.exitCode=p.GENERIC_FAILURE);break}case"driver":await Uo(t,o,i,a,r,s);break;default:throw I({command_path:"merge",token:e,allowed:B,display_name:"merge"})}s.profile&&v(`profile:command=merge took_ms=${Date.now()-d}`)}async function Bo(e,t,o){let i=y(o),a=Date.now(),r=await te(e,{title:l(t,"title"),author:l(t,"author"),message:l(t,"message"),allowDuplicate:t.allowDuplicate===!0},i);await b(i,r),f(r,i),i.profile&&v(`profile:command=copy took_ms=${Date.now()-a}`)}async function jo(e,t,o){let i=y(o),a=Date.now(),r=await ie(e,{clear:t.clear===!0},i);f(r,i),i.profile&&v(`profile:command=focus took_ms=${Date.now()-a}`)}async function qo(e,t,o){let i=y(o),a=Date.now();G(t);let r=t.stdinJson===!0;if(r){let g=await C().resolveValue("-","--stdin-json");t=await Ut(g??"","update",t,i)}let n=Lt(t,r);r||await se(t);let s=typeof t.bodyFile=="string";s&&(t.body=await J(String(t.bodyFile),t.body!==void 0?String(t.body):void 0),delete t.bodyFile);let d=Y(t);Ht(d,s,n),r&&V(d);let m=await mt(e,d,i);await b(i,m),f(await E("update",[e],t,i,m),i),i.profile&&v(`profile:command=update took_ms=${Date.now()-a}`)}async function Vo(e,t,o){let i=y(o),a=Date.now(),r=await oe(e,{author:l(t,"author"),message:l(t,"message"),force:!!t.force,dryRun:t.dryRun===!0},i);r.dry_run!==!0&&await b(i,r),f(r,i),i.profile&&v(`profile:command=delete took_ms=${Date.now()-a}`)}function zo(e,t){let o=l(t,"body"),i=l(t,"text"),a=typeof e=="string"?e:void 0;if([o,i,a].filter(n=>n!==void 0).length>1)throw new u("Specify append text with exactly one source: positional [text], --body, or --text",p.USAGE);let r=o??i??a;if(r===void 0)throw new u("Missing append text. Provide it as positional [text], --body <value>, or --text <value> (use - for stdin).",p.USAGE);return r}async function Jo(e,t,o,i){let a=y(i),r=Date.now(),n=await ct(e,{body:zo(t,o),author:l(o,"author"),message:l(o,"message"),force:!!o.force},a);await b(a,n),f(n,a),a.profile&&v(`profile:command=append took_ms=${Date.now()-r}`)}async function Ko(e,t,o,i){let a=y(i),r=Date.now(),{PROFILE_SUBCOMMANDS:n}=F,s=(e??"").trim().toLowerCase();if(!s)throw new u(`pm profile requires a subcommand. Allowed: ${n.join(", ")}`,p.USAGE,{code:"missing_required_argument",examples:["pm profile list","pm profile show agile","pm profile apply agile --dry-run","pm profile lint agile"]});if(!n.includes(s))throw I({command_path:"profile",token:s,allowed:n});let d=await So(F,s,t,o,a);a.json===!0||a.defaultOutputFormat==="json"?f(d,a):a.quiet||Ao(F,d),d.action==="lint"&&!d.ok&&(process.exitCode=p.GENERIC_FAILURE),a.profile&&v(`profile:command=profile took_ms=${Date.now()-r}`)}function _(e,t){return M(e[t])??[]}async function Wo(e,t,o){let i=y(o),a=Date.now(),r=_(t,"add"),n=_(t,"addGlob"),s=_(t,"remove"),d=_(t,"migrate"),m=await rt(e,{add:r,addGlob:n,remove:s,migrate:d,note:l(t,"note"),list:!!t.list,appendStable:!!t.appendStable,validatePaths:!!t.validatePaths,author:l(t,"author"),message:l(t,"message"),force:!!t.force},i);(r.length>0||n.length>0||s.length>0||d.length>0)&&await b(i,m),f(await E("files",[e],t,i,m),i),i.profile&&v(`profile:command=files took_ms=${Date.now()-a}`)}async function Xo(e,t,o){let i=y(o),a=Date.now(),r={...o.optsWithGlobals(),...t},n=await st(e,{apply:!!r.apply,note:l(r,"note"),appendStable:!!r.appendStable,author:l(r,"author"),message:l(r,"message"),force:!!r.force},i);n.changed&&await b(i,n),f(n,i),i.profile&&v(`profile:command=files.discover took_ms=${Date.now()-a}`)}async function Yo(e,t,o){let i=y(o),a=Date.now(),r=_(t,"add"),n=_(t,"addGlob"),s=_(t,"remove"),d=_(t,"migrate"),m=await at(e,{add:r,addGlob:n,remove:s,migrate:d,note:l(t,"note"),list:!!t.list,validatePaths:!!t.validatePaths,author:l(t,"author"),message:l(t,"message"),force:!!t.force},i);(r.length>0||n.length>0||s.length>0||d.length>0)&&await b(i,m),f(await E("docs",[e],t,i,m),i),i.profile&&v(`profile:command=docs took_ms=${Date.now()-a}`)}async function Zo(e,t,o){let i=y(o),a=Date.now(),r=await it(e,{format:t.format,maxDepth:l(t,"maxDepth"),collapse:t.collapse,summary:t.summary===!0,full:t.full===!0,nodeLimit:l(t,"nodeLimit"),edgeLimit:l(t,"edgeLimit"),tokenBudget:l(t,"tokenBudget"),cursor:l(t,"cursor"),direction:l(t,"direction"),...Array.isArray(t.kind)?{kind:t.kind}:{}},i);f(r,i),i.profile&&v(`profile:command=deps took_ms=${Date.now()-a}`)}function Ka(e,t={}){let o=e.command("create").argument("[type-or-title]",'Item title, or item type when a title follows (e.g. `pm create task "Fix bug"`)').argument("[title]","Item title when the first argument is an item type").description("Create a new project management item.");if(me(o,W),o.option("--stdin-json","Read a full item JSON document from stdin; explicit flags override document values").option("--body-file <path>","Load body from a file or stdin (-); conflicts with --body").option("--clear-deps","Clear dependency entries").option("--clear-comments","Clear comments").option("--clear-notes","Clear notes").option("--clear-learnings","Clear learnings").option("--clear-files","Clear linked files").option("--clear-tests","Clear linked tests").option("--clear-docs","Clear linked docs").option("--clear-reminders","Clear reminders").option("--clear-events","Clear events").option("--clear-type-options","Clear type options").option("--allow-duplicate","Explicitly create even when strict similarity governance finds likely duplicates").action(To),t.targetCommandName==="create")return;e.command("copy").argument("<id>","Source item id").option("--title <value>","Optional title override for the copied item").option("--author <value>","Mutation author").option("--message <value>","History message").option("--allow-duplicate","Explicitly copy even when strict similarity governance finds likely duplicates").description("Copy an item into a new item id while resetting lifecycle fields.").action(Bo),e.command("focus").argument("[id]","Item id to focus (omit to show current focus)").option("--clear","Clear the focused item").description("Set/clear/show the session focused item that new items default --parent to.").action(jo);let i=e.command("update").argument("<id>","Item id").description("Update item fields and metadata.");me(i,Ae),i.option("--stdin-json","Read a full item JSON document from stdin; explicit flags override document values").option("--body-file <path>","Load body from a file or stdin (-); conflicts with --body").option("--replace-deps","Atomically replace dependency entries with the provided --dep values").option("--replace-tests","Atomically replace linked test entries with the provided --test values").option("--replace-files","Atomically replace linked file entries with the provided --file values").option("--replace-docs","Atomically replace linked doc entries with the provided --doc values").option("--clear-deps","Clear dependency entries").option("--clear-comments","Clear comments").option("--clear-notes","Clear notes").option("--clear-learnings","Clear learnings").option("--clear-files","Clear linked files").option("--clear-tests","Clear linked tests").option("--clear-docs","Clear linked docs").option("--clear-reminders","Clear reminders").option("--clear-events","Clear events").option("--clear-type-options","Clear type options").option("--force","Force ownership override"),i.action(qo),It(e);let a=e.command("update-many").description("Bulk-update matched items with dry-run plans and rollback checkpoints.").option("--filter-status <value>","Filter by status before applying updates").option("--filter-type <value>","Filter by item type before applying updates").option("--filter-tag <value>","Filter by tag before applying updates").option("--filter-priority <value>","Filter by priority before applying updates").option("--filter-deadline-before <value>","Filter by deadline upper bound before applying updates").option("--filter-deadline-after <value>","Filter by deadline lower bound before applying updates").option("--filter-updated-after <value>","Filter by updated_at lower bound before applying updates (ISO/relative)").option("--filter-updated-before <value>","Filter by updated_at upper bound before applying updates (ISO/relative)").option("--filter-created-after <value>","Filter by created_at lower bound before applying updates (ISO/relative)").option("--filter-created-before <value>","Filter by created_at upper bound before applying updates (ISO/relative)").option("--filter-assignee <value>","Filter by assignee before applying updates").option("--filter-assignee-filter <value>","Filter assignee presence: assigned|unassigned before applying updates").option("--filter-parent <value>","Filter by parent item ID before applying updates").option("--filter-sprint <value>","Filter by sprint before applying updates").option("--filter-release <value>","Filter by release before applying updates").option("--filter-ac-missing","Select only items missing acceptance_criteria (bulk backfill)").option("--filter-estimates-missing","Select only items missing estimated_minutes (bulk backfill)").option("--filter-resolution-missing","Select only terminal items missing resolution (bulk backfill)").option("--filter-metadata-missing","Select only items missing any tracked metadata (AC, estimate, or resolution)");Nt(a,"applying updates"),a.option("--ids <value>","Explicit ID allowlist: comma/newline text, - stdin, or @path file").option("--limit <n>","Limit matched item count before apply/preview").option("--offset <n>","Skip first n matched rows before apply/preview").option("--dry-run","Preview per-item diffs and checkpoint intent without mutating").option("--rollback <value>","Rollback a prior update-many checkpoint ID").option("--no-checkpoint","Disable checkpoint creation during apply mode").option("--title, -t <value>","Set title").option("--description, -d <value>","Set description").option("--body, -b <value>","Set body (allow empty string)").option("--status, -s <value>","Set status (use close command for closed)").option("--priority, -p <value>","Set priority").option("--type <value>","Set type").option("--tags <value>","Set comma-separated tags (replaces existing). Use --add-tags / --remove-tags to mutate additively.").option("--add-tags <value>","Add tags additively without replacing existing (repeatable; CSV accepted)",c).option("--remove-tags <value>","Remove tags from the existing list (repeatable; CSV accepted)",c).option("--deadline <value>","Set deadline (ISO/date string or relative)").option("--estimate, --estimated-minutes <value>","Set estimated minutes").option("--acceptance-criteria <value>","Set acceptance criteria").option("--ac <value>","Alias for --acceptance-criteria").option("--add-ac <value>","Add one semicolon-free acceptance criterion without replacing the existing list (repeatable)",c).option("--remove-ac <value>","Remove one semicolon-free acceptance criterion by exact text match (repeatable)",c).option("--definition-of-ready <value>","Set definition of ready").option("--order <value>","Set planning order/rank integer").option("--rank <value>","Alias for --order").option("--goal <value>","Set goal identifier").option("--objective <value>","Set objective identifier").option("--value <value>","Set business value summary").option("--impact <value>","Set business impact summary").option("--outcome <value>","Set expected outcome summary").option("--why-now <value>","Set why-now rationale").option("--assignee <value>","Set assignee").option("--parent <value>","Set parent item ID").option("--reviewer <value>","Set reviewer").option("--risk <value>","Set risk level").option("--confidence <value>","Set confidence level").option("--sprint <value>","Set sprint identifier").option("--release <value>","Set release identifier").option("--blocked-by <value>","Set blocked-by item ID or reason").option("--blocked-reason <value>","Set blocked reason").option("--unblock-note <value>","Set unblock rationale note").option("--reporter <value>","Set issue reporter").option("--severity <value>","Set issue severity").option("--environment <value>","Set issue environment context").option("--repro-steps <value>","Set issue reproduction steps").option("--resolution <value>","Set issue resolution summary").option("--expected-result <value>","Set issue expected behavior").option("--expected <value>","Short alias for --expected-result").option("--actual-result <value>","Set issue observed behavior").option("--actual <value>","Short alias for --actual-result").option("--affected-version <value>","Set affected version identifier").option("--fixed-version <value>","Set fixed version identifier").option("--component <value>","Set issue component ownership").option("--regression [value]","Set regression marker; bare flag means true, or pass true|false|1|0").option("--customer-impact <value>","Set customer impact summary").option("--dep <value>","Add dependency entry id=<id>,kind=<kind>,author=<author>,created_at=<timestamp>",c).option("--dep-remove <value>","Remove dependency entries by id/kind/author/timestamp signature",c).option("--replace-deps","Atomically replace dependency entries with provided --dep values").option("--replace-tests","Atomically replace linked tests with provided --test values").option("--replace-files","Atomically replace linked files with provided --file values").option("--replace-docs","Atomically replace linked docs with provided --doc values").option("--comment <value>","Add comment seed author=<value>,created_at=<iso|now>,text=<value>",c).option("--note <value>","Add note seed author=<value>,created_at=<iso|now>,text=<value>",c).option("--learning <value>","Add learning seed author=<value>,created_at=<iso|now>,text=<value>",c).option("--file <value>","Add linked file path=<value>,scope=<project|global>,note=<text>",c).option("--test <value>","Add linked test command=<value>,path=<value>,scope=<project|global>",c).option("--doc <value>","Add linked doc path=<value>,scope=<project|global>,note=<text>",c).option("--reminder <value>","Add reminder entry at=<iso|relative>|date=<iso|relative>,text=<text>|title=<text>",c).option("--event <value>","Add event entry start=<iso|relative>,end=<iso|relative>,recur_*",c).option("--type-option <value>","Set type options key=value (repeatable)",c).option("--unset <field>","Clear scalar metadata field by name (repeatable)",c).option("--clear-deps","Clear dependency entries").option("--clear-comments","Clear comments").option("--clear-notes","Clear notes").option("--clear-learnings","Clear learnings").option("--clear-files","Clear linked files").option("--clear-tests","Clear linked tests").option("--clear-docs","Clear linked docs").option("--clear-reminders","Clear reminders").option("--clear-events","Clear events").option("--clear-type-options","Clear type options").option("--author <value>","Mutation author").option("--message <value>","Mutation message").option("--force","Force ownership override"),O(a,[["--filter-assignee_filter <value>","Alias for --filter-assignee-filter"],["--estimated_minutes <value>","Alias for --estimated-minutes"],["--acceptance_criteria <value>","Alias for --acceptance-criteria"],["--definition_of_ready <value>","Alias for --definition-of-ready"],["--why_now <value>","Alias for --why-now"],["--blocked_by <value>","Alias for --blocked-by"],["--blocked_reason <value>","Alias for --blocked-reason"],["--unblock_note <value>","Alias for --unblock-note"],["--repro_steps <value>","Alias for --repro-steps"],["--expected_result <value>","Alias for --expected-result"],["--actual_result <value>","Alias for --actual-result"],["--affected_version <value>","Alias for --affected-version"],["--fixed_version <value>","Alias for --fixed-version"],["--customer_impact <value>","Alias for --customer-impact"],["--filter-estimate-missing","Alias for --filter-estimates-missing"]],!1),O(a,[["--dep_remove <value>","Alias for --dep-remove"],["--type_option <value>","Alias for --type-option"],["--add_tags <value>","Alias for --add-tags"],["--remove_tags <value>","Alias for --remove-tags"],["--add_ac <value>","Alias for --add-ac"],["--remove_ac <value>","Alias for --remove-ac"]],!0),a.action(Fo);let r=e.command("close").option("--release-assignment","Release ownership after closure").argument("<id>","Item id").argument("[text]","Close reason text (alias: --reason)").option("-r, --reason <value>","Close reason text (alias for positional <text>)").option("--close-reason <value>","Close reason text (alias for positional <text>)").option("--completed-at <value>","Actual completion timestamp (ISO or relative), distinct from tracker close time").option("-d, --duplicate-of <id>","Close as a duplicate of the canonical item id and auto-fill duplicate closure metadata").option("--author <value>","Mutation author").option("-m, --message <value>","History message").option("--validate-close [mode]",'Validate closure metadata before close: "off", "warn", or "strict" (default: settings governance preset)').option("--resolution <value>","Closure resolution summary (checked by --validate-close strict)").option("--expected-result <value>","Expected outcome for closure validation").option("--expected <value>","Short alias for --expected-result").option("--actual-result <value>","Observed outcome for closure validation").option("--actual <value>","Short alias for --actual-result").option("--force","Force ownership override").description("Close an item. Close reason requirement follows governance.require_close_reason.");w(r,"--expected_result <value>","Alias for --expected-result",!1),w(r,"--actual_result <value>","Alias for --actual-result",!1),r.action(Mo);let n=e.command("close-many").description("Bulk-close matched items with a shared reason and full runClose semantics (dry-run + rollback checkpoint).").option("--filter-status <value>","Filter by status before closing").option("--filter-type <value>","Filter by item type before closing").option("--filter-tag <value>","Filter by tag before closing").option("--filter-priority <value>","Filter by priority before closing").option("--filter-deadline-before <value>","Filter by deadline upper bound before closing").option("--filter-deadline-after <value>","Filter by deadline lower bound before closing").option("--filter-updated-after <value>","Filter by updated_at lower bound before closing (ISO/relative)").option("--filter-updated-before <value>","Filter by updated_at upper bound before closing (ISO/relative)").option("--filter-created-after <value>","Filter by created_at lower bound before closing (ISO/relative)").option("--filter-created-before <value>","Filter by created_at upper bound before closing (ISO/relative)").option("--filter-assignee <value>","Filter by assignee before closing").option("--filter-assignee-filter <value>","Filter assignee presence: assigned|unassigned before closing").option("--filter-parent <value>","Filter by parent item ID before closing").option("--filter-sprint <value>","Filter by sprint before closing").option("--filter-release <value>","Filter by release before closing");Nt(n,"closing"),n.option("--ids <value>","Explicit ID allowlist: comma/newline text, - stdin, or @path file").option("--limit <n>","Limit matched item count before apply/preview").option("--offset <n>","Skip first n matched rows before apply/preview").option("--reason <value>","Shared close reason applied to matched items (required when governance.require_close_reason is enabled)").option("--completed-at <value>","Actual completion timestamp (ISO or relative) applied to every matched item").option("--resolution <value>","Shared closure resolution applied to every matched item (closure-validation field)").option("--expected-result <value>","Shared expected-result note (closure-validation field)").option("--expected <value>","Short alias for --expected-result").option("--actual-result <value>","Shared actual-result note (closure-validation field)").option("--actual <value>","Short alias for --actual-result").option("--validate-close [mode]",'Validate closure metadata per item: "off", "warn", or "strict" (default: settings governance preset)').option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Re-close already-terminal matches and override ownership").option("--dry-run","Preview matched items + per-item skip/active-child plan without mutating").option("--rollback <value>","Rollback a prior close-many checkpoint ID").option("--no-checkpoint","Disable checkpoint creation during apply mode"),w(n,"--filter-assignee_filter <value>","Alias for --filter-assignee-filter",!1),w(n,"--expected_result <value>","Alias for --expected-result",!1),w(n,"--actual_result <value>","Alias for --actual-result",!1),n.action(Oo),e.command("delete").argument("<id>","Item id").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership override").option("--dry-run","Preview the item file that would be deleted without mutating").description("Delete an item and record the change in history.").action(Vo),e.command("append").argument("<id>","Item id").argument("[text]","Body text; same as --body (- reads stdin)").option("--body <value>","Text to append to body (or - for stdin)").option("--text <value>","Alias for --body").option("--author <value>","Mutation author").option("--message <value>","Mutation message").option("--force","Force ownership override").description("Append text to an item's body. For concurrent writes, use pm notes.").action(Jo);let s=e.command("plan").description("Agent-optimized Plan item workflow: create, manage steps, link dependencies, approve, and materialize.").argument("[subcommand]","Required; Plan subcommand: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize").argument("[id]","Plan id (required for non-create subcommands); for create this may be the positional title").argument("[step]","Step reference: stable id (plan-step-001) or order integer").argument("[new-order]","New order integer for reorder-step").option("--title <value>","Plan title").option("--description <value>","Plan description").option("--scope <value>","Short scope statement of the target change or investigation").option("--parent <value>","Parent pm item id").option("--related <value>","Related pm item ids (repeatable, csv-friendly)",c).option("--blocks <value>","Pm item ids this plan blocks (repeatable, csv-friendly)",c).option("--blocked-by <value>","Pm item ids that block this plan (repeatable, csv-friendly)",c).option("--harness <value>","Plan harness provenance: codex|claude-code|cursor|generic").option("--mode <value>","Plan mode: draft|research|review|approved|executing|paused|completed|superseded").option("--resume-context <value>","Compact context summary for a future stateless agent").option("--tags <value>","Comma-separated tags").option("--priority <value>","Priority 0-4").option("--body <value>","Plan item body").option("--claim","Claim the plan on create for the author").option("--from-search <value>","Record the search query that led to plan creation").option("--template <value>","Seed plan steps from a built-in template: bug-investigation|feature-implementation|refactoring-sprint").option("--step-title <value>","Step title for add-step / update-step").option("--step <value>","Step title (repeatable on create: each --step appends an ordered step; elsewhere a single value aliases --step-title)",c).option("--step-body <value>","Step body text").option("--step-owner <value>","Step owner").option("--step-status <value>","Step status: pending|in_progress|completed|blocked|skipped|superseded").option("--step-evidence <value>","Step evidence text (used by update-step/complete-step)").option("--step-blocked-reason <value>","Step blocked reason (required when blocking)").option("--step-replacement <value>","Replacement reference for a superseded step").option("--depends-on <value>","Pm item ids the step depends on (repeatable, csv-friendly)",c).option("--link <value>","Pm item id to link (repeatable, csv-friendly)",c).option("--link-kind <value>",`Link kind: ${ge.join("|")}`).option("--link-note <value>","Optional note for the link").option("--promote-to-item-dep","Also add the linked id as a top-level item dependency when linking").option("--allow-multiple-active","Allow multiple steps to be in_progress at once").option("--file <value>","Step linked file path=<value>[,scope=project|global,note=<text>] (repeatable)",c).option("--test <value>","Step linked test command=<value>[,path=<value>,note=<text>] (repeatable)",c).option("--doc <value>","Step linked doc path=<value>[,scope=project|global,note=<text>] (repeatable)",c).option("--decision-text <value>","Decision log entry text").option("--decision <value>","Alias for --decision-text").option("--decision-rationale <value>","Decision log entry rationale").option("--decision-evidence <value>","Decision log entry evidence").option("--discovery-text <value>","Discovery log entry text").option("--discovery <value>","Alias for --discovery-text").option("--validation-text <value>","Validation log entry text").option("--validation <value>","Alias for --validation-text").option("--validation-command <value>","Validation log entry command").option("--validation-expected <value>","Validation log entry expected outcome").option("--depth <value>","Show depth: brief|standard|deep (default: brief)").option("--fields <value>","Comma-separated field projection for show output").option("--steps <value>","Comma-separated step ids/orders for materialize").option("--materialize-type <value>","Item type for materialized steps (default: Task)").option("--materialize-parent <value>","Parent item id for materialized children (default: the plan)").option("--materialize-tags <value>","Comma-separated tags for materialized children").option("--field <name=value>","Custom field value forwarded to every materialized child (repeatable)",c).option("--author <value>","Mutation author").option("--message <value>","Mutation message").option("--force","Force ownership override");me(s,W.filter(m=>wo.has(m.target))),O(s,[["--resume_context <value>","Alias for --resume-context"],["--from_search <value>","Alias for --from-search"],["--step_title <value>","Alias for --step-title"],["--step_body <value>","Alias for --step-body"],["--step_owner <value>","Alias for --step-owner"],["--step_status <value>","Alias for --step-status"],["--step_evidence <value>","Alias for --step-evidence"],["--step_blocked_reason <value>","Alias for --step-blocked-reason"],["--step_replacement <value>","Alias for --step-replacement"],["--link_kind <value>","Alias for --link-kind"],["--link_note <value>","Alias for --link-note"],["--promote_to_item_dep","Alias for --promote-to-item-dep"],["--allow_multiple_active","Alias for --allow-multiple-active"],["--decision_text <value>","Alias for --decision-text"],["--decision_rationale <value>","Alias for --decision-rationale"],["--decision_evidence <value>","Alias for --decision-evidence"],["--discovery_text <value>","Alias for --discovery-text"],["--validation_text <value>","Alias for --validation-text"],["--validation_command <value>","Alias for --validation-command"],["--validation_expected <value>","Alias for --validation-expected"],["--materialize_type <value>","Alias for --materialize-type"],["--materialize_parent <value>","Alias for --materialize-parent"],["--materialize_tags <value>","Alias for --materialize-tags"]],!1),O(s,[["--blocked_by <value>","Alias for --blocked-by"],["--depends_on <value>","Alias for --depends-on"]],!0),s.action(Ho),wt(e,!1),Rt(e),e.command("merge").argument("<subcommand>",`${B.join(" | ")}`).argument("[artifact]",`driver: ${ae.join(" | ")}`).argument("[base]","driver: ancestor file (%O)").argument("[ours]","driver: current file (%A)").argument("[theirs]","driver: incoming file (%B)").option("--dry-run","install/reconcile: preview").option("--pre-commit-hook","install: opt into merge settlement hook").option("--stage","reconcile: stage lossless audit evidence").option("--message <text>","reconcile: audit message").option("--force","reconcile: accept reviewed decisions").option("--include-reconciled","report: include settled receipts").option("--output <path>","driver: alternate output").option("--item-path <path>","driver: repository-relative path (%P)").option("--prefer <side>","driver: ours|theirs (default ours)").description("Manage tracker merges.").action(Go),Pt(e),e.command("profile").argument("[subcommand]","Required; Profile subcommand: list, show, apply, or lint").argument("[name]","Profile name for show/apply/lint: agile, ops, or research").option("--dry-run","Preview the apply diff without writing any files (apply)").option("--author <value>","Mutation author").option("--force","Force ownership/lock override").description("List, show, apply, and lint project profiles \u2014 archetype bundles of item types, statuses, fields, workflows, config, templates, and recommended packages.").action(Ko),Ot(e,ko);let d=e.command("files").description("Manage files linked to an item.");d.argument("<id>","Item id").option("--add <value>","Add linked file entry (CSV/markdown pairs or - for stdin)",c).option("--add-glob <value>","Add linked file entries from a glob (plain glob or pattern=<glob>,scope=<scope>,note=<text>; repeatable)",c).option("--remove <value>","Remove linked file by path only (path=<value>, path:<value>, plain path, or - for stdin); does not accept note=/scope= \u2014 record removal context with --message",c).option("--migrate <value>","Migrate linked file paths in-place (from=<prefix>,to=<prefix>; repeatable)",c).option("--note <value>","Note attached to every link added by --add/--add-glob in this invocation (embedded note= wins)").option("--list","List linked files without mutating").option("--append-stable","Preserve existing linked-file order and append new links without full-array resorting").option("--validate-paths","Validate linked file paths for existence and file shape").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership override").action(Wo),d.command("discover").argument("<id>","Item id").option("--apply","Add discovered missing files to the item").option("--note <value>","Note to attach to discovered file links").option("--append-stable","Preserve existing linked-file order and append discovered links without full-array resorting").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership override").description("Discover existing file paths referenced in item text and optionally link missing files.").action(Xo),Ft(d),e.command("docs").argument("<id>","Item id").option("--add <value>","Add linked doc entry (CSV/markdown pairs or - for stdin)",c).option("--add-glob <value>","Add linked doc entries from a glob (plain glob or pattern=<glob>,scope=<scope>,note=<text>; repeatable)",c).option("--remove <value>","Remove linked doc by path only (path=<value>, path:<value>, plain path, or - for stdin); does not accept note=/scope= \u2014 record removal context with --message",c).option("--migrate <value>","Migrate linked doc paths in-place (from=<prefix>,to=<prefix>; repeatable)",c).option("--note <value>","Note attached to every link added by --add/--add-glob in this invocation (embedded note= wins)").option("--list","List linked docs without mutating").option("--validate-paths","Validate linked doc paths for existence and file shape").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership override").description("Manage docs linked to an item.").action(Yo),e.command("deps").argument("<id>","Item id").option("--format <value>","Output format (tree, graph, or context)","tree").option("--max-depth <value>","Maximum dependency traversal depth (0 keeps only the root)").option("--collapse <value>","Collapse mode (none or repeated)","none").option("--summary","Return counts only without full tree/graph payload").option("--full","Return the complete dependency row projection").option("--node-limit <value>","Maximum nodes in context output").option("--edge-limit <value>","Maximum edges and missing-reference rows in context output").option("--token-budget <value>","Maximum estimated tokens in context output").option("--cursor <value>","Continue an equivalent context query").option("--direction <value>","Context traversal direction (outgoing, incoming, or both)").option("--kind <value>","Restrict context traversal to registered relationship kinds (repeatable or comma-separated)",c).description("Show dependency relationships for an item.").action(Zo)}export{ue as looksLikeSchemaSubcommandTypo,ko as parsePositiveIntOption,U as parseSchemaOrderOption,me as registerCommanderOptionContracts,Ka as registerMutationCommands};
20
- //# sourceMappingURL=register-mutation-JZVVJUHY.js.map